Sub topic 5
The type parameter syntax from Python 3.12
This chapter assumes you can read basic annotations such as list[int]. It also assumes you know what a generic function does, and that you run a checker such as mypy or pyright. You also need Python 3.12 or later to run the examples.
Why a new syntax
Before 3.12, a generic function needed a module-level TypeVar, and a generic class also needed a Generic[T] base. The variable T lived outside the function that used it, and the name had to be written twice (T = TypeVar("T")). PEP 695 moves the declaration into square brackets right after the name, so each definition owns its type parameters.
from typing import Generic, TypeVar
T = TypeVar("T")
def first_old(items: list[T]) -> T:
return items[0]
class Box_old(Generic[T]):
def __init__(self, value: T) -> None:
self.value = valuedef first[T](items: list[T]) -> T:
return items[0]
class Box[T]:
def __init__(self, value: T) -> None:
self.value = valueThe two pairs mean the same thing to a type checker.
Converting step by step
- Find each
TypeVarused by the definition. - Put its name in brackets after the function or class name. Separate several parameters with commas.
- Delete the module-level
TypeVarand theGeneric[...]base class.
A class with two parameters looks like this:
class Pair[K, V]:
def __init__(self, key: K, value: V) -> None:
self.key = key
self.value = value
def swap(self) -> "Pair[V, K]":
return Pair(self.value, self.key)
p = Pair("age", 41)
q = p.swap() # checker infers Pair[int, str]
print(q.key) # 41Scope of a type parameter
A parameter declared in brackets exists only inside that definition. Two functions can each declare their own T without sharing anything. A method can add its own parameters on top of the class's:
class Stack[T]:
def __init__(self) -> None:
self._items: list[T] = []
def push(self, item: T) -> None:
self._items.append(item)
def map[U](self, fn: "Callable[[T], U]") -> "Stack[U]":
out = Stack[U]()
for item in self._items:
out.push(fn(item))
return out
from collections.abc import CallableHere T belongs to the class, and U belongs to map alone. Because the annotations are strings, the Callable import can come after the class. Normally you would put it at the top of the file.
What changes and what does not
| Topic | `TypeVar` and `Generic` | 3.12 syntax |
|---|---|---|
| Declaration | Separate module-level line | In brackets after the name |
| Class base | `Generic[T]` required | Not needed |
| Bounds | `TypeVar("T", bound=X)` | `[T: X]` |
| Variance | Written by hand | Inferred by the checker |
| Minimum Python | 3.5 or later (older still with backports) | 3.12 |
Bounds and variance get their own chapters, so this chapter only notes that they are handled differently.
Common errors
- SyntaxError on older Python. The brackets are grammar, not a library feature. Python 3.11 and earlier reject
def f[T]outright. If you must support those versions, keep the classic style. - Mixing styles. Do not inherit from
Generic[T]in a class that already has a bracketed parameter list. Do not use a module-levelTypeVarinside a definition that declares its own parameters. Checkers report both. Pick one style per definition. - Reusing a name from outside. Inside
class Stack[T], a method writtendef f[T]shadows the class'sT. Use a different name unless you mean a new variable.
Exercise
Convert this code to the Python 3.12 syntax. from typing import Generic, TypeVar K = TypeVar("K") V = TypeVar("V") class Cache(Generic[K, V]): def get(self, key: K) -> V | None: ...
Show answer
class Cache[K, V]: def get(self, key: K) -> V | None: ... Both TypeVar lines and the Generic base are deleted, and K and V move into brackets after the class name.