Sub topic 13
Designing small protocols and avoiding common pitfalls
This chapter assumes you can define a Protocol, know how a type checker such as mypy or pyright matches a class to it, and have seen @runtime_checkable. It covers how to size and shape protocols so they stay useful, and the mistakes that most often make them confusing or wrong.
Start from the consumer
A protocol describes what one piece of code needs. It does not describe everything a class can do. Write the function first, list the operations it calls on its parameter, and put exactly those operations in the protocol.
Consider a checksum function. It needs one thing, a read method.
import io
from typing import Protocol
class SupportsRead(Protocol):
def read(self, size: int = -1, /) -> bytes: ...
def checksum(source: SupportsRead) -> int:
return sum(source.read()) % 256
print(checksum(io.BytesIO(b"abc"))) # 38Files, BytesIO, sockets wrapped as file objects, and your own test doubles all qualify. If you had annotated the parameter as io.BufferedReader, none of the others would.
Split by capability
A protocol with many members forces every implementer, and every test fake, to provide all of them, even when a function uses only one. Split wide protocols into narrow ones, then combine them only where a function really needs both.
from typing import Protocol
class KeyReader(Protocol):
def read(self, key: str, /) -> bytes: ...
class KeyWriter(Protocol):
def write(self, key: str, data: bytes, /) -> None: ...
class KeyStore(KeyReader, KeyWriter, Protocol):
"""Both capabilities, for code that needs to read and write."""
class MemoryStore:
def __init__(self) -> None:
self._data: dict[str, bytes] = {}
def read(self, key: str, /) -> bytes:
return self._data[key]
def write(self, key: str, data: bytes, /) -> None:
self._data[key] = data
def copy(src: KeyReader, dst: KeyWriter, key: str) -> None:
dst.write(key, src.read(key))
def touch_up(store: KeyStore, key: str) -> None:
store.write(key, store.read(key).strip())
store = MemoryStore()
store.write("a", b" hello ")
copy(store, store, "a")
touch_up(store, "a")
print(store.read("a")) # b'hello'copy documents that it never deletes or lists anything. A read-only cache can be passed as src even though it has no write.
Where to put protocols
Define a protocol next to the code that consumes it, not next to the classes that implement it. The implementers never import it, which is the point of structural typing. If you put it beside the implementers, you recreate the coupling you were trying to remove.
Name protocols for the capability: SupportsRead, KeyWriter, Closeable. A name like IStorage suggests a class that must be inherited.
Common pitfalls
Composing protocols without listing Protocol
In the KeyStore example, Protocol appears in the bases list. If you leave it out, class KeyStore(KeyReader, KeyWriter) creates an ordinary class that inherits from protocols. It is no longer a protocol, so unrelated classes with the right methods no longer match it.
Writable attributes versus read-only properties
A protocol member declared as name: str means a writable attribute. A frozen dataclass or a read-only property does not satisfy it, because callers could assign to it. If the consumer only reads the value, say so with a property.
from dataclasses import dataclass
from typing import Protocol
class HasName(Protocol):
name: str # writable attribute
class ReadsName(Protocol):
@property
def name(self) -> str: ... # read-only is enough
@dataclass(frozen=True)
class Tag:
name: str
def rename(item: HasName) -> None:
item.name = item.name.title()
def greet(item: ReadsName) -> str:
return f"Hello, {item.name}"
print(greet(Tag("ada"))) # accepted
# rename(Tag("ada")) # rejected by a type checker: Tag.name is read-only,
# # and it would raise FrozenInstanceError at runtimePrefer the read-only form unless the function really assigns. It accepts more classes and tells the reader the function will not mutate the attribute.
Parameter names become part of the contract
A method parameter that can be passed by keyword is part of the protocol. If the protocol says factor and the class says x, a call such as s.scale(factor=3.0) fails, so the type checker rejects the class. If callers pass the argument positionally, mark the parameter positional-only with /. Implementers may then choose any name.
from typing import Protocol
class Scaler(Protocol):
def scale(self, factor: float, /) -> float: ...
class Doubler:
def scale(self, x: float) -> float:
return x * 2
def apply(scaler: Scaler) -> float:
return scaler.scale(3.0)
print(apply(Doubler())) # 6.0Without the /, a type checker reports Doubler as incompatible with Scaler, because the names differ.
Forgetting that explicit subclasses inherit the stubs
When a class explicitly subclasses a protocol, it inherits the protocol's method bodies. A body of ... returns None. If the class forgets to override the method, it runs without error and does nothing.
from typing import Protocol
class Closer(Protocol):
def close(self) -> None: ...
class Forgetful(Closer):
pass
print(Forgetful().close()) # None: the inherited stub ran silentlyMany type checkers flag this for protocol methods with trivial bodies, but you cannot rely on that for every method. If you want a hard runtime error for missing methods, subclass an ABC instead, as the previous chapter on choosing between the two explained. For protocols, usually skip explicit subclassing and let the checker verify the match.
Trusting isinstance more than it deserves
@runtime_checkable makes isinstance check that the named members exist. It does not check signatures, return types, or attribute types. Calling issubclass on a protocol with data members raises TypeError.
from typing import Protocol, runtime_checkable
@runtime_checkable
class Saveable(Protocol):
id: int
def save(self) -> None: ...
class Row:
id = "not an int"
def save(self, force: bool) -> None:
print("saved")
print(isinstance(Row(), Saveable)) # True, although both members are wrong
try:
issubclass(Row, Saveable)
except TypeError as error:
print("issubclass failed:", error)Use runtime checks for cheap dispatch between a few known shapes, such as "does this have a close method". Do not use them for validating untrusted input. For protocols with only methods and a pass-or-fail answer, isinstance is acceptable. For anything with data members, treat the result as a hint.
Narrow return types, wide parameter types
A function that returns list[int] can stand in for a protocol method that returns Sequence[int], since the caller expects at most a sequence. The reverse fails. For parameters the direction flips. A protocol method that accepts str can be implemented by a class whose method accepts object, but not one that accepts only LiteralString.
When a protocol's type variable appears only in return positions, declare it covariant (T_co). When it appears only in parameters, declare it contravariant (T_contra). If a checker complains about variance, check where the variable is used before changing anything else.
Protocols for things that have one implementation
A protocol with one implementer and one consumer adds a file and a name without adding flexibility. Introduce it when a second implementation or a test fake appears, or when you must avoid an import dependency. Because the match is structural, adding the protocol later requires no change to the existing class.
Summary of pitfalls
| Pitfall | Symptom | Fix |
|---|---|---|
| Wide protocol | Test fakes implement many unused methods | Split by capability, combine with a protocol subclass |
| Missing `Protocol` in bases | Unrelated classes no longer match | List `Protocol` explicitly |
| `name: str` for read-only data | Frozen dataclasses and properties rejected | Use a `@property` member |
| Keyword-name mismatch | Checker rejects a class with the right method | Use `/` for positional-only parameters |
| Explicit subclass, method not overridden | Method silently returns `None` | Override it, or use an ABC |
| Over-trusting `isinstance` | Wrong signatures pass at runtime | Treat it as a presence check only |
| Premature protocol | Extra abstraction with one implementer | Add it when a second implementer appears |
Exercises
Exercise
A function log_all(items) calls only item.describe() on each element. A colleague proposes a protocol Entity with describe, save, delete and id. Rewrite the design in one short protocol and say why it is better.
Show answer
Define class Describable(Protocol): def describe(self) -> str: ... and annotate the parameter as Iterable[Describable]. It is better because any class with describe can be passed, including test fakes that implement nothing else, and the signature shows that log_all never saves or deletes anything. The wide Entity protocol would force every implementer to provide four members for a function that uses one.
Exercise
Given class Config(Protocol): timeout: float and a @dataclass(frozen=True) class Settings: timeout: float, a type checker rejects connect(Settings(2.0)) where connect(cfg: Config) only reads cfg.timeout. What change fixes it, and why does it work?
Show answer
Declare the protocol member as a read-only property: @property def timeout(self) -> float: .... A plain timeout: float declares a writable attribute, which a frozen dataclass cannot provide. A read-only property requires only that the value can be read, so a frozen dataclass, a plain attribute and a property all satisfy it.
Exercise
A @runtime_checkable protocol requires def save(self) -> None. A class defines def save(self, force: bool) -> None. What does isinstance(obj, Protocol) return, and what does a type checker say?
Show answer
isinstance returns True, because it only checks that a member named save exists. A type checker reports that the class is incompatible with the protocol, since a caller using obj.save() with no arguments would fail on the required force parameter.