【发布时间】:2019-02-15 06:26:36
【问题描述】:
我来自 Typescript 背景。我正在将静态类型检查引入我正在处理的 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 中,不允许我从注释为返回 str 的函数返回 None。
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 的函数遍布我的代码库。
【问题讨论】:
-
你能不能只返回一个空字符串?
-
这是合乎逻辑的:在 Python 中,
None不是一个“空引用”,它是一个对象(就像任何其他对象一样),它的类型是NoneType。 -
@WillemVanOnsem 是的,python 中的 None 类型与 javascript 中的 null 引用不同。
标签: python function return-type static-typing mypy