Sub topic 13
Structural typing with Protocol
This chapter assumes you can write Python classes and functions, read basic annotations such as str and list[int], and run a static checker like mypy or pyright. A static checker is a tool that reads your code and reports type mismatches without running it.
Nominal and structural typing
Most class-based typing is nominal. A function that asks for an Animal accepts only instances of Animal or its subclasses. The class must name its parent explicitly.
Structural typing asks a different question: does the object have the methods and attributes the function needs? If it does, the checker accepts it. This matches how Python code is usually written, where you call .close() on an object without caring about its base class.
A Protocol lets you write that expectation down.
Defining and using a Protocol
A protocol is a class that inherits from typing.Protocol and lists the members a matching object must have. Method bodies are written as ... because the protocol is a description, not an implementation.
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. The checker accepts it because it has a close method with a compatible signature. Compatible means the same parameters and a return type that fits.
Common errors
If you pass an object that lacks the member, the checker reports it and names the missing member. For example, passing shutdown("text") is flagged because str has no close method.
Other mistakes come up often:
- Wrong signature. A
close(self, force: bool)method does not matchclose(self) -> None, because the caller would have to supply an extra argument. - Expecting runtime checks. Like all hints, a protocol is not enforced when the program runs. Calling
shutdown("text")fails with anAttributeErroronly when.close()is reached. - Using
isinstancewith a plain protocol. This raises aTypeErrorunless the protocol is decorated with@runtime_checkable. Even then, the check only confirms that the member names exist, not their signatures.
Attributes in protocols
A protocol can also require attributes, declared with annotations.
from typing import Protocol
class Named(Protocol):
name: str
class User:
def __init__(self, name: str) -> None:
self.name = name
def show(item: Named) -> None:
print(item.name)
show(User("Ada"))When to choose a Protocol
| Situation | Better choice |
|---|---|
| You control the classes and want shared behavior | A base class |
| You accept objects from libraries you cannot change | A Protocol |
| You need only one or two methods from a large class | A Protocol |
Keep protocols small. A protocol with one or two members is easy to satisfy and makes the function usable with more kinds of objects.
Exercise
A class Logger has a method write(self, text: str) -> None but does not inherit from anything. Write a protocol Writer that Logger satisfies, and say why a checker accepts Logger where a Writer is expected.
Show answer
Define class Writer(Protocol): def write(self, text: str) -> None: .... The checker accepts Logger because it has a write method with the same parameters and return type. Inheritance is not required, since protocols match by structure.