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.