Sub topic 4
Defining your first Protocol
This chapter assumes you can write Python classes and functions, use basic type hints, and know what a static type checker such as mypy or pyright does. It also assumes you have seen abstract base classes (ABCs). By the end you will be able to declare a Protocol, use it to annotate parameters, and read the errors a checker reports when an object does not match.
The problem a Protocol solves
Earlier chapters covered two ways to think about compatibility. Nominal subtyping says a class is acceptable only if it declares the relationship, by inheriting from a base class. Duck typing says any object with the right methods works, but nothing records or checks which methods are expected.
Here is plain duck typing:
class Duck:
def speak(self) -> str:
return "Quack"
class Robot:
def speak(self) -> str:
return "Beep"
def announce(speaker) -> None:
# No type information: any object with .speak() works at runtime,
# and a wrong argument only fails when the line executes.
print(speaker.speak())
announce(Duck())
announce(Robot())
announce(42) # AttributeError at runtimeThe parameter speaker has no annotation. A reader cannot tell what shape of object is expected, and a type checker cannot flag announce(42). The mistake shows up only when that line runs.
A Protocol fixes this. It is a class that describes a shape: the methods and attributes an object must have. A type checker then accepts any object whose class has that shape, with no inheritance required. This is structural subtyping.
Writing a protocol
A protocol is a class that inherits from typing.Protocol. Its body lists the members that a matching object must provide. Method bodies are written as ... because the protocol never runs them.
from typing import Protocol
class SupportsClose(Protocol):
def close(self) -> None: ...
class Resource:
def close(self) -> None:
print("closed")
def shutdown(item: SupportsClose) -> None:
item.close()
shutdown(Resource()) # accepted: Resource has a matching close()
shutdown(42) # rejected by a type checker: int has no close()Resource does not inherit from SupportsClose. It does not mention it at all. The checker accepts shutdown(Resource()) because Resource has a close method with a compatible signature. It rejects shutdown(42) because int has no close.
Running this file with Python still works for the first call. The second call fails at runtime with an AttributeError, because annotations are not enforced when the program runs. The protocol helps your checker and your readers, not the interpreter.
A checker such as mypy reports the bad call with a message like this:
error: Argument 1 to "shutdown" has incompatible type "int"; expected "SupportsClose"
note: "int" is missing following "SupportsClose" protocol member:
note: closePyright words it differently but names the same missing member.
What goes inside a protocol body
A protocol body can contain:
- Methods, with their full signatures.
- Attributes, declared with an annotation such as
name: str. - Properties, declared with
@property.
The next chapter covers attributes and properties in detail. For now, focus on methods.
How the shape is compared
When you pass an object where a protocol is expected, the checker compares the object's class to the protocol member by member. For each member in the protocol, the class must have a member with the same name and a compatible type.
For methods, compatible means the class's method can be called in every way the protocol's method can be called:
- Parameters must accept at least the arguments the protocol promises. A class method may accept more, if the extras have defaults.
- The return type must be the same as, or a subtype of, the protocol's return type.
- Extra members on the class are fine. The protocol sets a minimum, not an exact match.
from typing import Protocol
class Greeter(Protocol):
def greet(self, name: str) -> str: ...
class Polite:
def greet(self, name: str, title: str = "") -> str:
return f"Good day, {title} {name}".replace(" ", " ")
def farewell(self) -> str: # extra member, ignored by the protocol
return "Goodbye"
class Rude:
def greet(self) -> str: # missing the name parameter
return "What?"
def welcome(g: Greeter) -> str:
return g.greet("Ada")
print(welcome(Polite())) # fine
print(welcome(Rude())) # type error, and a TypeError at runtimePolite.greet has an extra optional parameter, so any call the protocol allows still works. Rude.greet cannot accept the name argument, so the checker rejects it.
The following diagram shows the decision the checker makes for each protocol member.
A protocol is a type, not a base class
A protocol is meant to be used in annotations. You use it for parameters, return values, and variables:
from typing import Protocol
class SupportsClose(Protocol):
def close(self) -> None: ...
class Resource:
def close(self) -> None:
print("closed")
def open_resource() -> SupportsClose:
return Resource()
handle: SupportsClose = open_resource()
handle.close()Here the function promises only that the result can be closed. Callers may use close and nothing else, even though the object is really a Resource. This is useful when you want to hide an implementation detail while still giving callers a checked interface.
You cannot create an instance of a protocol class directly. A protocol describes a shape, so there is nothing concrete to build. Calling SupportsClose() raises a TypeError at runtime, and a checker reports it as well.
from typing import Protocol
class SupportsClose(Protocol):
def close(self) -> None: ...
try:
SupportsClose()
except TypeError as exc:
print(exc) # Protocols cannot be instantiatedProtocols and the classes you already have
A major benefit is that protocols work with classes you did not write. Suppose a library gives you a class with a close method. You cannot edit it to add a base class. With a protocol you do not need to: if the shape matches, it is accepted.
import io
from typing import Protocol
class SupportsClose(Protocol):
def close(self) -> None: ...
def shutdown(item: SupportsClose) -> None:
item.close()
buffer = io.StringIO("hello")
shutdown(buffer) # StringIO has close(), so a checker accepts it
print(buffer.closed) # TrueWith nominal typing you would need an adapter class or a registration step for this case. A protocol lets you describe what your function needs, and the standard library and third-party classes qualify without changes.
Name the protocol after the need
The shutdown function uses only close. The protocol therefore lists only close. Keeping protocols to the members a caller actually uses makes more classes eligible and makes the function easier to test, because a test double needs one method rather than a dozen.
A common naming convention is a Supports... prefix (as in SupportsClose) or an adjective such as Closeable. Choose a name that says what the function needs, not what the implementation is.
| Approach | Declares the relationship? | Checked before running? | Works on classes you cannot edit? |
|---|---|---|---|
| Duck typing, no annotation | No | No | Yes |
| ABC and inheritance | Yes, by subclassing | Yes | Only by adapting or registering |
| Protocol | No, it is inferred from the shape | Yes | Yes |
Common errors when you start
These mistakes appear often with a first protocol:
- Forgetting
Protocolas the base class. A class with only...bodies that does not inherit fromProtocolis an ordinary class. Instances must then inherit from it, and the structural behavior disappears. - Writing real method bodies and expecting them to be inherited. A class that does not subclass the protocol does not get its bodies. Treat a protocol body as a declaration.
- Mismatched signatures. A method named
closethat takes a required extra argument does not matchdef close(self) -> None. Check names, parameter lists, and return types. - Expecting runtime enforcement. Passing the wrong object does not fail at the call site. It fails later when the missing member is used, or never, if you never use it.
- Over-wide protocols. A protocol with many members matches few classes. Split it by use.
A complete worked example
Suppose you write a function that saves any object that can serialize itself to text. You do not control all the classes involved.
from typing import Protocol
class SupportsSerialize(Protocol):
def serialize(self) -> str: ...
class Note:
def __init__(self, text: str) -> None:
self.text = text
def serialize(self) -> str:
return f"note:{self.text}"
class Counter:
def __init__(self, value: int) -> None:
self.value = value
def serialize(self) -> str:
return f"counter:{self.value}"
def save_all(items: list[SupportsSerialize]) -> list[str]:
return [item.serialize() for item in items]
print(save_all([Note("buy milk"), Counter(3)]))Neither Note nor Counter knows about SupportsSerialize. The list [Note(...), Counter(...)] is accepted because the checker infers each element against the protocol. Output:
['note:buy milk', 'counter:3']If you add a third class without a serialize method and put it in the list, the checker flags that exact element, and the message names the missing method.
Exercise
Write a protocol named SupportsArea with one method area(self) -> float. Then write a function total_area(shapes: list[SupportsArea]) -> float that sums the areas. Do the classes passed to it need to inherit from SupportsArea? What would a type checker say about a class that defines area(self, scale: float) -> float with a required scale argument?
Show answer
The protocol is class SupportsArea(Protocol): def area(self) -> float: ..., and total_area returns sum(shape.area() for shape in shapes). No, classes do not need to inherit from it; any class with a compatible area(self) -> float method matches. A class whose area requires a scale argument does not match, because the protocol promises a call with no arguments. The checker reports an incompatible type and notes the signature difference.
Exercise
Why does shutdown(42) run into an error only at runtime if you skip the type checker, and what does that tell you about what a protocol does and does not do?
Show answer
Annotations, including protocol annotations, are not enforced by the interpreter. Python only fails when item.close() is evaluated and int has no close attribute, so it raises an AttributeError. A protocol is a description that a static checker verifies and that readers can rely on; it does not add checks at the call site.