Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python 3.12 Generics: PEP 695 Syntax, Type Parameters, and TypeVar

How Python 3.12 PEP 695 type parameter syntax works: bracket declarations for classes, functions, and type aliases, bounds and constraints, inferred variance, lazy evaluation, and the runtime scope rules.

~5 min readPython
#Python#Generics#Type Hints#PEP 695
Python 3.12 generic class Box with T and U type parameter slots

Python 3.12 changes how generics are declared, not how they behave at runtime. PEP 695 moves the type parameter list into the declaration itself — def first[T](items: list[T]) -> T, class Box[T]:, type Pair[T] = tuple[T, T] — so there is no module-level TypeVar, no Generic[T] base class, and no _T_co naming convention to remember. The brackets declare a lexically scoped parameter, class variance is inferred from how the parameter is used, and every annotation that mentions it is evaluated lazily. Existing typing.TypeVar code still runs, but the two styles cannot be mixed inside a single declaration.

The declaration site now owns its type parameters

Before 3.12 a generic function needed a module-level object that was repeated in three places:

python
from typing import TypeVar _T = TypeVar("_T") def first(items: list[_T]) -> _T: return items[0]

With PEP 695 the parameter is declared where it is used and nowhere else:

python
def first[T](items: list[T]) -> T: return items[0] class Box[T]: def __init__(self, item: T) -> None: self.item = item def get(self) -> T: return self.item type Pair[T] = tuple[T, T]

Box[T] implies Generic[T]: Generic appears in the class's __mro__ and __orig_bases__, Box[int] still produces a types.GenericAlias, Box.__parameters__ still reports (T,), and Box[int]("x") still builds an instance. The rule that breaks migrating code is that the old base can no longer be written out: class Box[T](Generic[T]) raises TypeError while the class body is being created, because Generic would be contributed twice.

Every generic object records its parameters on __type_params__:

python
Box.__type_params__ # (<TypeVar 'T'>,) first.__type_params__ # (<TypeVar 'T'>,) Pair.__type_params__ # (<TypeVar 'T'>,)

That tuple is the only runtime handle on the parameter, and it is what serializers, dependency-injection containers, and test factories read instead of parsing annotation strings.

Bounds, constraints, and variance in one table

IntentBefore 3.12PEP 695
UnconstrainedT = TypeVar("T")[T]
Upper boundTypeVar("T", bound=Base)[T: Base]
Constraint setTypeVar("C", str, bytes)[C: (str, bytes)]
CovarianceTypeVar("T_co", covariant=True)inferred per class
Packed tupleTypeVarTuple("Ts")[*Ts]
Callable shapeParamSpec("P")[**P]
Generic aliasListOr: TypeAlias = list[T]type ListOr[T] = list[T]

A bound and a constraint set answer different questions. [T: Base] accepts Base and any subclass, and it gives the checker the members of Base to work with inside the declaration. A constraint tuple restricts the parameter to that finite list of types, which is what you want for something like text encoding where str and bytes need genuinely different treatment:

python
class Codec[C: (str, bytes)]: def encode(self, value: C) -> bytes: return value.encode() if isinstance(value, str) else value

Variance is no longer written by hand. For a class declared with the new syntax, the checker infers variance from the positions where each parameter appears: only in return types means covariant, only in parameter types means contravariant, and both means invariant. A TypeVar created the old way stays invariant unless it is declared covariant=True, contravariant=True, or — in 3.12 and later — built with infer_variance=True.

Lazy evaluation and the type statement

The type statement creates a typing.TypeAliasType object, not an assignment target. Its __name__, __type_params__, and __value__ attributes are read-only, and __value__ is computed on first access rather than when the statement runs. That is what allows an alias to contain an unquoted forward reference or to describe itself:

python
type Json = dict[str, Json] | list[Json] | str | int | float | bool | None type Tree[T] = T | list[Tree[T]] Json.__value__ # evaluates the recursive definition once, safely

The same laziness applies to the annotations and bounds of generic functions and classes, so a name that only exists after an import cycle has resolved no longer fails at import time.

