🐍 Python Advanced

What is Python's Protocol class for structural subtyping?

Why Interviewers Ask This

Senior Python engineers are expected to reason about architecture, performance, and edge cases. This question separates mid-level from senior candidates by testing deep system-level understanding.

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.

Pro Tip

If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.