mypy 中的可选[]类型

apo*_*sis 2 python static-analysis python-3.x mypy

我有以下嵌套函数

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)))
Run Code Online (Sandbox Code Playgroud)

mypy抛出以下错误:

error: Argument 2 to "inner" has incompatible type "Optional[int]"; expected "int"
Run Code Online (Sandbox Code Playgroud)

鉴于我给出了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)))
Run Code Online (Sandbox Code Playgroud)

这似乎破坏了声明中默认参数的用处。这是最好的/Python式的方法吗?

azr*_*zro 5

由于有默认值,所以 outer_bar不是一个Optional,因为它不会None

def outer(outer_foo: int, outer_bar: int = 5):
    return inner(outer_foo, outer_bar)
Run Code Online (Sandbox Code Playgroud)

注意,当默认值需要为空列表时,将“Least Astonishment”和 Mutable Default Argument用作None默认值,则or []

def outer(outer_foo: int, outer_bar: Optional[list[int]] = None):
    return inner(outer_foo, outer_bar or [])
Run Code Online (Sandbox Code Playgroud)