Variadic generics keep the new spelling

TypeVarTuple and ParamSpec survive with shorter syntax. A star declares a tuple of unknown length, and a double star captures a callable's parameter list:

python
class Batch[*Shape]: def __init__(self, data: tuple[*Shape]) -> None: self.data = data def traced[**P, R](fn: Callable[P, R]) -> Callable[P, R]: @wraps(fn) def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: print(fn.__name__) return fn(*args, **kwargs) return wrapper

Batch[int, str] and Batch[*tuple[int, ...]] both remain valid type expressions; the runtime object still reports __parameters__ with a TypeVarTuple instance.

Edge cases that only show up in real code

1. Inferred variance is silent, so one added method invalidates every call site

python
class Producer[T]: def __init__(self, value: T) -> None: self._value = value def get(self) -> T: return self._value def consume(item: Producer[object]) -> None: ... consume(Producer[Dog](Dog())) # accepted: T is inferred covariant

Now add def set(self, value: T) -> None and T appears in a parameter position as well, so the class becomes invariant and consume(Producer[Dog](...)) is a type error — in code nobody touched. If a class must keep a direction permanently, express the role as a Protocol with a @property, or keep the explicit TypeVar(..., covariant=True) form for that class so the direction is stated rather than inferred.

2. The parameter does not exist as a name inside the body

python
def wrap[T](value: T) -> list[T]: print(T) # NameError: name 'T' is not defined print(list[T]) # NameError as well return [value]

The type parameter lives in a dedicated annotation scope: it is visible to other type parameters and to annotations, not to the function body's lookup chain. Read wrap.__type_params__[0] when a library genuinely needs the object at runtime.

3. A broken bound fails at request time instead of import time

python
class Report[T: Serializer]: # Serializer not imported yet: fine ... import json json.dumps({}, default=str) # unrelated code keeps working Report.__bound__ # NameError here, not at import

Because bounds are lazy, a missing import inside a bound no longer prevents the module from loading; it surfaces the first time a framework calls get_type_hints() or reads __bound__. Add one test that touches get_type_hints() on every public generic type so the failure lands in CI.

4. Constraint sets are exact types, not subclasses

python
class MyStr(str): ... Codec[MyStr] # error: MyStr is not one of the constraints (str, bytes)

str satisfies the constraint because it is literally one of the listed types; a subclass does not, even though it is a str. That is the same rule TypeVar("C", str, bytes) always had, and it is the most common reason a constrained parameter "mysteriously rejects" an obvious argument. Switch to [C: str] when subclasses are legitimate.

5. An alias is an object, not a class

python
type IntList = list[int] IntList.__value__ # list[int] isinstance([], IntList) # TypeError: arg 2 must be a type list[int].__origin__ # list, for registry lookups

Serializers that dispatch on get_origin(annotation) is list keep working with IntList because the alias resolves to a generic alias, but isinstance() and issubclass() need the resolved class from __value__.

Common mistakes

SymptomCauseFix
SyntaxError: invalid syntax at def first[T]interpreter older than 3.12run 3.12+, or keep the TypeVar form
TypeError when the class is createdclass Box[T](Generic[T]) inherits Generic twicedrop Generic[T] from the bases
NameError: name 'T' is not defined in the bodytype parameters are scoped to annotations onlyread __type_params__
checker: "TypeVar is not allowed in a type alias"type X = list[T] with an old-style TypeVarwrite type X[T] = list[T]
TypeError: isinstance() arg 2 must be a typethe alias is a TypeAliasTypetest against Alias.__value__
SyntaxError on class A[T, T]duplicate parameter namerename one parameter
covariance error only after a refactorvariance was inferred, then usage changedpin direction with a Protocol or explicit TypeVar

The migration order that avoids all of it: upgrade the interpreter and the checker first, convert one module at a time from TypeVar to brackets, delete the now-unused TypeVar imports, and add a test that calls get_type_hints() on the converted public types so lazy evaluation never hides a missing name.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.