ReviseAlgo Logo

Type Hints & Annotations

Protocols

Structural subtyping with Protocol — defining interfaces based on shape rather than inheritance, enabling duck typing with static checking.

Interview: Modern Python interface design — Protocol is preferred over ABCs for most use cases.

Last Updated: June 12, 2026 8 min read

Protocol (Python 3.8+, PEP 544) enables structural subtyping — "duck typing with static checking." A class satisfies a Protocol if it has the right methods, regardless of whether it explicitly inherits from the Protocol. This is Python's answer to interfaces in other languages.

Structural vs Nominal Subtyping

  • Nominal (ABCs): Must explicitly inherit — class Dog(Animal):
  • Structural (Protocols): Just have the right methods — no inheritance needed
  • Protocols check shape, not lineage — any object with .draw() satisfies Drawable
  • This formalizes Python's duck typing with static type checking

Defining Protocols

  • Inherit from Protocol and define method signatures
  • Use ... (ellipsis) as method body — it's just a signature
  • @runtime_checkable enables isinstance() checks at runtime
  • Protocols can have properties, class variables, and other attributes

Interview Insight

Know the difference between Protocol (structural) and ABC (nominal). Protocols are preferred when you want duck typing with static checking — no inheritance ceremony required.

Use Cases

Dependency injection — depend on Protocols, not concrete classes

Testing — easy mock implementations that satisfy Protocols

Plugin systems — any class with the right methods works as a plugin

Repository pattern — abstract data access without ABC inheritance

Adapter pattern — adapt existing classes to new interfaces without modification

Common Mistakes

Using ... (ellipsis) body but forgetting Protocol methods need it (not pass)

Not using @runtime_checkable when you need isinstance checks

Confusing Protocol (structural) with ABC (nominal) — different subtyping models

Adding unnecessary inheritance — Protocols are satisfied structurally, no need to inherit

Defining too many methods in a Protocol — keep interfaces small and focused