Sub topic 12
Choosing between a Protocol and an ABC
This chapter assumes you can write classes and functions with type hints, know how inheritance and abc.ABC work, and have run a static type checker such as mypy or pyright. It compares the two tools and gives rules for choosing between them.
Two ways to say "this shape"
An abstract base class (ABC) uses nominal subtyping. A class is compatible only if it declares the relationship by inheriting from the ABC (or by being registered with it). A Protocol uses structural subtyping. A class is compatible if it has the right members, whether or not it mentions the protocol.
from abc import ABC, abstractmethod
from typing import Protocol
class ClosableABC(ABC):
@abstractmethod
def close(self) -> None: ...
class ClosableProto(Protocol):
def close(self) -> None: ...
class Resource:
def close(self) -> None:
print("closed")
def shutdown_abc(item: ClosableABC) -> None:
item.close()
def shutdown_proto(item: ClosableProto) -> None:
item.close()
shutdown_proto(Resource()) # accepted: the shape matches
shutdown_abc(Resource()) # rejected by a type checker: Resource does not inherit ClosableABCResource has never heard of either type. Only the protocol accepts it.
What each one gives you
| Question | ABC | Protocol |
|---|---|---|
| Must implementers inherit from it? | Yes (or call `register`) | No |
| Can it supply shared method code? | Yes, concrete methods are inherited | Only if a class subclasses it explicitly |
| Does it block instantiation of incomplete classes? | Yes, at runtime | Only for explicit subclasses |
| Does `isinstance` work by default? | Yes | No, needs `@runtime_checkable` |
| Works with classes you cannot edit? | Only through `register` | Yes, automatically |
The third row matters in practice. If a class inherits from an ABC and forgets an abstract method, calling the constructor raises TypeError. A class that merely matches a protocol gets no such runtime check. The type checker is the only safeguard.
Decision criteria
Choose a Protocol when:
- The code that consumes the type is separate from the code that implements it, and you want to avoid an import dependency between them.
- You need to accept third-party or standard-library classes that you cannot modify.
- The contract is small, such as one or two methods, and has no shared behavior.
Choose an ABC when:
- You want to provide a template, meaning concrete helper methods built on top of a few abstract ones.
- You want a runtime guarantee that subclasses are complete, and you control all the implementations.
- You rely on
isinstancechecks in the program logic and want them to be reliable.
Combining both
The two tools work together. A common design uses a protocol for the parameter type that callers see, and an ABC as an optional base class that supplies defaults.
from abc import ABC, abstractmethod
from typing import Protocol
class Exporter(Protocol):
def export(self, rows: list[dict[str, str]]) -> str: ...
class BaseExporter(ABC):
"""Optional helper: implements the shared header logic."""
@abstractmethod
def format_row(self, row: dict[str, str]) -> str: ...
def export(self, rows: list[dict[str, str]]) -> str:
return "\n".join(self.format_row(r) for r in rows)
class CsvExporter(BaseExporter):
def format_row(self, row: dict[str, str]) -> str:
return ",".join(row.values())
class JsonLinesExporter:
"""Does not inherit anything, but matches Exporter."""
def export(self, rows: list[dict[str, str]]) -> str:
return "\n".join(str(r) for r in rows)
def run(exporter: Exporter) -> None:
print(exporter.export([{"a": "1", "b": "2"}]))
run(CsvExporter())
run(JsonLinesExporter())run depends only on the protocol. CsvExporter reuses the ABC's code. JsonLinesExporter stays independent of both.
Common mistakes
- Using a protocol and then calling
isinstancewithout@runtime_checkable. This raisesTypeError. - Assuming
@runtime_checkableverifies signatures. It only checks that the named members exist. - Making a large protocol with many methods. Callers then have to satisfy more than they need. Prefer several small protocols.
- Using an ABC where only a parameter type was needed. This forces every implementer to import and inherit it.
Exercise
You are writing a plugin system. Plugins come from other teams and from third-party packages, and each needs only a run() -> None method. Should the plugin type be a Protocol or an ABC, and why?
Show answer
A Protocol. Third-party plugin authors should not have to import and inherit from your base class, and the contract is a single method with no shared code. A structural type accepts any class with a compatible run method. You would switch to an ABC only if you wanted to provide shared helper methods or enforce completeness at instantiation time.