PyDocs

Nav

Development Tools

TypeVar

typing

class
  • TypeVar(name, *constraints, bound=None, covariant=False, contravariant=False, infer_variance=False, default=typing.NoDefault)
Type variable.

The preferred way to construct a type variable is via the dedicated
syntax for generic functions, classes, and type aliases::

    class Sequence[T]:  # T is a TypeVar
        ...

This syntax can also be used to create bound and constrained type
variables::

    # S is a TypeVar bound to str
    class StrSequence[S: str]:
        ...

    # A is a TypeVar constrained to str or bytes
    class StrOrBytesSequence[A: (str, bytes)]:
        ...

Type variables can also have defaults:

    class IntDefault[T = int]:
        ...

However, if desired, reusable type variables can also be constructed
manually, like so::

   T = TypeVar('T')  # Can be anything
   S = TypeVar('S', bound=str)  # Can be any subtype of str
   A = TypeVar('A', str, bytes)  # Must be exactly str or bytes
   D = TypeVar('D', default=int)  # Defaults to int

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 and type alias definitions.

The variance of type variables is inferred by type checkers when they
are created through the type parameter syntax and when
``infer_variance=True`` is passed. Manually created type variables may
be explicitly marked covariant or contravariant by passing
``covariant=True`` or ``contravariant=True``. By default, manually
created type variables are invariant. See PEP 484 and PEP 695 for more
details.
Changed in 3.12, 3.13
  • 3.12: Type variables can now be declared using the type parameter syntax introduced by PEP 695. The infer_variance parameter was added.
  • 3.13: Support for default values was added.
Members of TypeVar

_

__bound__
The upper bound of the type variable, if any.
__constraints__
A tuple containing the constraints of the type variable, if any.
__contravariant__
Whether the type var has been explicitly marked as contravariant.
__covariant__
Whether the type var has been explicitly marked as covariant.
__default__
The default value of the type variable, or typing.NoDefault if it has no default.
__infer_variance__
Whether the type variable’s variance should be inferred by type checkers.
__name__
The name of the type variable.

e

evaluate_bound
An evaluate function corresponding to the __bound__ attribute.
evaluate_constraints
An evaluate function corresponding to the __constraints__ attribute.
evaluate_default
An evaluate function corresponding to the __default__ attribute.

h

has_default
Return whether or not the type variable has a default value.
0 Examples
No examples for typing/TypeVar.
See Also
No see-alsos for typing/TypeVar
0 Notes
No notes for TypeVar