Structural typing with protocols
A report should work with a file or an in-memory buffer. Describe precisely what it needs from its destination.
On this page
Read the model
A protocol describes operations that a static type checker can look for. A class can satisfy that contract without inheriting from the protocol. Here the only requirement is a write method accepting positional text and returning an integer.
Follow the example
from io import StringIO
from typing import Protocol
class Writer(Protocol):
def write(self, text: str, /) -> int: ...
def report(destination: Writer) -> None:
destination.write("ready")
buffer = StringIO()
report(buffer)
print(buffer.getvalue())StringIO accepts the string and records it in memory. The return value is a count of characters, though report does not need it. Reading the buffer prints ready. A test can use the same function with this buffer and inspect the report without opening a file.
Change one condition
Pass a list instead of the buffer. A type checker can flag the missing write method before execution. Running the call in ordinary Python raises AttributeError when the method is used. An annotation alone does not inspect or convert an incoming object.