Python Tutorial: Protocols & ABCs
Write code that works with anything. Duck typing, Protocol, and ABC — Python's approach to interfaces.
Write code that works with anything
What if you want a function that accepts any object with a `.save()` method — regardless of its class?
Python has two approaches: ABCs (formal contracts) and Protocols (structural, check-by-shape). Both let you write flexible code that works with any compatible type. Ten steps.
What you'll learn in this Python protocols & abcs tutorial
This interactive Python tutorial has 7 hands-on exercises. Estimated time: 20 minutes.
- If it has a .speak() method, it works — Python's philosophy: 'if it walks like a duck and quacks like a duck, it's a duck.'
- ABC — enforce the contract — Duck typing is flexible but informal. What if you want to **enforce** that every subclass must implement certain methods…
- ABCs prevent instantiation — Abstract classes are blueprints only — you cannot create an instance of one.
- Protocol — the modern approach — `Protocol` (from `typing`) is Python 3.8+'s answer to interfaces. Unlike ABCs, you do NOT inherit from it.
- @runtime_checkable — use isinstance with Protocols — By default, Protocols are only checked by type-checkers (like mypy), not at runtime.
- ABC vs Protocol — know when to use which — Use **ABC** when:
- Build a plugin system — Final challenge — no starter code.
Python Protocols & ABCs concepts covered
- Write code that works with anything