Cor*_*ole 8 python static-typing function return-type mypy
我来自打字稿背景。我正在将静态类型检查引入到我正在研究的python项目中(使用mypy)。
在Typescript中,从带有注释以返回其他内容(例如字符串)的函数中返回null是有效的:
function test(flag: boolean): string {
if(flag) {
return 'success';
} else {
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
对函数进行注释以使其具有多种潜在的返回类型(例如字符串或布尔值)也是有效的:
function test(flag: boolean): string | boolean {
if(flag) {
return 'success';
} else {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,在使用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")
Run Code Online (Sandbox Code Playgroud)
此外,我看不到注释多种返回类型的方法,即str | None
。
我应该如何使用mypy处理类似的事情?从错误状态返回None的函数遍布我的代码库。
Cor*_*ole 10
好的,由于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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果要注释该函数可能返回多种类型,即str | bool
,请使用Union
:
from typing import Union
def test(flag: bool) -> Union[str, bool] {
if(flag) {
return 'success';
} else {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1476 次 |
最近记录: |