Source code: Lib/types.py
This module defines utility functions to assist in dynamic creation of new types.
It also defines names for some object types that are used by the standard Python interpreter, but not exposed as builtins like int or str are.
Finally, it provides some additional type-related utility classes and functions that are not fundamental enough to be builtins.
Creates a class object dynamically using the appropriate metaclass.
The first three arguments are the components that make up a class definition header: the class name, the base classes (in order), the keyword arguments (such as metaclass).
The exec_body argument is a callback that is used to populate the freshly created class namespace. It should accept the class namespace as its sole argument and update the namespace directly with the class contents. If no callback is provided, it has the same effect as passing in lambda ns: ns.
New in version 3.3.
Calculates the appropriate metaclass and creates the class namespace.
The arguments are the components that make up a class definition header: the class name, the base classes (in order) and the keyword arguments (such as metaclass).
The return value is a 3-tuple: metaclass, namespace, kwds
metaclass is the appropriate metaclass, namespace is the prepared class namespace and kwds is an updated copy of the passed in kwds argument with any 'metaclass' entry removed. If no kwds argument is passed in, this will be an empty dict.
New in version 3.3.
Changed in version 3.6: The default value for the namespace element of the returned tuple has changed. Now an insertion-order-preserving mapping is used when the metaclass does not have a __prepare__ method.
See also
Full details of the class creation process supported by these functions
Introduced the __prepare__ namespace hook
Resolve MRO entries dynamically as specified by PEP 560.
This function looks for items in bases that are not instances of type, and returns a tuple where each such object that has an __mro_entries__ method is replaced with an unpacked result of calling this method. If a bases item is an instance of type, or it doesn’t have an __mro_entries__ method, then it is included in the return tuple unchanged.
New in version 3.7.
See also
PEP 560 - Core support for typing module and generic types
This module provides names for many of the types that are required to implement a Python interpreter. It deliberately avoids including some of the types that arise only incidentally during processing such as the listiterator type.
Typical use of these names is for isinstance() or issubclass() checks.
If you instantiate any of these types, note that signatures may vary between Python versions.
Standard names are defined for the following types:
The type of user-defined functions and functions created by lambda expressions.
Raises an auditing event function.__new__ with argument code.
The audit event only occurs for direct instantiation of function objects, and is not raised for normal compilation.
The type of generator-iterator objects, created by generator functions.
The type of coroutine objects, created by async def functions.
New in version 3.5.
The type of asynchronous generator-iterator objects, created by asynchronous generator functions.
New in version 3.6.
The type for code objects such as returned by compile().
Raises an auditing event code.__new__ with arguments code, filename, name, argcount, posonlyargcount, kwonlyargcount, nlocals, stacksize, flags.
Note that the audited arguments may not match the names or positions required by the initializer. The audit event only occurs for direct instantiation of code objects, and is not raised for normal compilation.
Return a copy of the code object with new values for the specified fields.
New in version 3.8.
The type for cell objects: such objects are used as containers for a function’s free variables.
New in version 3.8.
The type of methods of user-defined class instances.
The type of built-in functions like len() or sys.exit(), and methods of built-in classes. (Here, the term “built-in” means “written in C”.)
The type of methods of some built-in data types and base classes such as object.__init__() or object.__lt__().
New in version 3.7.
The type of bound methods of some built-in data types and base classes. For example it is the type of object().__str__.
New in version 3.7.
The type of methods of some built-in data types such as str.join().
New in version 3.7.
The type of unbound class methods of some built-in data types such as dict.__dict__['fromkeys'].
New in version 3.7.
The type of modules. The constructor takes the name of the module to be created and optionally its docstring.
Note
Use importlib.util.module_from_spec() to create a new module if you wish to set the various import-controlled attributes.
The docstring of the module. Defaults to None.
The loader which loaded the module. Defaults to None.
This attribute is to match importlib.machinery.ModuleSpec.loader as stored in the attr:__spec__ object.
Note
A future version of Python may stop setting this attribute by default. To guard against this potential change, preferrably read from the __spec__ attribute instead or use getattr(module, "__loader__", None) if you explicitly need to use this attribute.
Changed in version 3.4: Defaults to None. Previously the attribute was optional.
The name of the module. Expected to match importlib.machinery.ModuleSpec.name.
Which package a module belongs to. If the module is top-level (i.e. not a part of any specific package) then the attribute should be set to '', else it should be set to the name of the package (which can be __name__ if the module is a package itself). Defaults to None.
This attribute is to match importlib.machinery.ModuleSpec.parent as stored in the attr:__spec__ object.
Note
A future version of Python may stop setting this attribute by default. To guard against this potential change, preferrably read from the __spec__ attribute instead or use getattr(module, "__package__", None) if you explicitly need to use this attribute.
Changed in version 3.4: Defaults to None. Previously the attribute was optional.
A record of the the module’s import-system-related state. Expected to be an instance of importlib.machinery.ModuleSpec.
New in version 3.4.
The type of parameterized generics such as list[int].
t_origin should be a non-parameterized generic class, such as list, tuple or dict. t_args should be a tuple (possibly of length 1) of types which parameterize t_origin:
New in version 3.9.
Changed in version 3.9.2: This type can now be subclassed.
The type of traceback objects such as found in sys.exc_info()[2].
See the language reference for details of the available attributes and operations, and guidance on creating tracebacks dynamically.
The type of frame objects such as found in tb.tb_frame if tb is a traceback object.
See the language reference for details of the available attributes and operations.
The type of objects defined in extension modules with PyGetSetDef, such as FrameType.f_locals or array.array.typecode. This type is used as descriptor for object attributes; it has the same purpose as the property type, but for classes defined in extension modules.
The type of objects defined in extension modules with PyMemberDef, such as datetime.timedelta.days. This type is used as descriptor for simple C data members which use standard conversion functions; it has the same purpose as the property type, but for classes defined in extension modules.
CPython implementation detail: In other implementations of Python, this type may be identical to GetSetDescriptorType.
Read-only proxy of a mapping. It provides a dynamic view on the mapping’s entries, which means that when the mapping changes, the view reflects these changes.
New in version 3.3.
Changed in version 3.9: Updated to support the new union (|) operator from PEP 584, which simply delegates to the underlying mapping.
Return True if the underlying mapping has a key key, else False.
Return the item of the underlying mapping with key key. Raises a KeyError if key is not in the underlying mapping.
Return an iterator over the keys of the underlying mapping. This is a shortcut for iter(proxy.keys()).
Return the number of items in the underlying mapping.
Return a shallow copy of the underlying mapping.
Return the value for key if key is in the underlying mapping, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
Return a new view of the underlying mapping’s items ((key, value) pairs).
Return a new view of the underlying mapping’s keys.
Return a new view of the underlying mapping’s values.
Return a reverse iterator over the keys of the underlying mapping.
New in version 3.9.
A simple object subclass that provides attribute access to its namespace, as well as a meaningful repr.
Unlike object, with SimpleNamespace you can add and remove attributes. If a SimpleNamespace object is initialized with keyword arguments, those are directly added to the underlying namespace.
The type is roughly equivalent to the following code:
SimpleNamespace may be useful as a replacement for class NS: pass. However, for a structured record type use namedtuple() instead.
New in version 3.3.
Changed in version 3.9: Attribute order in the repr changed from alphabetical to insertion (like dict).
Route attribute access on a class to __getattr__.
This is a descriptor, used to define attributes that act differently when accessed through an instance and through a class. Instance access remains normal, but access to an attribute through a class will be routed to the class’s __getattr__ method; this is done by raising AttributeError.
This allows one to have properties active on an instance, and have virtual attributes on the class with the same name (see enum.Enum for an example).
New in version 3.4.
This function transforms a generator function into a coroutine function which returns a generator-based coroutine. The generator-based coroutine is still a generator iterator, but is also considered to be a coroutine object and is awaitable. However, it may not necessarily implement the __await__() method.
If gen_func is a generator function, it will be modified in-place.
If gen_func is not a generator function, it will be wrapped. If it returns an instance of collections.abc.Generator, the instance will be wrapped in an awaitable proxy object. All other types of objects will be returned as is.
New in version 3.5.


