Sub topic 9
Generic protocols
This chapter assumes you know ordinary protocols (typing.Protocol), generic functions and classes, and the def f[T] and class C[T] syntax from Python 3.12. It builds on the variance chapter. If "covariant" and "contravariant" are unfamiliar, read that chapter first.
What a generic protocol is
A protocol describes a set of methods or attributes. Any class that has them matches the protocol, even if it never names the protocol as a base class. This is structural typing. A generic protocol adds a type parameter, so the shape can mention a type that varies from one implementation to the next.
A plain protocol can say "has a get() method". A generic protocol can say "has a get() method that returns some T", where the checker works out T for each class it sees.
from typing import Protocol, runtime_checkable
@runtime_checkable
class Source[T](Protocol):
def get(self) -> T: ...
class Counter:
def __init__(self) -> None:
self.n = 0
def get(self) -> int:
self.n += 1
return self.n
def take[T](src: Source[T], count: int) -> list[T]:
return [src.get() for _ in range(count)]
print(take(Counter(), 3)) # [1, 2, 3]
print(isinstance(Counter(), Source)) # True
try:
isinstance(Counter(), Source[int])
except TypeError:
print("TypeError: subscripted generics cannot be used with isinstance")Counter does not inherit from Source. The checker compares Counter.get with Source[T].get, solves T = int, and so infers that take(Counter(), 3) returns list[int].
The class header class Source[T](Protocol) puts the type parameters first and the base classes in parentheses. Protocol is a normal base class here and needs no subscript.
How the checker matches a class
The checker does not look at a class's ancestors. It checks each member the protocol requires, and it does so with the type parameter left open.
If Counter.get required an extra argument, or returned str where the call site needed int, the match would fail at the same step.
Variance in protocols
Variance is the rule for whether Source[int] may stand in for Source[float], or the reverse. With the 3.12 syntax, the checker infers variance from how T is used in the protocol body. You do not declare it.
- If
Tappears only in return types, the protocol is covariant inT. This is a producer. - If
Tappears only in parameter types, the protocol is contravariant inT. This is a consumer. - If
Tappears in both places, or in a mutable attribute, the protocol is invariant.
from typing import Protocol
class Source[T](Protocol):
def get(self) -> T: ...
class Sink[T](Protocol):
def put(self, item: T) -> None: ...
class Channel[T](Protocol):
def get(self) -> T: ...
def put(self, item: T) -> None: ...
class Collector:
def put(self, item: object) -> None:
print("got", item)
def feed(sink: Sink[int]) -> None:
sink.put(42)
feed(Collector()) # accepted: Sink[object] works where Sink[int] is expectedCollector.put accepts any object, so it can safely receive an int. That is contravariance: a sink of a wider type can replace a sink of a narrower type. Source[int] can likewise replace Source[float], because every int the source returns is also a float. Channel[T] both returns and accepts T, so it is invariant, and neither substitution is allowed.
Attributes are mutable by default
A plain attribute in a protocol is read-write, so the checker treats it as both an input and an output. It makes T invariant. To express "read only", use a property:
from typing import Protocol
class HasValue[T](Protocol):
@property
def value(self) -> T: ... # read-only, so covariant
class MutableValue[T](Protocol):
value: T # read-write, so invariantUse the read-only form unless the function really assigns to the attribute.
The classic spelling
Before 3.12, a protocol listed its type variables in Protocol[...], and you had to pick the variance yourself:
from typing import Protocol, TypeVar
T_co = TypeVar("T_co", covariant=True)
T_contra = TypeVar("T_contra", contravariant=True)
class Source(Protocol[T_co]):
def get(self) -> T_co: ...
class Sink(Protocol[T_contra]):
def put(self, item: T_contra) -> None: ...The checker verifies the declared variance against the protocol body. If you write TypeVar("T") (invariant) but use it only in a return type, mypy and pyright report that the type variable should be covariant. This is a common error when converting older code. The _co and _contra suffixes are a naming convention that the checkers expect.
| Aspect | Classic style | Python 3.12 syntax |
|---|---|---|
| Declaring the parameter | `T_co = TypeVar("T_co", covariant=True)` | `class Source[T](Protocol)` |
| Naming the protocol base | `Protocol[T_co]` | `Protocol` |
| Variance | Written by hand, checked by the tool | Inferred by the tool |
| Scope of `T` | Module-level name shared by many classes | Local to the class |
You cannot mix the two on one class. Writing class Source[T](Protocol[T]) is an error, because the class already declares T.
Protocols from the standard library
Many familiar types are generic protocols. collections.abc.Iterable[T] requires __iter__, and Iterator[T] adds __next__. typing.SupportsAbs[T] requires __abs__() -> T, and SupportsIndex is a non-generic example. When you write def total[T](items: Iterable[T]), you accept lists, sets, generators, and your own classes that define __iter__, without any registration step.
Prefer these over writing your own when they fit. A parameter typed Iterable[str] is easier to call than one typed list[str], since callers need not convert their data.
Callback protocols
A protocol with a __call__ method describes a callable. It can express things that Callable[[...], ...] cannot, such as keyword-only parameters, default values, and named arguments. Making it generic lets one definition cover many event types.
from typing import Protocol
class Handler[T](Protocol):
def __call__(self, event: T, *, retries: int = 0) -> bool: ...
def dispatch[T](handler: Handler[T], event: T) -> bool:
return handler(event, retries=2)
def on_text(event: str, *, retries: int = 0) -> bool:
print(f"handling {event!r} with {retries} retries")
return True
dispatch(on_text, "hello")The function on_text matches Handler[str] because its parameters line up with __call__. The parameter event is in an input position, so Handler is contravariant in T.
Subclassing a protocol explicitly
You may inherit from a protocol, with the type argument filled in:
class Counter(Source[int]):
def get(self) -> int:
return 1This has two effects. The checker verifies at the class definition that you implemented every member, and the protocol's non-abstract methods become available as defaults. The gotcha is that a protocol method whose body is just ... is inherited as-is. If you forget to override it, the call returns None at runtime, and the checker may not warn you unless the method is marked @abstractmethod. Mark required members abstract if you plan to subclass explicitly.
Runtime behavior
Protocols are static constructs. At runtime, Source[int] is an alias object that records its arguments, and it does nothing else.
isinstance(x, Source)works only if the protocol is decorated with@runtime_checkable. It checks that the method names exist. It does not check signatures or return types.isinstance(x, Source[int])always raisesTypeError, because the type argument cannot be verified from an object.- Protocols with non-method members (data attributes) cannot be used with
issubclass.
Choosing between a protocol and a base class
| Situation | Better choice |
|---|---|
| You need to accept classes you do not control | Generic protocol |
| Implementations should share code or state | Abstract base class with `Generic` or `[T]` |
| You want `isinstance` checks on type arguments | Neither works. Store a runtime tag instead. |
| The shape is "one function with this signature" | Callback protocol or `Callable` |
Exercise
A protocol is written as class Box[T](Protocol): value: T. A function takes Box[float]. Can you pass a Box[int]? How would you change the protocol so you can?
Show answer
No. The attribute value: T is read-write, so the checker infers T as invariant, and Box[int] is not accepted where Box[float] is expected. Change the member to a read-only property: @property def value(self) -> T: .... T then appears only in an output position, so it is inferred as covariant, and Box[int] is accepted.
Exercise
Write a generic protocol Parser[T] with a method parse(self, text: str) -> T. Then write a function parse_all[T](parser: Parser[T], lines: list[str]) -> list[T]. What does the checker infer for parse_all(IntParser(), ["1", "2"]) if IntParser.parse returns int?
Show answer
The protocol is class Parser[T](Protocol): def parse(self, text: str) -> T: .... The function body is return [parser.parse(line) for line in lines]. The checker compares IntParser.parse with Parser[T].parse, solves T = int, and infers list[int].