Sub topic 7
Variance and Automatic Variance Inference
This chapter assumes you can write generic classes with class Box[T] or Generic[T]. It also assumes you know that a static checker such as mypy or pyright reads your annotations without running the program. Here you will learn how the relationship between two types carries over to generic types built from them. You will also see how Python 3.12 lets the checker work that out for you.
The question variance answers
A subtype is a type that can be used wherever another type is expected. For type checking, int is accepted wherever float is expected, so int counts as a subtype of float.
Take a generic container Box[T]. If int is a subtype of float, is Box[int] a subtype of Box[float]? The answer depends on how the class uses T. Variance is the name for that answer.
| Variance | Meaning | `Box[int]` vs `Box[float]` |
|---|---|---|
| Covariant | Subtyping goes the same direction as the argument | `Box[int]` is usable as `Box[float]` |
| Contravariant | Subtyping goes the opposite direction | `Box[float]` is usable as `Box[int]` |
| Invariant | No subtyping between different arguments | Neither is usable as the other |
Why mutable containers are invariant
Suppose list[int] were accepted wherever list[float] is expected:
def add_pi(xs: list[float]) -> None:
xs.append(3.14)
ints: list[int] = [1, 2, 3]
add_pi(ints) # a type checker reports an error hereIf the checker allowed this call, ints would end up holding a float, and the declaration list[int] would be false. The checker blocks the call because list both reads and writes its elements, so it is invariant in T.
A read-only view has no such problem. Sequence[float] only hands out elements, so a Sequence[int] is always a valid Sequence[float]:
from collections.abc import Sequence
def total(xs: Sequence[float]) -> float:
return sum(xs)
print(total([1, 2, 3])) # 6, accepted because Sequence is covariantThe rule of thumb is that producing values is safe to widen, and consuming values is safe to narrow.
The three cases in code
Here is a covariant class. T only comes out of it:
class ReadOnlyBox[T]:
def __init__(self, value: T) -> None:
self._value = value
def get(self) -> T:
return self._value
numbers: ReadOnlyBox[float] = ReadOnlyBox[int](3) # acceptedHere is a contravariant class. T only goes in:
class Printer[T]:
def show(self, item: T) -> None:
print(item)
def show_one(p: Printer[int]) -> None:
p.show(1)
show_one(Printer[float]()) # accepted: a printer of floats can print intsA Printer[float] can handle any float, and every int is acceptable as a float. So it is safe wherever a Printer[int] is needed. The reverse is unsafe, because a Printer[int] might fail on 3.14.
Here is an invariant class. T goes both in and out:
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()push consumes T and pop produces it, so both directions are unsafe and Stack[int] and Stack[float] are unrelated.
Declaring variance by hand (classic style)
Before Python 3.12 you chose the variance yourself when you created the type variable:
from typing import Generic, TypeVar
T_co = TypeVar("T_co", covariant=True)
T_contra = TypeVar("T_contra", contravariant=True)
class ReadOnlyBox(Generic[T_co]):
def __init__(self, value: T_co) -> None:
self._value = value
def get(self) -> T_co:
return self._value
class Printer(Generic[T_contra]):
def show(self, item: T_contra) -> None:
print(item)By convention the names end in _co and _contra. A plain TypeVar("T") is invariant.
The checker verifies your declaration. If you declare T_co covariant and then use it as a method parameter, you get an error like "covariant type variable cannot be used in parameter type":
from typing import Generic, TypeVar
T_co = TypeVar("T_co", covariant=True)
class BrokenBox(Generic[T_co]):
def set(self, value: T_co) -> None: # a type checker reports an error here
...__init__ is exempt from this check, which is why ReadOnlyBox above can accept T_co in its constructor. The constructor runs before the object exists, so no existing Box[float] reference can be corrupted through it.
Hand-declared variance has two drawbacks. You must keep the declaration in step with the class as methods are added. You also need three kinds of TypeVar and naming rules to track them.
Automatic variance inference (Python 3.12)
Type parameters declared with the new syntax have no variance setting at all. The checker infers it from the class body. This applies to class Box[T], to classes declared with type aliases, and to protocols.
In outline, the checker tests whether a hypothetical Box[Narrow] can stand in for Box[Wide], and the reverse, by checking every member of the class. The usual outcomes are:
Tappears only in return types and in read-only attributes: covariant.Tappears only in method parameter types: contravariant.Tappears in both, or in a mutable attribute that outside code can assign: invariant.
Mutable attributes matter. The ReadOnlyBox above stores T in self._value, which looks like a writable attribute. Checkers such as pyright treat attributes whose names start with an underscore as private and leave them out of the check, so the class is covariant. A public attribute self.value = value would count as writable, and the class would be invariant. Immutable forms also stay covariant:
from dataclasses import dataclass
@dataclass(frozen=True)
class Item[T]:
value: T # frozen, so only read access exists: covariant
def describe(x: Item[float]) -> str:
return f"item {x.value}"
print(describe(Item[int](4))) # acceptedTwo details are worth remembering:
__init__and__new__are exempt from inference, as in the classic case.- Inference follows the class as written. If you later add a method that takes
Tas a parameter to a covariant class, the class silently becomes invariant. Callers who relied on the covariance now get errors at their call sites.
For that reason, if a class is part of a public API and its variance is a promise, write a small test that assigns Box[int] to Box[float] and have the checker run it.
You can also get inference with the old syntax, from Python 3.12 on, with TypeVar("T", infer_variance=True). This helps when you must keep Generic[T] but want the checker to decide.
Variance at runtime
Variance is checker-only information. Python does not compute it, and you can see this on the type parameter object:
class ReadOnlyBox[T]:
def __init__(self, value: T) -> None:
self._value = value
def get(self) -> T:
return self._value
t = ReadOnlyBox.__type_params__[0]
print(t.__infer_variance__) # True
print(t.__covariant__) # False
print(t.__contravariant__) # FalsePython only records that the checker was asked to infer the variance. No runtime check enforces it, and Box[int] and Box[float] instances behave the same way when the program runs.
Variance of common standard types
Knowing these saves you from many puzzling errors:
| Type | Variance | Notes |
|---|---|---|
| `list[T]`, `set[T]`, `dict[K, V]` (in `V`) | Invariant | They can be modified |
| `Sequence[T]`, `Iterable[T]`, `Collection[T]` | Covariant | Read-only interfaces |
| `tuple[T, ...]` | Covariant | Immutable |
| `Mapping[K, V]` | Invariant in `K`, covariant in `V` | Keys are used for lookup, so they cannot be widened |
| `Callable[[A], R]` | Contravariant in `A`, covariant in `R` | A function that accepts more can replace one that accepts less |
Fixing an invariance error
When the checker says list[int] is not compatible with list[float], work through these steps:
- Ask whether the function really modifies the list. If it only reads, change the parameter to
Sequence[float]orIterable[float]. This is the usual fix. - If the function does modify the list, the checker is right. Make the function generic, as in
def add[T: float](xs: list[T], x: T), or change the caller's variable type. - Do not silence the error with
# type: ignoreunless you can explain why the code is safe, because the error usually points at a real bug.
Exercise
A class Queue[T] has def put(self, item: T) -> None and def get(self) -> T. Using the 3.12 syntax, what variance does the checker infer for T? What change to the class would make T covariant, and what would you lose?
Show answer
Invariant, because T appears both as a parameter (put) and as a return type (get). Removing put (or making the queue read-only after construction) leaves T only in return types, so it becomes covariant and a Queue[int] can be used as a Queue[float]. You lose the ability to add items after the queue is built.
Exercise
A function is declared as def total(xs: list[float]) -> float: return sum(xs). Passing a list[int] raises a checker error. Rewrite the signature so the call is accepted without # type: ignore, and explain why that is safe.
Show answer
Use def total(xs: Sequence[float]) -> float: return sum(xs) with from collections.abc import Sequence. Sequence is covariant and read-only, so a Sequence[int] is a valid Sequence[float], and the function cannot insert a float into the caller's list.
Exercise
What do __covariant__ and __infer_variance__ show on Stack.__type_params__[0] for a class Stack[T] defined with the 3.12 syntax, and what does that tell you about who computes variance?
Show answer
__covariant__ is False and __infer_variance__ is True. Python only records that inference was requested. The static checker computes the actual variance, and nothing is enforced at runtime.