比较这两个函数:
from typing import Optional
def foo1(bar: str = None) -> None:
print(bar)
def foo2(bar: Optional[str] = None) -> None:
print(bar)
Mypy 不会提示它们中的任何一个。是Optional[]
那么真的有必要吗?这两个声明之间有什么细微的区别吗?
最佳答案
自原始答案编写以来,PEP-484 已更新。在现代 python 类型检查中,最好将 Optional
显式化。引用 PEP:
A past version of this PEP allowed type checkers to assume an optional type when the default value is None, as in this code:
def handle_employee(e: Employee = None): ...
This would have been treated as equivalent to:
def handle_employee(e: Optional[Employee] = None) -> None: ...
This is no longer the recommended behavior. Type checkers should move towards requiring the optional type to be made explicit.
关于python - 默认为 None 的参数是否应该始终被类型提示为Optional[]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49724085/