Sub topic 12
Choosing between ABCs and typing.Protocol
This chapter assumes you know how ABC and @abstractmethod work, including the instantiation check, register, and __subclasshook__. It also assumes you have seen type hints. You don't need to have used typing.Protocol before.
Both tools describe an interface. They differ in how a class qualifies as matching it, and in who checks: Python at runtime, or a static type checker such as mypy or pyright.
Two ways to say "this object has the right shape"
An ABC uses nominal typing. A class conforms if it inherits from the ABC, or if someone registers it. __subclasshook__ can loosen this at runtime, but the type checker doesn't know about that.
A protocol uses structural typing. A class conforms if it has the required members with compatible signatures. It never has to mention the protocol. This is the static version of duck typing.
Here is the close interface written both ways.
from abc import ABC, abstractmethod
from typing import Protocol
class CloseableABC(ABC):
@abstractmethod
def close(self) -> None:
...
class SupportsClose(Protocol):
def close(self) -> None:
...
class Connection:
def close(self) -> None:
print("connection closed")
def shutdown(resource: SupportsClose) -> None:
resource.close()
shutdown(Connection())Connection inherits from neither class. A type checker accepts shutdown(Connection()) because Connection has a matching close. A checker would reject shutdown(Connection()) if the parameter were annotated CloseableABC, because Connection is not a subclass of it.
What each tool checks, and when
| Question | ABC | Protocol |
|---|---|---|
| How does a class conform? | Inherit, register, or match a hook | Have matching members |
| Must the class mention the interface? | Yes, unless a hook accepts it | No |
| Missing method detected at runtime? | Yes, at instantiation, for subclasses | No, unless you call the missing method |
| Missing method detected statically? | Yes | Yes |
| `isinstance` works? | Always | Only with `@runtime_checkable` |
| Can supply shared code? | Yes, concrete methods | Only to classes that explicitly subclass it |
| Signatures checked at runtime? | No | No |
The most important row is the third. An ABC gives you a runtime guarantee: you can't create an incomplete subclass. A plain protocol gives you nothing at runtime. A type checker is its only enforcement, and Python itself will not stop an incompatible object.
Runtime checks with @runtime_checkable
By default, isinstance against a protocol raises TypeError. Decorate the protocol with @runtime_checkable to allow it.
from typing import Protocol, runtime_checkable
@runtime_checkable
class SupportsClose(Protocol):
def close(self) -> None:
...
class Plain(Protocol):
def close(self) -> None:
...
class Connection:
def close(self) -> None:
print("connection closed")
print(isinstance(Connection(), SupportsClose))
print(isinstance(42, SupportsClose))
try:
isinstance(Connection(), Plain)
except TypeError as exc:
print("TypeError:", exc)The first two checks print True and False. The third raises TypeError because Plain is not runtime-checkable.
The runtime check is shallow. It only tests that the names exist. It does not compare parameters or return types.
from typing import Protocol, runtime_checkable
@runtime_checkable
class SupportsClose(Protocol):
def close(self) -> None:
...
class Odd:
def close(self, force: bool, timeout: float) -> int:
return 0
print(isinstance(Odd(), SupportsClose))This prints True, even though calling Odd().close() with no arguments fails. A static checker would reject Odd as a SupportsClose. The runtime check can't.
Two more limits apply to runtime-checkable protocols:
- A protocol with non-method members, such as plain attributes, supports
isinstancebut notissubclass.issubclassraisesTypeErrorfor it. - The check only looks for the name. A class that sets
close = Nonecan still be treated as matching, depending on the Python version.
Choosing: the decision criteria
Reach for an ABC when:
- You want a runtime guarantee. A subclass that forgets a method should fail at instantiation, not deep inside a request handler.
- You ship shared behavior. Concrete methods in the base class, such as a template method that calls abstract steps, are the main reason to use inheritance. This is why
collections.abc.Mappingsuppliesget,items, andvaluesonce you write three methods. - You own the implementations, or you can require them to subclass. Plugin systems and framework extension points fit here.
- You want a visible, named hierarchy.
isinstance(x, Plugin)then means exactly "this was designed as a plugin."
Reach for a protocol when:
- You describe what a function needs from its argument and don't control the classes that will be passed. Third-party types and standard library types can conform without changes.
- You want to keep the caller decoupled from your package. A caller doesn't import your interface just to satisfy it.
- The interface is small, often one or two methods, and there is no shared code to supply.
- Your priority is static checking in a typed codebase.
Both can coexist. A common design uses a protocol for the narrow thing a function consumes, and an ABC for the families of classes you implement yourself.
import io
from abc import ABC, abstractmethod
from typing import Protocol
class Reader(Protocol):
def read(self, size: int = -1) -> bytes:
...
class Codec(ABC):
@abstractmethod
def encode(self, data: bytes) -> bytes:
...
@abstractmethod
def decode(self, data: bytes) -> bytes:
...
def roundtrip(self, data: bytes) -> bytes:
return self.decode(self.encode(data))
class Reverse(Codec):
def encode(self, data: bytes) -> bytes:
return data[::-1]
def decode(self, data: bytes) -> bytes:
return data[::-1]
def load(source: Reader, codec: Codec) -> bytes:
return codec.decode(source.read())
print(load(io.BytesIO(b"cba"), Reverse()))
print(Reverse().roundtrip(b"hello"))load accepts any object with a compatible read, so files, BytesIO, and sockets wrapped as file objects all work. Codec is an ABC because you want incomplete codecs to fail at construction and you want roundtrip shared.
Protocols and ABCs can overlap
A protocol class is allowed to use @abstractmethod. Python's protocol machinery is built on ABCMeta. If a class explicitly subclasses the protocol, it inherits the abstract method and the instantiation check applies.
from abc import abstractmethod
from typing import Protocol
class Greeter(Protocol):
@abstractmethod
def greet(self) -> str:
...
class Incomplete(Greeter):
pass
try:
Incomplete()
except TypeError as exc:
print("TypeError:", exc)You can't instantiate a protocol class directly either. Subclassing a protocol explicitly is useful when you want default method bodies, or when you want the runtime check for your own classes while still letting outside classes match structurally.
How this interacts with the standard library
Some of collections.abc is structural in practice. Typeshed, the type stub collection that checkers use, declares Iterable, Sized, Container, Hashable, and similar one-method interfaces as protocols. A class with __iter__ is accepted where Iterable is annotated, with no inheritance.
The richer ABCs, such as Mapping, MutableSequence, and Set, remain nominal in stubs. At runtime, isinstance(x, Iterable) works through __subclasshook__, the same technique from the earlier chapter. Mapping has no such hook, so a class that only looks like a mapping is not an instance of it unless it inherits or is registered.
Pitfalls specific to this choice
- Registered classes are invisible to type checkers.
Closeable.register(LegacyFile)makesisinstancereturnTrueat runtime. Static checkers generally don't honor it, so annotations using that ABC still flagLegacyFile. If you need to accept third-party classes in typed code, a protocol is the better fit. - Protocols give no runtime safety net. If your code is untyped, or types are not enforced in CI, a protocol documents intent and enforces nothing.
- Don't mix up
@runtime_checkablewith validation. It is forisinstancedispatch, such as choosing a branch. It is not for verifying input. - Overbroad protocols match by accident. A protocol requiring only
readmatches many unrelated classes. Name the protocol after the capability and keep it narrow, for exampleSupportsReadrather thanStream. - Changing a protocol breaks outside implementers silently. A class you don't own conforms by shape, so adding a required method to the protocol breaks it without any change on its side. With an ABC, you control the subclasses, and a new abstract method fails visibly at instantiation.
Exercise
You write a function archive(item) that calls item.close(). It must accept file objects from the standard library, your own classes, and classes from a third-party package you can't edit. Your team runs mypy in CI. Should the parameter be annotated with an ABC or a Protocol? Name one reason, and one case where you would switch to an ABC.
Show answer
Use a Protocol, such as SupportsClose with a single close(self) -> None method. The third-party and standard library classes already have close, and they can't be made to inherit from your ABC. A protocol lets mypy accept them without registration, and mypy does not honor register. Switch to an ABC for a family of classes you implement yourself that should share concrete methods, such as a template method, or when you want a missing method to fail at instantiation with TypeError instead of only in a static check.
Exercise
Given a class Odd whose close(self, force, timeout) requires two arguments, and a @runtime_checkable protocol SupportsClose with close(self) -> None, what does isinstance(Odd(), SupportsClose) return, and what does mypy say about shutdown(Odd())?
Show answer
isinstance returns True, because the runtime check only tests that a close attribute exists. mypy reports an incompatible argument type, because the signature of close does not match the protocol.