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
| Name | Type | Description |
|---|---|---|
| name | str | Type variable name. |
| constraints | types | Alternative allowed types; cannot combine with bound. |
| bound | type or None | Upper bound. |
| covariant | bool | Declare covariance. |
| contravariant | bool | Declare contravariance. |
| infer_variance | bool | Request inference of variance. |
| default | type or NoDefault | Default 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))