The type of asynchronous generator-iterator objects, created by asynchronous generator functions.
New in version 3.6.


The type of built-in functions like len() or sys.exit(), and methods of built-in classes. (Here, the term “built-in” means “written in C”.)


The type for cell objects: such objects are used as containers for a function’s free variables.
New in version 3.8.


The type of unbound class methods of some built-in data types such as dict.__dict__['fromkeys'].
New in version 3.7.


The type for code objects such as returned by compile().
Raises an auditing event code.__new__ with arguments code, filename, name, argcount, posonlyargcount, kwonlyargcount, nlocals, stacksize, flags.
Note that the audited arguments may not match the names or positions required by the initializer. The audit event only occurs for direct instantiation of code objects, and is not raised for normal compilation.
Return a copy of the code object with new values for the specified fields.
New in version 3.8.


Return a copy of the code object with new values for the specified fields.
New in version 3.8.


This function transforms a generator function into a coroutine function which returns a generator-based coroutine. The generator-based coroutine is still a generator iterator, but is also considered to be a coroutine object and is awaitable. However, it may not necessarily implement the __await__() method.
If gen_func is a generator function, it will be modified in-place.
If gen_func is not a generator function, it will be wrapped. If it returns an instance of collections.abc.Generator, the instance will be wrapped in an awaitable proxy object. All other types of objects will be returned as is.
New in version 3.5.


The type of coroutine objects, created by async def functions.
New in version 3.5.


Route attribute access on a class to __getattr__.
This is a descriptor, used to define attributes that act differently when accessed through an instance and through a class. Instance access remains normal, but access to an attribute through a class will be routed to the class’s __getattr__ method; this is done by raising AttributeError.
This allows one to have properties active on an instance, and have virtual attributes on the class with the same name (see enum.Enum for an example).
New in version 3.4.


The type of frame objects such as found in tb.tb_frame if tb is a traceback object.
See the language reference for details of the available attributes and operations.


The type of user-defined functions and functions created by lambda expressions.
Raises an auditing event function.__new__ with argument code.
The audit event only occurs for direct instantiation of function objects, and is not raised for normal compilation.


The type of generator-iterator objects, created by generator functions.


The type of parameterized generics such as list[int].
t_origin should be a non-parameterized generic class, such as list, tuple or dict. t_args should be a tuple (possibly of length 1) of types which parameterize t_origin:
New in version 3.9.
Changed in version 3.9.2: This type can now be subclassed.


The type of objects defined in extension modules with PyGetSetDef, such as FrameType.f_locals or array.array.typecode. This type is used as descriptor for object attributes; it has the same purpose as the property type, but for classes defined in extension modules.


Read-only proxy of a mapping. It provides a dynamic view on the mapping’s entries, which means that when the mapping changes, the view reflects these changes.
New in version 3.3.
Changed in version 3.9: Updated to support the new union (|) operator from PEP 584, which simply delegates to the underlying mapping.
Return True if the underlying mapping has a key key, else False.
Return the item of the underlying mapping with key key. Raises a KeyError if key is not in the underlying mapping.
Return an iterator over the keys of the underlying mapping. This is a shortcut for iter(proxy.keys()).
Return the number of items in the underlying mapping.
Return a shallow copy of the underlying mapping.
Return the value for key if key is in the underlying mapping, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
Return a new view of the underlying mapping’s items ((key, value) pairs).
Return a new view of the underlying mapping’s keys.
Return a new view of the underlying mapping’s values.
Return a reverse iterator over the keys of the underlying mapping.
New in version 3.9.


Return a shallow copy of the underlying mapping.


Return the value for key if key is in the underlying mapping, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.


Return a new view of the underlying mapping’s items ((key, value) pairs).


Return a new view of the underlying mapping’s keys.


Return a new view of the underlying mapping’s values.


The type of objects defined in extension modules with PyMemberDef, such as datetime.timedelta.days. This type is used as descriptor for simple C data members which use standard conversion functions; it has the same purpose as the property type, but for classes defined in extension modules.
CPython implementation detail: In other implementations of Python, this type may be identical to GetSetDescriptorType.


The type of methods of some built-in data types such as str.join().
New in version 3.7.


The type of methods of user-defined class instances.


The type of bound methods of some built-in data types and base classes. For example it is the type of object().__str__.
New in version 3.7.


The type of modules. The constructor takes the name of the module to be created and optionally its docstring.
Note
Use importlib.util.module_from_spec() to create a new module if you wish to set the various import-controlled attributes.
The docstring of the module. Defaults to None.
The loader which loaded the module. Defaults to None.
This attribute is to match importlib.machinery.ModuleSpec.loader as stored in the attr:__spec__ object.
Note
A future version of Python may stop setting this attribute by default. To guard against this potential change, preferrably read from the __spec__ attribute instead or use getattr(module, "__loader__", None) if you explicitly need to use this attribute.
Changed in version 3.4: Defaults to None. Previously the attribute was optional.
The name of the module. Expected to match importlib.machinery.ModuleSpec.name.
Which package a module belongs to. If the module is top-level (i.e. not a part of any specific package) then the attribute should be set to '', else it should be set to the name of the package (which can be __name__ if the module is a package itself). Defaults to None.
This attribute is to match importlib.machinery.ModuleSpec.parent as stored in the attr:__spec__ object.
Note
A future version of Python may stop setting this attribute by default. To guard against this potential change, preferrably read from the __spec__ attribute instead or use getattr(module, "__package__", None) if you explicitly need to use this attribute.
Changed in version 3.4: Defaults to None. Previously the attribute was optional.
A record of the the module’s import-system-related state. Expected to be an instance of importlib.machinery.ModuleSpec.
New in version 3.4.


The docstring of the module. Defaults to None.


The loader which loaded the module. Defaults to None.
This attribute is to match importlib.machinery.ModuleSpec.loader as stored in the attr:__spec__ object.
Note
A future version of Python may stop setting this attribute by default. To guard against this potential change, preferrably read from the __spec__ attribute instead or use getattr(module, "__loader__", None) if you explicitly need to use this attribute.
Changed in version 3.4: Defaults to None. Previously the attribute was optional.


The name of the module. Expected to match importlib.machinery.ModuleSpec.name.


Which package a module belongs to. If the module is top-level (i.e. not a part of any specific package) then the attribute should be set to '', else it should be set to the name of the package (which can be __name__ if the module is a package itself). Defaults to None.
This attribute is to match importlib.machinery.ModuleSpec.parent as stored in the attr:__spec__ object.
Note
A future version of Python may stop setting this attribute by default. To guard against this potential change, preferrably read from the __spec__ attribute instead or use getattr(module, "__package__", None) if you explicitly need to use this attribute.
Changed in version 3.4: Defaults to None. Previously the attribute was optional.


A record of the the module’s import-system-related state. Expected to be an instance of importlib.machinery.ModuleSpec.
New in version 3.4.


Creates a class object dynamically using the appropriate metaclass.
The first three arguments are the components that make up a class definition header: the class name, the base classes (in order), the keyword arguments (such as metaclass).
The exec_body argument is a callback that is used to populate the freshly created class namespace. It should accept the class namespace as its sole argument and update the namespace directly with the class contents. If no callback is provided, it has the same effect as passing in lambda ns: ns.
New in version 3.3.


Calculates the appropriate metaclass and creates the class namespace.
The arguments are the components that make up a class definition header: the class name, the base classes (in order) and the keyword arguments (such as metaclass).
The return value is a 3-tuple: metaclass, namespace, kwds
metaclass is the appropriate metaclass, namespace is the prepared class namespace and kwds is an updated copy of the passed in kwds argument with any 'metaclass' entry removed. If no kwds argument is passed in, this will be an empty dict.
New in version 3.3.
Changed in version 3.6: The default value for the namespace element of the returned tuple has changed. Now an insertion-order-preserving mapping is used when the metaclass does not have a __prepare__ method.


