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

标签 python type-hinting typechecking mypy

比较这两个函数:

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/

相关文章:

python - Pandas ,带有 datetime64 列的数据框,按小时查询

python - __name__ 在 TypeVar, NewType 中的用途

c++ - 检查模板函数的数据类型

python - 有没有办法调整组合框条目的大小?

python - Flask 和 WTForms - 如何让 wtforms 刷新选择的数据

c++ - OpenCV 中的 Python C++ 绑定(bind)

python - 生成器在 Python 中有什么类型签名?

python - 如何键入具有不同类型值的字典提示

c++ - 空投的运行时检查*

python - 检查数字零时的多个条件声明 - python