Sub topic 10
Generic Protocols, Type Variables and Variance
This chapter assumes you can write a basic Protocol, you know how type checkers such as mypy or pyright match a class to a protocol by shape, and you have seen TypeVar and list[int]-style generics. Here you combine the two ideas. You will make protocols generic, constrain type variables with a protocol, and learn why a protocol's type variables need a declared variance.
Why make a protocol generic
A plain protocol such as SupportsClose fixes every type in its signature. Many shapes depend on another type, though. A "source" has a get() method, but what get() returns depends on the source. A generic protocol leaves that type as a parameter, the same way list[T] does.
Without a parameter you would have to choose between -> object, which loses information, and one protocol per element type, which does not scale. A generic protocol lets the checker work out the element type from the object you pass in.
Declaring a generic protocol
Subscript Protocol with the type variables. Then use the protocol with a concrete type, as you would list[int].
from typing import Protocol, TypeVar
T_co = TypeVar("T_co", covariant=True)
T = TypeVar("T")
class Source(Protocol[T_co]):
def get(self) -> T_co: ...
class IntSource:
def get(self) -> int:
return 7
class StrSource:
def get(self) -> str:
return "seven"
def first(source: Source[T]) -> T:
return source.get()
print(first(IntSource())) # the checker infers int
print(first(StrSource())) # the checker infers strNeither IntSource nor StrSource mentions Source. The checker compares the shape of get, solves T from its return type, and gives each call the right result type. Note that first uses a plain invariant T in its own signature. The variance requirement applies to type variables declared on the protocol class, not to every function that uses the protocol.
What variance means
Variance answers one question: if A is a subtype of B, what is the relationship between Source[A] and Source[B]? There are three answers.
| Variance | Declared with | Relationship | Typical position |
|---|---|---|---|
| Covariant | `covariant=True` | `Source[int]` is usable as `Source[float]` | Return types, read-only properties |
| Contravariant | `contravariant=True` | `Sink[float]` is usable as `Sink[int]` | Method parameters |
| Invariant | default | Neither direction is allowed | Both, or mutable attributes |
The reasoning is about safety. A caller who wants a Source[float] will read floats from it. A source that produces ints never hands over anything unexpected, so it is safe. A caller who wants a Sink[int] will only put ints in. A sink that accepts any float handles those ints, so it is safe too. The type flows out in the first case and in in the second, and the variance follows that direction.
Covariant protocols: values flowing out
When the type variable appears only in return positions, declare it covariant. This is the example from the introduction to this idea:
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()
print(read_one(IntSource())) # accepted: int is compatible with floatThe _co suffix is a naming convention, not a Python rule. Type checkers rely on you following it, and some will warn if a covariant variable lacks the suffix.
Contravariant protocols: values flowing in
When the type variable appears only in parameter positions, declare it contravariant:
from typing import Protocol, TypeVar
T_contra = TypeVar("T_contra", contravariant=True)
class Sink(Protocol[T_contra]):
def put(self, item: T_contra) -> None: ...
class PrintSink:
def put(self, item: object) -> None:
print(f"got {item!r}")
def fill(sink: Sink[int]) -> None:
for number in range(3):
sink.put(number)
fill(PrintSink()) # accepted: a sink for any object can take intsPrintSink accepts object, which is wider than int. That is exactly the case contravariance permits: a method that accepts more can replace one that accepts less.
Invariant protocols: reading and writing
If a type variable appears in both a parameter and a return type, no direction is safe, so it must stay invariant.
from typing import Protocol, TypeVar
T = TypeVar("T")
class Box(Protocol[T]):
def get(self) -> T: ...
def set(self, value: T) -> None: ...
class IntBox:
def __init__(self, value: int) -> None:
self.value = value
def get(self) -> int:
return self.value
def set(self, value: int) -> None:
self.value = value
def reset(box: Box[int]) -> None:
box.set(0)
reset(IntBox(5)) # fine: exact match on intIf a Box[int] could be used as a Box[float], a caller could call set(1.5) and store a float in a box that only holds ints. If it could be used the other way, get() might return something that is not an int. Invariance blocks both mistakes.
The checker verifies your declarations against the members. If you leave T invariant on Source, which only uses it in a return type, mypy and pyright report that an invariant type variable is used where a covariant one is expected. Such a protocol is not wrong, but it is needlessly strict: Source[int] would not be accepted for Source[float]. Treat the message as a hint to choose the right variance.
Mutable attributes are a frequent trap. A protocol with items: T declares a read-write attribute, which behaves like a getter and a setter, so T must be invariant. If callers only read it, declare a read-only property and use a covariant variable:
from typing import Protocol, TypeVar
T_co = TypeVar("T_co", covariant=True)
class HasValue(Protocol[T_co]):
@property
def value(self) -> T_co: ...
class Reading:
def __init__(self, value: float) -> None:
self.value = value
def show(item: HasValue[float]) -> None:
print(item.value)
show(Reading(21.5))Bounding a type variable with a protocol
A protocol can also be the upper bound of an ordinary TypeVar. This says: any type is allowed as long as it fits the shape, and the same type is returned.
from typing import Any, Protocol, TypeVar
class SupportsLessThan(Protocol):
def __lt__(self, other: Any, /) -> 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"]))The parameter is typed Any for a reason. The built-in int.__lt__ accepts only an int. If the protocol demanded that __lt__ accept any object, int would fail the check, because a method with a narrower parameter cannot stand in for one with a wider parameter. The standard library's own comparison protocols in typeshed avoid this with a contravariant type variable for the other operand. For most application code, Any is the simple choice.
The bound gives you two things that -> SupportsLessThan would not. The checker knows that smallest([3, 1, 2]) returns int, not just "something comparable". It also rejects a list that mixes types with no shared comparison.
Python 3.12 syntax
Python 3.12 added a compact syntax where the checker infers variance from how the variable is used, so you no longer write the suffixes or the covariant argument:
from typing import Protocol
class Source[T](Protocol):
def get(self) -> T: ...
class IntSource:
def get(self) -> int:
return 7
def read_one(source: Source[float]) -> float:
return source.get()
print(read_one(IntSource()))Use this form if your minimum supported version is 3.12. Otherwise, keep the TypeVar form shown earlier.
Common errors
- Wrong variance declaration. Declaring
T_cocovariant and then using it as a method parameter gets an error. Move it to a return type, or make it invariant. - Mixing flow directions. One variable used for both input and output must be invariant. Splitting the protocol into a
Sourceand aSinkis often cleaner. - Expecting runtime enforcement. Variance exists only for the checker. At runtime,
Source[int]is just a subscripted class and nothing verifies the element type. - Subscripting a runtime check.
isinstance(x, Source[int])raises aTypeError. A runtime check can only use the unsubscripted protocol, and only if it is decorated with@runtime_checkable. - Forgetting the bound on a mixed list. Without a bound,
item < resultis an error because a bareThas no__lt__.
Exercise
You write class Sink(Protocol[T]) with an invariant T and a single method def put(self, item: T) -> None. A function takes a Sink[int], and you pass an object whose put accepts object. Does the checker accept it, and what change would you make to the protocol?
Show answer
With an invariant T, the checker requires an exact match, so Sink[object] is not accepted as Sink[int] and the call is rejected. T appears only in a parameter position, so declare it contravariant: T_contra = TypeVar("T_contra", contravariant=True) and class Sink(Protocol[T_contra]). Then a sink that accepts object is accepted where a Sink[int] is expected.
Exercise
A protocol has def get(self) -> T and def set(self, value: T) -> None. Which variance must T have, and why can neither covariant nor contravariant work?
Show answer
T must be invariant. Covariant would let a Box[int] be used as a Box[float], so set(1.5) could store a float in an int box. Contravariant would let a Box[float] be used as a Box[int], so get() could return a float where an int is expected. Both directions are unsafe, so only an exact match is allowed.