Abstraction
Abstraction in Python: Duck Typing, Protocol, ABC
"Program to an interface, not an implementation." — Erich Gamma et al., Design Patterns (1994)
"Don't ask what the object is, look at what it can do." — The spirit of duck typing in Python (community folklore; Alex Martelli popularised the term in comp.lang.python, 2000)
Core idea
Abstraction is about separating "what is done" from "how exactly it is implemented". The caller should not care which concrete class it is calling. Only that the promised methods are there.
Why it matters
| Without abstraction | With abstraction |
|---|---|
OrderProcessor is hard-coded to EmailNotifier |
It depends on Notifier, any one will do |
| Switching email for SMS = rewrite the consumer | Plug in SmsNotifier, the consumer does not notice |
| Testing needs a real email server | Plug in FakeNotifier, the test runs offline |
Adding a second channel = if/elif branches |
Just a new class that satisfies the contract |
Three levels of formality in Python
1. Duck Typing — "if it quacks like a duck, it's a duck"
No contracts. We call obj.send() and hope the method is there.
class EmailNotifier:
def send(self, message: str) -> None:
print(f"EMAIL: {message}")
class SmsNotifier:
def send(self, message: str) -> None:
print(f"SMS: {message}")
def notify_all(notifiers, message: str) -> None:
for n in notifiers:
n.send(message) # ← just call it. If .send() is missing, AttributeError
notify_all([EmailNotifier(), SmsNotifier()], "Hello!")
Pros:
- The simplest, zero boilerplate.
- The classes are not linked by any explicit inheritance.
EmailNotifierdoes not "know" about anyNotifier. - Pythonic. The classic Python style.
Cons:
- Errors only at runtime, when it is too late.
- The IDE cannot suggest what to expect.
- The type checker (
mypy) is helpless. - No documentation. You have to read the code to understand the contract.
When to use:
- Prototypes, scripts, learning code.
- Internal APIs where the caller and the implementation live next to each other.
- Dynamic code where type checking does not make sense (plugins, AST transformations).
2. Protocol — structural contract (PEP 544, Python 3.8+)
We describe the contract as a separate type. Implementations do not need to inherit anything — having the right methods is enough.
from typing import Protocol
class Notifier(Protocol):
def send(self, message: str) -> None: ...
class EmailNotifier: # ← does NOT inherit Notifier!
def send(self, message: str) -> None:
print(message)
class SmsNotifier: # ← also does not inherit
def send(self, message: str) -> None:
print(message)
def notify_all(notifiers: list[Notifier], message: str) -> None:
for n in notifiers:
n.send(message)
How it works:
Notifierdescribes "what must be there". The body is....EmailNotifieris structurally compatible withNotifier: it hassend(message: str) -> None. That is enough.mypy,pyright, and the IDE check statically. If you pass an object withoutsend(), the error is raised before the program runs.- At runtime Python does nothing. Same as duck typing.
Pros:
- Explicit contract,
Notifierreads as documentation. - Implementations are decoupled from the contract. A class can be written before
Notifiereven existed. That is a real advantage over traditional interfaces. - IDE autocompletes, mypy type-checks.
- Works with third-party classes you cannot modify.
Cons:
- No runtime check. If someone passes an "almost compatible" object, it crashes at the call site.
When to use: by default, for describing contracts in Python 3.8+.
3. ABC — nominal contract (abc.ABC)
Classes explicitly inherit an abstract base. Trying to instantiate one without implementing the methods raises TypeError at runtime.
from abc import ABC, abstractmethod
class Notifier(ABC):
@abstractmethod
def send(self, message: str) -> None: ...
class EmailNotifier(Notifier): # ← explicit inheritance
def send(self, message: str) -> None:
print(message)
class BrokenNotifier(Notifier): # ← forgot send()
pass
BrokenNotifier() # ❌ TypeError: Can't instantiate
# abstract class BrokenNotifier
# without an implementation for
# abstract method 'send'
Pros:
- Runtime guarantee: you cannot create a subclass without implementing the methods.
- You can put shared logic into the abstract class (unlike Protocol, which is signatures only):
class Notifier(ABC): @abstractmethod def send(self, message: str) -> None: ... def send_many(self, messages: list[str]) -> None: # ← regular method for m in messages: self.send(m) # template method isinstance(x, Notifier)works.
Cons:
- Implementations are tied to the ABC. You cannot add a "contract" to someone else's class.
- Multiple inheritance plus ABC equals MRO confusion.
- Boilerplate.
When to use:
- You need shared logic in the base (template method pattern).
- You need a runtime guarantee that the subclass implements a method.
- You build a framework or library where users explicitly declare inheritance (the contract acts as registration).
- You work with
isinstancechecks (for example, dispatching different event types).
How to choose: a practical decision tree
Are you describing a contract between parts of the code?
├── NO → no abstraction needed
└── YES:
│
├── One implementation that will not change?
│ └── YES → extract nothing (YAGNI)
│
├── Need SHARED LOGIC in the base?
│ └── YES → ABC with concrete methods + @abstractmethod
│
├── Need a RUNTIME guarantee that methods are implemented?
│ └── YES → ABC
│
├── Could the implementations be THIRD-PARTY (you do not control them)?
│ └── YES → Protocol
│
└── Default → Protocol (Python 3.8+)
Worked example: why Protocol is usually better
You depend on acme_email, an external library that gives you class AcmeMailer. It has send(self, msg: str). You want to use it as a Notifier.
With ABC — does not work without workarounds
class Notifier(ABC):
@abstractmethod
def send(self, message: str) -> None: ...
# AcmeMailer does NOT inherit Notifier — we cannot change someone else's code
def notify_all(notifiers: list[Notifier], message: str): ...
notify_all([AcmeMailer()], "Hi") # ❌ mypy: AcmeMailer is not a Notifier
So you write an adapter:
class AcmeAdapter(Notifier):
def __init__(self, mailer): self._m = mailer
def send(self, message: str): self._m.send(message)
An extra layer just because ABC requires explicit inheritance.
With Protocol — works straight away
class Notifier(Protocol):
def send(self, message: str) -> None: ...
notify_all([AcmeMailer()], "Hi") # ✅ AcmeMailer is structurally compatible
AcmeMailer has .send(message: str), so it is structurally a Notifier. No changes to its code.
This is called typed duck typing — duck typing's flexibility with static checking on top.
@runtime_checkable — when you need isinstance for a Protocol
By default isinstance(x, MyProtocol) does not work. If you need it, add the decorator:
from typing import Protocol, runtime_checkable
@runtime_checkable
class Notifier(Protocol):
def send(self, message: str) -> None: ...
isinstance(EmailNotifier(), Notifier) # True (structural check: methods present)
⚠️ Careful: @runtime_checkable only checks for the presence of the methods, not their signatures. A method with wrong arguments will still pass isinstance and crash at the call.
Why you should NOT create an interface for every class
A classic mistake from Java / C# people: creating IFoo for every Foo:
# ❌ Anti-pattern — interface for the sake of an interface
class IUserRepository(Protocol):
def get(self, id: int) -> User: ...
class UserRepository:
def get(self, id: int) -> User: ...
# And that is it. There is no other UserRepository, and there will not be.
This is a YAGNI violation:
- An interface makes sense when you have at least two implementations (or a strong need for test mocks).
- If there is one implementation, the caller can type-hint the concrete class.
- When the second one appears, that is when you extract a
Protocol. In Python it is a five-minute refactor.
Special case: tests
Here abstraction is justified even with one production implementation:
class PaymentGateway(Protocol):
def charge(self, amount: float) -> str: ...
class StripeGateway: # production
def charge(self, amount: float) -> str:
# actually calls the Stripe API
...
class FakePaymentGateway: # for tests
def __init__(self): self.charges = []
def charge(self, amount: float) -> str:
self.charges.append(amount)
return "fake-tx-123"
# Production:
processor = OrderProcessor(gateway=StripeGateway())
# Test:
def test_order_charges_correctly():
fake = FakePaymentGateway()
processor = OrderProcessor(gateway=fake)
processor.process(order_with_total_100)
assert fake.charges == [100]
Without Protocol you could not pass FakePaymentGateway where StripeGateway was expected. With Protocol both are structurally PaymentGateway and the test works.
This is DIP (the D in SOLID).
ABC + Template Method — when ABC is irreplaceable
If there is a shared algorithm with varying steps, ABC gives you what Protocol cannot:
from abc import ABC, abstractmethod
class ReportGenerator(ABC):
def generate(self) -> str:
"""Template method — fixed algorithm."""
data = self._load_data()
rows = self._transform(data)
return self._format(rows)
@abstractmethod
def _load_data(self) -> list[dict]: ...
@abstractmethod
def _format(self, rows: list[dict]) -> str: ...
def _transform(self, data: list[dict]) -> list[dict]: # default implementation
return sorted(data, key=lambda r: r["date"])
class SalesReport(ReportGenerator):
def _load_data(self): return db.query("SELECT ...")
def _format(self, rows): return "\n".join(f"{r['id']}: ${r['amount']}" for r in rows)
class UsersReport(ReportGenerator):
def _load_data(self): return api.get("/users")
def _format(self, rows): return json.dumps(rows)
generate() is the only public contract, _load_data and _format vary in subclasses. Protocol cannot do this (it does not carry code). This is the Template Method pattern.
Anti-patterns
1. An abstract method that "contracts" nothing
class BaseThing(ABC):
@abstractmethod
def do_something(self, x): # ← no types, no description
pass
This is not a contract. It is an empty promise. Either type it and document it, or do not extract it.
2. ABC with mutable state
class Base(ABC):
_registry = [] # ← shared mutable state
All subclasses suddenly share _registry. A classic trap. If state is needed, use __init__ plus self._x.
3. Protocol with an implementation
class Notifier(Protocol):
def send(self, msg: str) -> None:
print(msg) # ← Protocol is not for code!
If there is a default implementation, this is an ABC, not a Protocol.
4. Multiple inheritance from ABCs
class A(ABC): ...
class B(ABC): ...
class C(A, B): ... # ← MRO becomes painful
Composition over inheritance. Almost always.
Rules of thumb
- Default to Protocol when you need an explicit contract.
- ABC when you need shared logic or a runtime guarantee.
- Duck typing for internal code, prototypes, or when there is exactly one implementation.
- YAGNI for abstractions. Do not extract an interface until there is a second implementation or a strong need for mocks.
- Protocol does not block third-party classes. Use it when you mix in someone else's API.
@runtime_checkableonly when you actually needisinstance. Otherwise keep it clean.- When the contract stabilises and behaviour is shared, move from Protocol to ABC.
One-line summary
The contract describes "what", the implementation describes "how". Python gives you three levels of formality: none (duck), structural (Protocol), nominal (ABC). Start with the smallest, escalate only when you have to.