Sub topic 7
Variance and automatic variance inference
This chapter assumes you can write generic classes with class Box[T], know that type arguments are checked only by static tools like mypy or pyright, and understand subtyping (int is accepted where float is expected under the typing rules).
The question variance answers
If int is acceptable where float is expected, is list[int] acceptable where list[float] is expected? The answer depends on how the generic class uses its type parameter. Variance is the rule that relates Box[int] and Box[float] to the relation between int and float.
There are three kinds:
| Kind | Meaning | Typical use |
|---|---|---|
| Covariant | `Box[int]` is a subtype of `Box[float]` | The type is only produced (returned) |
| Contravariant | `Box[float]` is a subtype of `Box[int]` | The type is only consumed (accepted) |
| Invariant | Neither is a subtype of the other | The type is both produced and consumed |
Why mutable containers are invariant
Suppose list[int] were accepted as list[float]. Code could then add a float to what is really a list of ints.
def add_half(values: list[float]) -> None:
values.append(0.5)
ints: list[int] = [1, 2, 3]
add_half(ints) # a type checker reports an error hereBecause list[T] both returns items and accepts them, it is invariant. The checker rejects the call, which protects ints from receiving 0.5.
Covariance and contravariance
A read-only container only produces values, so substituting a narrower type is safe. Anything that reads a float from it also accepts an int.
A consumer works the other way. A function that accepts any float can handle an int, so a consumer of float can stand in for a consumer of int.
from collections.abc import Callable
def apply(handler: Callable[[int], None], value: int) -> None:
handler(value)
def handle_float(x: float) -> None:
print(x)
apply(handle_float, 3) # accepted: a float handler can take an intCallable is contravariant in its parameter types and covariant in its return type.
Automatic inference with the new syntax
Before Python 3.12 you declared variance by hand: TypeVar("T_co", covariant=True). With the type parameter syntax, you write class Box[T] and the type checker infers variance from how T is used in the class body. This is specified in PEP 695.
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)T appears only in the return type of get, and the constructor is not counted. The checker infers covariance, so the assignment is accepted. If you add a method set(self, value: T) and a public attribute that can be assigned, T becomes invariant and the assignment is rejected.
A Sink[T] whose methods only accept T is inferred as contravariant.
class Sink[T]:
def send(self, item: T) -> None:
print(item)
def feed_ints(sink: Sink[int]) -> None:
sink.send(1)
feed_ints(Sink[float]()) # accepted: Sink is contravariantCommon errors
- Annotating a parameter as
list[float]and passinglist[int]. UseSequence[float], which is covariant, when the function only reads. - Expecting a mutable attribute to stay covariant. A public, assignable attribute of type
TmakesTinvariant. - Assuming variance is checked at runtime. It is not. Only the static checker uses it.
Exercise
A class Queue[T] has put(self, item: T) and get(self) -> T. With the Python 3.12 syntax, will a checker accept Queue[int] where Queue[float] is expected? Why?
Show answer
No. T is both accepted (in put) and returned (in get), so the checker infers T as invariant. Queue[int] and Queue[float] are unrelated types.
Exercise
A function def total(xs: list[float]) -> float rejects a list[int] argument. What change to the annotation lets it accept both, and why is it safe?
Show answer
Change the parameter to Sequence[float] (or Iterable[float]). These types only produce items, so they are covariant, and a function that only reads cannot insert a wrong type.