Sub topic 16
Writing Generic Classes
This chapter assumes you can write generic functions with TypeVar, annotate collections such as list[int], and run mypy or pyright. A generic class applies the TypeVar idea to a whole class. Its methods and attributes share one or more type parameters, so a checker can track what a container holds.
Why a class needs type parameters
Suppose you write a stack that holds any kind of item. Annotating the items as object or Any loses information. A checker cannot tell whether pop() returns an int or a str, so every caller needs a cast or an isinstance check.
A generic class avoids this. You declare a placeholder type, and each use of the class fills it in. list[int] and list[str] work this way. You can write your own classes the same way.
Declaring a generic class with Generic and TypeVar
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 is_empty(self) -> bool:
return not self._items
numbers: Stack[int] = Stack()
numbers.push(1)
numbers.push(2)
print(numbers.pop())
numbers.push("three") # runs fine; a static checker reports an error hereThe annotation Stack[int] binds T to int for this variable. A checker then treats push as taking an int and pop as returning an int. For the last line, mypy reports Argument 1 to "push" of "Stack" has incompatible type "str"; expected "int".
Python itself does not object to that last line. As in earlier chapters, the interpreter ignores the hints.
Type inference at construction
You do not always have to write the argument. When the constructor uses T, the checker infers it from the call.
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
box = Box("hello") # checker infers Box[str]
print(box.get().upper())When the constructor gives no hint, as with Stack(), the checker cannot infer T. It asks for an annotation, usually with the message Need type annotation for "numbers". Write numbers: Stack[int] = Stack() to fix it.
More than one type parameter
List several variables in Generic[...]. The order you give them is the order callers use.
from collections.abc import Hashable
from typing import Generic, TypeVar
K = TypeVar("K", bound=Hashable)
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)
users: Registry[int, str] = Registry()
users.register(1, "Ada")
print(users.lookup(1))bound=Hashable limits K to types that can be dictionary keys. A checker rejects Registry[list[int], str] because lists are not hashable. A bound accepts any subtype of the named type. For a fixed set of exact types, pass them as constraints instead, such as TypeVar("N", int, float).
The Python 3.12 syntax
Python 3.12 added a shorter form (PEP 695). You put the parameters in square brackets after the class name. No TypeVar or Generic import is 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()
names: Stack[str] = Stack()
names.push("Ada")
print(names.pop())Bounds are written inline, as in class Registry[K: Hashable, V]. This form fails with a SyntaxError on Python 3.11 and earlier. If your project supports older versions, use Generic[T].
Subclassing generic classes
A subclass can fix the type argument, or it can stay generic.
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()
class IntStack(Stack[int]):
def total(self) -> int:
return sum(self._items)
class LoggedStack(Stack[T]):
def push(self, item: T) -> None:
print(f"pushing {item!r}")
super().push(item)
ints = IntStack()
ints.push(4)
ints.push(5)
print(ints.total())
words: LoggedStack[str] = LoggedStack()
words.push("hi")IntStack is not generic. LoggedStack[T] keeps the parameter open, so each use chooses its own type.
Variance: why Stack[int] is not a Stack[float]
By default, a TypeVar is invariant. Stack[int] is not accepted where Stack[float] is expected, even though int is accepted where float is expected. The reason is that a Stack[float] allows push(2.5). If you could pass it a Stack[int], a float would end up in a stack of ints. list behaves the same way.
If a class only produces values and never accepts them after construction, the restriction is unnecessary. Mark the parameter covariant with covariant=True.
from typing import Generic, TypeVar
T_co = TypeVar("T_co", covariant=True)
class Box(Generic[T_co]):
def __init__(self, value: T_co) -> None:
self._value = value
def get(self) -> T_co:
return self._value
def show(box: Box[float]) -> None:
print(box.get())
show(Box(3)) # Box[int] is accepted as Box[float]A checker enforces the rule. If you add a method such as def set(self, value: T_co) -> None, it reports that a covariant type variable cannot be used in a parameter. The opposite marking, contravariant=True, suits classes that only consume values, such as a callback sink. You will rarely need it.
What happens at runtime
Type arguments are erased. The interpreter does not remember whether an object was created as Stack[int].
from typing import Generic, TypeVar
T = TypeVar("T")
class Stack(Generic[T]):
pass
numbers: Stack[int] = Stack()
print(type(numbers))
print(isinstance(numbers, Stack))
try:
isinstance(numbers, Stack[int])
except TypeError as error:
print("TypeError:", error)The first two lines print <class '__main__.Stack'> and True. The isinstance call with Stack[int] raises a TypeError, because you cannot test a parameterized generic at runtime. Test against the bare class instead.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `Need type annotation for "x"` | The checker cannot infer `T` from an empty constructor call | Annotate the variable, for example `x: Stack[int] = Stack()` |
| `Type argument "list[int]" ... must be a subtype of "Hashable"` | The type argument breaks the `bound` | Use a type that satisfies the bound |
| `Cannot use a covariant type variable as a parameter` | A covariant `T_co` appears in a method argument | Make the class read-only, or switch to an invariant `TypeVar` |
| `TypeError` from `isinstance(x, Stack[int])` | Type arguments do not exist at runtime | Use `isinstance(x, Stack)` |
| `SyntaxError` on `class Stack[T]:` | The interpreter is older than Python 3.12 | Use `Generic[T]` |
| `Stack[int]` rejected where `Stack[float]` is expected | The parameter is invariant | Accept this behavior, or make a read-only class covariant |
Design guidance
- Add a type parameter only when the class holds or returns values whose type varies. A class that always stores strings needs no parameter.
- Use as few parameters as you can. Each one forces every annotation of your class to name more types.
- Give each parameter a descriptive name when its role matters, such as
KandVfor keys and values. - Use
boundwhen the class calls methods on the items, so the checker can verify those calls.
Exercise
Write a generic class Queue[T] with enqueue(item: T) -> None and dequeue() -> T | None. Use collections.deque for storage. Return None when the queue is empty. Show how a caller would annotate a queue of strings and why the result of dequeue() needs a check before use.
Show answer
from collections import deque
from typing import Generic, TypeVar
T = TypeVar("T")
class Queue(Generic[T]):
def _init(self) -> None:
self.items: deque[T] = deque()
def enqueue(self, item: T) -> None:
self.items.append(item)
def dequeue(self) -> T | None:
if not self.items:
return None
return self._items.popleft()
names: Queue[str] = Queue()
names.enqueue("Ada")
first = names.dequeue()
if first is not None:
print(first.upper())
The variable is annotated as Queue[str], because the empty constructor call gives the checker nothing to infer from. dequeue() returns str | None, so calling first.upper() directly is an error. The is not None test narrows the type to str inside the if block.
Exercise
A class ReadOnlyList[T] stores items passed to its constructor and offers only get(index: int) -> T. A function accepts ReadOnlyList[float]. Can you pass it a ReadOnlyList[int]? What change makes that possible, and which kind of method would break it?
Show answer
With an invariant TypeVar the call is rejected. Declare T_co = TypeVar("T_co", covariant=True) and write class ReadOnlyList(Generic[T_co]). Then ReadOnlyList[int] is accepted as ReadOnlyList[float], because the class only returns values. A method that takes T_co as a parameter, such as add(item: T_co), would break it, and the checker would report an error.