Polymorphism & Abstraction
Interfaces in Python
ABCs, Protocols, and structural typing approaches
Interview: API design — tests knowledge of Python interface options and when to use ABCs vs Protocols
Unlike Java or C#, Python doesn't have a dedicated interface keyword. Instead, interfaces are implemented through three approaches: ABCs (nominal subtyping), Protocols (structural subtyping), and informal protocols (duck typing). Choosing the right approach depends on your use case.
Three Approaches
- ABCs: Classes must explicitly inherit and implement abstract methods (nominal typing)
- Protocols: Any class with matching methods satisfies the interface (structural typing)
- Informal protocols: Duck typing — any object with required methods works
ABC vs Protocol
Use ABCs when you want explicit inheritance and enforcement. Use Protocols when you want structural typing (any matching class works) without requiring inheritance. Protocols are especially useful for type checking with mypy.
Interview Tip
Know that Protocols enable "static duck typing" — you get the flexibility of duck typing with static type checking. This is a modern Python feature (PEP 544, Python 3.8+).
Use Cases
Defining API contracts for plugins and extensions
Type-safe duck typing with Protocols (mypy integration)
Repository pattern with interchangeable data sources
Strategy pattern: swappable algorithms with common interface
Adapter pattern: wrapping incompatible APIs behind common interfaces
Common Mistakes
Using ABC when Protocol would be simpler (no inheritance required)
Forgetting @runtime_checkable when using isinstance() with Protocols
Creating overly large interfaces (prefer small, composable protocols)
Not understanding that Protocol methods need '...' body (ellipsis, not pass)
Mixing ABC and Protocol approaches inconsistently in a codebase