简体   繁体   English

从用 mypy 注释的 python 函数返回 None,多种返回类型

[英]Return None from python function annotated with mypy, multiple return types

I come from a Typescript background.我来自打字稿背景。 I'm bringing static type checking into a python project I'm working on (using mypy).我正在将静态类型检查引入我正在处理的 python 项目中(使用 mypy)。

In Typescript, it is valid to return null from a function that is annotated to return something else, ie a string:在 Typescript 中,从被注释为返回其他内容的函数返回 null 是有效的,即字符串:

function test(flag: boolean): string {
    if(flag) {
        return 'success';
    } else {
        return null;
    }
}

It is also valid to annotate your function to have multiple potential return types, ie string or boolean:将您的函数注释为具有多种潜在的返回类型(即字符串或布尔值)也是有效的:

function test(flag: boolean): string | boolean {
    if(flag) {
        return 'success';
    } else {
        return false;
    }
}

But, in python using mypy, I'm disallowed from returning None from a function that is annotated to return str .但是,在使用 mypy 的 python 中,我不允许从注释为返回str的函数返回 None 。

def test(flag: bool) -> str:
    if flag:
        return 'success'
    else:
        return None
        # [mypy] error:Incompatible return value type (got "None", expected "str")

Furthermore, I don't see a way to annotate multiple return types, ie str | None此外,我没有看到注释多个返回类型的方法,即str | None str | None . str | None

How should I approach something like this using mypy?我应该如何使用 mypy 处理这样的事情? Functions that return None from the error state are all over my codebase.从错误状态返回 None 的函数遍布我的代码库。

Okay, I found what I was missing in the documentation thanks to @zsol on the mypy gitter!好的,感谢 mypy gitter 上的 @zsol,我找到了文档中缺少的内容!

Two helpful mypy features are the Optional and Union types that can be imported from python's typing module.两个有用的 mypy 功能是 Optional 和 Union 类型,它们可以从 python 的输入模块中导入。 Documentation here. 文档在这里。

If you want to annotate that the function can potentially return None in addition to the primary type, eg str , use Optional :如果您想注释该函数除了主要类型之外还可能返回 None ,例如str ,请使用Optional

from typing import Optional

def test(flag: bool) -> Optional[str]:
    if flag:
        return 'success'
    else:
        return None

If you want to annotate that the function can potentially return multiple types, eg str | bool如果要注释该函数可能返回多种类型,例如str | bool str | bool , use Union : str | bool ,使用Union

from typing import Union

def test(flag: bool) -> Union[str, bool]:
    if flag:
        return 'success'
    else:
        return False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM