Return None 来自 python 函数,用 mypy 注释,多个 return 类型
Return None from python function annotated with mypy, multiple return types
我有 Typescript 背景。我正在将静态类型检查引入我正在处理的 python 项目(使用 mypy)。
在 Typescript 中,从注释为 return 其他内容(即字符串)的函数中 return null 是有效的:
function test(flag: boolean): string {
if(flag) {
return 'success';
} else {
return null;
}
}
将您的函数注释为具有多种可能的 return 类型也是有效的,即字符串或布尔值:
function test(flag: boolean): string | boolean {
if(flag) {
return 'success';
} else {
return false;
}
}
但是,在使用 mypy 的 python 中,不允许我从注释为 return str
的函数中 returning None。
def test(flag: bool) -> str:
if flag:
return 'success'
else:
return None
# [mypy] error:Incompatible return value type (got "None", expected "str")
此外,我没有看到注释多个 return 类型的方法,即 str | None
。
我应该如何使用 mypy 处理这样的事情? return None 来自错误状态的函数遍布我的代码库。
好的,感谢 mypy gitter 上的@zsol,我找到了文档中缺少的内容!
两个有用的 mypy 功能是可以从 python 的输入模块导入的可选和联合类型。 Documentation here.
如果您想注释该函数可能 return None 除了主要类型,例如str
, 使用 Optional
:
from typing import Optional
def test(flag: bool) -> Optional[str]:
if flag:
return 'success'
else:
return None
如果您想注释该函数可能 return 多种类型,例如str | bool
, 使用 Union
:
from typing import Union
def test(flag: bool) -> Union[str, bool]:
if flag:
return 'success'
else:
return False
我有 Typescript 背景。我正在将静态类型检查引入我正在处理的 python 项目(使用 mypy)。
在 Typescript 中,从注释为 return 其他内容(即字符串)的函数中 return null 是有效的:
function test(flag: boolean): string {
if(flag) {
return 'success';
} else {
return null;
}
}
将您的函数注释为具有多种可能的 return 类型也是有效的,即字符串或布尔值:
function test(flag: boolean): string | boolean {
if(flag) {
return 'success';
} else {
return false;
}
}
但是,在使用 mypy 的 python 中,不允许我从注释为 return str
的函数中 returning None。
def test(flag: bool) -> str:
if flag:
return 'success'
else:
return None
# [mypy] error:Incompatible return value type (got "None", expected "str")
此外,我没有看到注释多个 return 类型的方法,即 str | None
。
我应该如何使用 mypy 处理这样的事情? return None 来自错误状态的函数遍布我的代码库。
好的,感谢 mypy gitter 上的@zsol,我找到了文档中缺少的内容!
两个有用的 mypy 功能是可以从 python 的输入模块导入的可选和联合类型。 Documentation here.
如果您想注释该函数可能 return None 除了主要类型,例如str
, 使用 Optional
:
from typing import Optional
def test(flag: bool) -> Optional[str]:
if flag:
return 'success'
else:
return None
如果您想注释该函数可能 return 多种类型,例如str | bool
, 使用 Union
:
from typing import Union
def test(flag: bool) -> Union[str, bool]:
if flag:
return 'success'
else:
return False