我有以下嵌套函数
from typing import Optional
def outer(
outer_foo:int,
outer_bar:Optional[int] = 5
):
return inner(outer_foo, outer_bar)
def inner(
inner_foo:int,
inner_bar:int
):
return inner_foo+inner_bar
print(outer((1)))
和 mypy
抛出以下错误:
error: Argument 2 to "inner" has incompatible type "Optional[int]"; expected "int"
鉴于我将 int
作为 outer_bar
的默认值,我没有发现潜在的问题。但是,我能够解决 mypy 错误,将代码更改为:
from typing import Optional
def outer(
outer_foo:int,
outer_bar:Optional[int] = None
):
if outer_bar is None:
outer_bar = 5
return inner(outer_foo, outer_bar)
def inner(
inner_foo:int,
inner_bar:int
):
return inner_foo+inner_bar
print(outer((1)))
这似乎破坏了声明中默认参数的用处。这是最好的/Python式的方法吗?
最佳答案
由于存在默认值,因此 outer_bar
不是 Optional
,因为它不会是 None
def outer(outer_foo: int, outer_bar: int = 5):
return inner(outer_foo, outer_bar)
注意,当默认值需要为空列表时,关于"Least Astonishment" and the Mutable Default Argument使用None
作为默认值,然后或[]
def outer(outer_foo: int, outer_bar: Optional[list[int]] = None):
return inner(outer_foo, outer_bar or [])
关于python - mypy 中的可选[]类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70657329/