Skip to content

Lesson 5 of 9 · 23m

Protocols: Structural Typing for Real Python

Protocols let type checkers verify duck typing: what objects must provide, how runtime_checkable changes the game, and why narrower interfaces beat heroic abstractions.

Python has always had interfaces; they were just implicit. If a function calls .read(), anything with a compatible .read() works. That flexibility is why Python is productive and why large Python codebases rot: nobody knows which attributes are actually required. typing.Protocol makes duck typing explicit without forcing inheritance.

Describe the shape you consume

from typing import Protocol

class SupportsClose(Protocol):
    def close(self) -> None: ...

def shutdown(resource: SupportsClose) -> None:
    resource.close()

A file object, a socket wrapper, and your own connection pool can all satisfy SupportsClose without importing your base class. Static type checkers verify the shape; runtime Python keeps doing what it always did. This is dependency inversion without framework machinery.

Narrow protocols beat broad interfaces

class PageSource(Protocol):
    def read_page(self, number: int) -> bytes: ...

def first_page(source: PageSource) -> bytes:
    return source.read_page(1)

If first_page only needs one method, say so. Accepting a giant StorageBackend interface couples the function to operations it never uses and makes tests construct fake backends with twelve irrelevant methods. The Interface Segregation Principle survives Python because it is not about classes; it is about minimizing the knowledge a consumer needs.

Runtime checks are shallow

from typing import runtime_checkable

@runtime_checkable
class Writable(Protocol):
    def write(self, data: bytes) -> int: ...

isinstance(file_like, Writable)

runtime_checkable only checks that attributes exist, not that their signatures or semantics are correct. An object with write = None can pass. Use runtime protocol checks for coarse plugin validation or debugging, not as proof of correctness. Static checking is where protocols shine.

Protocols are documentation that type checkers read

The most valuable effect is often human: the protocol says exactly which operations a boundary depends on. When someone adds a new implementation in another package, they do not need to inherit your class or depend on your package internals. They need only satisfy the shape. That is how Python scales across team boundaries without turning every interface into a framework.

Field notes

  • Use Protocol for consumer-owned interfaces; don't mirror entire concrete classes automatically.
  • Protocol methods with ... bodies are declarations, not implementation placeholders.
  • Mutable attributes in protocols are tricky; prefer read-only properties unless mutation is part of the contract.
  • isinstance against non-runtime-checkable protocols raises TypeError — catch this in tests before production does.

Was this lesson helpful?

Sign in to rate