Sub topic 13
Structural Typing with Protocol
This chapter assumes you can annotate functions and classes, you know X | None unions, and you have run mypy or pyright on a file. You do not need generics beyond what earlier chapters covered.
Nominal and structural typing
Ordinary class annotations use nominal typing. A function that takes a Dog accepts only a Dog or a subclass of it, so a class must declare its relationship to Dog through inheritance.
Structural typing asks a different question: does the object have the right shape? If a function needs something with a close() method, any object with a compatible close() method qualifies, whatever its base classes. Python's duck typing has always worked this way at runtime. Protocol lets a static checker verify it before the code runs.
Defining a protocol
A protocol is a class that inherits from typing.Protocol. Its body lists the methods and attributes that an object must have.
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 never inherits from SupportsClose, but the checker accepts the call because Connection has a matching close method. The ... body is the convention for methods that only describe a signature.
What "compatible" means
The checker compares each member of the protocol with the same member on the argument's class. These rules cover most cases:
- The member name must exist on the class.
- Parameters must accept at least what the protocol promises to pass. Extra parameters are fine if they have defaults.
- The return type must be the protocol's return type or a subtype of it.
- Parameter names matter for arguments that callers could pass by keyword, unless the protocol marks them positional-only.
This example has a name that matches but a return type that does not:
from typing import Protocol
class SupportsClose(Protocol):
def close(self) -> None: ...
class Leaky:
def close(self) -> int:
return 0
def shutdown(resource: SupportsClose) -> None:
resource.close()
shutdown(Leaky()) # runs fine; a checker reports an incompatible return typePython runs this without complaint. Only the static checker rejects the call.
Attributes in protocols
A protocol can also require attributes. A plain annotation means the attribute must be readable and writable.
from typing import Protocol
class Named(Protocol):
name: str
class User:
def __init__(self, name: str) -> None:
self.name = name
def greet(thing: Named) -> str:
return f"Hello, {thing.name}"
print(greet(User("Ada")))A frozen dataclass has a read-only name, so it would not match name: str. If the function only reads the attribute, declare it as a read-only property. Then both mutable and read-only implementations match:
from dataclasses import dataclass
from typing import Protocol
class Named(Protocol):
@property
def name(self) -> str: ...
@dataclass(frozen=True)
class Planet:
name: str
def greet(thing: Named) -> str:
return f"Hello, {thing.name}"
print(greet(Planet("Mars")))Protocols at runtime
Like other hints, a protocol is not enforced when the program runs. A call to shutdown("text") raises AttributeError at the moment close is looked up. It does not fail at the call itself.
If you need an isinstance check, decorate the protocol with @runtime_checkable:
from typing import Protocol, runtime_checkable
@runtime_checkable
class SupportsClose(Protocol):
def close(self) -> None: ...
class Connection:
def close(self) -> None:
print("closed")
print(isinstance(Connection(), SupportsClose))
print(isinstance(42, SupportsClose))This prints True and then False. The runtime check only tests that the named members exist. It does not compare signatures or return types, so the Leaky class above would also pass it. Without the decorator, isinstance against a protocol raises TypeError. Use runtime checks sparingly, and use the static checker for correctness.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Checker says the argument is incompatible with the protocol | A signature differs: return type, parameter type, or a required extra parameter | Compare the checker's note on the mismatched member with the protocol |
| Frozen dataclass rejected for an attribute protocol | The protocol declares a writable attribute | Use a read-only `@property` in the protocol |
| `TypeError` from `isinstance` | The protocol lacks `@runtime_checkable` | Add the decorator, or avoid the runtime check |
| `isinstance` returns `True` but the call still fails | Runtime checks look only at member names | Rely on the static checker for signatures |
| Cannot instantiate the protocol class | Protocols describe shapes and are not meant to be created | Create a concrete class instead |
Protocols compared with abstract base classes
An abstract base class (ABC) uses nominal typing: each implementer must inherit from it. A protocol does not need that link.
| Question | Protocol | ABC |
|---|---|---|
| Must implementers inherit from it? | No | Yes |
| Works with classes you cannot edit, such as third-party or standard library classes? | Yes | Only through registration or wrapper classes |
| Can it supply shared method code to subclasses? | Only if classes inherit it explicitly | Yes |
| Checked at instantiation? | No | Yes, for unimplemented abstract methods |
Choose a protocol when you are describing what a function needs from its argument, especially when callers may pass classes you do not control. Choose an ABC when you own the hierarchy and want to share code or fail early at instantiation.
Keep protocols small. A protocol that lists one or two methods, like SupportsClose, is easy for many classes to satisfy. A protocol that mirrors a whole class makes the call site as rigid as a concrete type and gives you little in return.
Exercise
A function log_all(items: list[SupportsClose]) is called with a list[Connection], where Connection has a matching close method. Some checkers reject this call. Why might that happen, and what annotation change would let the function accept it?
Show answer
list is invariant: a list[Connection] is not a list[SupportsClose], because the function could append another SupportsClose object to it. If the function only reads the items, annotate the parameter with a read-only type such as Sequence[SupportsClose], which is covariant and accepts list[Connection].
Exercise
You write class Box(Protocol): size: int and pass an instance of a frozen dataclass with size: int. The checker reports an error. Rewrite the protocol so the call is accepted, and explain why the original failed.
Show answer
Declare the member as a read-only property: class Box(Protocol): followed by @property and def size(self) -> int: .... The original size: int requires a writable attribute, and a frozen dataclass forbids assignment. A read-only property only requires that size can be read.