Typing and Generics

typing.TypeVar

Creates a type parameter linking occurrences of an unknown type. Bounds limit subtypes; constraints select among listed types. Python 3.13 adds defaults. Prefer declaration syntax where appropriate; no runtime enforcement.

Formal Syntax & Structure

python syntaxpython
typing.TypeVar(name, *constraints, bound=None, covariant=False, contravariant=False, infer_variance=False, default=NoDefault)

Parameters & Attributes

NameTypeDescription
namestrType variable name.
constraintstypesAlternative allowed types; cannot combine with bound.
boundtype or NoneUpper bound.
covariantboolDeclare covariance.
contravariantboolDeclare contravariance.
infer_varianceboolRequest inference of variance.
defaulttype or NoDefaultDefault type argument, added in 3.13.

Return Value

TypeVar

Typing construct or runtime result as described; static typing rules are not runtime validation.

Working Example

Example Snippetpython
from typing import TypeVar
T = TypeVar('T', bound=str, default=str)def first(values: list[T]) -> T: return values[0]print((first(['a','b']), T.__bound__ is str, T.__default__ is str))
Python Reference