Sub topic 4
Defining your first Protocol
This chapter assumes you can write Python functions and classes, use basic type hints, and know what a static type checker such as mypy or pyright does. You should also know how inheritance and abstract base classes work.
The problem a protocol solves
Duck typing accepts any object that has the method you call. The cost is that the expected shape appears nowhere in the code, so a wrong argument fails only when that line runs. A protocol writes the expected shape down, and a type checker enforces it before the program runs.
A protocol is a class that inherits from typing.Protocol and lists the members an object must have. Any class with matching members is accepted, even if it never mentions the protocol.
A first protocol
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()SupportsClose declares one method, close, that takes no arguments and returns None. The body is ... because a protocol describes a shape and does not implement it.
Resource does not inherit from SupportsClose. The checker accepts it anyway because Resource has a compatible close method. This is structural subtyping: compatibility comes from the shape of the class, not from a declared inheritance link.
The call shutdown(42) is reported as an error because int has no close method. The checker reports it without running the code. At runtime, Python ignores annotations and shutdown(42) fails with an AttributeError.
What "compatible" means
The checker compares each member the protocol declares with the member on the candidate class. A method must be callable the way the protocol's signature says. This means:
- The name must match exactly.
- The candidate must accept the arguments the protocol's signature allows.
- The return type must be the same as, or a subtype of, the protocol's return type.
Extra members on the candidate are fine. Resource could also have open, read and write methods and would still satisfy SupportsClose. The protocol constrains only what the function needs.
A candidate with the wrong signature is rejected:
from typing import Protocol
class SupportsClose(Protocol):
def close(self) -> None: ...
class BadResource:
def close(self, force: bool) -> None: # requires an argument
print("closed")
def shutdown(item: SupportsClose) -> None:
item.close()
shutdown(BadResource()) # rejected: close() needs an argument that shutdown does not passHere BadResource has a method named close, but the protocol says callers invoke close() with no arguments. The candidate's method cannot be called that way, so the match fails.
Naming and placement
Name a protocol after the capability it describes. Common choices are the Supports... prefix (SupportsClose) or an adjective such as Closeable. Define the protocol next to the code that consumes it, because the consumer decides which members it needs. Classes that satisfy it can live anywhere, including in third-party libraries you cannot modify. This is the main advantage over inheritance.
Common mistakes
- Adding a method body to a protocol method and expecting it to be inherited by other classes. Classes that match structurally get nothing from the protocol.
- Declaring more members than the function uses. Every extra member narrows the set of classes that match.
- Expecting
isinstance(x, SupportsClose)to work. It raises aTypeErrorunless the protocol is marked@runtime_checkable, which a later chapter covers.
Exercise
A function save(target: SupportsClose) is called with an object whose class defines close(self, flush: bool = True) -> None, and the class does not inherit from SupportsClose. Does a type checker accept it? Why?
Show answer
Yes. The class has a method named close that can be called with no arguments, because flush has a default. Its return type is None, so it matches the protocol's signature. Structural subtyping needs no inheritance.
Exercise
Write a protocol SupportsFlush with a method flush that takes no arguments and returns None.
Show answer
from typing import Protocol class SupportsFlush(Protocol): def flush(self) -> None: ...