Sub topic 9
Structural typing with Protocol
This chapter assumes you can annotate functions and classes, run mypy or Pyright, and read their error messages. It builds on the annotation chapters and uses Python 3.10 or newer.
Nominal and structural typing
Most class-based annotations are nominal. A parameter typed as Animal accepts only instances of Animal or its subclasses. The class must name its parent in the class statement.
Python code often relies on duck typing instead. A function calls .close() on its argument and does not care what class the argument has. A protocol lets a checker describe that expectation. A protocol is a class that lists the methods and attributes a type must have. Any class with a matching shape is accepted, even if it never mentions the protocol. This is called structural typing.
Defining and using a protocol
Subclass typing.Protocol and write the members you require. Method bodies are usually ... because the protocol is never instantiated.
from typing import Protocol
class SupportsClose(Protocol):
def close(self) -> None: ...
class Connection:
def close(self) -> None:
print("closed")
def shutdown(resource: SupportsClose) -> None:
resource.close()
shutdown(Connection())Connection does not inherit from SupportsClose. The checker accepts the call because Connection has a close method with a compatible signature.
What a mismatch looks like
If the signature differs, the checker reports the difference and does not run anything. A class whose close takes a required extra argument fails.
from typing import Protocol
class SupportsClose(Protocol):
def close(self) -> None: ...
class Broken:
def close(self, force: bool) -> None:
pass
def shutdown(resource: SupportsClose) -> None:
resource.close()
shutdown(Broken()) # flagged: "close" has an incompatible signatureBoth mypy and Pyright list the expected and actual signatures. Reading that comparison is the quickest way to fix the error.
Attributes in protocols
A protocol can also require attributes. Declare them with annotations in the class body.
from typing import Protocol
class Named(Protocol):
name: str
class User:
def __init__(self, name: str) -> None:
self.name = name
def label(item: Named) -> str:
return item.name.title()
print(label(User("ada")))A plain name: str requirement means the attribute must be readable and writable. If you only read it, a read-only @property in the protocol is more permissive and also accepts frozen dataclasses.
Protocols versus abstract base classes
| Aspect | Protocol | Abstract base class |
|---|---|---|
| Relationship | Structural, by matching members | Nominal, by inheritance |
| Third-party classes | Accepted if the shape fits | Cannot be accepted without registration or a wrapper |
| Runtime `isinstance` | Needs `@runtime_checkable` | Works by default |
| Best for | Describing what a function needs | Sharing code and enforcing a class hierarchy |
Prefer a protocol for function parameters, and keep it small. A protocol with one or two methods describes exactly what the function uses and is easy for callers to satisfy.
Exercise
A function save(target) calls target.write(data: str) -> int. Write a protocol for target, and say why a io.StringIO object can be passed even though it does not inherit from your protocol.
Show answer
Define class Writer(Protocol): with def write(self, data: str, /) -> int: ... and annotate save(target: Writer). io.StringIO has a write method that takes a string and returns an int, so its members match the protocol. Protocol matching is structural, so no inheritance is required.