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.

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:
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:
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__:
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
| Intent | Before 3.12 | PEP 695 |
|---|---|---|
| Unconstrained | T = TypeVar("T") | [T] |
| Upper bound | TypeVar("T", bound=Base) | [T: Base] |
| Constraint set | TypeVar("C", str, bytes) | [C: (str, bytes)] |
| Covariance | TypeVar("T_co", covariant=True) | inferred per class |
| Packed tuple | TypeVarTuple("Ts") | [*Ts] |
| Callable shape | ParamSpec("P") | [**P] |
| Generic alias | ListOr: 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:
class Codec[C: (str, bytes)]:
def encode(self, value: C) -> bytes:
return value.encode() if isinstance(value, str) else valueVariance 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:
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, safelyThe 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:
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 wrapperBatch[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
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 covariantNow 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
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
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 importBecause 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
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
type IntList = list[int]
IntList.__value__ # list[int]
isinstance([], IntList) # TypeError: arg 2 must be a type
list[int].__origin__ # list, for registry lookupsSerializers 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
| Symptom | Cause | Fix |
|---|---|---|
SyntaxError: invalid syntax at def first[T] | interpreter older than 3.12 | run 3.12+, or keep the TypeVar form |
TypeError when the class is created | class Box[T](Generic[T]) inherits Generic twice | drop Generic[T] from the bases |
NameError: name 'T' is not defined in the body | type parameters are scoped to annotations only | read __type_params__ |
| checker: "TypeVar is not allowed in a type alias" | type X = list[T] with an old-style TypeVar | write type X[T] = list[T] |
TypeError: isinstance() arg 2 must be a type | the alias is a TypeAliasType | test against Alias.__value__ |
SyntaxError on class A[T, T] | duplicate parameter name | rename one parameter |
| covariance error only after a refactor | variance was inferred, then usage changed | pin 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 toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.