typing#
Classes
Add context-specific metadata to a type. |
|
Special type indicating an unconstrained type. |
|
Internal wrapper to hold a forward reference. |
|
Abstract base class for generic types. |
|
Parameter specification variable. |
|
Base class for protocol classes. |
|
Type variable. |
|
Type variable tuple. |
|
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__. |
|
An ABC with one abstract method __int__. |
|
An ABC with one abstract method __round__ that is covariant in its return type. |
|
Typed version of the return of open() in binary mode. |
|
Generic base class for TextIO and BinaryIO. |
|
Typed version of the return of open() in text mode. |
|
NewType creates simple unique types with almost zero runtime overhead. |
|
The args for a ParamSpec object. |
|
The kwargs for a ParamSpec object. |
|
alias of |
Functions
Typed version of namedtuple. |
|
A simple typed namespace. |
|
Ask a static type checker to confirm that the value is of the given type. |
|
Statically assert that a line of code is unreachable. |
|
Cast a value to a type. |
|
Clear all overloads in the registry. |
|
Decorator to mark an object as providing dataclass-like behaviour. |
|
Decorator to indicate final methods and final classes. |
|
Get type arguments with all substitutions performed. |
|
Get the unsubscripted version of a type. |
|
Return all defined overloads for func as a sequence. |
|
Return type hints for an object. |
|
Check if an annotation is a TypedDict class. |
|
Decorator to indicate that annotations are not type hints. |
|
Decorator to give another decorator the @no_type_check effect. |
|
Decorator for overloaded functions/methods. |
|
Ask a static type checker to reveal the inferred type of an expression. |
|
Mark a protocol class as a runtime protocol. |
The typing module: Support for gradual typing as defined by PEP 484 and subsequent PEPs.
Among other things, the module includes the following: * Generic, Protocol, and internal machinery to support generic aliases.
All subscripted types like X[int], Union[int, str] are generic aliases.
Various “special forms” that have unique meanings in type annotations: NoReturn, Never, ClassVar, Self, Concatenate, Unpack, and others.
Classes whose instances can be type arguments to generic classes and functions: TypeVar, ParamSpec, TypeVarTuple.
Public helper functions: get_type_hints, overload, cast, final, and others.
Several protocols to support duck-typing: SupportsFloat, SupportsIndex, SupportsAbs, and others.
Special types: NewType, NamedTuple, TypedDict.
Deprecated wrapper submodules for re and io related types.
Deprecated aliases for builtin types and collections.abc ABCs.
Any name not present in __all__ is an implementation detail that may be changed without notice. Use at your own risk!
- class typing.Annotated(*args, **kwargs)#
Bases:
object
Add context-specific metadata to a type.
Example: Annotated[int, runtime_check.Unsigned] indicates to the hypothetical runtime_check module that this type is an unsigned int. Every other consumer of this type can ignore this metadata and treat this type as int.
The first argument to Annotated must be a valid type.
Details:
It’s an error to call Annotated with less than two arguments.
Access the metadata via the
__metadata__
attribute:assert Annotated[int, '$'].__metadata__ == ('$',)
Nested Annotated types are flattened:
assert Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
Instantiating an annotated type is equivalent to instantiating the
underlying type:
assert Annotated[C, Ann1](5) == C(5)
Annotated can be used as a generic type alias:
Optimized: TypeAlias = Annotated[T, runtime.Optimize()] assert Optimized[int] == Annotated[int, runtime.Optimize()] OptimizedList: TypeAlias = Annotated[list[T], runtime.Optimize()] assert OptimizedList[int] == Annotated[list[int], runtime.Optimize()]
Annotated cannot be used with an unpacked TypeVarTuple:
Variadic: TypeAlias = Annotated[*Ts, Ann1] # NOT valid
This would be equivalent to:
Annotated[T1, T2, T3, ..., Ann1]
where T1, T2 etc. are TypeVars, which would be invalid, because only one type should be passed to Annotated.
- class typing.Any(*args, **kwargs)#
Bases:
object
Special type indicating an unconstrained type.
Any is compatible with every type.
Any assumed to have all methods.
All values assumed to be instances of Any.
Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance checks.
- class typing.ForwardRef(arg, is_argument=True, module=None, *, is_class=False)#
Bases:
_Final
Internal wrapper to hold a forward reference.
- class typing.Generic#
Bases:
object
Abstract base class for generic types.
A generic type is typically declared by inheriting from this class parameterized 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:
def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT: try: return mapping[key] except KeyError: return default
- class typing.IO#
Bases:
Generic
Generic base class for TextIO and BinaryIO.
This is an abstract, generic version of the return of open().
NOTE: This does not distinguish between the different possible classes (text vs. binary, read vs. write vs. read/write, append-only, unbuffered). The TextIO and BinaryIO subclasses below capture the distinctions between text vs. binary, which is pervasive in the interface; however we currently do not offer a way to track the other distinctions in the type system.
- class typing.NewType(name, tp)#
Bases:
object
NewType creates simple unique types with almost zero runtime overhead.
NewType(name, tp) is considered a subtype of tp by static type checkers. At runtime, NewType(name, tp) returns a dummy callable that simply returns its argument.
Usage:
UserId = NewType('UserId', int) def name_by_id(user_id: UserId) -> str: ... UserId('user') # Fails type check name_by_id(42) # Fails type check name_by_id(UserId(42)) # OK num = UserId(5) + 1 # type: int
- class typing.ParamSpec(name, *, bound=None, covariant=False, contravariant=False)#
Bases:
_Final
,_Immutable
,_BoundVarianceMixin
,_PickleUsingNameMixin
Parameter specification variable.
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. See class Generic for more information on generic types. An example for annotating a decorator: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 + y
Parameter specification variables can be introspected. e.g.:
P.__name__ == ‘P’
Note that only parameter specification variables defined in global scope can be pickled.
- class typing.ParamSpecArgs(origin)#
Bases:
_Final
,_Immutable
The args for a ParamSpec object.
Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.
ParamSpecArgs objects have a reference back to their ParamSpec:
P.args.__origin__ is P
This type is meant for runtime introspection and has no special meaning to static type checkers.
- class typing.ParamSpecKwargs(origin)#
Bases:
_Final
,_Immutable
The kwargs for a ParamSpec object.
Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.
ParamSpecKwargs objects have a reference back to their ParamSpec:
P.kwargs.__origin__ is P
This type is meant for runtime introspection and has no special meaning to static type checkers.
- class typing.Protocol#
Bases:
Generic
Base class for protocol classes.
Protocol classes are defined as:
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 check
See PEP 544 for details. Protocol classes decorated with @typing.runtime_checkable act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures. Protocol classes can be generic, they are defined as:
class GenProto(Protocol[T]): def meth(self) -> T: ...
- class typing.SupportsAbs(*args, **kwargs)#
Bases:
Protocol
An ABC with one abstract method __abs__ that is covariant in its return type.
- class typing.SupportsBytes(*args, **kwargs)#
Bases:
Protocol
An ABC with one abstract method __bytes__.
- class typing.SupportsComplex(*args, **kwargs)#
Bases:
Protocol
An ABC with one abstract method __complex__.
- class typing.SupportsFloat(*args, **kwargs)#
Bases:
Protocol
An ABC with one abstract method __float__.
- class typing.SupportsIndex(*args, **kwargs)#
Bases:
Protocol
An ABC with one abstract method __index__.
- class typing.SupportsRound(*args, **kwargs)#
Bases:
Protocol
An ABC with one abstract method __round__ that is covariant in its return type.
- typing.Text#
alias of
str
- class typing.TypeVar(name, *constraints, bound=None, covariant=False, contravariant=False)#
Bases:
_Final
,_Immutable
,_BoundVarianceMixin
,_PickleUsingNameMixin
Type variable.
Usage:
T = TypeVar('T') # Can be anything A = TypeVar('A', str, bytes) # Must be str or bytes
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 class Generic for more information on generic types. Generic functions work as follows:
- def repeat(x: T, n: int) -> List[T]:
‘’’Return a list containing n references to x.’’’ return [x]*n
- def longest(x: A, y: A) -> A:
‘’’Return the longest of two strings.’’’ return x if len(x) >= len(y) else y
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) and issubclass(C, T) will raise TypeError.
Type variables defined with covariant=True or contravariant=True can be used to declare covariant or contravariant generic types. See PEP 484 for more details. By default generic types are invariant in all type variables.
Type variables can be introspected. e.g.:
T.__name__ == ‘T’ T.__constraints__ == () T.__covariant__ == False T.__contravariant__ = False A.__constraints__ == (str, bytes)
Note that only type variables defined in global scope can be pickled.
- class typing.TypeVarTuple(name)#
Bases:
_Final
,_Immutable
,_PickleUsingNameMixin
Type variable tuple.
Usage:
Ts = TypeVarTuple(‘Ts’) # Can be given any name
Just as a TypeVar (type variable) is a placeholder for a single type, a TypeVarTuple is a placeholder for an arbitrary number of types. For example, if we define a generic class using a TypeVarTuple:
class C(Generic[*Ts]): …
Then we can parameterize that class with an arbitrary number of type arguments:
C[int] # Fine C[int, str] # Also fine C[()] # Even this is fine
For more details, see PEP 646.
Note that only TypeVarTuples defined in global scope can be pickled.
- typing.NamedTuple(typename, fields=None, /, **kwargs)#
Typed version of namedtuple.
Usage:
class Employee(NamedTuple): name: str id: int
This is equivalent to:
Employee = collections.namedtuple('Employee', ['name', 'id'])
The resulting class has an extra __annotations__ attribute, giving a dict that maps field names to types. (The field names are also in the _fields attribute, which is part of the namedtuple API.) An alternative equivalent functional syntax is also accepted:
Employee = NamedTuple('Employee', [('name', str), ('id', int)])
- typing.TypedDict(typename, fields=None, /, *, total=True, **kwargs)#
A simple typed namespace. At runtime it is equivalent to a plain dict.
TypedDict creates a dictionary type such that a type checker will expect all 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.
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 >>> Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first') True
The type info can be accessed via the Point2D.__annotations__ dict, and the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets. TypedDict supports an additional equivalent form:
Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
By default, all keys must be present in a TypedDict. It is possible to override this by specifying totality:
class Point2D(TypedDict, total=False): x: int y: int
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.
The Required and NotRequired special forms can also be used to mark individual keys as being required or not required:
class Point2D(TypedDict): x: int # the "x" key must always be present (Required is the default) y: NotRequired[int] # the "y" key can be omitted
See PEP 655 for more details on Required and NotRequired.
- typing.assert_never(arg, /)#
Statically assert that a line of code is unreachable.
Example:
def int_or_str(arg: int | str) -> None: match arg: case int(): print("It's an int") case str(): print("It's a str") case _: assert_never(arg)
If a type checker finds that a call to assert_never() is reachable, it will emit an error.
At runtime, this throws an exception when called.
- Parameters:
arg (
Never
)- Return type:
Never
- typing.assert_type(val, typ, /)#
Ask a static type checker to confirm that the value is of the given type.
At runtime this does nothing: it returns the first argument unchanged with no checks or side effects, no matter the actual type of the argument.
When a static type checker encounters a call to assert_type(), it emits an error if the value is not of the specified type:
def greet(name: str) -> None: assert_type(name, str) # OK assert_type(name, int) # type checker error
- 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.clear_overloads()#
Clear all overloads in the registry.
- typing.dataclass_transform(*, eq_default=True, order_default=False, kw_only_default=False, field_specifiers=(), **kwargs)#
Decorator to mark an object as providing dataclass-like behaviour.
The decorator can be applied to a function, class, or metaclass.
Example usage with a decorator function:
T = TypeVar("T") @dataclass_transform() def create_model(cls: type[T]) -> type[T]: ... return cls @create_model class CustomerModel: id: int name: str
On a base class:
@dataclass_transform() class ModelBase: ... class CustomerModel(ModelBase): id: int name: str
On a metaclass:
@dataclass_transform() class ModelMeta(type): ... class ModelBase(metaclass=ModelMeta): ... class CustomerModel(ModelBase): id: int name: str
The
CustomerModel
classes defined above will be treated by type checkers similarly to classes created with@dataclasses.dataclass
. For example, type checkers will assume these classes have__init__
methods that acceptid
andname
.The arguments to this decorator can be used to customize this behavior: -
eq_default
indicates whether theeq
parameter is assumed to beTrue
orFalse
if it is omitted by the caller.order_default
indicates whether theorder
parameter isassumed to be True or False if it is omitted by the caller.
kw_only_default
indicates whether thekw_only
parameter isassumed to be True or False if it is omitted by the caller.
field_specifiers
specifies a static list of supported classesor functions that describe fields, similar to
dataclasses.field()
.
- Arbitrary other keyword arguments are accepted in order to allow for
possible future extensions.
At runtime, this decorator records its arguments in the
__dataclass_transform__
attribute on the decorated object. It has no other runtime effect.See PEP 681 for more details.
- typing.final(f)#
Decorator to indicate final methods and final classes.
Use this decorator to indicate to type checkers that the decorated method cannot be overridden, and 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. The decorator attempts to set the
__final__
attribute toTrue
on the decorated object to allow runtime introspection.
- typing.get_args(tp)#
Get type arguments with all substitutions performed.
For unions, basic simplifications used by Union constructor are performed.
Examples:
>>> T = TypeVar('T') >>> assert get_args(Dict[str, int]) == (str, int) >>> assert get_args(int) == () >>> assert get_args(Union[int, Union[T, int], str][int]) == (int, str) >>> assert get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) >>> assert get_args(Callable[[], T][int]) == ([], int)
- typing.get_origin(tp)#
Get the unsubscripted version of a type.
This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar, Annotated, and others. Return None for unsupported types.
Examples:
>>> P = ParamSpec('P') >>> assert get_origin(Literal[42]) is Literal >>> assert get_origin(int) is None >>> assert get_origin(ClassVar[int]) is ClassVar >>> assert get_origin(Generic) is Generic >>> assert get_origin(Generic[T]) is Generic >>> assert get_origin(Union[T, int]) is Union >>> assert get_origin(List[Tuple[T, T]][int]) is list >>> assert get_origin(P.args) is P
- typing.get_overloads(func)#
Return all defined overloads for func as a sequence.
- typing.get_type_hints(obj, globalns=None, localns=None, include_extras=False)#
Return type hints for an object.
This is often the same as obj.__annotations__, but it handles forward references encoded as string literals and recursively replaces all ‘Annotated[T, …]’ with ‘T’ (unless ‘include_extras=True’).
The argument may be a module, class, method, or function. The annotations are returned as a dictionary. For classes, annotations include also inherited members.
TypeError is raised if the argument is not of a type that can contain annotations, and an empty dictionary is returned if no annotations are present.
BEWARE – the behavior of globalns and localns is counterintuitive (unless you are familiar with how eval() and exec() work). The search order is locals first, then globals.
If no dict arguments are passed, an attempt is made to use the globals from obj (or the respective module’s globals for classes), and these are also used as the locals. If the object does not appear to have globals, an empty dictionary is used. For classes, the search order is globals first then locals.
If one dict argument is passed, it is used for both globals and locals.
If two dict arguments are passed, they specify globals and locals, respectively.
- typing.is_typeddict(tp)#
Check if an annotation is a TypedDict class.
For example:
>>> from typing import TypedDict >>> class Film(TypedDict): ... title: str ... year: int ... >>> is_typeddict(Film) True >>> is_typeddict(dict) False
- typing.no_type_check(arg)#
Decorator to indicate that annotations are not type hints.
The argument must be a class or function; if it is a class, it applies recursively to all methods and classes defined in that class (but not to methods defined in its superclasses or subclasses).
This mutates the function(s) or class(es) in place.
- typing.no_type_check_decorator(decorator)#
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.
- typing.overload(func)#
Decorator for overloaded functions/methods.
In a stub file, place two or more stub definitions for the same function in a row, each decorated with @overload.
For example:
@overload def utf8(value: None) -> None: ... @overload def utf8(value: bytes) -> bytes: ... @overload def utf8(value: str) -> bytes: ...
In a non-stub file (i.e. a regular .py file), do the same but follow it with an implementation. The implementation should not be decorated with @overload:
@overload def utf8(value: None) -> None: ... @overload def utf8(value: bytes) -> bytes: ... @overload def utf8(value: str) -> bytes: ... def utf8(value): ... # implementation goes here
The overloads for a function can be retrieved at runtime using the get_overloads() function.
- typing.reveal_type(obj, /)#
Ask a static type checker to reveal the inferred type of an expression.
When a static type checker encounters a call to
reveal_type()
, it will emit the inferred type of the argument:x: int = 1 reveal_type(x)
Running a static type checker (e.g., mypy) on this example will produce output similar to ‘Revealed type is “builtins.int”’.
At runtime, the function prints the runtime type of the argument and returns the argument unchanged.
- typing.runtime_checkable(cls)#
Mark a protocol class as a runtime protocol.
Such protocol can be used with isinstance() and issubclass(). Raise TypeError if 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:
@runtime_checkable class Closable(Protocol): def close(self): ... assert isinstance(open('/some/file'), Closable)
Warning: this will check only the presence of the required methods, not their type signatures!