默认为 None 的参数是否应该始终被类型提示为 Optional[]?

Should arguments that default to None always be type hinted as Optional[]?

比较这两个函数:

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-type-checking 中,最好使 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.