Python 标准库之 typing (类型标注)

date
Apr 9, 2020
slug
5589750461327360
status
Published
tags
Python
summary
type
Post
PEP 3107引入了功能注释的语法,PEP 484 加入了类型检查
标准库 typing 为类型提示指定的运行时提供支持。 示例:
def f(a: str, b:int) -> str: return a * b
notion image
如果实参不是预期的类型:
notion imagenotion image
但是,Python运行时不强制执行函数和变量类型注释。使用类型检查器,IDE,lint等才能帮助代码进行强制类型检查。

使用NewType 创建类型

NewType() 是一个辅助函数,用于向类型检查器指示不同的类型,在运行时,它返回一个函数,该函数返回其参数。
import typing Id = typing.NewType("Id", int) a = Id(2020)
使用 NewType() 创建的类型会被类型检查器视为它的原始类型的子类。

回调(Callable)

将回调函数类型标注为 Callable[[Arg1Type, Arg2Type], ReturnType]
from typing import Callable def f(a: int) -> str: return str(a) def callback(a: int, func: Callable[[int], str]) -> str: return func(a) print(callback(1, f))

泛型

为容器元素添加预期的类型
from typing import Mapping a: Mapping[str, str]
notion imagenotion image
通过
TypeVar
进行参数化来约束一个类型集合:
from typing import TypeVar T = TypeVar('T') # 可以是任何东西。A = TypeVar('A', str, bytes) # 必须是 str 或 bytes
notion image
使用
TypeVar
约束一个类型集合,但不允许单个约束 例如:
T = TypeVar('T', str)
这样会抛出一个异常 TypeError: A single constraint is not allowed

typing 包含的类型

AbstractSet = typing.AbstractSet Any = typing.Any AnyStr = ~AnyStr AsyncContextManager = typing.AbstractAsyncContextManager AsyncGenerator = typing.AsyncGenerator AsyncIterable = typing.AsyncIterable AsyncIterator = typing.AsyncIterator Awaitable = typing.Awaitable ByteString = typing.ByteString Callable = typing.Callable ClassVar = typing.ClassVar Collection = typing.Collection Container = typing.Container ContextManager = typing.AbstractContextManager Coroutine = typing.Coroutine Counter = typing.Counter DefaultDict = typing.DefaultDict Deque = typing.Deque Dict = typing.Dict FrozenSet = typing.FrozenSet Generator = typing.Generator Hashable = typing.Hashable ItemsView = typing.ItemsView Iterable = typing.Iterable Iterator = typing.Iterator KeysView = typing.KeysView List = typing.List Mapping = typing.Mapping MappingView = typing.MappingView MutableMapping = typing.MutableMapping MutableSequence = typing.MutableSequence MutableSet = typing.MutableSet NoReturn = typing.NoReturn Optional = typing.Optional Reversible = typing.Reversible Sequence = typing.Sequence Set = typing.Set Sized = typing.Sized TYPE_CHECKING = False Tuple = typing.Tuple Type = typing.Type Union = typing.Union ValuesView = typing.ValuesView
 
对于本文内容有任何疑问, 可与我联系.