Python 3.12+astterm
ast.TypeVar
type parameters
Node for a type parameter T in square brackets of def f[T](), class C[T] or type A[T] (Python 3.12): name, bound and, since 3.13, default_value.
Syntax
ast.TypeVar(name, bound=None, default_value=None)
name here is a string, not a Name. The bound field holds both a bound T: int (a Name) and constraints T: (int, str), which are a Tuple, so an upper bound and a list of allowed types differ only by node type. The default_value field for T = int arrived in 3.13 and is absent on 3.12. The old T = TypeVar('T') style is just an Assign with a Call in ast.
Examples
import ast
f = ast.parse('def first[T: int](xs: list[T]) -> T: ...').body[0]
tv = f.type_params[0]
print(type(tv).__name__, tv.name, tv.bound.id) # → TypeVar T int
c = ast.parse('class Box[T: (int, str)]: pass').body[0]
print(type(c.type_params[0].bound).__name__) # → Tuple
See also
Open in the full glossarydocs.python.orgReport an inaccuracy