Sub topic 12
Choosing between ABCs and typing.Protocol
This chapter assumes you can define an ABC with @abstractmethod, know how isinstance and register work with ABCs, and have seen type hints. Both tools describe an interface. They differ in who has to know about that interface and when a mismatch is caught.
Nominal and structural typing
An ABC uses nominal typing. A class counts as a Closeable only if it inherits from it or is registered with it. The relationship is declared by name.
A typing.Protocol uses structural typing. A class matches if it has the required members, whatever its parents are. This is the static form of duck typing.
from abc import ABC, abstractmethod
from typing import Protocol, runtime_checkable
class CloseableABC(ABC):
@abstractmethod
def close(self) -> None:
...
@runtime_checkable
class SupportsClose(Protocol):
def close(self) -> None:
...
class Connection:
def close(self) -> None:
print("connection closed")
print(isinstance(Connection(), CloseableABC))
print(isinstance(Connection(), SupportsClose))
print(isinstance(42, SupportsClose))This prints False, True, False. Connection never mentions either interface. The protocol accepts it because it has a close method. The ABC rejects it until you inherit from it, call register, or add a __subclasshook__.
Where each one checks
| Question | ABC | Protocol |
|---|---|---|
| Needs inheritance or registration | Yes | No |
| Missing method detected | At instantiation, with `TypeError` | By a static type checker such as mypy |
| Can supply shared concrete methods | Yes | Possible only to classes that explicitly subclass it |
| `isinstance` works | Always | Only with `@runtime_checkable` |
| Works with classes you cannot edit | Only via `register` | Yes |
An ABC enforces its contract at runtime for subclasses. A protocol does nothing at runtime unless you ask for isinstance, and even then the check is shallow.
The limits of runtime-checkable protocols
isinstance against a runtime-checkable protocol checks only that the attribute names exist. It does not check signatures, argument types, or return types.
from typing import Protocol, runtime_checkable
@runtime_checkable
class SupportsClose(Protocol):
def close(self) -> None:
...
class NotReallyCloseable:
close = 5
print(isinstance(NotReallyCloseable(), SupportsClose))This prints True, even though close is not callable. The real value of a protocol is the static check. A type checker reads the signatures and reports a mismatch before the code runs.
Decision guide
Choose an ABC when:
- Subclasses should inherit concrete helpers, as with the template method pattern.
- You want
TypeErrorat instantiation if a method is missing. - You are building a plugin system where authors are expected to subclass your base.
Choose a Protocol when:
- Callers need only one or two methods, such as
readorclose. - The implementing classes come from other libraries or the standard library.
- You want to annotate function parameters without forcing an inheritance relationship.
You can combine them. Annotate parameters with a protocol, and offer an ABC as an optional convenient base that provides defaults.
Common mistakes
- Forgetting
@runtime_checkableand then callingisinstance. This raisesTypeError. - Treating a passing
isinstancecheck against a protocol as proof that the signatures are right. - Expecting a protocol to stop instantiation of an incomplete class. Only a class that explicitly subclasses the protocol and leaves its methods unimplemented behaves like an ABC in that respect.
Exercise
A library gives you a Socket class that has a close() method. You cannot edit it, and you want a function shutdown(resource) that accepts any object with close(). Would you use an ABC or a Protocol, and why?
Show answer
Use a Protocol such as SupportsClose. Socket matches structurally without any change. With an ABC you would have to call register or write a __subclasshook__. You could also use @runtime_checkable if shutdown needs an isinstance check, but remember that it checks only that close exists.