Sub topic 5
The type parameter syntax from Python 3.12
This chapter assumes you can read generic code written with TypeVar and Generic, as shown in the earlier chapters. It also assumes you can run Python 3.12 or newer and a type checker such as mypy or pyright. The chapter covers how the new syntax declares type parameters, how to convert old code, and where the new rules differ from the old ones.
Why a new syntax
Before Python 3.12, a generic function needed three separate pieces. You created a TypeVar at module level, repeated its name as a string, and for classes you added Generic[T] to the bases:
from typing import Generic, TypeVar
T = TypeVar("T")
class Stack(Generic[T]):
def __init__(self) -> None:
self._items: list[T] = []This has three problems. The string "T" must match the variable name. T is a module-level name, so every function in the module shares one variable even when the functions are unrelated. The Generic[T] base looks like inheritance but only marks the class as generic.
PEP 695 moves the declaration into the definition. Type parameters go in square brackets directly after the name of a function, class, or type alias.
Generic functions
from collections.abc import Sequence
def first[T](items: Sequence[T]) -> T:
return items[0]
n = first([1, 2, 3]) # checker infers int
s = first(("a", "b")) # checker infers str[T] declares T as a type parameter of first. It exists only for this function's signature and body. A second function that also writes [T] gets its own independent T.
You can declare several parameters, separated by commas:
def pair_up[K, V](key: K, value: V) -> tuple[K, V]:
return (key, value)
p = pair_up("age", 30) # checker infers tuple[str, int]Methods can add their own parameters on top of the ones the class provides. These are called method-scoped type parameters:
class Stack[T]:
def __init__(self) -> None:
self._items: list[T] = []
def push(self, item: T) -> None:
self._items.append(item)
def pop(self) -> T:
return self._items.pop()
def map[U](self, func: "Callable[[T], U]") -> "Stack[U]":
result = Stack[U]()
for item in self._items:
result.push(func(item))
return resultHere T belongs to the class and U belongs only to map. A Stack[int] can call map with a function returning str and get a Stack[str].
The quoted annotations in map are only there because Callable has not been imported in this snippet. With from collections.abc import Callable at the top you can write them without quotes.
Generic classes
class Stack[T]:
def __init__(self) -> None:
self._items: list[T] = []
def push(self, item: T) -> None:
self._items.append(item)
def pop(self) -> T:
return self._items.pop()
ints = Stack[int]()
ints.push(1)
value = ints.pop() # checker infers intWriting class Stack[T] has the same effect as inheriting from Generic[T]. Python adds Generic to the class's bases for you, so Stack[int] still works at runtime. You do not write Generic yourself.
When the class also has real base classes, they go in parentheses after the type parameters:
from collections.abc import Iterator
class Countdown[T](Iterator[T]):
def __init__(self, items: list[T]) -> None:
self._items = list(items)
def __iter__(self) -> "Countdown[T]":
return self
def __next__(self) -> T:
if not self._items:
raise StopIteration
return self._items.pop()The T after Countdown is declared once. The T inside Iterator[T] refers to that declaration.
Converting old code to the new syntax
Conversion follows a fixed recipe:
- Delete the module-level
T = TypeVar("T")line. - Add
[T]after the function or class name. - Remove
Generic[T]from the bases. If it was the only base, remove the parentheses too. - Keep any bound or constraints, moving them into the brackets (the next chapter covers these).
| Old style | New style |
|---|---|
| `T = TypeVar("T")` | Declared in brackets: `def f[T](...)` |
| `class Box(Generic[T]):` | `class Box[T]:` |
| `class Box(Base[T], Generic[T]):` | `class Box[T](Base[T]):` |
| `P = ParamSpec("P")` | `def f[**P](...)` |
| `Ts = TypeVarTuple("Ts")` | `def f[*Ts](...)` |
| `Alias: TypeAlias = list[T]` | `type Alias[T] = list[T]` |
The last three rows preview features that later chapters explain. The prefix rule is simple: T is a plain type variable, *Ts is a variadic one, and **P captures a parameter list.
# Before
from typing import Generic, TypeVar
T = TypeVar("T")
class Box(Generic[T]):
def __init__(self, value: T) -> None:
self.value = value
def get(self) -> T:
return self.value# After
class Box[T]:
def __init__(self, value: T) -> None:
self.value = value
def get(self) -> T:
return self.valueBoth versions behave the same way for callers. Box[int](3) works with either.
How the pieces fit together
Scoping rules
The type parameters live in their own scope, which sits between the enclosing scope and the body of the definition. This has several consequences.
- A parameter is visible in the signature, in the body, in annotations, and in the bases of a class. It is not visible outside.
- An inner definition can use the parameters of an enclosing generic definition without redeclaring them.
- If an inner definition declares a parameter with the same name, it shadows the outer one. Type checkers report this as an error for classes and methods, because the two
Ts would be confusing. - A class body can see its type parameters, but names defined in the class body are not visible to the bracketed list.
You can inspect the declared parameters at runtime through __type_params__:
def first[T](items: list[T]) -> T:
return items[0]
class Stack[T]:
pass
print(first.__type_params__) # (T,)
print(Stack.__type_params__[0].__name__) # TEach entry is a real typing.TypeVar, ParamSpec, or TypeVarTuple object. The syntax is a more compact way of creating the same objects that you used to create by hand.
Rules and restrictions
The new syntax is stricter than the old one in a few places.
- Python version. It is a syntax error on Python 3.11 and older. Code using it cannot be imported by older interpreters at all. A library that still supports 3.11 must stay with
TypeVar. - No
Generic[...]base. Combining a bracketed list with an explicitGeneric[T]base is an error. The same applies toProtocol[T]. Writeclass Reader[T](Protocol):instead. - No mixing styles on one class. Using an old-style
TypeVarinside a class or function that has a bracketed list is reported by type checkers. Pick one style per definition. - Variance is inferred. A
Tdeclared in brackets has nocovariant=Trueorcontravariant=Trueargument. The checker works out the variance from howTis used. The variance chapter explains the details. - Class-level parameters apply to all instances. You cannot give two methods of one class different meanings for the same class-level
T. Use a method-scoped parameter such asUwhen a method needs its own relationship.
Common mistakes
- Declaring a parameter that is used once.
def log[T](x: T) -> Noneworks, butTrelates nothing. A plainobjectannotation says the same thing with less noise. A type parameter is useful when it appears at least twice, for example in an argument and the return type. - Forgetting to specialize.
Stack()without[int]leavesTfor the checker to infer, which often yieldsStack[Any]or an "unknown type" report. WriteStack[int]()or give the variable an annotation such ass: Stack[int] = Stack(). - Expecting runtime checks.
Stack[int]().push("x")runs without error. Only the type checker complains. The runtime chapter returns to this. - Reusing names across scopes. Writing
T = TypeVar("T")at module level and alsodef f[T]leaves the module-level name unused insidef. The bracketedTalways wins within that function, which can confuse readers.
Exercises
Exercise
Convert this code to the Python 3.12 syntax. from typing import Generic, TypeVar K = TypeVar("K") V = TypeVar("V") class Registry(Generic[K, V]): def _init(self) -> None: self.data: dict[K, V] = {} def add(self, key: K, value: V) -> None: self.data[key] = value def get(self, key: K) -> V: return self.data[key]
Show answer
Remove the two TypeVar lines, remove the Generic base, and declare both parameters after the class name: class Registry[K, V]: def _init(self) -> None: self.data: dict[K, V] = {} def add(self, key: K, value: V) -> None: self.data[key] = value def get(self, key: K) -> V: return self.data[key]
Exercise
Why is class Box[T](Generic[T]): rejected, and how do you fix it?
Show answer
The bracketed list already makes the class generic, so an explicit Generic[T] base is redundant and is an error. Remove the base and write class Box[T]:.
Exercise
What does Stack.__type_params__ return for class Stack[T]: pass, and what is each element?
Show answer
It returns a tuple with one element, (T,). The element is a real typing.TypeVar object named T, created by the syntax.