Sub topic 3
The classic way: TypeVar and Generic
This chapter covers the pre-3.12 way to write generic code. It assumes you can write Python functions, classes, and methods, you know annotations such as list[int] and str | None, and you know that checkers like mypy or pyright read those annotations without running your program. You need this style for three reasons. It works on every supported Python version, a large amount of existing code uses it, and the newer syntax is easiest to understand as a shorthand for it.
What a TypeVar is
A TypeVar is a placeholder for a type. You create one with a call to typing.TypeVar, and you assign the result to a variable whose name matches the string you pass in.
from collections.abc import Sequence
from typing import TypeVar
T = TypeVar("T")
def first(items: Sequence[T]) -> T:
return items[0]
n = first([1, 2, 3]) # checker infers int
s = first(("a", "b")) # checker infers strEvery use of T inside one call refers to the same type. When you pass list[int], the checker solves T = int, so the return type is int. The function is generic because the relationship between input and return is stated once for all element types.
Without the placeholder you would have two poor options. Annotating with object or Any would lose the element type. Writing one overload per type would not scale.
A function-level TypeVar is solved separately for each call. The T in first([1, 2, 3]) and the T in first(("a", "b")) do not interfere.
Rules for creating a TypeVar
- The string must equal the variable name.
T = TypeVar("U")is an error in checkers, because they use the assignment target as the identity of the variable. - Create it at module level, as a plain assignment. Checkers do not follow type variables created inside functions or conditionals.
- Use short names (
T,K,V) or descriptive names with a leadingT(TItem) so they are easy to tell apart from real classes. - A
TypeVarbelongs to the scope that first uses it. ReusingTin many unrelated functions is normal and safe.
A type variable that appears only once in a function signature is usually a mistake:
from typing import TypeVar
T = TypeVar("T")
def count_items(items: list[T]) -> int: # T links nothing to anything
return len(items)Here T relates no two positions, so list[object] would say the same thing less confusingly. Some checkers report this. A TypeVar pays for itself when it appears at least twice, for example in a parameter and in the return type.
Making a class generic with Generic
A class becomes generic when it inherits from Generic[...], listing the type variables it uses.
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
a = Box(42) # checker infers Box[int]
b = Box[str]("hi") # explicit type argument
reveal_type(b.get()) # checker reports: strreveal_type is understood by checkers and is also available from typing in Python 3.11 and later. You can leave it out of real code.
There are two ways a type argument gets fixed. The checker can infer it from the constructor argument (Box(42)), or you can write it yourself (Box[str]("hi")). Writing it is necessary when inference has nothing to work with, as in an empty container:
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()
ints = Stack[int]()
ints.push(1)
ints.push("two") # checker error: str is not intWithout the [int], a checker usually asks for an annotation such as ints: Stack[int] = Stack().
Several type variables, and the order that matters
A generic class can take more than one parameter. The order inside Generic[...] defines the order of the type arguments.
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:
return self._data[key]
r = Registry[str, int]() # K = str, V = int
r.register("a", 1)If you write Generic[V, K], then Registry[str, int] means V = str, K = int. Keep the order natural for the reader.
Two rules apply to the Generic base:
- Every type variable used in the class body must appear in
Generic[...], or in another generic base class that is parameterized with it. - The arguments to
Generic[...]must be distinct type variables.Generic[int]andGeneric[T, T]are errors.
Subclassing generic classes
A subclass can fix some type parameters, all of them, or none.
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
class IntRegistry(Registry[str, int]): # fully specialized, not generic
pass
class NamedRegistry(Registry[str, V]): # still generic in V
pass
class Passthrough(Registry[K, V]): # same parameters as the base
pass
x = NamedRegistry[bytes]() # K = str, V = bytesNamedRegistry does not need to inherit Generic[V] again. Because its base Registry[str, V] mentions V, the class is automatically generic in V. If you want to list the parameters in a specific order, you can add Generic[...] explicitly, but it must include every type variable that appears.
Bounds, constraints, and variance flags
The TypeVar call takes keyword arguments that restrict or describe the variable. The next chapters cover the theory. The table shows where each one is written in the classic style.
| Goal | Classic form | Meaning |
|---|---|---|
| Upper bound | `TypeVar("T", bound=Sized)` | `T` must be `Sized` or a subtype |
| Constraints | `TypeVar("T", int, str)` | `T` is exactly `int` or exactly `str` in each call |
| Covariant | `TypeVar("T_co", covariant=True)` | Read-only use; `Box[int]` fits `Box[float]` |
| Contravariant | `TypeVar("T_contra", contravariant=True)` | Write-only use; reversed subtyping |
A bound lets you call the methods of the bound type:
from collections.abc import Sized
from typing import TypeVar
S = TypeVar("S", bound=Sized)
def longest(a: S, b: S) -> S:
return a if len(a) >= len(b) else bIn the classic style you must declare variance yourself. By convention a covariant variable ends in _co and a contravariant one in _contra.
from typing import Generic, TypeVar
T_co = TypeVar("T_co", covariant=True)
class ReadOnlyBox(Generic[T_co]):
def __init__(self, value: T_co) -> None:
self._value = value
def get(self) -> T_co:
return self._value
numbers: ReadOnlyBox[float] = ReadOnlyBox[int](3) # acceptedIf you declare covariant=True but then use the variable as a method parameter type (other than in __init__), checkers report an error. If you leave variance off, the variable is invariant, which is the safe default.
What exists at runtime
Python stores some generic information but does not enforce it. TypeVar objects and Generic bases are real objects that you can inspect.
from typing import Generic, TypeVar
T = TypeVar("T")
class Box(Generic[T]):
def __init__(self, value: T) -> None:
self.value = value
b = Box[int]("text") # a type checker reports an error here
print(type(b)) # <class '__main__.Box'>
print(Box.__parameters__) # (~T,)
print(Box.__orig_bases__) # (typing.Generic[~T],)
print(T.__name__) # TThe program runs without error. Box[int] creates a small alias object, and calling it builds an ordinary Box. The instance does not remember int. The __parameters__ and __orig_bases__ attributes exist so that tools and libraries can introspect the class.
Common errors
- Name mismatch.
T = TypeVar("X")fails checking. Always match the name. - Missing from Generic. Using
Tin a method of a class that does not list it inGeneric[...]leavesTscoped to that method only, which is rarely what you want. - Bare class used as a type. Writing
def f(b: Box)meansBox[Any]to the checker. Strict modes flag this, so writeBox[int]or a type variable. - Mixing Generic and Protocol. Protocol classes are generic already. Write
class Reader(Protocol[T_co]), notProtocol, Generic[T_co]. - Expecting runtime checks.
Box[int]("text")does not raise. Only the static checker complains. - Wrong variance. Declaring
covariant=Trueon a variable that appears as an input produces a checker error.
Exercise
A class is written as class Pair(Generic[A, B]) with A = TypeVar("A") and B = TypeVar("B"). A subclass is written class StrPair(Pair[str, B]). What are the type parameters of StrPair, and what does StrPair[int] mean for the two inputs of Pair?
Show answer
StrPair has one type parameter, B, because its base mentions B and so the subclass is generic in it. StrPair[int] means A = str and B = int for the underlying Pair. StrPair does not need to repeat Generic[B].
Exercise
The code below runs without any exception, yet a checker rejects it. Name the line that the checker rejects, and explain why Python itself does not. from typing import Generic, TypeVar T = TypeVar("T") class Cell(Generic[T]): def _init_(self, value: T) -> None: self.value = value c = Cell[int]("x") print(c.value)
Show answer
The checker rejects c = Cell[int]("x"), because the argument "x" is a str where T was fixed as int. Python does not reject it because type arguments are erased: Cell[int] is an alias that builds a normal Cell, and __init__ performs no type test. The program prints x.