Sub topic 12
Choosing between a Protocol and an ABC
This chapter assumes you can write Python classes and use basic type hints. It also assumes you know what an abstract base class (ABC) is and what a type checker such as mypy or pyright does. It builds on the earlier chapters on defining protocols, @runtime_checkable, and explicit subclassing.
Both tools let you write a function that accepts "anything with these methods". They differ in where the agreement lives. An ABC makes the agreement a fact about the class hierarchy. A Protocol makes it a fact about the object's shape. That difference decides which tool fits.
Two ways to name a contract
An ABC is a class that other classes inherit from. The inheritance is the declaration: if MemoryStorage lists Storage as a base, it claims to follow the contract. Python enforces part of that claim at runtime.
from abc import ABC, abstractmethod
class Storage(ABC):
@abstractmethod
def read(self, key: str) -> bytes: ...
@abstractmethod
def write(self, key: str, data: bytes) -> None: ...
def copy(self, src: str, dst: str) -> None:
# Shared behavior built on the abstract methods.
self.write(dst, self.read(src))
class MemoryStorage(Storage):
def __init__(self) -> None:
self._data: dict[str, bytes] = {}
def read(self, key: str) -> bytes:
return self._data[key]
def write(self, key: str, data: bytes) -> None:
self._data[key] = data
class Broken(Storage):
def read(self, key: str) -> bytes:
return b""
store = MemoryStorage()
store.write("a", b"1")
store.copy("a", "b")
print(store.read("b"))
try:
Broken()
except TypeError as exc:
print(exc) # the message names the missing abstract method, writeTwo things happen here that a protocol alone does not give you. Broken fails the moment you try to create an instance, even if no type checker ever runs. copy is written once and inherited by every subclass.
A protocol states only the shape. Any class with matching members qualifies, whether or not it knows the protocol exists.
from typing import Protocol
class Reader(Protocol):
def read(self, key: str) -> bytes: ...
class LegacyCache:
"""Imagine this lives in a library you cannot edit."""
def read(self, key: str) -> bytes:
return key.encode()
def load(source: Reader, key: str) -> bytes:
return source.read(key)
print(load(LegacyCache(), "abc"))LegacyCache never mentions Reader, and a type checker accepts the call. If Reader were an ABC, you would have to wrap or subclass LegacyCache.
Side-by-side comparison
| Question | ABC | Protocol |
|---|---|---|
| How does a class qualify? | It inherits from the ABC (or is registered). | It has the required members with compatible types. |
| Can you adapt classes you do not own? | Not without a wrapper, a subclass, or `register`. | Yes, with no changes. |
| Missing method detected | At instantiation, with `TypeError`. | By the type checker. At runtime only if the class explicitly subclasses a protocol that uses `@abstractmethod`. |
| Shared implementation | Natural: concrete methods and `__init__` are inherited. | Possible only for classes that explicitly subclass the protocol. |
| `isinstance` | Checks the hierarchy (and registrations). | Needs `@runtime_checkable`, and then checks only that the names exist. |
| Coupling | Implementers import and depend on the ABC. | Implementers need not import anything. |
A decision flow
The questions below cover most cases. They are a guide, not a rule, and the later sections explain each branch.
Case 1: classes you do not control
Standard-library and third-party classes cannot inherit from your ABC. This is the strongest argument for protocols. A function that only needs close() should accept files, sockets, and your own resources alike.
from typing import Protocol
import io
class SupportsClose(Protocol):
def close(self) -> None: ...
def shutdown_all(items: list[SupportsClose]) -> None:
for item in items:
item.close()
shutdown_all([io.StringIO(), io.BytesIO()])
print("all closed")An ABC has a runtime-only workaround called register. It declares an existing class a "virtual subclass" without changing it.
from abc import ABC, abstractmethod
class Closer(ABC):
@abstractmethod
def close(self) -> None: ...
@Closer.register
class Connection:
def close(self) -> None:
print("closed")
print(isinstance(Connection(), Closer)) # Trueregister does not check that Connection really has close. Most type checkers also ignore the registration, so they will not treat Connection as a Closer in annotations. For code that is checked statically, a protocol is the better fit.
Case 2: shared implementation
If every implementer needs the same helper methods or the same __init__, inheritance is the natural tool. The Storage.copy method above is an example: you write it once and every subclass gets it. A protocol cannot deliver that to classes that match only by shape, because those classes never inherit from it.
You can still put default method bodies in a protocol and have a class subclass it explicitly.
from typing import Protocol
class Shape(Protocol):
def area(self) -> float: ...
def describe(self) -> str:
return f"area={self.area():.2f}"
class Square(Shape):
def __init__(self, side: float) -> None:
self.side = side
def area(self) -> float:
return self.side**2
print(Square(3).describe()) # area=9.00This works, but it carries a gotcha. describe is still a protocol member, so a class that matches only structurally must define its own describe. A class with just area will not satisfy Shape in a type checker. If you want the default body to be optional for callers, keep it out of the protocol and use a separate base class.
A common and clean arrangement uses both tools. The function parameter is typed with a small protocol, and your own implementations share a base class.
from typing import Protocol
class Notifier(Protocol):
def send(self, message: str) -> None: ...
class BaseNotifier:
def __init__(self, prefix: str) -> None:
self.prefix = prefix
def format(self, message: str) -> str:
return f"[{self.prefix}] {message}"
class ConsoleNotifier(BaseNotifier):
def send(self, message: str) -> None:
print(self.format(message))
def alert(target: Notifier) -> None:
target.send("disk almost full")
alert(ConsoleNotifier("ops"))ConsoleNotifier reuses code through BaseNotifier. Callers depend only on Notifier, so a test double with a send method also works without inheriting from anything.
Case 3: failing early at runtime
A type checker is optional. Plugin systems, scripts without type checking, and code where users subclass your base class may never be checked statically. In those settings an ABC's instantiation error is a real safeguard.
A protocol can borrow that behavior if a class explicitly subclasses it and the member is marked @abstractmethod.
from abc import abstractmethod
from typing import Protocol
class Plugin(Protocol):
@abstractmethod
def run(self) -> None: ...
class GoodPlugin(Plugin):
def run(self) -> None:
print("running")
class BadPlugin(Plugin):
pass
GoodPlugin().run()
try:
BadPlugin()
except TypeError as exc:
print(exc)Without @abstractmethod, BadPlugin() would succeed at runtime because the protocol's ... body counts as an implementation. A type checker such as mypy reports the problem, but Python itself does not.
Case 4: `isinstance` and dispatch
Branching on type is where the two tools differ most in what the check promises. An isinstance check against an ABC tests a declared relationship. An isinstance check against a @runtime_checkable protocol tests only that attributes with the right names exist.
import io
from typing import Protocol, runtime_checkable
@runtime_checkable
class Closeable(Protocol):
def close(self) -> None: ...
class Impostor:
def close(self, force: bool, timeout: float) -> str:
return "wrong signature"
print(isinstance(io.StringIO(), Closeable)) # True
print(isinstance(Impostor(), Closeable)) # True, signature not checked
print(isinstance(42, Closeable)) # FalseImpostor passes even though calling close() with no arguments would raise TypeError. Treat a runtime protocol check as "has this name", not "behaves correctly". If you dispatch on isinstance often and need the result to mean something, an ABC is the more reliable base.
Two more limits apply. issubclass() raises TypeError for protocols that have non-method members, such as attributes. Runtime checks on protocols are also slower than checks against a plain class.
Common errors
- Using an ABC for a one-method contract that others must satisfy. Callers who want to pass a lambda-like object or a library class must now wrap it. A small protocol removes that friction.
- Using a protocol and expecting inheritance-style enforcement. A protocol alone never stops
Broken()from being created. Only the type checker reports the mismatch. - Forgetting that explicit subclasses inherit
...bodies. Without@abstractmethod, a forgotten method silently returnsNoneat runtime. - Trusting
isinstanceagainst a protocol. It confirms names only, as shown withImpostor. - Putting state in a protocol. Protocols describe what callers need. If you find yourself adding
__init__and instance fields to share them, you want a base class.
Summary of the trade-off
Choose an ABC when you own the hierarchy, want to share implementation, or need a TypeError at instantiation without a type checker. Choose a Protocol when you describe what a function needs, when implementers come from code you cannot change, or when you want to keep modules independent. Combine them when you need both: type the parameter with a protocol and let your own classes share a base.
Exercise
A library gives you a Timer class with a start() and stop() method. You cannot edit it. Your function measure(t) calls both methods. Would you type t with an ABC or a Protocol, and why? Name one thing the Protocol will not do for you at runtime.
Show answer
Use a Protocol with start() and stop(). Timer cannot inherit from your ABC, and ABC.register is invisible to most type checkers. A type checker will accept Timer because its shape matches. At runtime, the protocol will not stop an object missing stop() from being passed in or created. It fails only when stop() is called, unless you use a type checker or an explicit @runtime_checkable check, and that check verifies only names, not signatures.
Exercise
You write a protocol Job with @abstractmethod def run(self) -> None: .... A teammate defines class Cleanup(Job): pass and calls Cleanup(). What happens, and what happens if you remove @abstractmethod?
Show answer
With @abstractmethod, Cleanup() raises TypeError because Cleanup is an explicit subclass that left an abstract method unimplemented. Without @abstractmethod, Cleanup() succeeds at runtime and run() returns None from the inherited ... body. A type checker such as mypy would still report the problem, but Python would not.