python - mypy 中的可选[]类型

标签 python python-3.x static-analysis 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)))

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/

相关文章:

python - 获取 Python shell 作业中的当前作业角色 - Aws Glue

python - 非致命地终止模块的导入?

django - 我的 Django/uWSGI vassal 的堆栈跟踪记录在哪里?

Python,正则表达式-如何匹配第二组,仅当第一组匹配时

c++ - 有没有人有使用 pc-lint 的好技巧?

ocaml - ocamlgraph 中的编译错误

java - 有没有办法使用静态代码分析来确定某个类型的所有字段是否都有注释?

python - 如何在 "my"python解释器中定义内置函数?

python - pyinstaller 和 reportlab 的问题

python-3.x - numpy 数组中数字前的冒号