Sub topic 10
Generic protocols, type variables and variance
This chapter assumes you can write Python classes and annotations, know what a protocol is, and have run a type checker such as mypy or pyright. Here you will make protocols generic, learn why a type variable's variance matters, and use a protocol as a type variable bound.
Why a protocol needs a type variable
A protocol such as SupportsClose names fixed types. Many useful shapes depend on a type that changes from one object to the next. A source of values returns an int in one class and a str in another. A generic protocol lets you write that shape once and fill in the type later.
Declaring a generic protocol and its variance
You declare a generic protocol by adding a type variable to Protocol[...]. The type variable also needs a variance, which says how subtyping of the argument carries over to subtyping of the protocol.
from typing import Protocol, TypeVar
T_co = TypeVar("T_co", covariant=True)
class Source(Protocol[T_co]):
def get(self) -> T_co: ...
class IntSource:
def get(self) -> int:
return 7
def read_one(source: Source[float]) -> float:
return source.get()
read_one(IntSource()) # accepted: int is compatible with float, and T_co is covariantIntSource never mentions Source. The checker sees that get returns an int, and int is acceptable where float is expected. That only works because T_co is covariant.
The three kinds of variance
| Variance | Declared with | Safe when the type variable appears | Meaning |
|---|---|---|---|
| Covariant | `covariant=True` | only in return positions | `Source[int]` can be used as `Source[float]` |
| Contravariant | `contravariant=True` | only in parameter positions | `Sink[float]` can be used as `Sink[int]` |
| Invariant | neither | in both positions | only the exact same argument matches |
Covariance fits a producer. If a function only hands out values, handing out an int where a float is expected is safe. Contravariance fits a consumer. A sink that accepts any float can safely stand in for a sink that only receives int values. Invariance is the default, and it is the correct choice when a type is both read and written, such as a mutable container.
The naming convention T_co and T_contra is not required. Checkers use it as a hint, and it makes the declared variance visible to readers.
A protocol as a type variable bound
A bound limits which types a type variable can stand for. When the bound is a protocol, one function can accept any element type that has the required shape, and the result keeps that element type.
from typing import Protocol, TypeVar
class SupportsLessThan(Protocol):
def __lt__(self, other: object, /) -> bool: ...
T = TypeVar("T", bound=SupportsLessThan)
def smallest(items: list[T]) -> T:
result = items[0]
for item in items[1:]:
if item < result:
result = item
return result
print(smallest([3, 1, 2]))
print(smallest(["pear", "apple"]))Calling smallest([3, 1, 2]) gives int, and smallest(["pear", "apple"]) gives str. A plain SupportsLessThan annotation on the return value would lose that information and return only the protocol type. The positional-only marker / in __lt__ means the parameter name does not have to match, so classes that name it differently still qualify.
Common errors
- Marking a type variable covariant and then using it as a parameter type. The checker rejects this.
- Using an invariant type variable and expecting
Source[int]to work asSource[float]. It will not. - Writing a bound as a concrete class when you only need a shape. A protocol bound accepts more types without inheritance.
Exercise
A protocol Sink[T] has one method, put(self, value: T) -> None. Should T be covariant, contravariant or invariant? What does that let you pass to a function that expects Sink[int]?
Show answer
T should be contravariant (contravariant=True, conventionally named T_contra), because it appears only in a parameter position. A Sink[float] can then be passed where a Sink[int] is expected, since a sink that accepts any float can also accept ints.