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:

Cons:

When to use:


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:

Pros:

Cons:

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:

Cons:

When to use:


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:


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

  1. Default to Protocol when you need an explicit contract.
  2. ABC when you need shared logic or a runtime guarantee.
  3. Duck typing for internal code, prototypes, or when there is exactly one implementation.
  4. YAGNI for abstractions. Do not extract an interface until there is a second implementation or a strong need for mocks.
  5. Protocol does not block third-party classes. Use it when you mix in someone else's API.
  6. @runtime_checkable only when you actually need isinstance. Otherwise keep it clean.
  7. 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.