Sub topic 9
Generic protocols
This chapter assumes you know generic functions and classes, the Python 3.12 [T] syntax, and the basic idea of variance. A generic protocol combines two ideas. A protocol describes a type by the methods it has. A type parameter lets those methods mention other types.
Why make a protocol generic
A plain Protocol says "any object with a close() method." Often that isn't enough, because you also need to say what the methods take or return. A protocol with a type parameter does that. Any class with matching methods satisfies it, with no inheritance needed.
from typing import Protocol
class Source[T](Protocol):
def get(self) -> T: ...
class Sink[T](Protocol):
def put(self, item: T) -> None: ...
class Counter:
def __init__(self) -> None:
self.n = 0
def get(self) -> int:
self.n += 1
return self.n
def drain[T](src: Source[T], count: int) -> list[T]:
return [src.get() for _ in range(count)]
print(drain(Counter(), 3)) # [1, 2, 3]; the checker infers list[int]Counter never mentions Source. The checker compares its get method with the protocol and solves T = int. The function drain therefore returns list[int].
Variance in protocols
Source[T] only returns T, so the checker infers T as covariant. Sink[T] only accepts T, so it infers T as contravariant. Here is Sink in use:
from typing import Protocol
class Sink[T](Protocol):
def put(self, item: T) -> None: ...
class Printer:
def put(self, item: object) -> None:
print(item)
def fill[T](sink: Sink[T], items: list[T]) -> None:
for item in items:
sink.put(item)
fill(Printer(), [1, 2, 3]) # accepted: a sink of object can take intsA Printer accepts any object, so it can stand in for a sink of int. Contravariance allows this: the more general consumer is the subtype.
The classic style needs explicit variance
Before Python 3.12, you write the type variable yourself and declare its variance by hand. Checkers report an error if the declared variance doesn't match how the protocol uses the variable.
from typing import Protocol, TypeVar
T_co = TypeVar("T_co", covariant=True)
class Source(Protocol[T_co]):
def get(self) -> T_co: ...The _co suffix is a naming convention for covariant variables. _contra marks contravariant ones. The 3.12 syntax removes this bookkeeping, because the checker infers the variance from the method signatures.
Protocols at runtime
A protocol is only a description for the checker. Calling isinstance(obj, Source) fails unless you add @runtime_checkable. Even then, it only checks that the method names exist. It cannot check T, and isinstance(obj, Source[int]) raises TypeError. Use runtime checks for "has this method" and rely on the static checker for the type arguments.
Exercise
A protocol Box[T] has def get(self) -> T and def set(self, value: T) -> None. What variance does the checker infer for T, and why can't you pass a Box[int] where a Box[float] is expected?
Show answer
It infers T as invariant, because T appears both as a return type (covariant position) and as a parameter type (contravariant position). If Box[int] were accepted as Box[float], a caller could call set(2.5) and put a float into a box that must hold only ints.