Python Glossary Русский

Python 3.12+astterm

ast.type_param

type parameters

The abstract base class of PEP 695 type parameters: TypeVar, ParamSpec, TypeVarTuple. The type_params field of def, class and type. Added in 3.12.

Syntax

isinstance(p, ast.type_param)

FunctionDef, ClassDef and TypeAlias have a type_params list since 3.12; with the old style (T = TypeVar('T') plus Generic[T]) it stays empty, since that is plain Assign and Call. The kind follows the syntax: T is TypeVar, *Ts is TypeVarTuple, **P is ParamSpec; a bound T: int is stored in TypeVar.bound.

Examples

import ast
f = ast.parse('def f[T: int, *Ts, **P](x): pass').body[0]
print([type(p).__name__ for p in f.type_params])  # → ['TypeVar', 'TypeVarTuple', 'ParamSpec']
print(f.type_params[0].name, ast.unparse(f.type_params[0].bound))  # → T int

See also

Open in the full glossarydocs.python.orgReport an inaccuracy