Python Snippet

Structural Typing with Protocol

Difficulty: Medium

`typing.Protocol` adds static structural typing (duck typing) to Python: any object that has the right methods is acceptable, no inheritance required. It is the right tool for plugin interfaces, dependency injection, and 'looks like a file' style APIs. This entry covers a basic protocol, the `@runtime_checkable` switch, and how Protocol differs from an abstract base class.

Code Snippets
/

Structural Typing with Protocol

Structural Typing with Protocol

`typing.Protocol` adds static structural typing (duck typing) to Python: any object that has the right methods is acceptable, no inheritance required. It is the right tool for plugin interfaces, dependency injection, and 'looks like a file' style APIs. This entry covers a basic protocol, the `@runtime_checkable` switch, and how Protocol differs from an abstract base class.

Python
Medium
3 snippets
py-type-hints
py-standard-library

1,130 views

25

Protocol is the static type for 'has these methods', the way Python developers always meant duck typing. Circle and Rect are not subclasses of SupportsArea, but the type checker treats them as compatible because they have an area() method with the matching signature. There is zero runtime cost: the protocol exists only for the type checker. Use protocols for plugin interfaces, anything you want to accept user-defined classes for, or any function that previously documented its expectations in a docstring like 'must have a .read() method'.