Types and contracts
What are protocols?
On this page
A protocol describes the operations that make a value usable in a role. A Python typing.Protocol can require close() so a static checker accepts suitable classes without explicit inheritance. Runtime-checkable protocols check limited aspects of member presence. They do not verify method signatures or promises about cleanup.
Worked example
Pythonfrom typing import Protocol
class Flushable(Protocol):
def flush(self) -> None: ...
class Batch:
def __init__(self):
self.pending = [1, 2]
def flush(self) -> None:
self.pending.clear()
def finish(writer: Flushable) -> None:
writer.flush()
batch = Batch()
finish(batch)
assert batch.pending == []Explore class relationships in the OOP Playground