Sub topic 8
Generic functions and classes with TypeVar
This chapter assumes you can annotate functions, read checker output, and use unions and None. You should also know that mypy and Pyright are static checkers that never run your code.
The problem generics solve
Suppose you write a function that returns the first item of a sequence. You could annotate it with Any, but then the checker forgets what went in. The result is Any, and later mistakes go unreported.
A generic function keeps the link between input and output. A TypeVar is a placeholder for a type that the checker fills in at each call.
A generic function
from typing import Sequence, TypeVar
T = TypeVar("T")
def first(items: Sequence[T]) -> T:
return items[0]
n = first([1, 2, 3])
s = first(["a", "b"])The checker reads Sequence[T] as "a sequence of some type T" and the return type T as "that same type". For the first call it solves T = int, so n is int. For the second call it solves T = str, so s is str. Use reveal_type(n) to confirm.
Generic classes
A class can also depend on a type variable. Inherit from Generic[T] to declare it.
from typing import Generic, TypeVar
T = TypeVar("T")
class Box(Generic[T]):
def __init__(self, item: T) -> None:
self.item = item
def get(self) -> T:
return self.item
box = Box(3)
reveal_type(box) # Box[int]
reveal_type(box.get()) # intYou can also write Box[str] in an annotation to state the type explicitly. Python 3.12 adds a shorter syntax, class Box[T]: and def first[T](items: Sequence[T]) -> T:. It needs no TypeVar import, but the older form works on every version in this tutorial's prerequisites.
Constraining a type variable
An unconstrained T can be anything, so you can only do things every object supports. To allow operations such as +, restrict the variable.
from typing import TypeVar
Number = TypeVar("Number", int, float)
Named = TypeVar("Named", bound=str)
def add(a: Number, b: Number) -> Number:
return a + b
def shout(value: Named) -> Named:
return value.upper() # checker may widen this to str- A list of constraints, as in
Number, meansTmust be exactly one of those types in a given call. - A
boundmeansTcan be that type or any subclass of it.
Constrained variables behave as one type per call. add(1, 2.5) is a common surprise, because the checker must pick a single solution.
Common mistakes
- Using a
TypeVaronce. IfTappears only in the parameters and nowhere else, it links nothing. Use the concrete type orobjectinstead. Pyright reports this case. - Mismatched names.
TypeVar("T")should be assigned to a variable calledT. Pyright and mypy both report a mismatch. - Expecting runtime checks. Generics exist only for the checker.
Box[int]("x")is flagged, but nothing stops it at runtime.
Exercise
In def pick(a: T, b: T) -> T, what type does the checker infer for pick(1, "x") in the unconstrained case, and why does that matter?
Show answer
It solves T to a common supertype of int and str, usually object (or int | str in Pyright). The result loses the specific types, so calling .upper() on it is an error. This shows that one TypeVar links all positions where it appears.