typing
— Support for type hints支持类型提示¶
New in version 3.5.版本3.5中新增。
Source code: Lib/typing.py
Note
The Python runtime does not enforce function and variable type annotations. Python运行时不强制执行函数和变量类型注释。They can be used by third party tools such as type checkers, IDEs, linters, etc.它们可以被第三方工具使用,如类型检查器、IDE、linters等。
This module provides runtime support for type hints. 此模块为类型提示提供运行时支持。The most fundamental support consists of the types 最基本的支持包括Any
, Union
, Callable
, TypeVar
, and Generic
. Any
、Union
、Callable
、TypeVar
和Generic
类型。For a full specification, please see PEP 484. 有关完整规范,请参阅PEP 484。For a simplified introduction to type hints, see PEP 483.有关类型提示的简化介绍,请参阅PEP 483。
The function below takes and returns a string and is annotated as follows:下面的函数接受并返回一个字符串,注释如下:
def greeting(name: str) -> str:
return 'Hello ' + name
In the function 在函数greeting
, the argument name
is expected to be of type str
and the return type str
. greeting
中,参数name
应为str
类型,返回类型为str
。Subtypes are accepted as arguments.子类型被接受为参数。
New features are frequently added to the typing
module. typing
模块中经常添加新功能。The typing_extensions package provides backports of these new features to older versions of Python.typing_extensions包为旧版本的Python提供了这些新功能的后端。
Relevant PEPs相关PEP¶
Since the initial introduction of type hints in PEP 484 and PEP 483, a number of PEPs have modified and enhanced Python’s framework for type annotations. 自从PEP 484和PEP 483中首次引入类型提示以来,许多PEP修改并增强了Python的类型注释框架。These include:其中包括:
- PEP 544
: Protocols: Structural subtyping (static duck typing):协议:结构子类型(静态鸭子类型) Introducing介绍Protocol
and the@runtime_checkable
decoratorProtocol
和@runtime_checkable
的装饰器
- PEP 544
- PEP 585
: Type Hinting Generics In Standard Collections:在标准集合中键入提示泛型 Introducing介绍types.GenericAlias
and the ability to use standard library classes as generic typestypes.GenericAlias
以及将标准库类用作泛型类型的能力
- PEP 585
- PEP 604
: Allow writing union types as:允许将联合类型写入X | Y
X|Y
Introducing介绍types.UnionType
and the ability to use the binary-or operator|
to signify a union of typestypes.UnionType
以及使用二进制或运算符|
表示类型联合的能力
- PEP 604
- PEP 612
: Parameter Specification Variables:参数规范变量 Introducing
ParamSpec
andConcatenate
- PEP 612
Type aliases类型别名¶
A type alias is defined by assigning the type to the alias. 通过将类型分配给别名来定义类型别名。In this example, 在本例中,Vector
and list[float]
will be treated as interchangeable synonyms:Vector
和list[floot]
将被视为可互换的同义词:
Vector = list[float]
def scale(scalar: float, vector: Vector) -> Vector:
return [scalar * num for num in vector]
# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
Type aliases are useful for simplifying complex type signatures. For example:类型别名对于简化复杂类型签名非常有用。例如:
from collections.abc import Sequence
ConnectionOptions = dict[str, str]
Address = tuple[str, int]
Server = tuple[Address, ConnectionOptions]
def broadcast_message(message: str, servers: Sequence[Server]) -> None:
...
# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
message: str,
servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
...
Note that 请注意,作为类型提示的None
as a type hint is a special case and is replaced by type(None)
.None
是一种特殊情况,并由type(None)
替换。
NewType¶
Use the 使用NewType
helper class to create distinct types:NewType
帮助器类创建不同的类型:
from typing import NewType
UserId = NewType('UserId', int)
some_id = UserId(524313)
The static type checker will treat the new type as if it were a subclass of the original type. 静态类型检查器会将新类型视为原始类型的子类。This is useful in helping catch logical errors:这有助于捕获逻辑错误:
def get_user_name(user_id: UserId) -> str:
...
# typechecks
user_a = get_user_name(UserId(42351))
# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)
You may still perform all 您仍然可以对int
operations on a variable of type UserId
, but the result will always be of type int
. UserId
类型的变量执行所有int
操作,但结果始终是int
类型。This lets you pass in a 这允许您将UserId
wherever an int
might be expected, but will prevent you from accidentally creating a UserId
in an invalid way:UserId
传递到可能需要int
的任何位置,但将防止您意外地以无效方式创建UserId
:
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
Note that these checks are enforced only by the static type checker. 请注意,这些检查仅由静态类型检查器执行。At runtime, the statement 在运行时,Derived = NewType('Derived', Base)
will make Derived
a class that immediately returns whatever parameter you pass it. Derived = NewType('Derived', Base)
语句将使Derived
成为一个类,该类将立即返回传递给它的任何参数。That means the expression 这意味着表达式Derived(some_value)
does not create a new class or introduce much overhead beyond that of a regular function call.Derived(some_value)
不会创建新类,也不会引入超出常规函数调用的开销。
More precisely, the expression 更准确地说,表达式some_value is Derived(some_value)
is always true at runtime.some_value is Derived(some_value)
在运行时始终为true
。
It is invalid to create a subtype of 创建Derived
:Derived
的子类型无效:
from typing import NewType
UserId = NewType('UserId', int)
# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass
However, it is possible to create a 但是,可以基于“派生”NewType
based on a ‘derived’ NewType
:NewType
创建NewType
:
from typing import NewType
UserId = NewType('UserId', int)
ProUserId = NewType('ProUserId', UserId)
and typechecking for ProUserId
will work as expected.ProUserId
的类型检查将按预期工作。
See PEP 484 for more details.详见PEP 484。
Note
Recall that the use of a type alias declares two types to be equivalent to one another. 回想一下,使用类型别名声明两个类型彼此等效。Doing 执行Alias = Original
will make the static type checker treat Alias
as being exactly equivalent to Original
in all cases. Alias=Original
将使静态类型检查器在所有情况下都将Alias
视为与Original
完全等效。This is useful when you want to simplify complex type signatures.当您想要简化复杂类型签名时,这非常有用。
In contrast, 相反,NewType
declares one type to be a subtype of another. NewType
将一种类型声明为另一种类型的子类型。Doing 执行Derived = NewType('Derived', Original)
will make the static type checker treat Derived
as a subclass of Original
, which means a value of type Original
cannot be used in places where a value of type Derived
is expected. Derived = NewType('Derived', Original)
将使静态类型检查器将Derived
视为Original
的子类型,这意味着Original类型的值不能用于需要Derived类型的值的地方。This is useful when you want to prevent logic errors with minimal runtime cost.当您希望以最小的运行时成本防止逻辑错误时,这非常有用。
New in version 3.5.2.版本3.5.2中新增。
Changed in version 3.10:版本3.10中更改: NewType
is now a class rather than a function. NewType
现在是一个类而不是函数。There is some additional runtime cost when calling 在常规函数上调用NewType
over a regular function. NewType
时会产生一些额外的运行时开销。However, this cost will be reduced in 3.11.0.但是,该成本将在3.11.0中降低。
Callable¶
Frameworks expecting callback functions of specific signatures might be type hinted using 预期特定签名的回调函数的框架可能使用Callable[[Arg1Type, Arg2Type], ReturnType]
.Callable[[Arg1Type, Arg2Type], ReturnType]
进行类型提示。
For example:
from collections.abc import Callable
def feeder(get_next_item: Callable[[], str]) -> None:
# Body
def async_query(on_success: Callable[[int], None],
on_error: Callable[[int, Exception], None]) -> None:
# Body
It is possible to declare the return type of a callable without specifying the call signature by substituting a literal ellipsis for the list of arguments in the type hint: 通过用文本省略号替换类型提示中的参数列表,可以在不指定调用签名的情况下声明可调用的返回类型:Callable[..., ReturnType]
.Callable[..., ReturnType]
。
Callables which take other callables as arguments may indicate that their parameter types are dependent on each other using 将其他可调用项作为参数的可调用项可以使用ParamSpec
. ParamSpec
指示其参数类型彼此依赖。Additionally, if that callable adds or removes arguments from other callables, the 此外,如果该可调用对象添加或删除其他可调用对象的参数,则可以使用Concatenate
operator may be used. Concatenate
运算符。They take the form 它们分别采用Callable[ParamSpecVariable, ReturnType]
and Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], ReturnType]
respectively.Callable[ParamSpecVariable, ReturnType]
和Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], ReturnType]
。
Changed in version 3.10:版本3.10中更改: Callable
now supports ParamSpec
and Concatenate
. Callable
现在支持ParamSpec
和Concatenate
。See PEP 612 for more information.更多信息请参见PEP 612。
See also
The documentation for ParamSpec
and Concatenate
provide examples of usage in Callable
.ParamSpec
和Concatenate
的文档提供了Callable
中的用法示例。
Generics泛型¶
Since type information about objects kept in containers cannot be statically inferred in a generic way, abstract base classes have been extended to support subscription to denote expected types for container elements.由于无法以通用方式静态推断容器中保存的对象的类型信息,抽象基类已被扩展以支持订阅,以表示容器元素的预期类型。
from collections.abc import Mapping, Sequence
def notify_by_email(employees: Sequence[Employee],
overrides: Mapping[str, str]) -> None: ...
Generics can be parameterized by using a factory available in typing called 泛型可以通过使用名为TypeVar
.TypeVar
的类型中可用的工厂来参数化。
from collections.abc import Sequence
from typing import TypeVar
T = TypeVar('T') # Declare type variable
def first(l: Sequence[T]) -> T: # Generic function
return l[0]
User-defined generic types用户定义的泛型类型¶
A user-defined class can be defined as a generic class.用户定义的类可以定义为泛型类。
from typing import TypeVar, Generic
from logging import Logger
T = TypeVar('T')
class LoggedVar(Generic[T]):
def __init__(self, value: T, name: str, logger: Logger) -> None:
self.name = name
self.logger = logger
self.value = value
def set(self, new: T) -> None:
self.log('Set ' + repr(self.value))
self.value = new
def get(self) -> T:
self.log('Get ' + repr(self.value))
return self.value
def log(self, message: str) -> None:
self.logger.info('%s: %s', self.name, message)
Generic[T]
as a base class defines that the class LoggedVar
takes a single type parameter T
. Generic[T]
作为基类定义了类LoggedVar
采用单个类型参数T
。This also makes 这也使得T
valid as a type within the class body.T
作为类主体中的类型有效。
The Generic
base class defines __class_getitem__()
so that LoggedVar[t]
is valid as a type:Generic
基类定义__class_getitem__()
,以便LoggedVar[t]
作为类型有效:
from collections.abc import Iterable
def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:
for var in vars:
var.set(0)
A generic type can have any number of type variables. 泛型类型可以有任意数量的类型变量。All varieties of 允许将所有类型的TypeVar
are permissible as parameters for a generic type:TypeVar
作为泛型类型的参数:
from typing import TypeVar, Generic, Sequence
T = TypeVar('T', contravariant=True)
B = TypeVar('B', bound=Sequence[bytes], covariant=True)
S = TypeVar('S', int, str)
class WeirdTrio(Generic[T, B, S]):
...
Each type variable argument to Generic
must be distinct. Generic
的每个类型变量参数必须不同。This is thus invalid:因此,这是无效的:
from typing import TypeVar, Generic
...
T = TypeVar('T')
class Pair(Generic[T, T]): # INVALID
...
You can use multiple inheritance with 您可以在Generic
:Generic
中使用多重继承:
from collections.abc import Sized
from typing import TypeVar, Generic
T = TypeVar('T')
class LinkedList(Sized, Generic[T]):
...
When inheriting from generic classes, some type variables could be fixed:从泛型类继承时,可以修复某些类型变量:
from collections.abc import Mapping
from typing import TypeVar
T = TypeVar('T')
class MyDict(Mapping[str, T]):
...
In this case 在这种情况下,MyDict
has a single parameter, T
.MyDict
只有一个参数T
。
Using a generic class without specifying type parameters assumes 在不指定类型参数的情况下使用泛型类,每个位置都假定为Any
for each position. Any
。In the following example, 在以下示例中,MyIterable
is not generic but implicitly inherits from Iterable[Any]
:MyIterable
不是泛型的,而是隐式继承自Iterable[Any]
:
from collections.abc import Iterable
class MyIterable(Iterable): # Same as Iterable[Any]
User defined generic type aliases are also supported. 还支持用户定义的泛型类型别名。Examples:示例:
from collections.abc import Iterable
from typing import TypeVar
S = TypeVar('S')
Response = Iterable[S] | int
# Return type here is same as Iterable[str] | int
def response(query: str) -> Response[str]:
...
T = TypeVar('T', int, float, complex)
Vec = Iterable[tuple[T, T]]
def inproduct(v: Vec[T]) -> T: # Same as Iterable[tuple[T, T]]
return sum(x*y for x, y in v)
Changed in version 3.7:版本3.7中更改: Generic
no longer has a custom metaclass.不再有自定义元类。
User-defined generics for parameter expressions are also supported via parameter specification variables in the form 通过Generic[P]
. Generic[P]
形式的参数规范变量,也支持参数表达式的用户定义泛型。The behavior is consistent with type variables’ described above as parameter specification variables are treated by the typing module as a specialized type variable. 该行为与上述类型变量一致,因为类型模块将参数规范变量视为专用类型变量。The one exception to this is that a list of types can be used to substitute a 一个例外是,可以使用类型列表替换ParamSpec
:ParamSpec
:
>>> from typing import Generic, ParamSpec, TypeVar
>>> T = TypeVar('T')
>>> P = ParamSpec('P')
>>> class Z(Generic[T, P]): ...
...
>>> Z[int, [dict, float]]
__main__.Z[int, (<class 'dict'>, <class 'float'>)]
Furthermore, a generic with only one parameter specification variable will accept parameter lists in the forms 此外,仅具有一个参数规范变量的泛型将接受形式为X[[Type1, Type2, ...]]
and also X[Type1, Type2, ...]
for aesthetic reasons. X[[Type1, Type2, ...]]
的参数列表,并且出于美学原因,也接受形式为X[Type1, Type2, ...]
的参数列表。Internally, the latter is converted to the former and are thus equivalent:在内部,后者被转换为前者,因此相当于:
>>> class X(Generic[P]): ...
...
>>> X[int, str]
__main__.X[(<class 'int'>, <class 'str'>)]
>>> X[[int, str]]
__main__.X[(<class 'int'>, <class 'str'>)]
Do note that generics with 请注意,在某些情况下,具有ParamSpec
may not have correct __parameters__
after substitution in some cases because they are intended primarily for static type checking.ParamSpec
的泛型在替换后可能没有正确的__parameters__
,因为它们主要用于静态类型检查。
Changed in version 3.10:版本3.10中更改: Generic
can now be parameterized over parameter expressions. 现在可以在参数表达式上参数化。See 有关详细信息,请参阅ParamSpec
and PEP 612 for more details.ParamSpec
和PEP 612。
A user-defined generic class can have ABCs as base classes without a metaclass conflict. 用户定义的泛型类可以将ABC作为基类,而没有元类冲突。Generic metaclasses are not supported. 不支持泛型元类。The outcome of parameterizing generics is cached, and most types in the typing module are hashable and comparable for equality.参数化泛型的结果是缓存的,类型模块中的大多数类型都是可散列的,并且可以进行相等的比较。
The Any
typeAny
类型¶
Any
typeA special kind of type is 一种特殊类型是Any
. Any
。A static type checker will treat every type as being compatible with 静态类型检查器会将每个类型视为与Any
and Any
as being compatible with every type.Any
和Any
兼容,并将其视为与每个类型兼容。
This means that it is possible to perform any operation or method call on a value of type 这意味着可以对Any
and assign it to any variable:Any
类型的值执行任何操作或方法调用,并将其分配给任何变量:
from typing import Any
a: Any = None
a = [] # OK
a = 2 # OK
s: str = ''
s = a # OK
def foo(item: Any) -> int:
# Typechecks; 'item' could be any type,
# and that type might have a 'bar' method
item.bar()
...
Notice that no typechecking is performed when assigning a value of type 请注意,当将Any
to a more precise type. Any
类型的值分配给更精确的类型时,不会执行类型检查。For example, the static type checker did not report an error when assigning 例如,静态类型检查器在将a
to s
even though s
was declared to be of type str
and receives an int
value at runtime!a
分配给s
时没有报告错误,即使s
被声明为str
类型,并且在运行时收到一个int
值!
Furthermore, all functions without a return type or parameter types will implicitly default to using 此外,所有没有返回类型或参数类型的函数都将默认使用Any
:Any
:
def legacy_parser(text):
...
return data
# A static type checker will treat the above
# as having the same signature as:
def legacy_parser(text: Any) -> Any:
...
return data
This behavior allows 当您需要混合动态和静态类型的代码时,此行为允许Any
to be used as an escape hatch when you need to mix dynamically and statically typed code.Any
用作转义符。
Contrast the behavior of 将Any
with the behavior of object
. Any
的行为与object
的行为进行对比。Similar to 与Any
, every type is a subtype of object
. Any
类似,每个类型都是object
的子类型。However, unlike 然而,与Any
, the reverse is not true: object
is not a subtype of every other type.Any
不同,相反的情况并非如此:object
不是所有其他类型的子类型。
That means when the type of a value is 这意味着,当值的类型是object
, a type checker will reject almost all operations on it, and assigning it to a variable (or using it as a return value) of a more specialized type is a type error. object
时,类型检查器将拒绝对其执行几乎所有的操作,并且将其分配给更特殊类型的变量(或将其用作返回值)是类型错误。For example:例如:
def hash_a(item: object) -> int:
# Fails; an object does not have a 'magic' method.
item.magic()
...
def hash_b(item: Any) -> int:
# Typechecks
item.magic()
...
# Typechecks, since ints and strs are subclasses of object
hash_a(42)
hash_a("foo")
# Typechecks, since Any is compatible with all types
hash_b(42)
hash_b("foo")
Use 使用object
to indicate that a value could be any type in a typesafe manner. object
指示值可以是类型安全方式的任何类型。Use 使用Any
to indicate that a value is dynamically typed.Any
表示值是动态类型的。
Nominal vs structural subtyping标称与结构子类型¶
Initially PEP 484 defined Python static type system as using nominal subtyping. 最初,PEP 484将Python静态类型系统定义为使用名义子类型。This means that a class 这意味着,当且仅当A
is allowed where a class B
is expected if and only if A
is a subclass of B
.A
是B
的子类时,类A
是允许的,其中类B
是期望的。
This requirement previously also applied to abstract base classes, such as 这一要求以前也适用于抽象基类,例如Iterable
. Iterable
。The problem with this approach is that a class had to be explicitly marked to support them, which is unpythonic and unlike what one would normally do in idiomatic dynamically typed Python code. 这种方法的问题是,类必须被显式标记以支持它们,这是不协调的,并且与通常在惯用的动态类型Python代码中所做的不同。For example, this conforms to PEP 484:例如,这符合PEP 484:
from collections.abc import Sized, Iterable, Iterator
class Bucket(Sized, Iterable[int]):
...
def __len__(self) -> int: ...
def __iter__(self) -> Iterator[int]: ...
PEP 544 allows to solve this problem by allowing users to write the above code without explicit base classes in the class definition, allowing 允许通过允许用户在类定义中不显式基类的情况下编写上述代码来解决这个问题,允许静态类型检查器隐式地将Bucket
to be implicitly considered a subtype of both Sized
and Iterable[int]
by static type checkers. Bucket
视为Sized
和Iterable[int]
的子类型。This is known as structural subtyping (or static duck-typing):这被称为结构子类型(或静态鸭子类型):
from collections.abc import Iterator, Iterable
class Bucket: # Note: no base classes
...
def __len__(self) -> int: ...
def __iter__(self) -> Iterator[int]: ...
def collect(items: Iterable[int]) -> int: ...
result = collect(Bucket()) # Passes type check
Moreover, by subclassing a special class 此外,通过子类化一个特殊的类Protocol
, a user can define new custom protocols to fully enjoy structural subtyping (see examples below).Protocol
,用户可以定义新的自定义协议,以充分享受结构子类型化(见下面的示例)。
Module contents模块内容¶
The module defines the following classes, functions and decorators.该模块定义了以下类、函数和修饰符。
Note
This module defines several types that are subclasses of pre-existing standard library classes which also extend 此模块定义了几个类型,这些类型是预先存在的标准库类的子类,这些标准库类还扩展了Generic
to support type variables inside []
. Generic
以支持[]
内的类型变量。These types became redundant in Python 3.9 when the corresponding pre-existing classes were enhanced to support 当相应的预先存在的类被增强以支持[]
.[]
时,这些类型在Python 3.9中变得多余。
The redundant types are deprecated as of Python 3.9 but no deprecation warnings will be issued by the interpreter. 从Python 3.9开始,冗余类型被弃用,但解释器不会发出弃用警告。It is expected that type checkers will flag the deprecated types when the checked program targets Python 3.9 or newer.当被检查的程序以Python 3.9或更高版本为目标时,类型检查器将标记不推荐的类型。
The deprecated types will be removed from the 在Python 3.9.0发布5年后发布的第一个Python版本中,弃用的类型将从typing
module in the first Python version released 5 years after the release of Python 3.9.0. typing
模块中删除。See details in PEP 585—Type Hinting Generics In Standard Collections.详见PEP 585《标准集合中的提示泛型类型》。
Special typing primitives特殊类型原语¶
Special types特殊类型¶
These can be used as types in annotations and do not support 这些可以用作注释中的类型,不支持[]
.[]
。
-
typing.
Any
¶ Special type indicating an unconstrained type.表示无约束类型的特殊类型。
-
typing.
NoReturn
¶ Special type indicating that a function never returns.指示函数永不返回的特殊类型。For example:例如:from typing import NoReturn
def stop() -> NoReturn:
raise RuntimeError('no way')New in version 3.5.4.版本3.5.4中新增。New in version 3.6.2.版本3.6.2中新增。
-
typing.
TypeAlias
¶ Special annotation for explicitly declaring a type alias.用于显式声明类型别名的特殊注释。For example:例如:from typing import TypeAlias
Factors: TypeAlias = list[int]See PEP 613 for more details about explicit type aliases.有关显式类型别名的详细信息,请参阅PEP 613。New in version 3.10.版本3.10中新增。
Special forms特殊形式¶
These can be used as types in annotations using 这些类型可以用作使用[]
, each having a unique syntax.[]
的注释中的类型,每个类型都具有唯一的语法。
-
typing.
Tuple
¶ Tuple type;褶皱型;Tuple[X, Y]
is the type of a tuple of two items with the first item of type X and the second of type Y.Tuple[X, Y]
是由两个项目组成的元组的类型,第一个项目为X类型,第二个项目为Y类型。The type of the empty tuple can be written as空元组的类型可以写成Tuple[()]
.Tuple[()]
。Example:示例:Tuple[T1, T2]
is a tuple of two elements corresponding to type variables T1 and T2.Tuple[T1, T2]
是对应于类型变量T1和T2的两个元素的元组。Tuple[int, float, str]
is a tuple of an int, a float and a string.是一个由int、float和字符串组成的元组。To specify a variable-length tuple of homogeneous type, use literal ellipsis, e.g.要指定同质类型的可变长度元组,请使用文本省略号,例如Tuple[int, ...]
.Tuple[int, ...]
。A plain一个简单的Tuple
is equivalent toTuple[Any, ...]
, and in turn totuple
.Tuple
等价于Tuple[Any, ...]
,反过来Tuple[Any, ...]
又等价于tuple
。Deprecated since version 3.9:自版本3.9起已弃用:builtins.tuple
now supports现在支持[]
.[]
。See PEP 585 and Generic Alias Type.请参见PEP 585和通用别名类型。
-
typing.
Union
¶ Union type;活接头类型;Union[X, Y]
is equivalent toX | Y
and means either X or Y.Union[X, Y]
等价于X|Y
,表示X
或Y
。To define a union, use e.g.要定义联合,请使用例如Union[int, str]
or the shorthandint | str
.Union[int, str]
或缩写int|str
。Using that shorthand is recommended.建议使用这种速记法。Details:细节:The arguments must be types and there must be at least one.参数必须是类型,并且必须至少有一个。Unions of unions are flattened, e.g.:工会被扁平化,例如:Union[Union[int, str], float] == Union[int, str, float]
Unions of a single argument vanish, e.g.:单一论点的联合消失,例如:Union[int] == int # The constructor actually returns int
Redundant arguments are skipped, e.g.:跳过冗余参数,例如:Union[int, str, int] == Union[int, str] == int | str
When comparing unions, the argument order is ignored, e.g.:比较联合时,参数顺序被忽略,例如:Union[int, str] == Union[str, int]
You cannot subclass or instantiate a不能子类化或实例化Union
.Union
。You cannot write不能写入Union[X][Y]
.Union[X][Y]
。
Changed in version 3.7:版本3.7中更改:Don’t remove explicit subclasses from unions at runtime.不要在运行时从联合中删除显式子类。Changed in version 3.10:版本3.10中更改:Unions can now be written as联合现在可以写成X | Y
.X|Y
。See union type expressions.请参见联合类型表达式。
-
typing.
Optional
¶ Optional type.可选类型。Optional[X]
is equivalent toX | None
(orUnion[X, None]
).Note that this is not the same concept as an optional argument, which is one that has a default.请注意,这与可选参数不是同一个概念,可选参数具有默认值。An optional argument with a default does not require the具有默认值的可选参数不需要在其类型注释上使用Optional
qualifier on its type annotation just because it is optional.Optional
限定符,因为它是可选的。For example:例如:def foo(arg: int = 0) -> None:
...On the other hand, if an explicit value of另一方面,如果允许显式值None
is allowed, the use ofOptional
is appropriate, whether the argument is optional or not.None
,则无论参数是否可选,都可以使用Optional
。For example:例如:def foo(arg: Optional[int] = None) -> None:
...Changed in version 3.10:版本3.10中更改:Optional can now be written as可选现在可以写成X | None
.X|None
。See union type expressions.请参见联合类型表达式。
-
typing.
Callable
¶ Callable type;可调用类型;Callable[[int], str]
is a function of (int) -> str.Callable[[int], str]
是(int) -> str.的函数。The subscription syntax must always be used with exactly two values: the argument list and the return type.订阅语法必须始终与两个值一起使用:参数列表和返回类型。The argument list must be a list of types or an ellipsis; the return type must be a single type.参数列表必须是类型列表或省略号;返回类型必须是单一类型。There is no syntax to indicate optional or keyword arguments; such function types are rarely used as callback types.没有语法指示可选参数或关键字参数;这种函数类型很少用作回调类型。Callable[..., ReturnType]
(literal ellipsis) can be used to type hint a callable taking any number of arguments and returningReturnType
.Callable[..., ReturnType]
(文本省略号)可用于类型提示接受任意数量参数并返回ReturnType
的可调用对象。A plain普通Callable
is equivalent toCallable[..., Any]
, and in turn tocollections.abc.Callable
.Callable
相当于Callable[..., Any]
,反过来又相当于collections.abc.Callable
。Callables which take other callables as arguments may indicate that their parameter types are dependent on each other using将其他可调用项作为参数的可调用项可以使用ParamSpec
.ParamSpec
指示其参数类型彼此依赖。Additionally, if that callable adds or removes arguments from other callables, the此外,如果该可调用对象添加或删除其他可调用对象的参数,则可以使用Concatenate
operator may be used.Concatenate
运算符。They take the form它们分别采用Callable[ParamSpecVariable, ReturnType]
andCallable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], ReturnType]
respectively.Callable[ParamSpecVariable, ReturnType]
和Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], ReturnType]
。Deprecated since version 3.9:自版本3.9起已弃用:collections.abc.Callable
now supports现在支持[]
.[]
。See PEP 585 and Generic Alias Type.请参见PEP 585和通用别名类型。Changed in version 3.10:版本3.10中更改:Callable
now supportsParamSpec
andConcatenate
. See PEP 612 for more information.See also
The documentation forParamSpec
andConcatenate
provide examples of usage withCallable
.ParamSpec
和Concatenate
的文档提供了Callable
的用法示例。
-
typing.
Concatenate
¶ Used with与Callable
andParamSpec
to type annotate a higher order callable which adds, removes, or transforms parameters of another callable.Callable
和ParamSpec
一起使用,可以对更高阶的可调用进行类型注释,以添加、删除或转换另一个可调用的参数。Usage is in the form用法的形式为Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable]
.Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable]
。Concatenate
is currently only valid when used as the first argument to aCallable
.Concatenate
当前仅在用作Callable
的第一个参数时有效。The last parameter to要Concatenate
must be aParamSpec
.Concatenate
的最后一个参数必须是ParamSpec
。For example, to annotate a decorator例如,若要注释为修饰函数提供with_lock
which provides athreading.Lock
to the decorated function,Concatenate
can be used to indicate thatwith_lock
expects a callable which takes in aLock
as the first argument, and returns a callable with a different type signature.threading.Lock
的装饰器with_lock
,可以使用Concatenate
来指示with_lock
需要一个以lock
作为第一个参数的可调用函数,并返回一个具有不同类型签名的可调用对象。In this case, the在这种情况下,ParamSpec
indicates that the returned callable’s parameter types are dependent on the parameter types of the callable being passed in:ParamSpec
表示返回的可调用参数类型取决于传入的可调用的参数类型:from collections.abc import Callable
from threading import Lock
from typing import Concatenate, ParamSpec, TypeVar
P = ParamSpec('P')
R = TypeVar('R')
# Use this lock to ensure that only one thread is executing a function
# at any time.
my_lock = Lock()
def with_lock(f: Callable[Concatenate[Lock, P], R]) -> Callable[P, R]:
'''A type-safe decorator which provides a lock.'''
global my_lock
def inner(*args: P.args, **kwargs: P.kwargs) -> R:
# Provide the lock as the first argument.
return f(my_lock, *args, **kwargs)
return inner
@with_lock
def sum_threadsafe(lock: Lock, numbers: list[float]) -> float:
'''Add a list of numbers together in a thread-safe manner.'''
with lock:
return sum(numbers)
# We don't need to pass in the lock ourselves thanks to the decorator.
sum_threadsafe([1.1, 2.2, 3.3])
New in version 3.10.版本3.10中新增。
See also
-
class
typing.
Type
(Generic[CT_co])¶ A variable annotated with
C
may accept a value of typeC
. In contrast, a variable annotated withType[C]
may accept values that are classes themselves – specifically, it will accept the class object ofC
. For example:a = 3 # Has type 'int'
b = int # Has type 'Type[int]'
c = type(a) # Also has type 'Type[int]'Note that注意Type[C]
is covariant:Type[C]
是协变的:class User: ...
class BasicUser(User): ...
class ProUser(User): ...
class TeamUser(User): ...
# Accepts User, BasicUser, ProUser, TeamUser, ...
def make_new_user(user_class: Type[User]) -> User:
# ...
return user_class()The fact that
Type[C]
is covariant implies that all subclasses ofC
should implement the same constructor signature and class method signatures asC
. The type checker should flag violations of this, but should also allow constructor calls in subclasses that match the constructor calls in the indicated base class. How the type checker is required to handle this particular case may change in future revisions of PEP 484.The only legal parameters forType
are classes,Any
, type variables, and unions of any of these types.Type
的唯一合法参数是类、Any
、类型变量和任何这些类型的联合。For example:例如:def new_non_team_user(user_class: Type[BasicUser | ProUser]): ...
Type[Any]
is equivalent toType
which in turn is equivalent totype
, which is the root of Python’s metaclass hierarchy.Type[Any]
相当于type
,而type
又相当于Python元类层次结构的根。New in version 3.5.2.版本3.5.2中新增。Deprecated since version 3.9:自版本3.9起已弃用:builtins.type
now supports[]
. See PEP 585 and Generic Alias Type.
-
typing.
Literal
¶ A type that can be used to indicate to type checkers that the corresponding variable or function parameter has a value equivalent to the provided literal (or one of several literals).一种类型,可用于向类型检查器指示对应的变量或函数参数具有与提供的文本(或多个文本之一)等效的值。For example:例如:def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checkerLiteral[...]
cannot be subclassed. At runtime, an arbitrary value is allowed as type argument toLiteral[...]
, but type checkers may impose restrictions. See PEP 586 for more details about literal types.New in version 3.8.版本3.8中新增。
-
typing.
ClassVar
¶ Special type construct to mark class variables.标记类变量的特殊类型构造。As introduced in PEP 526, a variable annotation wrapped in ClassVar indicates that a given attribute is intended to be used as a class variable and should not be set on instances of that class. Usage:
class Starship:
stats: ClassVar[dict[str, int]] = {} # class variable
damage: int = 10 # instance variableClassVar
accepts only types and cannot be further subscribed.只接受类型,不能进一步订阅。ClassVar
is not a class itself, and should not be used withisinstance()
orissubclass()
.ClassVar
does not change Python runtime behavior, but it can be used by third-party type checkers.For example, a type checker might flag the following code as an error:例如,类型检查器可能会将以下代码标记为错误:enterprise_d = Starship(3000)
enterprise_d.stats = {} # Error, setting class variable on instance
Starship.stats = {} # This is OKNew in version 3.5.3.版本3.5.3中新增。
-
typing.
Final
¶ A special typing construct to indicate to type checkers that a name cannot be re-assigned or overridden in a subclass.一种特殊的类型构造,用于向类型检查器指示不能在子类中重新分配或重写名称。For example:例如:MAX_SIZE: Final = 9000
MAX_SIZE += 1 # Error reported by type checker
class Connection:
TIMEOUT: Final[int] = 10
class FastConnector(Connection):
TIMEOUT = 1 # Error reported by type checkerThere is no runtime checking of these properties. See PEP 591 for more details.
New in version 3.8.版本3.8中新增。
-
typing.
Annotated
¶ A type, introduced in PEP 593 (
Flexible function and variable annotations
), to decorate existing types with context-specific metadata (possibly multiple pieces of it, asAnnotated
is variadic). Specifically, a typeT
can be annotated with metadatax
via the typehintAnnotated[T, x]
. This metadata can be used for either static analysis or at runtime. If a library (or tool) encounters a typehintAnnotated[T, x]
and has no special logic for metadatax
, it should ignore it and simply treat the type asT
. Unlike theno_type_check
functionality that currently exists in thetyping
module which completely disables typechecking annotations on a function or a class, theAnnotated
type allows for both static typechecking ofT
(e.g., via mypy or Pyre, which can safely ignorex
) together with runtime access tox
within a specific application.Ultimately, the responsibility of how to interpret the annotations (if at all) is the responsibility of the tool or library encountering the最终,如何解释注释(如果有的话)的责任是遇到Annotated
type.Annotated
类型的工具或库的责任。A tool or library encountering an遇到Annotated
type can scan through the annotations to determine if they are of interest (e.g., usingisinstance()
).Annotated
类型的工具或库可以扫描注释以确定它们是否感兴趣(例如,使用isinstance()
)。When a tool or a library does not support annotations or encounters an unknown annotation it should just ignore it and treat annotated type as the underlying type.当工具或库不支持注释或遇到未知注释时,应忽略它,并将注释类型视为基础类型。It’s up to the tool consuming the annotations to decide whether the client is allowed to have several annotations on one type and how to merge those annotations.这取决于使用注释的工具来决定是否允许客户端在一种类型上具有多个注释,以及如何合并这些注释。Since the由于Annotated
type allows you to put several annotations of the same (or different) type(s) on any node, the tools or libraries consuming those annotations are in charge of dealing with potential duplicates.Annotated
类型允许您在任何节点上放置多个相同(或不同)类型的注释,因此使用这些注释的工具或库负责处理潜在的重复项。For example, if you are doing value range analysis you might allow this:例如,如果您正在进行价值范围分析,您可能会允许:T1 = Annotated[int, ValueRange(-10, 5)]
T2 = Annotated[T1, ValueRange(-20, 3)]Passing将include_extras=True
toget_type_hints()
lets one access the extra annotations at runtime.include_extras=True
传递给get_type_hints()
,可以在运行时访问额外的注释。The details of the syntax:语法的详细信息:The first argument toAnnotated
must be a valid typeAnnotated
的第一个参数必须是有效类型Multiple type annotations are supported (支持多个类型注释(Annotated
supports variadic arguments):Annotated
支持可变参数):Annotated[int, ValueRange(3, 10), ctype("char")]
必须使用至少两个参数调用Annotated
must be called with at least two arguments (Annotated[int]
is not valid)Annotated
(Annotated[int]
无效)The order of the annotations is preserved and matters for equality checks:注释的顺序保持不变,等式检查的事项如下:Annotated[int, ValueRange(3, 10), ctype("char")] != Annotated[
int, ctype("char"), ValueRange(3, 10)
]Nested嵌套的Annotated
types are flattened, with metadata ordered starting with the innermost annotation:Annotated
类型被展平,元数据以最内部的注释开始排序:Annotated[Annotated[int, ValueRange(3, 10)], ctype("char")] == Annotated[
int, ValueRange(3, 10), ctype("char")
]Duplicated annotations are not removed:不会删除重复的注释:Annotated[int, ValueRange(3, 10)] != Annotated[
int, ValueRange(3, 10), ValueRange(3, 10)
]Annotated
can be used with nested and generic aliases:Annotated
可以与嵌套别名和泛型别名一起使用:T = TypeVar('T')
Vec = Annotated[list[tuple[T, T]], MaxLen(10)]
V = Vec[int]
V == Annotated[list[tuple[int, int]], MaxLen(10)]
New in version 3.9.版本3.9中新增。
-
typing.
TypeGuard
¶ Special typing form used to annotate the return type of a user-defined type guard function.用于注释用户定义的类型保护函数的返回类型的特殊类型表单。TypeGuard
only accepts a single type argument. At runtime, functions marked this way should return a boolean.TypeGuard
aims to benefit type narrowing – a technique used by static type checkers to determine a more precise type of an expression within a program’s code flow.Usually type narrowing is done by analyzing conditional code flow and applying the narrowing to a block of code.通常,类型缩小是通过分析条件代码流并将缩小应用于代码块来完成的。The conditional expression here is sometimes referred to as a “type guard”:这里的条件表达式有时被称为“类型保护”:def is_str(val: str | float):
# "isinstance" type guard
if isinstance(val, str):
# Type of ``val`` is narrowed to ``str``
...
else:
# Else, type of ``val`` is narrowed to ``float``.
...Sometimes it would be convenient to use a user-defined boolean function as a type guard. Such a function should use
TypeGuard[...]
as its return type to alert static type checkers to this intention.Using
-> TypeGuard
tells the static type checker that for a given function:The return value is a boolean.返回值是布尔值。If the return value is如果返回值为True
, the type of its argument is the type insideTypeGuard
.True
,则其参数的类型为TypeGuard
中的类型。For example:
def is_str_list(val: List[object]) -> TypeGuard[List[str]]:
'''Determines whether all objects in the list are strings'''
return all(isinstance(x, str) for x in val)
def func1(val: List[object]):
if is_str_list(val):
# Type of ``val`` is narrowed to ``List[str]``.
print(" ".join(val))
else:
# Type of ``val`` remains as ``List[object]``.
print("Not a list of strings!")
If如果is_str_list
is a class or instance method, then the type inTypeGuard
maps to the type of the second parameter aftercls
orself
.is_str_list
是类或实例方法,则TypeGuard
中的类型映射到cls
或self
之后的第二个参数的类型。In short, the form简而言之,表单def foo(arg: TypeA) -> TypeGuard[TypeB]: ...
, means that iffoo(arg)
returnsTrue
, thenarg
narrows fromTypeA
toTypeB
.def foo(arg: TypeA) -> TypeGuard[TypeB]: ...
表示如果foo(arg)
返回True
,则arg
从TypeA
缩小到TypeB
。Note
TypeB
need not be a narrower form of不必是TypeA
– it can even be a wider form.TypeA
的较窄形式,它甚至可以是更宽的形式。The main reason is to allow for things like narrowing主要原因是允许将List[object]
toList[str]
even though the latter is not a subtype of the former, sinceList
is invariant.List[object]
缩小为List[str]
,即使后者不是前者的子类型,因为List
是不变的。The responsibility of writing type-safe type guards is left to the user.编写类型安全型防护装置的责任留给用户。TypeGuard
also works with type variables. For more information, see PEP 647 (User-Defined Type Guards).New in version 3.10.版本3.10中新增。
Building generic types生成泛型类型¶
These are not used in annotations. 这些不会在注释中使用。They are building blocks for creating generic types.它们是创建泛型类型的构建块。
-
class
typing.
Generic
¶ Abstract base class for generic types.泛型类型的抽象基类。A generic type is typically declared by inheriting from an instantiation of this class with one or more type variables.泛型类型通常是通过从具有一个或多个类型变量的类的实例化继承来声明的。For example, a generic mapping type might be defined as:例如,通用映射类型可以定义为:class Mapping(Generic[KT, VT]):
def __getitem__(self, key: KT) -> VT:
...
# Etc.This class can then be used as follows:该类可按如下方式使用:X = TypeVar('X')
Y = TypeVar('Y')
def lookup_name(mapping: Mapping[X, Y], key: X, default: Y) -> Y:
try:
return mapping[key]
except KeyError:
return default
-
class
typing.
TypeVar
¶ Type variable.类型变量。Usage:用法:T = TypeVar('T') # Can be anything
S = TypeVar('S', bound=str) # Can be any subtype of str
A = TypeVar('A', str, bytes) # Must be exactly str or bytesType variables exist primarily for the benefit of static type checkers.类型变量主要用于静态类型检查器。They serve as the parameters for generic types as well as for generic function definitions.它们用作泛型类型和泛型函数定义的参数。See有关泛型类型的详细信息,请参阅Generic
for more information on generic types.Generic
。Generic functions work as follows:通用函数的工作方式如下:def repeat(x: T, n: int) -> Sequence[T]:
"""Return a list containing n references to x."""
return [x]*n
def print_capitalized(x: S) -> S:
"""Print x capitalized, and return x."""
print(x.capitalize())
return x
def concatenate(x: A, y: A) -> A:
"""Add two strings or bytes objects together."""
return x + yNote that type variables can be bound, constrained, or neither, but cannot be both bound and constrained.请注意,类型变量可以是绑定的,也可以是受约束的,或者两者都不能,但不能同时是绑定的和受约束的。Constrained type variables and bound type variables have different semantics in several important ways.约束类型变量和绑定类型变量在几个重要方面具有不同的语义。Using a constrained type variable means that the使用受约束的类型变量意味着TypeVar只能作为给定的约束之一进行求解:TypeVar
can only ever be solved as being exactly one of the constraints given:a = concatenate('one', 'two') # Ok, variable 'a' has type 'str'
b = concatenate(StringSubclass('one'), StringSubclass('two')) # Inferred type of variable 'b' is 'str',
# despite 'StringSubclass' being passed in
c = concatenate('one', b'two') # error: type variable 'A' can be either 'str' or 'bytes' in a function call, but not bothUsing a bound type variable, however, means that the然而,使用绑定类型变量意味着TypeVar
will be solved using the most specific type possible:TypeVar
将使用最具体的类型来解决:print_capitalized('a string') # Ok, output has type 'str'
class StringSubclass(str):
pass
print_capitalized(StringSubclass('another string')) # Ok, output has type 'StringSubclass'
print_capitalized(45) # error: int is not a subtype of strType variables can be bound to concrete types, abstract types (ABCs or protocols), and even unions of types:类型变量可以绑定到具体类型、抽象类型(ABC或协议),甚至类型的联合:U = TypeVar('U', bound=str|bytes) # Can be any subtype of the union str|bytes
V = TypeVar('V', bound=SupportsAbs) # Can be anything with an __abs__ methodBound type variables are particularly useful for annotating
classmethods
that serve as alternative constructors. In the following example (© Raymond Hettinger), the type variableC
is bound to theCircle
class through the use of a forward reference. Using this type variable to annotate thewith_circumference
classmethod, rather than hardcoding the return type asCircle
, means that a type checker can correctly infer the return type even if the method is called on a subclass:import math
C = TypeVar('C', bound='Circle')
class Circle:
"""An abstract circle"""
def __init__(self, radius: float) -> None:
self.radius = radius
# Use a type variable to show that the return type
# will always be an instance of whatever ``cls`` is
@classmethod
def with_circumference(cls: type[C], circumference: float) -> C:
"""Create a circle with the specified circumference"""
radius = circumference / (math.pi * 2)
return cls(radius)
class Tire(Circle):
"""A specialised circle (made out of rubber)"""
MATERIAL = 'rubber'
c = Circle.with_circumference(3) # Ok, variable 'c' has type 'Circle'
t = Tire.with_circumference(4) # Ok, variable 't' has type 'Tire' (not 'Circle')At runtime,
isinstance(x, T)
will raiseTypeError
. In general,isinstance()
andissubclass()
should not be used with types.Type variables may be marked covariant or contravariant by passing
covariant=True
orcontravariant=True
. See PEP 484 for more details.By default, type variables are invariant.默认情况下,类型变量是不变的。
-
class
typing.
ParamSpec
(name, *, bound=None, covariant=False, contravariant=False)¶ Parameter specification variable. A specialized version of
type variables
.Usage:用法:P = ParamSpec('P')
Parameter specification variables exist primarily for the benefit of static type checkers.参数规范变量主要用于静态类型检查器。They are used to forward the parameter types of one callable to another callable – a pattern commonly found in higher order functions and decorators.它们用于将一个可调用对象的参数类型转发给另一个可调对象,这是一种常见于高阶函数和修饰符的模式。They are only valid when used in它们仅在Concatenate
, or as the first argument toCallable
, or as parameters for user-defined Generics.Concatenate
中使用、用作Callable
的第一个参数或用作用户定义泛型的参数时有效。See有关泛型类型的详细信息,请参阅Generic
for more information on generic types.Generic
。For example, to add basic logging to a function, one can create a decorator例如,要向函数添加基本日志记录,可以创建一个装饰器add_logging
to log function calls.add_logging
来记录函数调用。The parameter specification variable tells the type checker that the callable passed into the decorator and the new callable returned by it have inter-dependent type parameters:参数规范变量告诉类型检查器,传递到装饰器的可调用函数和它返回的新可调用函数具有相互依赖的类型参数:from collections.abc import Callable
from typing import TypeVar, ParamSpec
import logging
T = TypeVar('T')
P = ParamSpec('P')
def add_logging(f: Callable[P, T]) -> Callable[P, T]:
'''A type-safe decorator to add logging to a function.'''
def inner(*args: P.args, **kwargs: P.kwargs) -> T:
logging.info(f'{f.__name__} was called')
return f(*args, **kwargs)
return inner
@add_logging
def add_two(x: float, y: float) -> float:
'''Add two numbers together.'''
return x + yWithout
ParamSpec
, the simplest way to annotate this previously was to use aTypeVar
with boundCallable[..., Any]
. However this causes two problems:-
args
¶
-
kwargs
¶ Since
ParamSpec
captures both positional and keyword parameters,P.args
andP.kwargs
can be used to split aParamSpec
into its components.P.args
represents the tuple of positional parameters in a given call and should only be used to annotate*args
.P.kwargs
represents the mapping of keyword parameters to their values in a given call, and should be only be used to annotate**kwargs
. Both attributes require the annotated parameter to be in scope. At runtime,P.args
andP.kwargs
are instances respectively ofParamSpecArgs
andParamSpecKwargs
.
Parameter specification variables created with
covariant=True
orcontravariant=True
can be used to declare covariant or contravariant generic types. Thebound
argument is also accepted, similar toTypeVar
. However the actual semantics of these keywords are yet to be decided.New in version 3.10.版本3.10中新增。Note
Only parameter specification variables defined in global scope can be pickled.只能对全局范围中定义的参数规范变量进行酸洗。See also
PEP 612 – Parameter Specification Variables (the PEP which introduced
ParamSpec
andConcatenate
).Callable
andConcatenate
.
-
-
typing.
ParamSpecArgs
¶
-
typing.
ParamSpecKwargs
¶ Arguments and keyword arguments attributes of a
ParamSpec
. TheP.args
attribute of aParamSpec
is an instance ofParamSpecArgs
, andP.kwargs
is an instance ofParamSpecKwargs
. They are intended for runtime introspection and have no special meaning to static type checkers.Calling
get_origin()
on either of these objects will return the originalParamSpec
:P = ParamSpec("P")
get_origin(P.args) # returns P
get_origin(P.kwargs) # returns PNew in version 3.10.版本3.10中新增。
-
typing.
AnyStr
¶ AnyStr
is aconstrained type variable
defined asAnyStr = TypeVar('AnyStr', str, bytes)
.It is meant to be used for functions that may accept any kind of string without allowing different kinds of strings to mix. For example:它用于可以接受任何类型的字符串而不允许混合不同类型的字符串的函数。例如:def concat(a: AnyStr, b: AnyStr) -> AnyStr:
return a + b
concat(u"foo", u"bar") # Ok, output has type 'unicode'
concat(b"foo", b"bar") # Ok, output has type 'bytes'
concat(u"foo", b"bar") # Error, cannot mix unicode and bytes
-
class
typing.
Protocol
(Generic)¶ Base class for protocol classes. Protocol classes are defined like this:协议类的基类。协议类的定义如下:class Proto(Protocol):
def meth(self) -> int:
...Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing), for example:此类类主要用于识别结构子类型(静态鸭子类型)的静态类型检查器,例如:class C:
def meth(self) -> int:
return 0
def func(x: Proto) -> int:
return x.meth()
func(C()) # Passes static type checkSee PEP 544 for details.详见PEP 544。Protocol classes decorated with用runtime_checkable()
(described later) act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures.runtime_checkable()
修饰的协议类(稍后描述)充当简单的运行时协议,只检查给定属性的存在,而忽略它们的类型签名。Protocol classes can be generic, for example:协议类可以是通用的,例如:class GenProto(Protocol[T]):
def meth(self) -> T:
...New in version 3.8.版本3.8中新增。
-
@
typing.
runtime_checkable
¶ Mark a protocol class as a runtime protocol.将协议类标记为运行时协议。Such a protocol can be used with
isinstance()
andissubclass()
. This raisesTypeError
when applied to a non-protocol class. This allows a simple-minded structural check, very similar to “one trick ponies” incollections.abc
such asIterable
. For example:@runtime_checkable
class Closable(Protocol):
def close(self): ...
assert isinstance(open('/some/file'), Closable)Note
runtime_checkable()
will check only the presence of the required methods, not their type signatures.将只检查所需方法的存在,而不检查其类型签名。For example,ssl.SSLObject
is a class, therefore it passes anissubclass()
check againstCallable
. However, thessl.SSLObject.__init__()
method exists only to raise aTypeError
with a more informative message, therefore making it impossible to call (instantiate)ssl.SSLObject
.New in version 3.8.版本3.8中新增。
Other special directives其他特殊指令¶
These are not used in annotations. 这些不会在注释中使用。They are building blocks for declaring types.它们是声明类型的构建块。
-
class
typing.
NamedTuple
¶ Typed version ofcollections.namedtuple()
.collections.namedtuple()
的类型版本。Usage:用法:class Employee(NamedTuple):
name: str
id: intThis is equivalent to:这相当于:Employee = collections.namedtuple('Employee', ['name', 'id'])
To give a field a default value, you can assign to it in the class body:要为字段指定默认值,可以在类主体中为其赋值:class Employee(NamedTuple):
name: str
id: int = 3
employee = Employee('Guido')
assert employee.id == 3Fields with a default value must come after any fields without a default.具有默认值的字段必须在没有默认值的任何字段之后。The resulting class has an extra attribute生成的类有一个额外的属性__annotations__
giving a dict that maps the field names to the field types.__annotations__
,它提供了一个将字段名称映射到字段类型的dict。(The field names are in the(字段名在_fields
attribute and the default values are in the_field_defaults
attribute both of which are part of the namedtuple API.)_fields
属性中,默认值在_field_faults
属性中,这两个属性都是namedtuple API的一部分。)NamedTuple
subclasses can also have docstrings and methods:子类也可以有docstring和方法:class Employee(NamedTuple):
"""Represents an employee."""
name: str
id: int = 3
def __repr__(self) -> str:
return f'<Employee {self.name}, id={self.id}>'Backward-compatible usage:向后兼容用法:Employee = NamedTuple('Employee', [('name', str), ('id', int)])
Changed in version 3.6:版本3.6中更改: Added support for PEP 526 variable annotation syntax.Changed in version 3.6.1:版本3.6.1中更改:Added support for default values, methods, and docstrings.添加了对默认值、方法和文档字符串的支持。Changed in version 3.8:版本3.8中更改: The_field_types
and__annotations__
attributes are now regular dictionaries instead of instances ofOrderedDict
.Changed in version 3.9:版本3.9中更改: Removed the_field_types
attribute in favor of the more standard__annotations__
attribute which has the same information.
-
class
typing.
NewType
(name, tp)¶ A helper class to indicate a distinct type to a typechecker, see NewType.用于向类型检查器指示不同类型的帮助器类,请参阅NewType。At runtime it returns an object that returns its argument when called.在运行时,它返回一个在调用时返回其参数的对象。Usage:用法:UserId = NewType('UserId', int)
first_user = UserId(1)New in version 3.5.2.版本3.5.2中新增。Changed in version 3.10:版本3.10中更改:NewType
is now a class rather than a function.现在是类而不是函数。
-
class
typing.
TypedDict
(dict)¶ Special construct to add type hints to a dictionary.向字典中添加类型提示的特殊构造。At runtime it is a plain在运行时,这是一个简单的dict
.dict
。TypedDict
declares a dictionary type that expects all of its instances to have a certain set of keys, where each key is associated with a value of a consistent type.声明一个字典类型,该类型期望其所有实例都具有特定的键集,其中每个键都与一致类型的值相关联。This expectation is not checked at runtime but is only enforced by type checkers. Usage:这种期望不会在运行时进行检查,而是仅由类型检查器强制执行。用法:class Point2D(TypedDict):
x: int
y: int
label: str
a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')To allow using this feature with older versions of Python that do not support PEP 526,
TypedDict
supports two additional equivalent syntactic forms:Point2D = TypedDict('Point2D', x=int, y=int, label=str)
Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})The functional syntax should also be used when any of the keys are not valid Identifiers and keywords, for example because they are keywords or contain hyphens.当任何键不是有效的标识符和关键字时,也应使用函数语法,例如,因为它们是关键字或包含连字符。Example:例子:# raises SyntaxError
class Point2D(TypedDict):
in: int # 'in' is a keyword
x-y: int # name with hyphens
# OK, functional syntax
Point2D = TypedDict('Point2D', {'in': int, 'x-y': int})By default, all keys must be present in a默认情况下,TypedDict
.TypedDict
中必须存在所有键。It is possible to override this by specifying totality. Usage:可以通过指定总体来覆盖这一点。用法:class Point2D(TypedDict, total=False):
x: int
y: intThis means that a
Point2D
TypedDict
can have any of the keys omitted. A type checker is only expected to support a literalFalse
orTrue
as the value of thetotal
argument.True
is the default, and makes all items defined in the class body required.It is possible for aTypedDict
type to inherit from one or more otherTypedDict
types using the class-based syntax. Usage:TypedDict
类型可以使用基于类的语法从一个或多个其他TypedDict
类型继承。用法:class Point3D(Point2D):
z: intPoint3D
has three items:有三个项目:x
,y
andz
.x
、y
和z
。It is equivalent to this definition:它相当于这个定义:class Point3D(TypedDict):
x: int
y: int
z: intA
TypedDict
cannot inherit from a non-TypedDict class, notably includingGeneric
. For example:class X(TypedDict):
x: int
class Y(TypedDict):
y: int
class Z(object): pass # A non-TypedDict class
class XY(X, Y): pass # OK
class XZ(X, Z): pass # raises TypeError
T = TypeVar('T')
class XT(X, Generic[T]): pass # raises TypeErrorA
TypedDict
can be introspected via annotations dicts (see Annotations Best Practices for more information on annotations best practices),__total__
,__required_keys__
, and__optional_keys__
.-
__total__
¶ Point2D.__total__
gives the value of the给出total
argument.total
参数的值。Example:例如:>>> from typing import TypedDict
>>> class Point2D(TypedDict): pass
>>> Point2D.__total__
True
>>> class Point2D(TypedDict, total=False): pass
>>> Point2D.__total__
False
>>> class Point3D(Point2D): pass
>>> Point3D.__total__
True
-
__required_keys__
¶
-
__optional_keys__
¶ Point2D.__required_keys__
andPoint2D.__optional_keys__
returnfrozenset
objects containing required and non-required keys, respectively. Currently the only way to declare both required and non-required keys in the sameTypedDict
is mixed inheritance, declaring aTypedDict
with one value for thetotal
argument and then inheriting it from anotherTypedDict
with a different value fortotal
. Usage:>>> class Point2D(TypedDict, total=False):
... x: int
... y: int
...
>>> class Point3D(Point2D):
... z: int
...
>>> Point3D.__required_keys__ == frozenset({'z'})
True
>>> Point3D.__optional_keys__ == frozenset({'x', 'y'})
True
See PEP 589 for more examples and detailed rules of using
TypedDict
.New in version 3.8.版本3.8中新增。-
Generic concrete collections通用混凝土集合¶
Corresponding to built-in types对应内置类型¶
-
class
typing.
Dict
(dict, MutableMapping[KT, VT])¶ A generic version ofdict
.dict
的泛型版本。Useful for annotating return types.用于注释返回类型。To annotate arguments it is preferred to use an abstract collection type such as要注释参数,最好使用抽象集合类型,如Mapping
.Mapping
。This type can be used as follows:该类型可按如下方式使用:def count_words(text: str) -> Dict[str, int]:
...Deprecated since version 3.9:自版本3.9起已弃用:builtins.dict
now supports现在支持[]
.[]
。See PEP 585 and Generic Alias Type.请参见PEP 585和泛型别名类型。
-
class
typing.
List
(list, MutableSequence[T])¶ Generic version oflist
.list
的通用版本。Useful for annotating return types.用于注释返回类型。To annotate arguments it is preferred to use an abstract collection type such as要注释参数,最好使用抽象集合类型,如Sequence
orIterable
.Sequence
或Iterable
。This type may be used as follows:该类型可按如下方式使用:T = TypeVar('T', int, float)
def vec2(x: T, y: T) -> List[T]:
return [x, y]
def keep_positives(vector: Sequence[T]) -> List[T]:
return [item for item in vector if item > 0]Deprecated since version 3.9:自版本3.9起已弃用:builtins.list
now supports[]
. See PEP 585 and Generic Alias Type.
-
class
typing.
Set
(set, MutableSet[T])¶ A generic version ofbuiltins.set
.builtins.set
的泛型版本。Useful for annotating return types.用于注释返回类型。To annotate arguments it is preferred to use an abstract collection type such as要注释参数,最好使用抽象集合类型,如AbstractSet
.AbstractSet
。Deprecated since version 3.9:自版本3.9起已弃用:builtins.set
now supports[]
. See PEP 585 and Generic Alias Type.
-
class
typing.
FrozenSet
(frozenset, AbstractSet[T_co])¶ A generic version of
builtins.frozenset
.Deprecated since version 3.9:自版本3.9起已弃用:builtins.frozenset
now supports[]
. See PEP 585 and Generic Alias Type.
Note
Tuple
is a special form.是一种特殊的形式。
Corresponding to types in collections
对应于collections
中的类型¶
collections
-
class
typing.
DefaultDict
(collections.defaultdict, MutableMapping[KT, VT])¶ A generic version of
collections.defaultdict
.New in version 3.5.2.版本3.5.2中新增。Deprecated since version 3.9:自版本3.9起已弃用:collections.defaultdict
now supports[]
. See PEP 585 and Generic Alias Type.
-
class
typing.
OrderedDict
(collections.OrderedDict, MutableMapping[KT, VT])¶ A generic version of
collections.OrderedDict
.New in version 3.7.2.版本3.7.2中新增。Deprecated since version 3.9:自版本3.9起已弃用:collections.OrderedDict
now supports[]
. See PEP 585 and Generic Alias Type.
-
class
typing.
ChainMap
(collections.ChainMap, MutableMapping[KT, VT])¶ A generic version ofcollections.ChainMap
.collections.ChainMap
的通用版本。New in version 3.5.4.版本3.5.4中新增。New in version 3.6.1.版本3.6.1中新增。Deprecated since version 3.9:自版本3.9起已弃用:collections.ChainMap
now supports[]
. See PEP 585 and Generic Alias Type.
-
class
typing.
Counter
(collections.Counter, Dict[T, int])¶ A generic version of
collections.Counter
.New in version 3.5.4.版本3.5.4中新增。New in version 3.6.1.版本3.6.1中新增。Deprecated since version 3.9:自版本3.9起已弃用:collections.Counter
now supports[]
. See PEP 585 and Generic Alias Type.
-
class
typing.
Deque
(deque, MutableSequence[T])¶ A generic version of
collections.deque
.New in version 3.5.4.版本3.5.4中新增。New in version 3.6.1.版本3.6.1中新增。Deprecated since version 3.9:自版本3.9起已弃用:collections.deque
now supports[]
. See PEP 585 and Generic Alias Type.
Other concrete types其他具体类型¶
-
class
typing.
IO
¶ -
class
typing.
TextIO
¶ -
class
typing.
BinaryIO
¶ Generic type泛型类型IO[AnyStr]
and its subclassesTextIO(IO[str])
andBinaryIO(IO[bytes])
represent the types of I/O streams such as returned byopen()
.IO[AnyStr]
及其子类TextIO(IO[str])
和BinaryIO(IO[bytes])
表示I/O流的类型,如open()
返回的类型。Deprecated since version 3.8, will be removed in version 3.12:自版本3.8起已弃用,将在版本3.12中删除:Thetyping.io
namespace is deprecated and will be removed.typing.io
命名空间已弃用,将被删除。These types should be directly imported from这些类型应该直接从typing
instead.typing
中导入。
-
class
typing.
Pattern
¶ -
class
typing.
Match
¶ These type aliases correspond to the return types from这些类型别名对应于re.compile()
andre.match()
.re.compile()
和re.match()
的返回类型。These types (and the corresponding functions) are generic in这些类型(以及相应的函数)在AnyStr
and can be made specific by writingPattern[str]
,Pattern[bytes]
,Match[str]
, orMatch[bytes]
.AnyStr
中是通用的,可以通过编写Pattern[str]
、Pattern[bytes]
、Match[str]
或Match[bytes]
。Deprecated since version 3.8, will be removed in version 3.12:自版本3.8起已弃用,将在版本3.12中删除:Thetyping.re
namespace is deprecated and will be removed.These types should be directly imported from这些类型应该直接从键入中导入。typing
instead.Deprecated since version 3.9:自版本3.9起已弃用:ClassesPattern
andMatch
fromre
now support[]
. See PEP 585 and Generic Alias Type.
-
class
typing.
Text
¶ Text
is an alias forstr
.It is provided to supply a forward compatible path for Python 2 code: in Python 2,提供它是为了为Python 2代码提供一个向前兼容的路径:在Python 2中,Text
is an alias forunicode
.Text
是unicode的别名。Use使用Text
to indicate that a value must contain a unicode string in a manner that is compatible with both Python 2 and Python 3:Text
指示值必须以与Python 2和Python 3兼容的方式包含unicode字符串:def add_unicode_checkmark(text: Text) -> Text:
return text + u' \u2713'New in version 3.5.2.版本3.5.2中新增。
Abstract Base Classes抽象基类¶
Corresponding to collections in collections.abc
对应于collections.abc
中的集合¶
collections.abc
-
class
typing.
AbstractSet
(Sized, Collection[T_co])¶ A generic version of
collections.abc.Set
.Deprecated since version 3.9:自版本3.9起已弃用:collections.abc.Set
now supports[]
. See PEP 585 and Generic Alias Type.
-
class
typing.
ByteString
(Sequence[int])¶ A generic version of
collections.abc.ByteString
.This type represents the types此类型表示字节序列的bytes
,bytearray
, andmemoryview
of byte sequences.bytes
、bytearray
和memoryview
的类型。As a shorthand for this type,作为这种类型的简写,bytes
can be used to annotate arguments of any of the types mentioned above.bytes
可以用于注释上述任何类型的参数。Deprecated since version 3.9:自版本3.9起已弃用:collections.abc.ByteString
now supports[]
. See PEP 585 and Generic Alias Type.
-
class
typing.
Collection
(Sized, Iterable[T_co], Container[T_co])¶ A generic version ofcollections.abc.Collection
的泛型版本。New in version 3.6.0.版本3.6.0中新增。Deprecated since version 3.9:自版本3.9起已弃用:collections.abc.Collection
now supports[]
. See PEP 585 and Generic Alias Type.
-
class
typing.
Container
(Generic[T_co])¶ A generic version ofcollections.abc.Container
.collections.abc.Container
的通用版本。Deprecated since version 3.9:自版本3.9起已弃用:collections.abc.Container
now supports[]
. See PEP 585 and Generic Alias Type.
-
class
typing.
ItemsView
(MappingView, Generic[KT_co, VT_co])¶ A generic version ofcollections.abc.ItemsView
.collections.abc.ItemsView
的通用版本。Deprecated since version 3.9:自版本3.9起已弃用:collections.abc.ItemsView
now supports[]
. See PEP 585 and Generic Alias Type.
-
class
typing.
KeysView
(MappingView[KT_co], AbstractSet[KT_co])¶ A generic version ofcollections.abc.KeysView
.collections.abc.KeysView
的通用版本。Deprecated since version 3.9:自版本3.9起已弃用:collections.abc.KeysView
now supports[]
. See PEP 585 and Generic Alias Type.
-
class
typing.
Mapping
(Sized, Collection[KT], Generic[VT_co])¶ A generic version ofcollections.abc.Mapping
.collections.abc.Mapping
的泛型版本。This type can be used as follows:该类型可按如下方式使用:def get_position_in_index(word_list: Mapping[str, int], word: str) -> int:
return word_list[word]Deprecated since version 3.9:自版本3.9起已弃用:collections.abc.Mapping
now supports[]
. See PEP 585 and Generic Alias Type.
-
class
typing.
MappingView
(Sized, Iterable[T_co])¶ A generic version of
collections.abc.MappingView
.Deprecated since version 3.9:自版本3.9起已弃用:collections.abc.MappingView
now supports[]
. See PEP 585 and Generic Alias Type.
-
class
typing.
MutableMapping
(Mapping[KT, VT])¶ A generic version of
collections.abc.MutableMapping
.Deprecated since version 3.9:自版本3.9起已弃用:collections.abc.MutableMapping
now supports[]
. See PEP 585 and Generic Alias Type.
-
class
typing.
MutableSequence
(Sequence[T])¶ A generic version of
collections.abc.MutableSequence
.Deprecated since version 3.9:自版本3.9起已弃用:collections.abc.MutableSequence
now supports[]
. See PEP 585 and Generic Alias Type.
-
class
typing.
MutableSet
(AbstractSet[T])¶ A generic version ofcollections.abc.MutableSet
.collections.abc.MutableSet
的泛型版本。Deprecated since version 3.9:自版本3.9起已弃用:collections.abc.MutableSet
now supports[]
. See PEP 585 and Generic Alias Type.
-
class
typing.
Sequence
(Reversible[T_co], Collection[T_co])¶ A generic version ofcollections.abc.Sequence
.collections.abc.Sequence
的通用版本。Deprecated since version 3.9:自版本3.9起已弃用:collections.abc.Sequence
now supports[]
. See PEP 585 and Generic Alias Type.
-
class
typing.
ValuesView
(MappingView[VT_co])¶ A generic version of
collections.abc.ValuesView
.Deprecated since version 3.9:自版本3.9起已弃用:collections.abc.ValuesView
now supports[]
. See PEP 585 and Generic Alias Type.
Corresponding to other types in collections.abc
对应于collections.abc
中的其他类型¶
collections.abc
-
class
typing.
Iterable
(Generic[T_co])¶ A generic version ofcollections.abc.Iterable
.collections.abc.Iterable
的通用版本。Deprecated since version 3.9:自版本3.9起已弃用:collections.abc.Iterable
now supports[]
. See PEP 585 and Generic Alias Type.
-
class
typing.
Iterator
(Iterable[T_co])¶ A generic version ofcollections.abc.Iterator
.collections.abc.Iterator
的通用版本。Deprecated since version 3.9:自版本3.9起已弃用:collections.abc.Iterator
now supports[]
.See PEP 585 and Generic Alias Type.请参见PEP 585和泛型别名类型。
-
class
typing.
Generator
(Iterator[T_co], Generic[T_co, T_contra, V_co])¶ A generator can be annotated by the generic type生成器可以由泛型类型Generator[YieldType, SendType, ReturnType]
.Generator[YieldType, SendType, ReturnType]
注释。For example:例如:def echo_round() -> Generator[int, float, str]:
sent = yield 0
while sent >= 0:
sent = yield round(sent)
return 'Done'Note that unlike many other generics in the typing module, the
SendType
ofGenerator
behaves contravariantly, not covariantly or invariantly.If your generator will only yield values, set the如果生成器只生成值,请将SendType
andReturnType
toNone
:SendType
和ReturnType
设置为None
:def infinite_stream(start: int) -> Generator[int, None, None]:
while True:
yield start
start += 1Alternatively, annotate your generator as having a return type of either或者,将生成器注释为返回类型为Iterable[YieldType]
orIterator[YieldType]
:Iterable[YieldType]
或Iterator[YieldType]
:def infinite_stream(start: int) -> Iterator[int]:
while True:
yield start
start += 1Deprecated since version 3.9:自版本3.9起已弃用:collections.abc.Generator
now supports[]
. See PEP 585 and Generic Alias Type.
-
class
typing.
Hashable
¶ An alias tocollections.abc.Hashable
的别名。
-
class
typing.
Reversible
(Iterable[T_co])¶ A generic version ofcollections.abc.Reversible
.collections.abc.Reversible
的通用版本。Deprecated since version 3.9:自版本3.9起已弃用:collections.abc.Reversible
now supports[]
. See PEP 585 and Generic Alias Type.
-
class
typing.
Sized
¶ An alias tocollections.abc.Sized
的别名
Asynchronous programming异步编程¶
-
class
typing.
Coroutine
(Awaitable[V_co], Generic[T_co, T_contra, V_co])¶ A generic version ofcollections.abc.Coroutine
.collections.abc.Coroutine
的通用版本。The variance and order of type variables correspond to those of类型变量的方差和顺序与Generator
, for example:Generator
的变量和顺序相对应,例如:from collections.abc import Coroutine
c: Coroutine[list[str], str, int] # Some coroutine defined elsewhere
x = c.send('hi') # Inferred type of 'x' is list[str]
async def bar() -> None:
y = await c # Inferred type of 'y' is intNew in version 3.5.3.版本3.5.3中新增。Deprecated since version 3.9:自版本3.9起已弃用:collections.abc.Coroutine
now supports[]
. See PEP 585 and Generic Alias Type.
-
class
typing.
AsyncGenerator
(AsyncIterator[T_co], Generic[T_co, T_contra])¶ An async generator can be annotated by the generic type异步生成器可以由泛型类型AsyncGenerator[YieldType, SendType]
.AsyncGenerator[YieldType, SendType]
注释。For example:例如:async def echo_round() -> AsyncGenerator[int, float]:
sent = yield 0
while sent >= 0.0:
rounded = await round(sent)
sent = yield roundedUnlike normal generators, async generators cannot return a value, so there is no与普通生成器不同,异步生成器无法返回值,因此没有ReturnType
type parameter.ReturnType
类型参数。As with相较之Generator
, theSendType
behaves contravariantly.Generator
,SendType
的行为相反。If your generator will only yield values, set the如果生成器只生成值,请将SendType
toNone
:SendType
设置为None
:async def infinite_stream(start: int) -> AsyncGenerator[int, None]:
while True:
yield start
start = await increment(start)Alternatively, annotate your generator as having a return type of either或者,将生成器注释为具有AsyncIterable[YieldType]
orAsyncIterator[YieldType]
:AsyncIterable[YieldType]
或AsyncIterator[YieldType]
的返回类型:async def infinite_stream(start: int) -> AsyncIterator[int]:
while True:
yield start
start = await increment(start)New in version 3.6.1.版本3.6.1中新增。Deprecated since version 3.9:自版本3.9起已弃用:collections.abc.AsyncGenerator
now supports[]
. See PEP 585 and Generic Alias Type.
-
class
typing.
AsyncIterable
(Generic[T_co])¶ A generic version of
collections.abc.AsyncIterable
.New in version 3.5.2.版本3.5.2中新增。Deprecated since version 3.9:自版本3.9起已弃用:collections.abc.AsyncIterable
now supports[]
. See PEP 585 and Generic Alias Type.
-
class
typing.
AsyncIterator
(AsyncIterable[T_co])¶ A generic version of
collections.abc.AsyncIterator
.New in version 3.5.2.版本3.5.2中新增。Deprecated since version 3.9:自版本3.9起已弃用:collections.abc.AsyncIterator
now supports[]
. See PEP 585 and Generic Alias Type.
-
class
typing.
Awaitable
(Generic[T_co])¶ A generic version of
collections.abc.Awaitable
.New in version 3.5.2.版本3.5.2中新增。Deprecated since version 3.9:自版本3.9起已弃用:collections.abc.Awaitable
now supports[]
. See PEP 585 and Generic Alias Type.
Context manager types上下文管理器类型¶
-
class
typing.
ContextManager
(Generic[T_co])¶ A generic version of
contextlib.AbstractContextManager
.New in version 3.5.4.版本3.5.4中新增。New in version 3.6.0.版本3.6.0中新增。Deprecated since version 3.9:自版本3.9起已弃用:contextlib.AbstractContextManager
now supports[]
. See PEP 585 and Generic Alias Type.
-
class
typing.
AsyncContextManager
(Generic[T_co])¶ A generic version of
contextlib.AbstractAsyncContextManager
.New in version 3.5.4.版本3.5.4中新增。New in version 3.6.2.版本3.6.2中新增。Deprecated since version 3.9:自版本3.9起已弃用:contextlib.AbstractAsyncContextManager
now supports[]
. See PEP 585 and Generic Alias Type.
Protocols协议¶
These protocols are decorated with 这些协议用runtime_checkable()
.runtime_checkable()
修饰。
-
class
typing.
SupportsAbs
¶ An ABC with one abstract method具有一个抽象方法__abs__
that is covariant in its return type.__abs__
的ABC,其返回类型为协变。
-
class
typing.
SupportsBytes
¶ An ABC with one abstract method具有一个抽象方法__bytes__
.__bytes__
的ABC。
-
class
typing.
SupportsComplex
¶ An ABC with one abstract method具有一个抽象方法__complex__
.__complex__
的ABC。
-
class
typing.
SupportsFloat
¶ An ABC with one abstract method具有一个抽象方法__float__
.__float__
的ABC。
-
class
typing.
SupportsIndex
¶ An ABC with one abstract method
__index__
.New in version 3.8.版本3.8中新增。
-
class
typing.
SupportsInt
¶ An ABC with one abstract method
__int__
.
-
class
typing.
SupportsRound
¶ An ABC with one abstract method具有一个抽象方法__round__
that is covariant in its return type.__round__
的ABC,其返回类型为协变。
Functions and decorators函数和装饰器¶
-
typing.
cast
(typ, val)¶ Cast a value to a type.将值强制转换为类型。This returns the value unchanged.这将返回值不变。To the type checker this signals that the return value has the designated type, but at runtime we intentionally don’t check anything (we want this to be as fast as possible).对于类型检查器,这表示返回值具有指定的类型,但在运行时,我们故意不检查任何内容(我们希望这尽可能快)。
-
@
typing.
overload
¶ The@overload
decorator allows describing functions and methods that support multiple different combinations of argument types.@overload
修饰符允许描述支持参数类型的多种不同组合的函数和方法。A series of一系列@overload
-decorated definitions must be followed by exactly one non-@overload
-decorated definition (for the same function/method).@overload
修饰定义后面必须紧跟一个非@overload
修饰定义(对于相同的函数/方法)。The@overload
-decorated definitions are for the benefit of the type checker only, since they will be overwritten by the non-@overload
-decorated definition, while the latter is used at runtime but should be ignored by a type checker.@overload
修饰的定义仅用于类型检查器,因为它们将被非@overload
修饰定义,而后者在运行时使用,但类型检查器应忽略。At runtime, calling a在运行时,直接调用@overload
-decorated function directly will raiseNotImplementedError
.@overload
修饰函数将引发NotImplementedError
。An example of overload that gives a more precise type than can be expressed using a union or a type variable:重载的一个例子,它给出了比使用并集或类型变量更精确的类型:@overload
def process(response: None) -> None:
...
@overload
def process(response: int) -> tuple[int, str]:
...
@overload
def process(response: bytes) -> str:
...
def process(response):
<actual implementation>See PEP 484 for details and comparison with other typing semantics.有关详细信息和与其他类型语义的比较,请参阅PEP 484。
-
@
typing.
final
¶ A decorator to indicate to type checkers that the decorated method cannot be overridden, and the decorated class cannot be subclassed.一个修饰符,用于向类型检查器指示修饰方法不能被重写,修饰类不能被子类化。For example:例如:class Base:
@final
def done(self) -> None:
...
class Sub(Base):
def done(self) -> None: # Error reported by type checker
...
@final
class Leaf:
...
class Other(Leaf): # Error reported by type checker
...There is no runtime checking of these properties.没有对这些属性进行运行时检查。See PEP 591 for more details.有关详细信息,请参阅PEP 591。New in version 3.8.版本3.8中新增。
-
@
typing.
no_type_check
¶ Decorator to indicate that annotations are not type hints.用于指示注释不是类型提示的修饰符。This works as class or function decorator.它用作类或函数装饰器。With a class, it applies recursively to all methods defined in that class (but not to methods defined in its superclasses or subclasses).对于类,它递归地应用于该类中定义的所有方法(但不应用于其超类或子类中定义定义的方法)。This mutates the function(s) in place.这会使函数发生突变。
-
@
typing.
no_type_check_decorator
¶ Decorator to give another decorator theDecorator为另一个Decorator提供no_type_check()
effect.no_type_check()
效果。This wraps the decorator with something that wraps the decorated function in这将用包装no_type_check()
.no_type_check()
中装饰函数的东西包装装饰器。
-
@
typing.
type_check_only
¶ Decorator to mark a class or function to be unavailable at runtime.用于标记类或函数在运行时不可用的修饰符。This decorator is itself not available at runtime.这个装饰器本身在运行时不可用。It is mainly intended to mark classes that are defined in type stub files if an implementation returns an instance of a private class:如果实现返回私有类的实例,则主要用于标记在类型存根文件中定义的类:@type_check_only
class Response: # private or not available at runtime
code: int
def get_header(self, name: str) -> str: ...
def fetch_response() -> Response: ...Note that returning instances of private classes is not recommended.注意,不建议返回私有类的实例。It is usually preferable to make such classes public.通常最好公开此类课程。
Introspection helpers反省帮助者¶
-
typing.
get_type_hints
(obj, globalns=None, localns=None, include_extras=False)¶ Return a dictionary containing type hints for a function, method, module or class object.返回包含函数、方法、模块或类对象的类型提示的字典。This is often the same as这通常与obj.__annotations__
.obj.__annotations__
相同。In addition, forward references encoded as string literals are handled by evaluating them in此外,编码为字符串文字的前向引用是通过在globals
andlocals
namespaces.globals
和locals
命名空间中对它们进行求值来处理的。If necessary,如果需要,如果设置了等于Optional[t]
is added for function and method annotations if a default value equal toNone
is set.None
的默认值,则为函数和方法注释添加Optional[t]
。For a class对于C
, return a dictionary constructed by merging all the__annotations__
alongC.__mro__
in reverse order.C
类,返回一个字典,该字典是按照相反的顺序将所有__annotations__
沿着C.__mro__
合并而成的。The function recursively replaces all
Annotated[T, ...]
withT
, unlessinclude_extras
is set toTrue
(seeAnnotated
for more information). For example:class Student(NamedTuple):
name: Annotated[str, 'some marker']
get_type_hints(Student) == {'name': str}
get_type_hints(Student, include_extras=False) == {'name': str}
get_type_hints(Student, include_extras=True) == {
'name': Annotated[str, 'some marker']
}Note
get_type_hints()
does not work with imported type aliases that include forward references.get_type_hints()
不适用于包含前向引用的导入类型别名。Enabling postponed evaluation of annotations (PEP 563) may remove the need for most forward references.启用注释的延迟评估(PEP 563)可以消除对大多数前向引用的需要。Changed in version 3.9:版本3.9中更改: Addedinclude_extras
parameter as part of PEP 593.
-
typing.
get_args
(tp)¶
-
typing.
get_origin
(tp)¶ Provide basic introspection for generic types and special typing forms.为泛型类型和特殊类型表单提供基本的内省。For a typing object of the form对于形式为X[Y, Z, ...]
these functions returnX
and(Y, Z, ...)
.X[Y, Z, ...]
的键入对象,这些函数返回X
和(Y, Z, ...)
。If如果X
is a generic alias for a builtin orcollections
class, it gets normalized to the original class.X
是内置类或collections
类的通用别名,则将其规范化为原始类。If如果X
is a union orLiteral
contained in another generic type, the order of(Y, Z, ...)
may be different from the order of the original arguments[Y, Z, ...]
due to type caching.X
是另一个泛型类型中包含的并集或Literal
,则由于类型缓存,(Y, Z, ...)
的顺序可能与原始参数[Y, Z, ...]
的顺序不同。For unsupported objects return对于不支持的对象,相应地返回None
and()
correspondingly.None
和()
。Examples:示例:assert get_origin(Dict[str, int]) is dict
assert get_args(Dict[int, str]) == (int, str)
assert get_origin(Union[int, str]) is Union
assert get_args(Union[int, str]) == (int, str)New in version 3.8.版本3.8中新增。
-
typing.
is_typeddict
(tp)¶ Check if a type is a检查类型是否为TypedDict
.TypedDict
。For example:例如:class Film(TypedDict):
title: str
year: int
is_typeddict(Film) # => True
is_typeddict(list | str) # => FalseNew in version 3.10.版本3.10中新增。
-
class
typing.
ForwardRef
¶ A class used for internal typing representation of string forward references.用于字符串前向引用的内部类型表示的类。For example,例如,List["SomeClass"]
is implicitly transformed intoList[ForwardRef("SomeClass")]
.List["SomeClass"]
隐式转换为List[ForwardRef("SomeClass")]
。This class should not be instantiated by a user, but may be used by introspection tools.该类不应由用户实例化,但可以由内省工具使用。Note
PEP 585
generic types such as诸如list["SomeClass"]
will not be implicitly transformed intolist[ForwardRef("SomeClass")]
and thus will not automatically resolve tolist[SomeClass]
.list["SomeClass"]
之类的泛型类型不会隐式转换为list[ForwardRef("SomeClass")]
,因此不会自动解析为list[SomeClass]
。New in version 3.7.4.版本3.7.4中新增。
Constant常数¶
-
typing.
TYPE_CHECKING
¶ A special constant that is assumed to be第三方静态类型检查器假定为True
by 3rd party static type checkers.True
的特殊常量。It is运行时为False
at runtime. Usage:False
。用法:if TYPE_CHECKING:
import expensive_mod
def fun(arg: 'expensive_mod.SomeType') -> None:
local_var: expensive_mod.AnotherType = other_fun()The first type annotation must be enclosed in quotes, making it a “forward reference”, to hide the第一个类型注释必须用引号括起来,使其成为“前向引用”,以便在解释器运行时隐藏expensive_mod
reference from the interpreter runtime.expenseive_mod
引用。Type annotations for local variables are not evaluated, so the second annotation does not need to be enclosed in quotes.不计算局部变量的类型注释,因此第二个注释不需要用引号括起来。Note
If如果在Python 3.7或更高版本中使用了from __future__ import annotations
is used in Python 3.7 or later, annotations are not evaluated at function definition time.from __future__ import annotations
,则在函数定义时不会计算注释。Instead, they are stored as strings in相反,它们作为字符串存储在__annotations__
, This makes it unnecessary to use quotes around the annotation.__annotations__
中,这使得不必在注释周围使用引号。(see PEP 563).(见PEP 563)。New in version 3.5.2.版本3.5.2中新增。