#3 Python 类型提示(Type Hints)
Python Python3 2021-01-28Type Hint, 英文直译应该是输入提示。
动态类型语言有一个优点,同时也是缺点:不好做静态类型检查,IDE 或者其他开发工具很难根据代码去准确判断一个变量的类型。
Python 3.0 开始引入并逐渐完善类型注解(Type Annotation)则给 Python 静态类型检查提供了可能性。
PS: Python 运行时会忽略类型注解,不会给任何提示或警告。
PS: 之前的一些工具可以通过注释来做类型检查 (Type Comment),起到相同的作用。
PEP
SF 3107 [2006-12-02] (3.0 ) Function Annotations 开始引入函数注解
SF 3141 [2007-04-23] ( ) A Type Hierarchy for Numbers
SF 424 [2012-07-14] (3.4 ) A method for exposing a length hint
SF 451 [2013-08-08] (3.4 ) A ModuleSpec Type for the Import System
SP 484 [2014-09-29] (3.5 ) Type Hints 类型提示
IF 483 [2014-12-19] ( ) The Theory of Type Hints
IF 482 [2015-01-08] ( ) Literature Overview for Type Hints
SF 526 [2016-08-09] (3.6 ) Syntax for Variable Annotations
SA 544 [2017-03-05] (3.8 ) Protocols: Structural subtyping (static duck typing)
SA 560 [2017-09-03] (3.7 ) Core support for typing module and generic types
SA 563 [2017-09-08] (3.7 ) Postponed Evaluation of Annotations
SA 561 [2017-09-09] (3.7 ) Distributing and Packaging Type Information
SA 585 [2019-03-03] (3.9 ) Type Hinting Generics In Standard Collections
SA 586 [2019-03-14] (3.8 ) Literal Types
SA 591 [2019-03-15] (3.8 ) Adding a final qualifier to typing
SA 589 [2019-03-20] (3.8 ) TypedDict: Type Hints for Dictionaries with a Fixed Set of Keys
SA 593 [2019-04-26] (3.9 ) Flexible function and variable annotations
SA 604 [2019-08-28] (3.10) Allow writing union types as ``X | Y``
SA 613 [2020-01-21] ( ) Explicit Type Aliases 引入类型别名
SA 647 [2020-10-07] (3.10) User-Defined Type Guards 引入 TypeGuard 类型,缩小类型检查时的范围
S 649 [2021-01-11] ( ) Deferred Evaluation Of Annotations Using Descriptors
S 655 [2021-01-30] (3.10) Marking individual TypedDict items as required or potentially-missing
基础用法
如果担心类型检查会,可以使用 @no_type_check
装饰器。
def greeting(name: str) -> str:
return 'Hello ' + name
Vector = list[float]
def scale(scalar: float, vector: Vector) -> Vector:
return [scalar * num for num in vector]
Union
from typing import NoReturn
Address = tuple[str, int]
def connect(Union[Address, str]) -> NoReturn:
pass
Optional[T]
是 Union[T, None]
的简写。
def get_argument(name:str, default:Optional[str]=None) -> Union[str, None]:
pass
其他常用类型
Any
Callable
ClassVar
NewType
stub 文件
https://github.com/python/typeshed
Collection of library stubs for Python, with static types
类型检查工具
IDE,比如 PyCharm,可以配置类型检查。
VSCode 或者 Atom 之类的编辑器也可以通过插件支持类型检查。
- mypy
- pyright
- pytype
- pyre
参考:
- https://github.com/topics/typechecker?l=python&stars:%3E1000
- https://github.com/search?q=type+python+stars%3A%3E3000&s=stars&o=desc
mypy
参考资料与拓展阅读
- Python 文档, typing — Support for type hints
- 阿里云开发者社区, 利用Stub File标注Python文件类型
- 知乎, Python 类型检查指南
- Typing Python with typing