Resolve MRO entries dynamically as specified by PEP 560.
This function looks for items in bases that are not instances of type, and returns a tuple where each such object that has an __mro_entries__ method is replaced with an unpacked result of calling this method. If a bases item is an instance of type, or it doesn’t have an __mro_entries__ method, then it is included in the return tuple unchanged.
New in version 3.7.


A simple object subclass that provides attribute access to its namespace, as well as a meaningful repr.
Unlike object, with SimpleNamespace you can add and remove attributes. If a SimpleNamespace object is initialized with keyword arguments, those are directly added to the underlying namespace.
The type is roughly equivalent to the following code:
SimpleNamespace may be useful as a replacement for class NS: pass. However, for a structured record type use namedtuple() instead.
New in version 3.3.
Changed in version 3.9: Attribute order in the repr changed from alphabetical to insertion (like dict).


The type of traceback objects such as found in sys.exc_info()[2].
See the language reference for details of the available attributes and operations, and guidance on creating tracebacks dynamically.


The type of methods of some built-in data types and base classes such as object.__init__() or object.__lt__().
New in version 3.7.


New in version 3.5.
Source code: Lib/typing.py
Note
The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc.
This module provides runtime support for type hints as specified by PEP 484, PEP 526, PEP 544, PEP 586, PEP 589, and PEP 591. The most fundamental support consists of the types Any, Union, Tuple, Callable, TypeVar, and Generic. For full specification please see PEP 484. For a simplified introduction to type hints see PEP 483.
The function below takes and returns a string and is annotated as follows:
In the function greeting, the argument name is expected to be of type str and the return type str. Subtypes are accepted as arguments.
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:
Type aliases are useful for simplifying complex type signatures. For example:
Note that None as a type hint is a special case and is replaced by type(None).
Use the NewType() helper function to create distinct types:
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:
You may still perform all int operations on a variable of type UserId, but the result will always be of type 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:
Note that these checks are enforced only by the static type checker. At runtime, the statement Derived = NewType('Derived', Base) will make Derived a function that immediately returns whatever parameter you pass it. That means the expression Derived(some_value) does not create a new class or introduce any overhead beyond that of a regular function call.
More precisely, the expression some_value is Derived(some_value) is always true at runtime.
This also means that it is not possible to create a subtype of Derived since it is an identity function at runtime, not an actual type:
However, it is possible to create a NewType() based on a ‘derived’ NewType:
and typechecking for ProUserId will work as expected.
See PEP 484 for more details.
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. This is useful when you want to simplify complex type signatures.
In contrast, NewType declares one type to be a subtype of another. 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. This is useful when you want to prevent logic errors with minimal runtime cost.
New in version 3.5.2.
Frameworks expecting callback functions of specific signatures might be type hinted using Callable[[Arg1Type, Arg2Type], ReturnType].
For example:
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].
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.
Generics can be parameterized by using a new factory available in typing called TypeVar.
A user-defined class can be defined as a generic class.
Generic[T] as a base class defines that the class LoggedVar takes a single type parameter T . This also makes T valid as a type within the class body.
The Generic base class defines __class_getitem__() so that LoggedVar[t] is valid as a type:
A generic type can have any number of type variables, and type variables may be constrained:
Each type variable argument to Generic must be distinct. This is thus invalid:
You can use multiple inheritance with Generic:
When inheriting from generic classes, some type variables could be fixed:
In this case MyDict has a single parameter, T.
Using a generic class without specifying type parameters assumes Any for each position. In the following example, MyIterable is not generic but implicitly inherits from Iterable[Any]:
User defined generic type aliases are also supported. Examples:
Changed in version 3.7: Generic no longer has a custom metaclass.
A user-defined generic class can have ABCs as base classes without a metaclass conflict. 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.
A special kind of type is Any. A static type checker will treat every type as being compatible with Any and Any as being compatible with every type.
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:
Notice that no typechecking is performed when assigning a value of type Any to a more precise type. 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!
Furthermore, all functions without a return type or parameter types will implicitly default to using Any:
This behavior allows Any to be used as an escape hatch when you need to mix dynamically and statically typed code.
Contrast the behavior of Any with the behavior of object. Similar to Any, every type is a subtype of object. However, unlike Any, the reverse is not true: object is not a subtype of every other type.
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. For example:
Use object to indicate that a value could be any type in a typesafe manner. Use Any to indicate that a value is dynamically typed.
Initially PEP 484 defined Python static type system as using nominal subtyping. This means that a class A is allowed where a class B is expected if and only if A is a subclass of B.
This requirement previously also applied to abstract base classes, such as 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. For example, this conforms to PEP 484:
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. This is known as structural subtyping (or static duck-typing):
Moreover, by subclassing a special class Protocol, a user can define new custom protocols to fully enjoy structural subtyping (see examples below).
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 []. These types became redundant in Python 3.9 when the corresponding pre-existing classes were enhanced to support [].
The redundant types are deprecated as of Python 3.9 but no deprecation warnings will be issued by the interpreter. It is expected that type checkers will flag the deprecated types when the checked program targets Python 3.9 or newer.
The deprecated types will be removed from the typing module in the first Python version released 5 years after the release of Python 3.9.0. See details in PEP 585—Type Hinting Generics In Standard Collections.
These can be used as types in annotations and do not support [].
Special type indicating an unconstrained type.
Special type indicating that a function never returns. For example:
New in version 3.5.4.
New in version 3.6.2.
These can be used as types in annotations using [], each having a unique syntax.
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. The type of the empty tuple can be written as Tuple[()].
Example: Tuple[T1, T2] is a tuple of two elements corresponding to type variables T1 and T2. Tuple[int, float, str] is a tuple of an int, a float and a string.
To specify a variable-length tuple of homogeneous type, use literal ellipsis, e.g. Tuple[int, ...]. A plain Tuple is equivalent to Tuple[Any, ...], and in turn to tuple.
Deprecated since version 3.9: builtins.tuple now supports []. See PEP 585 and Generic Alias Type.
Union type; Union[X, Y] means either X or Y.
To define a union, use e.g. Union[int, str]. Details:
Unions of unions are flattened, e.g.:
Unions of a single argument vanish, e.g.:
Redundant arguments are skipped, e.g.:
When comparing unions, the argument order is ignored, e.g.:
Changed in version 3.7: Don’t remove explicit subclasses from unions at runtime.
Optional type.
Optional[X] is equivalent to Union[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. For example:
On the other hand, if an explicit value of None is allowed, the use of Optional is appropriate, whether the argument is optional or not. For example:
Callable type; Callable[[int], str] is a function of (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 returning ReturnType. A plain Callable is equivalent to Callable[..., Any], and in turn to collections.abc.Callable.
Deprecated since version 3.9: collections.abc.Callable now supports []. See PEP 585 and Generic Alias Type.
A variable annotated with C may accept a value of type C. In contrast, a variable annotated with Type[C] may accept values that are classes themselves – specifically, it will accept the class object of C. For example:
Note that Type[C] is covariant:
The fact that Type[C] is covariant implies that all subclasses of C should implement the same constructor signature and class method signatures as C. 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 for Type are classes, Any, type variables, and unions of any of these types. For example:
Type[Any] is equivalent to Type which in turn is equivalent to type, which is the root of Python’s metaclass hierarchy.
New in version 3.5.2.
Deprecated since version 3.9: builtins.type now supports []. See PEP 585 and Generic Alias Type.
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:
Literal[...] cannot be subclassed. At runtime, an arbitrary value is allowed as type argument to Literal[...], but type checkers may impose restrictions. See PEP 586 for more details about literal types.
New in version 3.8.
Changed in version 3.9.1: Literal now de-duplicates parameters. Equality comparison of Literal objects are no longer order dependent. Literal objects will now raise a TypeError exception during equality comparisons if one of their parameters are not immutable.
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:
ClassVar accepts only types and cannot be further subscribed.
ClassVar is not a class itself, and should not be used with isinstance() or issubclass(). 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:
New in version 3.5.3.
A special typing construct to indicate to type checkers that a name cannot be re-assigned or overridden in a subclass. For example:
There is no runtime checking of these properties. See PEP 591 for more details.
New in version 3.8.
A type, introduced in PEP 593 (Flexible function and variable
annotations), to decorate existing types with context-specific metadata (possibly multiple pieces of it, as Annotated is variadic). Specifically, a type T can be annotated with metadata x via the typehint Annotated[T, x]. This metadata can be used for either static analysis or at runtime. If a library (or tool) encounters a typehint Annotated[T, x] and has no special logic for metadata x, it should ignore it and simply treat the type as T. Unlike the no_type_check functionality that currently exists in the typing module which completely disables typechecking annotations on a function or a class, the Annotated type allows for both static typechecking of T (e.g., via mypy or Pyre, which can safely ignore x) together with runtime access to x 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. A tool or library encountering an Annotated type can scan through the annotations to determine if they are of interest (e.g., using 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. For example, if you are doing value range analysis you might allow this:
Passing include_extras=True to get_type_hints() lets one access the extra annotations at runtime.
The details of the syntax:
Multiple type annotations are supported (Annotated supports variadic arguments):
The order of the annotations is preserved and matters for equality checks:
Nested Annotated types are flattened, with metadata ordered starting with the innermost annotation:
Duplicated annotations are not removed:
Annotated can be used with nested and generic aliases:
New in version 3.9.
These are not used in annotations. They are building blocks for creating generic types.
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:
This class can then be used as follows:
Type variable.
Usage:
Type 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 functions work as follows:
The latter example’s signature is essentially the overloading of (str, str) -> str and (bytes, bytes) -> bytes. Also note that if the arguments are instances of some subclass of str, the return type is still plain str.
At runtime, isinstance(x, T) will raise TypeError. In general, isinstance() and issubclass() should not be used with types.
Type variables may be marked covariant or contravariant by passing covariant=True or contravariant=True. See PEP 484 for more details. By default type variables are invariant. Alternatively, a type variable may specify an upper bound using bound=<type>. This means that an actual type substituted (explicitly or implicitly) for the type variable must be a subclass of the boundary type, see PEP 484.
AnyStr is a type variable defined as AnyStr = 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:
Base class for protocol classes. Protocol classes are defined like this:
Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing), for example:
See PEP 544 for details. 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.
Protocol classes can be generic, for example:
New in version 3.8.
Mark a protocol class as a runtime protocol.
Such a protocol can be used with isinstance() and issubclass(). This raises TypeError when applied to a non-protocol class. This allows a simple-minded structural check, very similar to “one trick ponies” in collections.abc such as Iterable. For example:
Note
runtime_checkable() will check only the presence of the required methods, not their type signatures! For example, builtins.complex implements __float__(), therefore it passes an issubclass() check against SupportsFloat. However, the complex.__float__ method exists only to raise a TypeError with a more informative message.
New in version 3.8.
These are not used in annotations. They are building blocks for declaring types.
Typed version of collections.namedtuple().
Usage:
This is equivalent to:
To give a field a default value, you can assign to it in the class body:
Fields 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. (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.)
NamedTuple subclasses can also have docstrings and methods:
Backward-compatible usage:
Changed in version 3.6: Added support for PEP 526 variable annotation syntax.
Changed in version 3.6.1: Added support for default values, methods, and docstrings.
Changed in version 3.8: The _field_types and __annotations__ attributes are now regular dictionaries instead of instances of OrderedDict.
Changed in version 3.9: Removed the _field_types attribute in favor of the more standard __annotations__ attribute which has the same information.
A helper function to indicate a distinct type to a typechecker, see NewType. At runtime it returns a function that returns its argument. Usage:
New in version 3.5.2.
Special construct to add type hints to a dictionary. At runtime it is a plain 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:
The type info for introspection can be accessed via Point2D.__annotations__ and Point2D.__total__. To allow using this feature with older versions of Python that do not support PEP 526, TypedDict supports two additional equivalent syntactic forms:
By default, all keys must be present in a TypedDict. It is possible to override this by specifying totality. Usage:
This means that a point2D TypedDict can have any of the keys omitted. A type checker is only expected to support a literal False or True as the value of the total argument. True is the default, and makes all items defined in the class body be required.
See PEP 589 for more examples and detailed rules of using TypedDict.
New in version 3.8.
A generic version of dict. Useful for annotating return types. To annotate arguments it is preferred to use an abstract collection type such as Mapping.
This type can be used as follows:
Deprecated since version 3.9: builtins.dict now supports []. See PEP 585 and Generic Alias Type.
Generic version of list. Useful for annotating return types. To annotate arguments it is preferred to use an abstract collection type such as Sequence or Iterable.
This type may be used as follows:
Deprecated since version 3.9: builtins.list now supports []. See PEP 585 and Generic Alias Type.
A generic version of builtins.set. Useful for annotating return types. To annotate arguments it is preferred to use an abstract collection type such as AbstractSet.
Deprecated since version 3.9: builtins.set now supports []. See PEP 585 and Generic Alias Type.
A generic version of builtins.frozenset.
Deprecated since version 3.9: builtins.frozenset now supports []. See PEP 585 and Generic Alias Type.
Note
Tuple is a special form.
A generic version of collections.defaultdict.
New in version 3.5.2.
Deprecated since version 3.9: collections.defaultdict now supports []. See PEP 585 and Generic Alias Type.
A generic version of collections.OrderedDict.
New in version 3.7.2.
Deprecated since version 3.9: collections.OrderedDict now supports []. See PEP 585 and Generic Alias Type.
A generic version of collections.ChainMap.
New in version 3.5.4.
New in version 3.6.1.
Deprecated since version 3.9: collections.ChainMap now supports []. See PEP 585 and Generic Alias Type.
A generic version of collections.Counter.
New in version 3.5.4.
New in version 3.6.1.
Deprecated since version 3.9: collections.Counter now supports []. See PEP 585 and Generic Alias Type.
A generic version of collections.deque.
New in version 3.5.4.
New in version 3.6.1.
Deprecated since version 3.9: collections.deque now supports []. See PEP 585 and Generic Alias Type.
Generic type IO[AnyStr] and its subclasses TextIO(IO[str]) and BinaryIO(IO[bytes]) represent the types of I/O streams such as returned by open(). These types are also in the typing.io namespace.
These type aliases correspond to the return types from re.compile() and re.match(). These types (and the corresponding functions) are generic in AnyStr and can be made specific by writing Pattern[str], Pattern[bytes], Match[str], or Match[bytes]. These types are also in the typing.re namespace.
Deprecated since version 3.9: Classes Pattern and Match from re now support []. See PEP 585 and Generic Alias Type.
Text is an alias for str. It is provided to supply a forward compatible path for Python 2 code: in Python 2, Text is an alias for 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:
New in version 3.5.2.
A generic version of collections.abc.Set.
Deprecated since version 3.9: collections.abc.Set now supports []. See PEP 585 and Generic Alias Type.
A generic version of collections.abc.ByteString.
This type represents the types bytes, bytearray, and memoryview of byte sequences.
As a shorthand for this type, bytes can be used to annotate arguments of any of the types mentioned above.
Deprecated since version 3.9: collections.abc.ByteString now supports []. See PEP 585 and Generic Alias Type.
A generic version of collections.abc.Collection
New in version 3.6.0.
Deprecated since version 3.9: collections.abc.Collection now supports []. See PEP 585 and Generic Alias Type.
A generic version of collections.abc.Container.
Deprecated since version 3.9: collections.abc.Container now supports []. See PEP 585 and Generic Alias Type.
A generic version of collections.abc.ItemsView.
Deprecated since version 3.9: collections.abc.ItemsView now supports []. See PEP 585 and Generic Alias Type.
A generic version of collections.abc.KeysView.
Deprecated since version 3.9: collections.abc.KeysView now supports []. See PEP 585 and Generic Alias Type.
A generic version of collections.abc.Mapping. This type can be used as follows:
Deprecated since version 3.9: collections.abc.Mapping now supports []. See PEP 585 and Generic Alias Type.
A generic version of collections.abc.MappingView.
Deprecated since version 3.9: collections.abc.MappingView now supports []. See PEP 585 and Generic Alias Type.
A generic version of collections.abc.MutableMapping.
Deprecated since version 3.9: collections.abc.MutableMapping now supports []. See PEP 585 and Generic Alias Type.
A generic version of collections.abc.MutableSequence.
Deprecated since version 3.9: collections.abc.MutableSequence now supports []. See PEP 585 and Generic Alias Type.
A generic version of collections.abc.MutableSet.
Deprecated since version 3.9: collections.abc.MutableSet now supports []. See PEP 585 and Generic Alias Type.
A generic version of collections.abc.Sequence.
Deprecated since version 3.9: collections.abc.Sequence now supports []. See PEP 585 and Generic Alias Type.
A generic version of collections.abc.ValuesView.
Deprecated since version 3.9: collections.abc.ValuesView now supports []. See PEP 585 and Generic Alias Type.
A generic version of collections.abc.Iterable.
Deprecated since version 3.9: collections.abc.Iterable now supports []. See PEP 585 and Generic Alias Type.
A generic version of collections.abc.Iterator.
Deprecated since version 3.9: collections.abc.Iterator now supports []. See PEP 585 and Generic Alias Type.
A generator can be annotated by the generic type Generator[YieldType, SendType, ReturnType]. For example:
Note that unlike many other generics in the typing module, the SendType of Generator behaves contravariantly, not covariantly or invariantly.
If your generator will only yield values, set the SendType and ReturnType to None:
Alternatively, annotate your generator as having a return type of either Iterable[YieldType] or Iterator[YieldType]:
Deprecated since version 3.9: collections.abc.Generator now supports []. See PEP 585 and Generic Alias Type.
An alias to collections.abc.Hashable
A generic version of collections.abc.Reversible.
Deprecated since version 3.9: collections.abc.Reversible now supports []. See PEP 585 and Generic Alias Type.
An alias to collections.abc.Sized
A generic version of collections.abc.Coroutine. The variance and order of type variables correspond to those of Generator, for example:
New in version 3.5.3.
Deprecated since version 3.9: collections.abc.Coroutine now supports []. See PEP 585 and Generic Alias Type.
An async generator can be annotated by the generic type AsyncGenerator[YieldType, SendType]. For example:
Unlike normal generators, async generators cannot return a value, so there is no ReturnType type parameter. As with Generator, the SendType behaves contravariantly.
If your generator will only yield values, set the SendType to None:
Alternatively, annotate your generator as having a return type of either AsyncIterable[YieldType] or AsyncIterator[YieldType]:
New in version 3.6.1.
Deprecated since version 3.9: collections.abc.AsyncGenerator now supports []. See PEP 585 and Generic Alias Type.
A generic version of collections.abc.AsyncIterable.
New in version 3.5.2.
Deprecated since version 3.9: collections.abc.AsyncIterable now supports []. See PEP 585 and Generic Alias Type.
A generic version of collections.abc.AsyncIterator.
New in version 3.5.2.
Deprecated since version 3.9: collections.abc.AsyncIterator now supports []. See PEP 585 and Generic Alias Type.
A generic version of collections.abc.Awaitable.
New in version 3.5.2.
Deprecated since version 3.9: collections.abc.Awaitable now supports []. See PEP 585 and Generic Alias Type.
A generic version of contextlib.AbstractContextManager.
New in version 3.5.4.
New in version 3.6.0.
Deprecated since version 3.9: contextlib.AbstractContextManager now supports []. See PEP 585 and Generic Alias Type.
A generic version of contextlib.AbstractAsyncContextManager.
New in version 3.5.4.
New in version 3.6.2.
Deprecated since version 3.9: contextlib.AbstractAsyncContextManager now supports []. See PEP 585 and Generic Alias Type.
These protocols are decorated with runtime_checkable().
An ABC with one abstract method __abs__ that is covariant in its return type.
An ABC with one abstract method __bytes__.
An ABC with one abstract method __complex__.
An ABC with one abstract method __float__.
An ABC with one abstract method __index__.
New in version 3.8.
An ABC with one abstract method __int__.
An ABC with one abstract method __round__ that is covariant in its return type.
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).
The @overload decorator allows describing functions and methods that support multiple different combinations of argument types. A series of @overload-decorated definitions must be followed by exactly one non-@overload-decorated definition (for the same function/method). 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. At runtime, calling a @overload-decorated function directly will raise NotImplementedError. An example of overload that gives a more precise type than can be expressed using a union or a type variable:
See PEP 484 for details and comparison with other typing semantics.
A decorator to indicate to type checkers that the decorated method cannot be overridden, and the decorated class cannot be subclassed. For example:
There is no runtime checking of these properties. See PEP 591 for more details.
New in version 3.8.
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.
Decorator to give another decorator the no_type_check() effect.
This wraps the decorator with something that wraps the decorated function in no_type_check().
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:
Note that returning instances of private classes is not recommended. It is usually preferable to make such classes public.
Return a dictionary containing type hints for a function, method, module or class object.
This is often the same as obj.__annotations__. In addition, forward references encoded as string literals are handled by evaluating them in globals and locals namespaces. If necessary, Optional[t] is added for function and method annotations if a default value equal to None is set. For a class C, return a dictionary constructed by merging all the __annotations__ along C.__mro__ in reverse order.
The function recursively replaces all Annotated[T, ...] with T, unless include_extras is set to True (see Annotated for more information). For example:
Changed in version 3.9: Added include_extras parameter as part of PEP 593.
Provide basic introspection for generic types and special typing forms.
For a typing object of the form X[Y, Z, ...] these functions return X and (Y, Z, ...). If X is a generic alias for a builtin or collections class, it gets normalized to the original class. If X is a Union or Literal 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. For unsupported objects return None and () correspondingly. Examples:
New in version 3.8.
A class used for internal typing representation of string forward references. For example, List["SomeClass"] is implicitly transformed into 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 into list[ForwardRef("SomeClass")] and thus will not automatically resolve to list[SomeClass].
New in version 3.7.4.
A special constant that is assumed to be True by 3rd party static type checkers. It is False at runtime. Usage:
The first type annotation must be enclosed in quotes, making it a “forward reference”, to hide the expensive_mod reference from the interpreter runtime. Type annotations for local variables are not evaluated, so the second annotation does not need to be enclosed in quotes.
Note
If from __future__ import annotations is used in Python 3.7 or later, annotations are not evaluated at function definition time. Instead, they are stored as strings in __annotations__, This makes it unnecessary to use quotes around the annotation. (see PEP 563).
New in version 3.5.2.


A generic version of collections.abc.Set.
Deprecated since version 3.9: collections.abc.Set now supports []. See PEP 585 and Generic Alias Type.


A type, introduced in PEP 593 (Flexible function and variable
annotations), to decorate existing types with context-specific metadata (possibly multiple pieces of it, as Annotated is variadic). Specifically, a type T can be annotated with metadata x via the typehint Annotated[T, x]. This metadata can be used for either static analysis or at runtime. If a library (or tool) encounters a typehint Annotated[T, x] and has no special logic for metadata x, it should ignore it and simply treat the type as T. Unlike the no_type_check functionality that currently exists in the typing module which completely disables typechecking annotations on a function or a class, the Annotated type allows for both static typechecking of T (e.g., via mypy or Pyre, which can safely ignore x) together with runtime access to x 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. A tool or library encountering an Annotated type can scan through the annotations to determine if they are of interest (e.g., using 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. For example, if you are doing value range analysis you might allow this:
Passing include_extras=True to get_type_hints() lets one access the extra annotations at runtime.
The details of the syntax:
Multiple type annotations are supported (Annotated supports variadic arguments):
The order of the annotations is preserved and matters for equality checks:
Nested Annotated types are flattened, with metadata ordered starting with the innermost annotation:
Duplicated annotations are not removed:
Annotated can be used with nested and generic aliases:
New in version 3.9.


Special type indicating an unconstrained type.


AnyStr is a type variable defined as AnyStr = 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:


A generic version of contextlib.AbstractAsyncContextManager.
New in version 3.5.4.
New in version 3.6.2.
Deprecated since version 3.9: contextlib.AbstractAsyncContextManager now supports []. See PEP 585 and Generic Alias Type.


An async generator can be annotated by the generic type AsyncGenerator[YieldType, SendType]. For example:
Unlike normal generators, async generators cannot return a value, so there is no ReturnType type parameter. As with Generator, the SendType behaves contravariantly.
If your generator will only yield values, set the SendType to None:
Alternatively, annotate your generator as having a return type of either AsyncIterable[YieldType] or AsyncIterator[YieldType]:
New in version 3.6.1.
Deprecated since version 3.9: collections.abc.AsyncGenerator now supports []. See PEP 585 and Generic Alias Type.


A generic version of collections.abc.AsyncIterable.
New in version 3.5.2.
Deprecated since version 3.9: collections.abc.AsyncIterable now supports []. See PEP 585 and Generic Alias Type.


A generic version of collections.abc.AsyncIterator.
New in version 3.5.2.
Deprecated since version 3.9: collections.abc.AsyncIterator now supports []. See PEP 585 and Generic Alias Type.


A generic version of collections.abc.Awaitable.
New in version 3.5.2.
Deprecated since version 3.9: collections.abc.Awaitable now supports []. See PEP 585 and Generic Alias Type.


Generic type IO[AnyStr] and its subclasses TextIO(IO[str]) and BinaryIO(IO[bytes]) represent the types of I/O streams such as returned by open(). These types are also in the typing.io namespace.


A generic version of collections.abc.ByteString.
This type represents the types bytes, bytearray, and memoryview of byte sequences.
As a shorthand for this type, bytes can be used to annotate arguments of any of the types mentioned above.
Deprecated since version 3.9: collections.abc.ByteString now supports []. See PEP 585 and Generic Alias Type.


Callable type; Callable[[int], str] is a function of (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 returning ReturnType. A plain Callable is equivalent to Callable[..., Any], and in turn to collections.abc.Callable.
Deprecated since version 3.9: collections.abc.Callable now supports []. See PEP 585 and Generic Alias Type.


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).


A generic version of collections.ChainMap.
New in version 3.5.4.
New in version 3.6.1.
Deprecated since version 3.9: collections.ChainMap now supports []. See PEP 585 and Generic Alias Type.


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:
ClassVar accepts only types and cannot be further subscribed.
ClassVar is not a class itself, and should not be used with isinstance() or issubclass(). 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:
New in version 3.5.3.


A generic version of collections.abc.Collection
New in version 3.6.0.
Deprecated since version 3.9: collections.abc.Collection now supports []. See PEP 585 and Generic Alias Type.


A generic version of collections.abc.Container.
Deprecated since version 3.9: collections.abc.Container now supports []. See PEP 585 and Generic Alias Type.


A generic version of contextlib.AbstractContextManager.
New in version 3.5.4.
New in version 3.6.0.
Deprecated since version 3.9: contextlib.AbstractContextManager now supports []. See PEP 585 and Generic Alias Type.


A generic version of collections.abc.Coroutine. The variance and order of type variables correspond to those of Generator, for example:
New in version 3.5.3.
Deprecated since version 3.9: collections.abc.Coroutine now supports []. See PEP 585 and Generic Alias Type.


A generic version of collections.Counter.
New in version 3.5.4.
New in version 3.6.1.
Deprecated since version 3.9: collections.Counter now supports []. See PEP 585 and Generic Alias Type.


A generic version of collections.defaultdict.
New in version 3.5.2.
Deprecated since version 3.9: collections.defaultdict now supports []. See PEP 585 and Generic Alias Type.


A generic version of collections.deque.
New in version 3.5.4.
New in version 3.6.1.
Deprecated since version 3.9: collections.deque now supports []. See PEP 585 and Generic Alias Type.


A generic version of dict. Useful for annotating return types. To annotate arguments it is preferred to use an abstract collection type such as Mapping.
This type can be used as follows:
Deprecated since version 3.9: builtins.dict now supports []. See PEP 585 and Generic Alias Type.


A special typing construct to indicate to type checkers that a name cannot be re-assigned or overridden in a subclass. For example:
There is no runtime checking of these properties. See PEP 591 for more details.
New in version 3.8.


A decorator to indicate to type checkers that the decorated method cannot be overridden, and the decorated class cannot be subclassed. For example:
There is no runtime checking of these properties. See PEP 591 for more details.
New in version 3.8.


A class used for internal typing representation of string forward references. For example, List["SomeClass"] is implicitly transformed into 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 into list[ForwardRef("SomeClass")] and thus will not automatically resolve to list[SomeClass].
New in version 3.7.4.


A generic version of builtins.frozenset.
Deprecated since version 3.9: builtins.frozenset now supports []. See PEP 585 and Generic Alias Type.


A generator can be annotated by the generic type Generator[YieldType, SendType, ReturnType]. For example:
Note that unlike many other generics in the typing module, the SendType of Generator behaves contravariantly, not covariantly or invariantly.
If your generator will only yield values, set the SendType and ReturnType to None:
Alternatively, annotate your generator as having a return type of either Iterable[YieldType] or Iterator[YieldType]:
Deprecated since version 3.9: collections.abc.Generator now supports []. See PEP 585 and Generic Alias Type.


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:
This class can then be used as follows:


Provide basic introspection for generic types and special typing forms.
For a typing object of the form X[Y, Z, ...] these functions return X and (Y, Z, ...). If X is a generic alias for a builtin or collections class, it gets normalized to the original class. If X is a Union or Literal 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. For unsupported objects return None and () correspondingly. Examples:
New in version 3.8.


Return a dictionary containing type hints for a function, method, module or class object.
This is often the same as obj.__annotations__. In addition, forward references encoded as string literals are handled by evaluating them in globals and locals namespaces. If necessary, Optional[t] is added for function and method annotations if a default value equal to None is set. For a class C, return a dictionary constructed by merging all the __annotations__ along C.__mro__ in reverse order.
The function recursively replaces all Annotated[T, ...] with T, unless include_extras is set to True (see Annotated for more information). For example:
Changed in version 3.9: Added include_extras parameter as part of PEP 593.


Generic type IO[AnyStr] and its subclasses TextIO(IO[str]) and BinaryIO(IO[bytes]) represent the types of I/O streams such as returned by open(). These types are also in the typing.io namespace.


A generic version of collections.abc.ItemsView.
Deprecated since version 3.9: collections.abc.ItemsView now supports []. See PEP 585 and Generic Alias Type.


A generic version of collections.abc.Iterable.
Deprecated since version 3.9: collections.abc.Iterable now supports []. See PEP 585 and Generic Alias Type.


A generic version of collections.abc.Iterator.
Deprecated since version 3.9: collections.abc.Iterator now supports []. See PEP 585 and Generic Alias Type.


A generic version of collections.abc.KeysView.
Deprecated since version 3.9: collections.abc.KeysView now supports []. See PEP 585 and Generic Alias Type.


Generic version of list. Useful for annotating return types. To annotate arguments it is preferred to use an abstract collection type such as Sequence or Iterable.
This type may be used as follows:
Deprecated since version 3.9: builtins.list now supports []. See PEP 585 and Generic Alias Type.


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:
Literal[...] cannot be subclassed. At runtime, an arbitrary value is allowed as type argument to Literal[...], but type checkers may impose restrictions. See PEP 586 for more details about literal types.
New in version 3.8.
Changed in version 3.9.1: Literal now de-duplicates parameters. Equality comparison of Literal objects are no longer order dependent. Literal objects will now raise a TypeError exception during equality comparisons if one of their parameters are not immutable.


A generic version of collections.abc.Mapping. This type can be used as follows:
Deprecated since version 3.9: collections.abc.Mapping now supports []. See PEP 585 and Generic Alias Type.


A generic version of collections.abc.MappingView.
Deprecated since version 3.9: collections.abc.MappingView now supports []. See PEP 585 and Generic Alias Type.


These type aliases correspond to the return types from re.compile() and re.match(). These types (and the corresponding functions) are generic in AnyStr and can be made specific by writing Pattern[str], Pattern[bytes], Match[str], or Match[bytes]. These types are also in the typing.re namespace.
Deprecated since version 3.9: Classes Pattern and Match from re now support []. See PEP 585 and Generic Alias Type.


A generic version of collections.abc.MutableMapping.
Deprecated since version 3.9: collections.abc.MutableMapping now supports []. See PEP 585 and Generic Alias Type.


A generic version of collections.abc.MutableSequence.
Deprecated since version 3.9: collections.abc.MutableSequence now supports []. See PEP 585 and Generic Alias Type.


A generic version of collections.abc.MutableSet.
Deprecated since version 3.9: collections.abc.MutableSet now supports []. See PEP 585 and Generic Alias Type.


Typed version of collections.namedtuple().
Usage:
This is equivalent to:
To give a field a default value, you can assign to it in the class body:
Fields 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. (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.)
NamedTuple subclasses can also have docstrings and methods:
Backward-compatible usage:
Changed in version 3.6: Added support for PEP 526 variable annotation syntax.
Changed in version 3.6.1: Added support for default values, methods, and docstrings.
Changed in version 3.8: The _field_types and __annotations__ attributes are now regular dictionaries instead of instances of OrderedDict.
Changed in version 3.9: Removed the _field_types attribute in favor of the more standard __annotations__ attribute which has the same information.


A helper function to indicate a distinct type to a typechecker, see NewType. At runtime it returns a function that returns its argument. Usage:
New in version 3.5.2.


Special type indicating that a function never returns. For example:
New in version 3.5.4.
New in version 3.6.2.


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.


Decorator to give another decorator the no_type_check() effect.
This wraps the decorator with something that wraps the decorated function in no_type_check().


Optional type.
Optional[X] is equivalent to Union[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. For example:
On the other hand, if an explicit value of None is allowed, the use of Optional is appropriate, whether the argument is optional or not. For example:


A generic version of collections.OrderedDict.
New in version 3.7.2.
Deprecated since version 3.9: collections.OrderedDict now supports []. See PEP 585 and Generic Alias Type.


The @overload decorator allows describing functions and methods that support multiple different combinations of argument types. A series of @overload-decorated definitions must be followed by exactly one non-@overload-decorated definition (for the same function/method). 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. At runtime, calling a @overload-decorated function directly will raise NotImplementedError. An example of overload that gives a more precise type than can be expressed using a union or a type variable:
See PEP 484 for details and comparison with other typing semantics.


Base class for protocol classes. Protocol classes are defined like this:
Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing), for example:
See PEP 544 for details. 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.
Protocol classes can be generic, for example:
New in version 3.8.


A generic version of collections.abc.Reversible.
Deprecated since version 3.9: collections.abc.Reversible now supports []. See PEP 585 and Generic Alias Type.


Mark a protocol class as a runtime protocol.
Such a protocol can be used with isinstance() and issubclass(). This raises TypeError when applied to a non-protocol class. This allows a simple-minded structural check, very similar to “one trick ponies” in collections.abc such as Iterable. For example:
Note
runtime_checkable() will check only the presence of the required methods, not their type signatures! For example, builtins.complex implements __float__(), therefore it passes an issubclass() check against SupportsFloat. However, the complex.__float__ method exists only to raise a TypeError with a more informative message.
New in version 3.8.


A generic version of collections.abc.Sequence.
Deprecated since version 3.9: collections.abc.Sequence now supports []. See PEP 585 and Generic Alias Type.


A generic version of builtins.set. Useful for annotating return types. To annotate arguments it is preferred to use an abstract collection type such as AbstractSet.
Deprecated since version 3.9: builtins.set now supports []. See PEP 585 and Generic Alias Type.


An ABC with one abstract method __abs__ that is covariant in its return type.


An ABC with one abstract method __bytes__.


An ABC with one abstract method __complex__.


An ABC with one abstract method __float__.


An ABC with one abstract method __index__.
New in version 3.8.


An ABC with one abstract method __int__.


An ABC with one abstract method __round__ that is covariant in its return type.


Text is an alias for str. It is provided to supply a forward compatible path for Python 2 code: in Python 2, Text is an alias for 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:
New in version 3.5.2.


Generic type IO[AnyStr] and its subclasses TextIO(IO[str]) and BinaryIO(IO[bytes]) represent the types of I/O streams such as returned by open(). These types are also in the typing.io namespace.


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. The type of the empty tuple can be written as Tuple[()].
Example: Tuple[T1, T2] is a tuple of two elements corresponding to type variables T1 and T2. Tuple[int, float, str] is a tuple of an int, a float and a string.
To specify a variable-length tuple of homogeneous type, use literal ellipsis, e.g. Tuple[int, ...]. A plain Tuple is equivalent to Tuple[Any, ...], and in turn to tuple.
Deprecated since version 3.9: builtins.tuple now supports []. See PEP 585 and Generic Alias Type.


A variable annotated with C may accept a value of type C. In contrast, a variable annotated with Type[C] may accept values that are classes themselves – specifically, it will accept the class object of C. For example:
Note that Type[C] is covariant:
The fact that Type[C] is covariant implies that all subclasses of C should implement the same constructor signature and class method signatures as C. 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 for Type are classes, Any, type variables, and unions of any of these types. For example:
Type[Any] is equivalent to Type which in turn is equivalent to type, which is the root of Python’s metaclass hierarchy.
New in version 3.5.2.
Deprecated since version 3.9: builtins.type now supports []. See PEP 585 and Generic Alias Type.


Special construct to add type hints to a dictionary. At runtime it is a plain 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:
The type info for introspection can be accessed via Point2D.__annotations__ and Point2D.__total__. To allow using this feature with older versions of Python that do not support PEP 526, TypedDict supports two additional equivalent syntactic forms:
By default, all keys must be present in a TypedDict. It is possible to override this by specifying totality. Usage:
This means that a point2D TypedDict can have any of the keys omitted. A type checker is only expected to support a literal False or True as the value of the total argument. True is the default, and makes all items defined in the class body be required.
See PEP 589 for more examples and detailed rules of using TypedDict.
New in version 3.8.


Type variable.
Usage:
Type 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 functions work as follows:
The latter example’s signature is essentially the overloading of (str, str) -> str and (bytes, bytes) -> bytes. Also note that if the arguments are instances of some subclass of str, the return type is still plain str.
At runtime, isinstance(x, T) will raise TypeError. In general, isinstance() and issubclass() should not be used with types.
Type variables may be marked covariant or contravariant by passing covariant=True or contravariant=True. See PEP 484 for more details. By default type variables are invariant. Alternatively, a type variable may specify an upper bound using bound=<type>. This means that an actual type substituted (explicitly or implicitly) for the type variable must be a subclass of the boundary type, see PEP 484.


A special constant that is assumed to be True by 3rd party static type checkers. It is False at runtime. Usage:
The first type annotation must be enclosed in quotes, making it a “forward reference”, to hide the expensive_mod reference from the interpreter runtime. Type annotations for local variables are not evaluated, so the second annotation does not need to be enclosed in quotes.
Note
If from __future__ import annotations is used in Python 3.7 or later, annotations are not evaluated at function definition time. Instead, they are stored as strings in __annotations__, This makes it unnecessary to use quotes around the annotation. (see PEP 563).
New in version 3.5.2.


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:
Note that returning instances of private classes is not recommended. It is usually preferable to make such classes public.


Union type; Union[X, Y] means either X or Y.
To define a union, use e.g. Union[int, str]. Details:
Unions of unions are flattened, e.g.:
Unions of a single argument vanish, e.g.:
Redundant arguments are skipped, e.g.:
When comparing unions, the argument order is ignored, e.g.:
Changed in version 3.7: Don’t remove explicit subclasses from unions at runtime.


A generic version of collections.abc.ValuesView.
Deprecated since version 3.9: collections.abc.ValuesView now supports []. See PEP 585 and Generic Alias Type.


Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable. This is a subclass of NameError.


This module provides access to the Unicode Character Database (UCD) which defines character properties for all Unicode characters. The data contained in this database is compiled from the UCD version 13.0.0.
The module uses the same names and symbols as defined by Unicode Standard Annex #44, “Unicode Character Database”. It defines the following functions:
Look up character by name. If a character with the given name is found, return the corresponding character. If not found, KeyError is raised.
Changed in version 3.3: Support for name aliases 1 and named sequences 2 has been added.
Returns the name assigned to the character chr as a string. If no name is defined, default is returned, or, if not given, ValueError is raised.
Returns the decimal value assigned to the character chr as integer. If no such value is defined, default is returned, or, if not given, ValueError is raised.
Returns the digit value assigned to the character chr as integer. If no such value is defined, default is returned, or, if not given, ValueError is raised.
Returns the numeric value assigned to the character chr as float. If no such value is defined, default is returned, or, if not given, ValueError is raised.
Returns the general category assigned to the character chr as string.
Returns the bidirectional class assigned to the character chr as string. If no such value is defined, an empty string is returned.
Returns the canonical combining class assigned to the character chr as integer. Returns 0 if no combining class is defined.
Returns the east asian width assigned to the character chr as string.
Returns the mirrored property assigned to the character chr as integer. Returns 1 if the character has been identified as a “mirrored” character in bidirectional text, 0 otherwise.
Returns the character decomposition mapping assigned to the character chr as string. An empty string is returned in case no such mapping is defined.
Return the normal form form for the Unicode string unistr. Valid values for form are ‘NFC’, ‘NFKC’, ‘NFD’, and ‘NFKD’.
The Unicode standard defines various normalization forms of a Unicode string, based on the definition of canonical equivalence and compatibility equivalence. In Unicode, several characters can be expressed in various way. For example, the character U+00C7 (LATIN CAPITAL LETTER C WITH CEDILLA) can also be expressed as the sequence U+0043 (LATIN CAPITAL LETTER C) U+0327 (COMBINING CEDILLA).
For each character, there are two normal forms: normal form C and normal form D. Normal form D (NFD) is also known as canonical decomposition, and translates each character into its decomposed form. Normal form C (NFC) first applies a canonical decomposition, then composes pre-combined characters again.
In addition to these two forms, there are two additional normal forms based on compatibility equivalence. In Unicode, certain characters are supported which normally would be unified with other characters. For example, U+2160 (ROMAN NUMERAL ONE) is really the same thing as U+0049 (LATIN CAPITAL LETTER I). However, it is supported in Unicode for compatibility with existing character sets (e.g. gb2312).
The normal form KD (NFKD) will apply the compatibility decomposition, i.e. replace all compatibility characters with their equivalents. The normal form KC (NFKC) first applies the compatibility decomposition, followed by the canonical composition.
Even if two unicode strings are normalized and look the same to a human reader, if one has combining characters and the other doesn’t, they may not compare equal.
Return whether the Unicode string unistr is in the normal form form. Valid values for form are ‘NFC’, ‘NFKC’, ‘NFD’, and ‘NFKD’.
New in version 3.8.
In addition, the module exposes the following constant:
The version of the Unicode database used in this module.
This is an object that has the same methods as the entire module, but uses the Unicode database version 3.2 instead, for applications that require this specific version of the Unicode database (such as IDNA).
Examples:
https://www.unicode.org/Public/13.0.0/ucd/NameAliases.txt
https://www.unicode.org/Public/13.0.0/ucd/NamedSequences.txt


Returns the bidirectional class assigned to the character chr as string. If no such value is defined, an empty string is returned.


Returns the general category assigned to the character chr as string.


Returns the canonical combining class assigned to the character chr as integer. Returns 0 if no combining class is defined.


Returns the decimal value assigned to the character chr as integer. If no such value is defined, default is returned, or, if not given, ValueError is raised.


Returns the character decomposition mapping assigned to the character chr as string. An empty string is returned in case no such mapping is defined.


Returns the digit value assigned to the character chr as integer. If no such value is defined, default is returned, or, if not given, ValueError is raised.


Returns the east asian width assigned to the character chr as string.


Return whether the Unicode string unistr is in the normal form form. Valid values for form are ‘NFC’, ‘NFKC’, ‘NFD’, and ‘NFKD’.
New in version 3.8.


Look up character by name. If a character with the given name is found, return the corresponding character. If not found, KeyError is raised.
Changed in version 3.3: Support for name aliases 1 and named sequences 2 has been added.


Returns the mirrored property assigned to the character chr as integer. Returns 1 if the character has been identified as a “mirrored” character in bidirectional text, 0 otherwise.


Returns the name assigned to the character chr as a string. If no name is defined, default is returned, or, if not given, ValueError is raised.


Return the normal form form for the Unicode string unistr. Valid values for form are ‘NFC’, ‘NFKC’, ‘NFD’, and ‘NFKD’.
The Unicode standard defines various normalization forms of a Unicode string, based on the definition of canonical equivalence and compatibility equivalence. In Unicode, several characters can be expressed in various way. For example, the character U+00C7 (LATIN CAPITAL LETTER C WITH CEDILLA) can also be expressed as the sequence U+0043 (LATIN CAPITAL LETTER C) U+0327 (COMBINING CEDILLA).
For each character, there are two normal forms: normal form C and normal form D. Normal form D (NFD) is also known as canonical decomposition, and translates each character into its decomposed form. Normal form C (NFC) first applies a canonical decomposition, then composes pre-combined characters again.
In addition to these two forms, there are two additional normal forms based on compatibility equivalence. In Unicode, certain characters are supported which normally would be unified with other characters. For example, U+2160 (ROMAN NUMERAL ONE) is really the same thing as U+0049 (LATIN CAPITAL LETTER I). However, it is supported in Unicode for compatibility with existing character sets (e.g. gb2312).
The normal form KD (NFKD) will apply the compatibility decomposition, i.e. replace all compatibility characters with their equivalents. The normal form KC (NFKC) first applies the compatibility decomposition, followed by the canonical composition.
Even if two unicode strings are normalized and look the same to a human reader, if one has combining characters and the other doesn’t, they may not compare equal.


Returns the numeric value assigned to the character chr as float. If no such value is defined, default is returned, or, if not given, ValueError is raised.


This is an object that has the same methods as the entire module, but uses the Unicode database version 3.2 instead, for applications that require this specific version of the Unicode database (such as IDNA).


The version of the Unicode database used in this module.


Raised when a Unicode-related error occurs during decoding. It is a subclass of UnicodeError.


Raised when a Unicode-related error occurs during encoding. It is a subclass of UnicodeError.


Raised when a Unicode-related encoding or decoding error occurs. It is a subclass of ValueError.
UnicodeError has attributes that describe the encoding or decoding error. For example, err.object[err.start:err.end] gives the particular invalid input that the codec failed on.
The name of the encoding that raised the error.
A string describing the specific codec error.
The object the codec was attempting to encode or decode.
The first index of invalid data in object.
The index after the last invalid data in object.


The name of the encoding that raised the error.


The index after the last invalid data in object.


The object the codec was attempting to encode or decode.


A string describing the specific codec error.


The first index of invalid data in object.


Raised when a Unicode-related error occurs during translating. It is a subclass of UnicodeError.


Base class for warnings related to Unicode.