Sub topic 8
Generic functions and classes with TypeVar
This chapter assumes you can annotate functions and variables, read basic mypy and Pyright output, and use reveal_type (earlier chapters cover these). Examples use str | None syntax, so they need Python 3.10 or newer.
The problem generics solve
Consider a function that returns the first element of a list. You could annotate it with list[int], but then it fails for lists of strings. You could annotate it with Any, but then the checker stops tracking the result. The function needs to say "whatever element type goes in comes out".
A generic function does this with a type variable. A TypeVar is a placeholder that the checker replaces with a concrete type at each call.
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"])
reveal_type(n)
reveal_type(s)The checker reads Sequence[T] and T as linked. For the first call it solves T = int, so n is int. For the second it solves T = str, so s is str. Without the TypeVar, both results would be Any, and mistakes such as n.upper() would go unreported.
The name T is a convention, and the string passed to TypeVar must match the variable name. A mismatch such as T = TypeVar("U") is an error in both checkers.
A TypeVar must connect things
A TypeVar only helps when it appears at least twice in a signature, for example in a parameter and the return type, or in two parameters. A signature like this is a common mistake:
from typing import TypeVar
T = TypeVar("T")
def log(value: T) -> None:
print(value)Here T appears once, so it links nothing. It behaves like object, and value: object says the same thing more plainly. Pyright reports this as a warning in strict mode, and linters flag it too.
Two parameters can also be tied together:
from typing import TypeVar
T = TypeVar("T")
def pick(a: T, b: T) -> T:
return a if len(str(a)) >= len(str(b)) else b
reveal_type(pick(1, 2))
reveal_type(pick(1, "x"))The first call gives int. The second call has no single solution, so the checker widens T to a common supertype. mypy reports object, and Pyright reports int | str. This is a real difference between the tools (see the later chapter on mypy and Pyright). Whichever you use, a result like this usually means the call mixes types you did not intend to mix.
Restricting a TypeVar
An unrestricted T accepts anything, so inside the function you can only do things every object supports. Two mechanisms narrow what T may be.
Bound
bound= says that T must be a subtype of a given class. Inside the function you can then use that class's methods, and the caller still gets back the specific subtype.
from typing import TypeVar
class Shape:
def area(self) -> float:
return 0.0
class Square(Shape):
def __init__(self, side: float) -> None:
self.side = side
def area(self) -> float:
return self.side * self.side
S = TypeVar("S", bound=Shape)
def largest(shapes: list[S]) -> S:
return max(shapes, key=lambda s: s.area())
biggest = largest([Square(1.0), Square(3.0)])
reveal_type(biggest)
print(biggest.side)reveal_type(biggest) shows Square, not Shape, so biggest.side is accepted. If the signature were def largest(shapes: list[Shape]) -> Shape, the last line would be an error because Shape has no side. Calling largest([1, 2]) is an error because int is not a Shape.
Constraints
Listing types positionally restricts T to exactly those types:
from typing import TypeVar
N = TypeVar("N", int, float)
def double(x: N) -> N:
return x * 2
reveal_type(double(2))
reveal_type(double(2.5))The checker type-checks the body once for each listed type. A call with str is rejected. Constraints differ from a bound in one way: a subclass of int passed to double is treated as plain int, so the result type loses the subclass. Prefer bound= unless the body really needs a different check for each type, as with str versus bytes.
| Form | Accepts | Result for a subclass argument | Typical use |
|---|---|---|---|
| `TypeVar("T")` | Any type | The exact type | Containers, identity-style helpers |
| `TypeVar("T", bound=Base)` | `Base` and subtypes | The exact subtype | Functions that call methods of `Base` |
| `TypeVar("T", int, float)` | Only the listed types | The listed type | Bodies that must be checked per type |
Generic classes
A class becomes generic by inheriting from Generic[T]. The TypeVar then stands for a type chosen when the class is used.
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()
numbers = Stack[int]()
numbers.push(1)
numbers.push("two")
reveal_type(numbers.pop())Stack[int]() fixes T to int for this instance. The call numbers.push("two") is reported as an incompatible argument (expected int), and numbers.pop() is int. You can also write numbers: Stack[int] = Stack() and let the annotation supply the type. If you write only numbers = Stack(), the checker cannot infer T from the empty constructor. mypy asks for an annotation ("Need type annotation"), and Pyright infers Stack[Unknown], which hides errors.
Built-in classes such as list, dict, and set are already generic, which is why list[int] works. Other generic classes you subclass supply their own type variables, for example class Names(list[str]).
Invariance and why list[int] is not list[float]
By default, generic classes are invariant. That means Stack[int] is not a Stack[float], even though int is accepted where float is expected. The rule exists because a mutable container could otherwise be corrupted:
def total(xs: list[float]) -> float:
return sum(xs)
ints: list[int] = [1, 2, 3]
total(ints)Both checkers reject this call. If total were allowed to take list[int] as list[float], it could append a float to a list the caller believes holds only int values. When the function only reads, use a read-only type such as Sequence[float], which is covariant and accepts Sequence[int].
The newer syntax
Python 3.12 added a shorter syntax (PEP 695) that declares type variables inline, with no TypeVar or Generic imports:
from collections.abc import Sequence
def first[T](items: Sequence[T]) -> T:
return items[0]
class Box[T]:
def __init__(self, value: T) -> None:
self.value = value
reveal_type(Box(3).value)A bound is written [S: Shape] and constraints [N: (int, float)]. This code only runs on Python 3.12 or newer, and it needs a checker version that understands the syntax (Pyright and current mypy releases do). Choose the TypeVar form when the project supports older Python versions, and the new form when it does not. Do not mix both styles for the same function.
Common errors
- Unsolved
Tin a return type only. A signature likedef make() -> Tgives the checker nothing to solve from. Both tools warn or inferUnknown/Never-like results. Return a concrete type, or accept a parameter that fixesT, such astype[T]. - Bare generic classes. Annotating a parameter as
listorStackmeanslist[Any]. Strict mode flags this (mypydisallow_any_generics). - Wrong
TypeVarname string. The string must equal the assigned name. - Using a constrained
TypeVarwhere a bound is enough. The result loses subclass information.
Exercise
You write T = TypeVar("T", bound=Shape) and def largest(shapes: list[T]) -> T. A teammate calls largest([Square(1.0)]) and then reads .side on the result. Will the checker accept this, and what would change if the signature were def largest(shapes: list[Shape]) -> Shape?
Show answer
With the TypeVar, the checker solves T = Square, so the result is Square and .side is accepted. With the plain Shape signature, the result is Shape, which has no side attribute, so the checker reports an error. (Passing list[Square] as list[Shape] is also rejected because list is invariant.)
Exercise
Why does def log(value: T) -> None add nothing over def log(value: object) -> None, and what rule of thumb does this suggest for TypeVars?
Show answer
T appears only once, so it links no two positions in the signature and the checker has nothing to carry from input to output. A TypeVar is useful only when it appears at least twice, such as in a parameter and the return type.