Sub topic 16
Writing generic classes
This chapter assumes you know how to write a generic function with TypeVar, annotate collections such as list[int], and run mypy or pyright.
Why a class needs a type parameter
A generic function links the types of its arguments to its return type. A container class has the same need. A stack that holds integers should return integers from pop(), and a stack that holds strings should return strings. Without a type parameter, you would annotate the items as object or Any, and the checker would lose track of what they are.
A generic class declares one or more type variables. Each instance then fixes those variables to concrete types.
Declaring a generic class
Create a TypeVar, then list it in Generic[...] as a base class.
from typing import Generic, TypeVar
T = TypeVar("T")
class Stack(Generic[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 peek(self) -> T | None:
return self._items[-1] if self._items else None
numbers: Stack[int] = Stack()
numbers.push(1)
numbers.push(2)
print(numbers.pop())
print(numbers.peek())Inside the class body, T stands for whatever type the instance was given. The annotation Stack[int] makes push accept only int and makes pop return int. A checker reports numbers.push("two") as an error, but the interpreter still runs it.
Several type variables
A class can take more than one type variable. List them in order in Generic.
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 register(self, key: K, value: V) -> None:
self._data[key] = value
def lookup(self, key: K) -> V | None:
return self._data.get(key)
handlers: Registry[str, int] = Registry()
handlers.register("retries", 3)
print(handlers.lookup("retries"))Common errors
- Leaving out
Generic[T]. A class that usesTin its methods without listingTas a type parameter is not generic. Checkers either reject it or treatTas an unrelated variable in each method. - Omitting the argument. A bare
Stackannotation meansStack[Any], so the checker stops catching mistakes. WriteStack[int]in annotations. In strict modes, mypy reports a missing type argument. - Expecting runtime checks.
Stack[int]()creates an ordinaryStack. Theintis not stored or enforced. - Using
Tonce. A type variable that appears only once in a signature links nothing, so a plain type orAnywould do the same job.
Newer syntax
Python 3.12 added a shorter form that declares the type variable in the class header. It needs no TypeVar and no Generic.
class Box[T]:
def __init__(self, item: T) -> None:
self.item = item
print(Box(5).item)Use it when your minimum supported version is 3.12. Use Generic[T] when you must support older versions.
Exercise
You wrote class Queue: def put(self, item: T) -> None: ... with T = TypeVar("T"), but the checker does not tie put to the type of the queue. What is missing, and how do you fix it?
Show answer
The class does not declare T as a type parameter. Change it to class Queue(Generic[T]): (or class Queue[T]: on Python 3.12 and later). Annotate instances as Queue[int] so put accepts only integers.