例如:
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/