Sub topic 13
Designing small protocols and avoiding common pitfalls
This chapter assumes you can write Protocol classes, know how a type checker such as mypy or pyright matches them, and have seen @runtime_checkable and the standard-library protocols. Here we turn those pieces into design rules.
Keep each protocol small
A protocol should describe what one function needs, not everything a class can do. Small protocols are easy to satisfy, easy to fake in tests, and rarely need to change.
Define the protocol next to the code that consumes it, not next to the implementations. The consumer knows what it needs. The implementations never have to import it.
import io
from typing import Protocol
class SupportsRead(Protocol):
def read(self, size: int = -1, /) -> bytes: ...
def count_bytes(source: SupportsRead) -> int:
return len(source.read())
print(count_bytes(io.BytesIO(b"abc")))count_bytes needs only read, so the protocol lists only read. A file, a BytesIO and a test double all qualify. If a function needs two capabilities, combine two small protocols instead of writing one large one.
from typing import Protocol
class SupportsRead(Protocol):
def read(self) -> bytes: ...
class SupportsClose(Protocol):
def close(self) -> None: ...
class ReadableResource(SupportsRead, SupportsClose, Protocol):
passA protocol that inherits from other protocols must list Protocol again as a base. Without it, the new class is an ordinary class.
Pitfalls and fixes
| Pitfall | What happens | Fix |
|---|---|---|
| Parameter names differ from the protocol | The checker rejects the class, because callers could pass the argument by keyword | Make protocol parameters positional-only with `/` |
| Protocol declares a mutable attribute | A read-only property or a narrower attribute type does not match | Declare a read-only `@property` if callers only read |
| `isinstance` treated as a full check | Only member names are checked, not signatures or types | Rely on the static checker. Use `isinstance` only for coarse dispatch |
| `issubclass` with a data protocol | Raises `TypeError` when the protocol has non-method members | Limit runtime checks to method-only protocols |
| Instantiating the protocol | `TypeError` at runtime | Protocols are only for annotations and as bases |
| Protocol much larger than the caller needs | Every implementation and test double must provide unused members | Split it by use site |
The first pitfall is the most common one in practice. The example below shows the fix.
from typing import Protocol
class Sender(Protocol):
def send(self, data: bytes, /) -> None: ...
class Connection:
def send(self, payload: bytes) -> None:
print(f"sent {len(payload)} bytes")
def transmit(sender: Sender) -> None:
sender.send(b"hello")
transmit(Connection())If the protocol had written def send(self, data: bytes) without /, a caller could legally write sender.send(data=b"x"). Connection would break that call, so the checker would reject it. The / tells the checker that names do not matter.
Decision checklist
Before adding a protocol, ask these questions in order:
- Does a standard-library protocol already fit, such as
Iterable,SizedorSupportsInt? Use it. - Do you control all implementations and want shared code or enforced registration? An abstract base class may fit better.
- Do you need to accept types you cannot modify? Use a protocol.
- Can you name the protocol after one capability, such as
SupportsClose? If you cannot, it probably does too much.
Exercise
A function save(target) calls only target.write(text). A teammate writes a Storage protocol with write, read, delete and close. What is wrong with this design, and how would you fix it? Also, what change makes def write(self, text: str) in the protocol accept a class whose method is named write(self, content: str)?
Show answer
The protocol is larger than the consumer needs. Every implementation and test double must provide read, delete and close even though save never uses them. Replace it with a small protocol, for example SupportsWrite with only write, defined next to save. To accept the differently named parameter, make the protocol parameter positional-only: def write(self, text: str, /) -> int: .... This tells the checker that callers cannot pass text by keyword, so the name in the implementation does not matter.