python - 如果我将默认设置为 None 可以省略 Optional 吗?

标签 python python-3.x type-hinting mypy python-typing

例如:

def foo(bar: int = None):
    pass
当我检查 bar 的类型/注释时pycharm 告诉我它是 Optional[int] .bar: int = None看起来干净多了 bar: Optional[int] = None ,尤其是当您有 10 多个参数时。
所以我可以简单地省略 Optional ?像 mypy 或其他 linter 这样的工具是否会将这种情况突出显示为错误?
看起来python本身不喜欢这个想法:
In [1]: from typing import Optional
In [2]: from inspect import signature

In [3]: def foo(a: int = None): pass
In [4]: def bar(a: Optional[int] = None): pass

In [5]: signature(foo).parameters['a'].annotation
Out[5]: int

In [6]: signature(bar).parameters['a'].annotation
Out[6]: typing.Union[int, NoneType]

最佳答案

编号省略Optional以前是允许的,但后来被删除了。

A past version of this PEP allowed type checkers to assume an optional type when the default value is None [...]

This is no longer the recommended behavior. Type checkers should move towards requiring the optional type to be made explicit.


某些工具可能仍会为遗留支持提供旧行为。即使是这种情况,也不要指望将来会支持它。

具体来说,mypy 仍然支持隐式 Optional默认情况下,但明确指出这可能会在 future 发生变化:

Optional types and the None type (mypy v0.782)

[...] You can use the --no-implicit-optional command-line option to stop treating arguments with a None default value as having an implicit Optional[...] type. It’s possible that this will become the default behavior in the future.


mypy/#9091 中跟踪了此行为的弃用情况

关于python - 如果我将默认设置为 None 可以省略 Optional 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62732402/

相关文章:

python-3.x - 读取由 nan 行分割的数据框,并在 Python 中将它们 reshape 为多个数据框

PHP 提示动态返回类型(基于 $class 参数)

python - 从 python 读取 excel 工作表单元格的背景颜色?

python - 我可以从 SQLAlchemy 中获取纯数组而不是字典的行吗?

python - Vim 中的 Google Pytype

python - 尽管包中包含 py.typed 标记,但 stub 文件未包含在分发中

Python:如何在函数中键入提示 tf.keras 对象?

python - 用 C 嵌入 Python

python - "Compiling" python 脚本

python - Django 迁移未检测到 unique=True 更改