可选[]类型在mypy中

问题描述 投票:0回答:1

我有以下嵌套函数

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式的方法吗?

python python-3.x static-analysis mypy
1个回答
5
投票

由于有默认值,所以

outer_bar
不是
Optional
,因为它不会是
None

def outer(outer_foo: int, outer_bar: int = 5):
    return inner(outer_foo, outer_bar)

注意,当默认值需要为空列表时,对于 “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 [])
© www.soinside.com 2019 - 2024. All rights reserved.