我来自打字稿背景。我正在将静态类型检查引入我正在处理的 python 项目中(使用 mypy)。在 Typescript 中,从被注释为返回其他内容的函数返回 null 是有效的,即字符串:function test(flag: boolean): string { if(flag) { return 'success'; } else { return null; }}将您的函数注释为具有多种潜在的返回类型(即字符串或布尔值)也是有效的:function test(flag: boolean): string | boolean { if(flag) { return 'success'; } else { return false; }}但是,在使用 mypy 的 python 中,我不允许从注释为 return 的函数返回 None str。def test(flag: bool) -> str: if flag: return 'success' else: return None # [mypy] error:Incompatible return value type (got "None", expected "str")此外,我没有看到注释多个返回类型的方法,即str | None.我应该如何使用 mypy 处理这样的事情?从错误状态返回 None 的函数遍布我的代码库。
1 回答

ITMISS
TA贡献1871条经验 获得超8个赞
好的,感谢 mypy gitter 上的 @zsol,我找到了文档中缺少的内容!
两个有用的 mypy 功能是 Optional 和 Union 类型,它们可以从 python 的输入模块中导入。文档在这里。
如果您想注释该函数除了主要类型之外还可能返回 None,例如str,使用Optional:
from typing import Optional
def test(flag: bool) -> Optional[str]:
if flag:
return 'success'
else:
return None
如果您想注释该函数可能返回多种类型,例如str | bool,使用Union:
from typing import Union
def test(flag: bool) -> Union[str, bool]:
if flag:
return 'success'
else:
return False
添加回答
举报
0/150
提交
取消