Sub topic 4
Generic classes
This chapter assumes you can write Python classes and methods, read annotations such as list[int], and have run a static checker such as mypy or pyright. It uses the classic TypeVar and Generic style first, then the Python 3.12 syntax. The syntax itself is covered in the next chapter.
Why a class needs type parameters
A generic function relates the types of its arguments to its return type. A class has the same need, but the relationship lasts across many method calls. A container accepts values in one method and returns them in another. The checker has to remember what you put in so it can tell you what comes out.
Without a type parameter, you have two poor options. You can annotate the contents as object, and every get() then needs a cast. Or you can annotate them as Any, and the checker stops helping. A generic class avoids both. It declares a placeholder type, called a type parameter, and each use of the class fills it in.
The classic form: TypeVar and Generic
Before Python 3.12, you created a TypeVar at module level and listed it in Generic[...] as a base class.
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.valueBox is now generic in T. Inside the class body, T means "whatever type this particular Box holds." Outside, you supply the type:
a: Box[int] = Box(3)
n = a.get() # checker infers intBox[int] is a specialization. The checker substitutes int for T in every method signature, so get() returns int and __init__ accepts an int.
The Python 3.12 form
The newer syntax declares the parameter directly after the class name. No Generic base and no module-level TypeVar are needed.
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 intThe two forms mean the same thing to the checker. The new form has one practical advantage: T belongs to this class alone. In the old form, a module-level T is shared by every class and function that uses it, which makes it easy to reuse one by accident.
How the checker fills in the parameter
There are two ways T gets a value.
- Explicit. You write
Stack[int]()or annotate a variable asStack[int]. - Inferred. The checker solves for
Tfrom the constructor arguments.Box("hi")is aBox[str], andBox(3.5)is aBox[float].
Inference needs evidence. An empty constructor gives the checker nothing to work with:
s = Stack() # mypy: Need type annotation for "s"
t: Stack[str] = Stack() # fine: the annotation supplies TPyright handles the first line differently. It infers Stack[Unknown], which behaves like Any, and reports it only in strict mode. Either way, the fix is to annotate.
Using a class's parameter in its methods
Every method can use the class's T. A method can also introduce its own type parameter and combine it with the class's. The map method below turns a Box[T] into a Box[U]:
from collections.abc import Callable
class Box[T]:
def __init__(self, value: T) -> None:
self.value = value
def map[U](self, func: Callable[[T], U]) -> "Box[U]":
return Box(func(self.value))
b = Box(21)
doubled = b.map(lambda n: n * 2) # Box[int]
label = b.map(str) # Box[str]
print(doubled.value, label.value) # 42 21T is fixed when the instance is created. U is solved separately at each call to map. The return annotation is quoted because Box is not yet fully defined while its own body is being evaluated.
More than one type parameter
List every parameter in the brackets, separated by commas. The order matters, because it determines how callers write Registry[str, int].
class Registry[K, V]:
def __init__(self) -> None:
self._data: dict[K, V] = {}
def register(self, key: K, value: V) -> None:
self._data[key] = value
def lookup(self, key: K) -> V | None:
return self._data.get(key)
r = Registry[str, int]()
r.register("answer", 42)
found = r.lookup("answer") # int | NoneWith the legacy style, the same class is written class Registry(Generic[K, V]). Every type variable that appears in the class's methods must also appear in Generic[...]. If you leave one out, the checker reports an error.
Subclassing generic classes
When you inherit from a generic class, you choose what happens to its parameter. There are two options.
Pin it to a concrete type. The subclass is not generic.
class IntStack(Stack[int]):
def total(self) -> int:
total = 0
while True:
try:
total += self.pop()
except IndexError:
return totalPass it through by declaring a parameter on the subclass and using it in the base.
class NamedStack[T](Stack[T]):
def __init__(self, name: str) -> None:
super().__init__()
self.name = name
books = NamedStack[str]("books")
books.push("Dune")If you subclass without brackets, as in class Bad(Stack), the checker treats the base as Stack[Any]. Strict modes warn about this because the type information is lost without any error.
Invariance: why `Stack[int]` is not a `Stack[object]`
Intermediate users often hit this error:
def fill(s: Stack[object]) -> None:
s.push("anything")
ints = Stack[int]()
fill(ints) # checker error: Stack[int] is not Stack[object]It looks harmless, but fill pushes a string into a stack that must hold only integers. A class whose parameter is used both for input and for output is invariant. Stack[int] and Stack[object] are unrelated types, even though int is a subtype of object. The chapter on variance explains when a class can safely be more flexible and how the 3.12 syntax infers that automatically. For now, remember that a generic class does not copy the subtype relationships of its parameter.
Where the type parameter may not appear
A type parameter describes one instance's type, so it only makes sense where an instance exists. These are the common mistakes:
| Mistake | Why it is wrong | Fix |
|---|---|---|
| `x: ClassVar[T]` in the class body | A class variable is shared by all specializations, so it cannot depend on `T`. | Make it an instance attribute set in `__init__`, or use a concrete type. |
| Using `T` in a `@staticmethod` signature as if it were the class's `T` | A static method has no instance to supply `T`. | Give the method its own parameter: `def make[U](x: U) -> Box[U]`. |
| Forgetting a variable in `Generic[...]` (legacy) | The class uses `K` but declares only `Generic[V]`. | List every variable used by the class. |
| Writing `Stack[int, str]` | The wrong number of type arguments. | Match the number of parameters declared. |
| Annotating with bare `Stack` | It silently becomes `Stack[Any]`. | Write `Stack[int]` or whatever you mean. |
What exists at runtime
The checker sees Stack[int] and Stack[str] as different types. At runtime they are the same class. Subscripting a generic class returns a lightweight alias object that remembers the arguments for introspection, but it does not enforce them. Calling Stack[int]() creates an ordinary Stack instance.
class Box[T]:
def __init__(self, value: T) -> None:
self.value = value
b = Box[int]("text") # a type checker reports an error here
print(type(b)) # <class '__main__.Box'>; no runtime check is madeBecause of this, a generic class is a promise to the checker and not a guarantee at runtime. If data enters your program from outside, such as JSON or user input, validate it with real checks before you trust the type parameter.
Summary of the working model
- A generic class declares type parameters. Each use of the class fills them in, either explicitly or by inference from constructor arguments.
- Methods see the class's parameters and can add their own.
- Subclasses either pin the parameters or pass them through.
- Specializations are invariant by default, so
Stack[int]is not aStack[object]. - The type arguments disappear at runtime. Only the checker uses them.
Exercise
Write a generic class Queue[T] with methods enqueue(item: T) -> None and dequeue() -> T, backed by collections.deque. Then say what a checker reports for q = Queue[int](); q.enqueue("x"), and what type(q) prints at runtime.
Show answer
from collections import deque
class Queue[T]:
def _init(self) -> None:
self.items: deque[T] = deque()
def enqueue(self, item: T) -> None:
self.items.append(item)
def dequeue(self) -> T:
return self.items.popleft()
The checker reports an error on q.enqueue("x"), because Queue[int].enqueue expects an int and gets a str. At runtime the program runs without any error. type(q) prints <class '__main__.Queue'>, because type arguments are not enforced or stored on the instance's class.
Exercise
Given class Stack[T] from this chapter, write one subclass that fixes the parameter to str and one that keeps it generic. Which one can still be written as Name[int]?
Show answer
class StrStack(Stack[str]): ...
class LabeledStack[T](Stack[T]): ...
Only LabeledStack can be subscripted, as in LabeledStack[int]. StrStack has no type parameters left, so StrStack[int] is an error.