🐍 Python Advanced

What is Python's Protocol class for structural subtyping?

Answer

Protocol (Python 3.8+, typing.Protocol) enables structural subtyping (duck typing with static type checking). Define a protocol: from typing import Protocol; class Drawable(Protocol): def draw(self) -> None: .... Any class that has a draw() method satisfies this protocol — without explicitly inheriting from it. Type checkers (mypy, pyright) verify structural compatibility. Runtime check: isinstance(obj, Drawable) works if @runtime_checkable is added to the Protocol. Compare to abstract classes: ABCs require explicit registration/inheritance; Protocols check structure only. Use protocols for: accepting any "file-like object" (SupportsRead), "iterable" (Iterable), or domain-specific interfaces without coupling to specific implementations. Python's built-in collections.abc classes are being retrofitted as runtime-checkable protocols. Protocols are the preferred way to express "duck typing" in typed Python code.