Sub topic 4
Generic classes
This chapter assumes you can write Python classes and methods. It also assumes you know annotations like list[int] and that mypy or pyright checks them without running your code. The previous chapters covered generic functions and the classic TypeVar.
Why a class needs a type parameter
A container class holds values, and callers care about what comes back out. Without a type parameter you have two bad choices. You can annotate with Any, which turns off checking. You can also write one class per element type, which duplicates code.
A generic class takes a type parameter, so one definition can be used as Box[int], Box[str], and so on. The checker remembers which type each instance was created with.
The classic form
Before Python 3.12, you create a type variable with TypeVar and inherit from Generic[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.valueT stands for one type, chosen per instance. Every use of T inside the class refers to that same type. If T is int, then __init__ accepts an int and get returns an int.
The same idea with Python 3.12 syntax
Python 3.12 lets the class declare its parameters directly after its name. The next chapter covers this syntax in detail. The examples below use it because it is shorter.
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 intStack[int]() supplies the type argument explicitly. You can also let the checker infer it from the constructor arguments, as in Box("hi"), which it treats as Box[str]. When nothing in the call mentions T, as with Stack(), there is nothing to infer from. Write Stack[int]() or annotate the variable, as in s: Stack[int] = Stack().
How the checker uses the parameter
ints = Stack[int]()
ints.push("two") # error: str is not int
name: str = ints.pop() # error: int is not strBoth errors come from replacing T with int in each method signature.
More than one parameter
A class can declare several parameters, and they are filled in left to right:
class Cache[K, V]:
def __init__(self) -> None:
self._data: dict[K, V] = {}
def put(self, key: K, value: V) -> None:
self._data[key] = value
def get(self, key: K) -> V | None:
return self._data.get(key)
users = Cache[int, str]()
users.put(7, "Ada")Subclassing a generic class
A subclass can fix the parameter, or pass it along:
class IntStack(Stack[int]):
def total(self) -> int:
result = 0
while True:
try:
result += self.pop()
except IndexError:
return result
class LoggedStack[T](Stack[T]):
def push(self, item: T) -> None:
print(f"push {item!r}")
super().push(item)IntStack is not generic any more. LoggedStack[T] stays generic and forwards its own T to the base class.
Common errors
- Leaving the parameter out. A bare
Stackannotation is treated asStack[Any], so the checker stops catching mistakes. Strict modes in mypy and pyright can report it. - Expecting subtype relationships to carry over.
Box[int]is not automatically aBox[float], even thoughintis accepted wherefloatis expected. Whether it is depends on variance, covered in a later chapter. - Using
Toutside the class. A type parameter only has meaning inside the class that declares it.
Exercise
Write a generic class Pair[A, B] that stores two values of possibly different types. Give it a method first() that returns the first value and a method second() that returns the second. What type does the checker infer for Pair(1, "x").second()?
Show answer
class Pair[A, B]: def _init(self, a: A, b: B) -> None: self.a = a self.b = b def first(self) -> A: return self.a def second(self) -> B: return self._b The checker infers A as int and B as str from the constructor arguments, so Pair(1, "x").second() has type str.