typing module

typing.ABCMeta(name, bases, namespace, **kwargs)

Metaclass for defining Abstract Base Classes (ABCs).

typing.BinaryIO(*args, **kwds)

Typed version of the return of open() in binary mode.

typing.ForwardRef(arg[, is_argument])

Internal wrapper to hold a forward reference.

typing.Generic(*args, **kwds)

Abstract base class for generic types.

typing.IO(*args, **kwds)

Generic base class for TextIO and BinaryIO.

typing.NamedTuple(typename[, fields])

Typed version of namedtuple.

typing.NamedTupleMeta(typename, bases, ns)

typing.Protocol(*args, **kwds)

Base class for protocol classes.

typing.SupportsAbs(*args, **kwargs)

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

typing.SupportsBytes(*args, **kwargs)

An ABC with one abstract method __bytes__.

typing.SupportsComplex(*args, **kwargs)

An ABC with one abstract method __complex__.

typing.SupportsFloat(*args, **kwargs)

An ABC with one abstract method __float__.

typing.SupportsIndex(*args, **kwargs)

An ABC with one abstract method __index__.

typing.SupportsInt(*args, **kwargs)

An ABC with one abstract method __int__.

typing.SupportsRound(*args, **kwargs)

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

typing.TextIO(*args, **kwds)

Typed version of the return of open() in text mode.

typing.TypeVar(name, *constraints[, bound, ...])

Type variable.

typing.TypedDict(typename[, fields, total])

A simple typed namespace.

typing.io

alias of io

typing.re

alias of re

The typing module: Support for gradual typing as defined by PEP 484.

At large scale, the structure of the module is following: * Imports and exports, all public names should be explicitly added to __all__. * Internal helper functions: these should never be used in code outside this module. * _SpecialForm and its instances (special forms): Any, NoReturn, ClassVar, Union, Optional * Two classes whose instances can be type arguments in addition to types: ForwardRef and TypeVar * The core of internal generics API: _GenericAlias and _VariadicGenericAlias, the latter is

currently only used by Tuple and Callable. All subscripted types like X[int], Union[int, str], etc., are instances of either of these classes.

  • The public counterpart of the generics API consists of two classes: Generic and Protocol.

  • Public helper functions: get_type_hints, overload, cast, no_type_check, no_type_check_decorator.

  • Generic aliases for collections.abc ABCs and few additional protocols.

  • Special types: NewType, NamedTuple, TypedDict.

  • Wrapper submodules for re and io related types.

class ForwardRef(arg, is_argument=True)[source]

Bases: _Final

Internal wrapper to hold a forward reference.

class Generic(*args, **kwds)[source]

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 NamedTuple(typename, fields=None, /, **kwargs)[source]

Bases: object

Typed version of namedtuple.

Usage in Python versions >= 3.6:

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.) Alternative equivalent keyword syntax is also accepted:

Employee = NamedTuple('Employee', name=str, id=int)

In Python versions <= 3.5 use:

Employee = NamedTuple('Employee', [('name', str), ('id', int)])
class Protocol(*args, **kwds)[source]

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 SupportsAbs(*args, **kwargs)[source]

Bases: Protocol

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

class SupportsBytes(*args, **kwargs)[source]

Bases: Protocol

An ABC with one abstract method __bytes__.

class SupportsComplex(*args, **kwargs)[source]

Bases: Protocol

An ABC with one abstract method __complex__.

class SupportsFloat(*args, **kwargs)[source]

Bases: Protocol

An ABC with one abstract method __float__.

class SupportsIndex(*args, **kwargs)[source]

Bases: Protocol

An ABC with one abstract method __index__.

class SupportsInt(*args, **kwargs)[source]

Bases: Protocol

An ABC with one abstract method __int__.

class SupportsRound(*args, **kwargs)[source]

Bases: Protocol

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

Text

alias of str

class TypeVar(name, *constraints, bound=None, covariant=False, contravariant=False)[source]

Bases: _Final, _Immutable

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 TypedDict(typename, fields=None, /, *, total=True, **kwargs)[source]

Bases: dict

A simple typed namespace. At runtime it is equivalent to a plain dict.

TypedDict creates a dictionary type that expects all of its instances to have a certain set of keys, where each key is associated with a value of a consistent type. This expectation is not checked at runtime but is only enforced by type checkers. Usage:

class Point2D(TypedDict):
    x: int
    y: int
    label: str

a: Point2D = {'x': 1, 'y': 2, 'label': 'good'}  # OK
b: Point2D = {'z': 3, 'label': 'bad'}           # Fails type check

assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')

The type info can be accessed via Point2D.__annotations__. TypedDict supports two additional equivalent forms:

Point2D = TypedDict('Point2D', x=int, y=int, label=str)
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. Usage:

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 class syntax is only supported in Python 3.6+, while two other syntax forms work for Python 2.7 and 3.2+

NewType(name, tp)[source]

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 function 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
cast(typ, val)[source]

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

final(f)[source]

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

get_args(tp)[source]

Get type arguments with all substitutions performed.

For unions, basic simplifications used by Union constructor are performed. Examples:

get_args(Dict[str, int]) == (str, int)
get_args(int) == ()
get_args(Union[int, Union[T, int], str][int]) == (int, str)
get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
get_args(Callable[[], T][int]) == ([], int)
get_origin(tp)[source]

Get the unsubscripted version of a type.

This supports generic types, Callable, Tuple, Union, Literal, Final and ClassVar. Return None for unsupported types. Examples:

get_origin(Literal[42]) is Literal
get_origin(int) is None
get_origin(ClassVar[int]) is ClassVar
get_origin(Generic) is Generic
get_origin(Generic[T]) is Generic
get_origin(Union[T, int]) is Union
get_origin(List[Tuple[T, T]][int]) == list
get_type_hints(obj, globalns=None, localns=None)[source]

Return type hints for an object.

This is often the same as obj.__annotations__, but it handles forward references encoded as string literals, and if necessary adds Optional[t] if a default value equal to None is set.

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.

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

no_type_check(arg)[source]

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.

no_type_check_decorator(decorator)[source]

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.

overload(func)[source]

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. For example:

@overload def utf8(value: None) -> None: … @overload def utf8(value: bytes) -> bytes: … @overload def utf8(value: str) -> bytes: … def utf8(value):

# implementation goes here

runtime_checkable(cls)[source]

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!