Sub topic 3
The classic way: TypeVar and Generic
This chapter assumes you can write Python functions and classes, read annotations such as list[int] and str | None, and know that tools like mypy or pyright check annotations without running your program. You will meet the pre-3.12 way to write generics. You will still see it in most existing code and in libraries that support older Python versions.
Declaring a type variable
A type variable is a placeholder for a type. You create one with TypeVar and use it in annotations to link types together.
from collections.abc import Sequence
from typing import TypeVar
T = TypeVar("T")
def first(items: Sequence[T]) -> T:
return items[0]
n = first([1, 2, 3]) # checker infers int
s = first(("a", "b")) # checker infers strThe checker solves for T separately at each call. For the first call it finds int from the argument, so the return type is int.
The string passed to TypeVar must match the variable name. Writing T = TypeVar("U") is an error that checkers report.
Making a class generic with Generic
A class becomes generic when it inherits from Generic[T]. Every method can then use T.
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
a = Box(3) # checker infers Box[int]
b = Box[str]("text") # type argument written explicitlyFor several parameters, list them in order: class Mapping2(Generic[K, V]). Order matters, because Mapping2[str, int] assigns K=str and V=int.
If the class has other base classes, put Generic[...] last by convention. A subclass can fix the parameter or stay generic:
class IntBox(Box[int]): # not generic any more
pass
class LabeledBox(Box[T]): # still generic in T
label: str = ""Bounds and constraints
TypeVar takes keyword arguments that restrict what the variable may be.
from collections.abc import Sized
from typing import TypeVar
S = TypeVar("S", bound=Sized)
N = TypeVar("N", int, str)
def longest(a: S, b: S) -> S:
return a if len(a) >= len(b) else b
def add(a: N, b: N) -> N:
return a + bbound=Sized accepts any type that has len(), and the result keeps the caller's own type. Listing int, str creates constraints. In each call, N must be exactly one of them, so add(1, "a") is rejected.
How it maps to the 3.12 syntax
| Classic style | Python 3.12 style |
|---|---|
| `T = TypeVar("T")` then `def f(x: T) -> T` | `def f[T](x: T) -> T` |
| `class Box(Generic[T])` | `class Box[T]` |
| `TypeVar("S", bound=Sized)` | `[S: Sized]` |
| `TypeVar("N", int, str)` | `[N: (int, str)]` |
The classic TypeVar is a module-level object, so one T can be shared by many functions. The new syntax scopes each parameter to the function or class that declares it.
Common errors
- A type variable used only once. In
def f(x: T) -> None,Tlinks nothing. Checkers may warn, and a plainobjectannotation says the same thing. - A mismatched name.
TypeVar("U")assigned toTis reported as an error. - Forgetting
Generic. A class that usesTin its methods but does not inherit fromGeneric[T](or a generic base) is not generic. Checkers flag the unboundT. - Expecting runtime checks.
Box[int]("text")runs without error. Type arguments are used only by the checker.
Exercise
Rewrite class Pair(Generic[A, B]) with A = TypeVar("A") and B = TypeVar("B") using the classic style, with an __init__(self, left: A, right: B) that stores both values. What does a checker infer for Pair(1, "x")?
Show answer
Declare A = TypeVar("A") and B = TypeVar("B"), define class Pair(Generic[A, B]), and write def __init__(self, left: A, right: B) -> None that sets self.left = left and self.right = right. A checker infers Pair[int, str].