Sub topic 3
Python Protocols and Structural Subtyping
Assume you know Python functions, classes, type annotations, inheritance, and static type checkers such as mypy or pyright.
Callback protocols: typing callables with keyword arguments
A callback protocol describes a callable object by defining __call__. This is more expressive than Callable when a callback has keyword-only arguments, defaults, or other detailed rules.
from typing import Protocol
class Handler(Protocol):
def __call__(self, event: str, *, retries: int = 0) -> bool: ...
def log_handler(event: str, *, retries: int = 0) -> bool:
print(f"{event} (retries={retries})")
return True
def run(handler: Handler) -> None:
handler("started", retries=2)
run(log_handler)log_handler does not inherit from Handler. A type checker accepts it because its callable shape matches the protocol.
Generic protocols, type variables, and variance
A generic protocol uses a type variable to preserve relationships between input and output types. A read-only source can be covariant: a source of a more specific type can replace a source of a more general type.
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()))Covariance is appropriate here because T_co appears only in a return position. A protocol that accepts values usually needs an invariant or contravariant design instead.
Standard-library protocols
The standard library provides protocols through collections.abc. Use them when your function needs behavior rather than a particular class.
from collections.abc import Iterable, Sized
def describe(items: Iterable[str]) -> str:
return ", ".join(items)
def is_empty(container: Sized) -> bool:
return len(container) == 0
print(describe(x for x in "ab"))
print(is_empty([]))Iterable[str] accepts lists, generators, and custom iterable objects. Sized describes objects that support len().
Protocol or abstract base class?
Choose a Protocol when unrelated classes should work because they already have the required shape. Choose an abstract base class when you control the hierarchy and need shared implementation, registration, or enforced inheritance.
Design guidelines and common pitfalls
- Use a protocol to describe what callers need, not how an object is implemented.
- Check method parameters carefully. A similar name is not enough.
- Remember that static compatibility does not validate behavior or runtime results.
- Use
@runtime_checkableonly for simple member-presence checks;isinstancedoes not verify signatures or return types. - Prefer standard-library protocols when one already describes the required operation.
Exercise
Why can a function with the right __call__ signature satisfy a callback protocol without inheriting from it?
Show answer
Protocols use structural subtyping, so a type checker compares the callable's members and signature instead of requiring declared inheritance.