ABC vs Protocol
Two ways to describe an interface. An ABC (abstract base class) is nominal: a class must inherit from it, and Python checks at run time that the required methods exist. A Protocol is structural: any class with matching methods fits, and a type checker (mypy, pyright) checks it before the code runs.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| force subclasses to implement a method | abc.ABC + @abstractmethod |
class Storage(ABC): ... |
| get an error before an incomplete object exists | an ABC | TypeError at Half() |
| share code between implementations | concrete methods on the ABC | def save_all(self, items): ... |
| an abstract property | @property above @abstractmethod |
def extension(self) -> str: ... |
| an abstract class method | @classmethod above @abstractmethod |
def from_url(cls, url): ... |
| list the methods still missing | Cls.__abstractmethods__ |
frozenset({'get'}) |
| count a class as a subclass without inheriting | Base.register(Other) |
virtual subclass |
| accept any object with certain methods | typing.Protocol |
class SupportsRead(Protocol): ... |
| type third-party objects you cannot edit | a Protocol |
def load(fp: SupportsRead) |
| require an attribute, not a method | a protocol with an annotation | name: str |
| type a callback with keyword arguments | a protocol with __call__ |
class OnEvent(Protocol): def __call__(...) |
| a generic protocol | class Repo[T](Protocol): (3.12+) |
Repo[User] |
use a protocol with isinstance() |
@runtime_checkable |
names only, not signatures |
| check “can I iterate / index / call it” | collections.abc |
isinstance(x, Iterable) |
| type a parameter “any read-only mapping” | collections.abc.Mapping |
def f(cfg: Mapping[str, str]) |
| type “any iterable” | collections.abc.Iterable |
def total(xs: Iterable[float]) |
| get many methods from a few | subclass a collections.abc class |
Sequence gives index, count, __iter__ |
| check “is it a path” | os.PathLike |
isinstance(p, os.PathLike) |
| check “is it hashable” | collections.abc.Hashable |
isinstance([], Hashable) → False |
| a quick script | plain duck typing | just call the method |
| fail loudly when a protocol is not met | run mypy or pyright | mypy src/ |
Abstract base classes
Section titled “Abstract base classes”from abc import ABC, abstractmethod
class Storage(ABC): @property @abstractmethod # innermost decorator def scheme(self) -> str: ...
@abstractmethod def get(self, key: str) -> bytes | None: ...
@abstractmethod def put(self, key: str, data: bytes) -> None: ...
def url(self, key: str) -> str: # concrete method built on abstract parts return f"{self.scheme}://{key}"
def copy(self, src: str, dst: str) -> None: # a template that every subclass gets data = self.get(src) if data is None: raise KeyError(src) self.put(dst, data)
class MemoryStorage(Storage): scheme = "mem" # a class attribute satisfies the abstract property
def __init__(self) -> None: self._data: dict[str, bytes] = {}
def get(self, key: str) -> bytes | None: return self._data.get(key)
def put(self, key: str, data: bytes) -> None: self._data[key] = data
s = MemoryStorage()s.put("a.txt", b"hi")s.copy("a.txt", "b.txt")print(s.url("b.txt"), s.get("b.txt"), sorted(Storage.__abstractmethods__))print(isinstance(s, Storage), MemoryStorage.__abstractmethods__ == frozenset())mem://b.txt b'hi' ['get', 'put', 'scheme']True TrueAn incomplete subclass fails when you create an instance, not when you define the class:
class HalfStorage(Storage): scheme = "half"
def get(self, key: str) -> bytes | None: return None
print(sorted(HalfStorage.__abstractmethods__))HalfStorage() # put() is missing['put']TypeError: Can't instantiate abstract class HalfStorage without an implementation for abstract method 'put'| Fact | Detail |
|---|---|
needs ABC (or metaclass=ABCMeta) in the tree |
@abstractmethod alone does nothing |
| checked when | at Cls(), not at class definition |
| what is checked | that the names are overridden, not signatures or return types |
| abstract method with a body | allowed; subclasses call it with super().method() |
| decorator order | @property, @classmethod or @staticmethod above @abstractmethod |
Cls.__abstractmethods__ |
a frozenset of names still missing |
Base.register(Other) |
isinstance() says True; nothing is inherited or checked |
__subclasshook__ |
lets an ABC accept classes by structure (how Sized and Iterable work) |
| an ABC with no abstract methods | can be instantiated; use it only as a marker base |
Protocols
Section titled “Protocols”import iofrom typing import Protocol
class SupportsRead(Protocol): def read(self, size: int = -1, /) -> str: ...
class Named(Protocol): name: str # an attribute member
def first_line(fp: SupportsRead) -> str: # no base class needed return fp.read().splitlines()[0]
class FakeFile: # a test double: matches by structure def read(self, size: int = -1, /) -> str: return "header\nrow"
class Job: def __init__(self, name: str) -> None: self.name = name
def label(obj: Named) -> str: return obj.name.upper()
print(first_line(io.StringIO("id,amount\n1,9.99")), first_line(FakeFile()))print(label(Job("nightly-export")))id,amount headerNIGHTLY-EXPORT| Protocol form | Code | Use |
|---|---|---|
| methods | def read(self) -> str: ... |
file-like, client-like objects |
| attributes | name: str |
any object with that attribute |
| read-only attribute | @property def name(self) -> str: ... |
accepts a property or a plain attribute |
| callable | def __call__(self, event: str, *, retry: bool) -> None: ... |
callbacks with keyword arguments; Callable[...] cannot name them |
| generic | class Repo[T](Protocol): def get(self, id: int) -> T: ... |
Repo[User], Repo[Order] |
| combined | class ReadWrite(SupportsRead, SupportsWrite, Protocol): ... |
list Protocol again |
| explicit | class FakeFile(SupportsRead): |
optional; mypy then checks the class body |
from collections.abc import Callablefrom typing import Protocol
class OnEvent(Protocol): def __call__(self, name: str, *, retry: bool = False) -> None: ...
def subscribe(handler: OnEvent) -> None: ...
def log_event(name: str, *, retry: bool = False) -> None: ...
subscribe(log_event) # OK: same signaturesubscribe(print) # mypy error: print has no retry parameterHandler = Callable[[str], None] # Callable cannot express keyword-only parameters@runtime_checkable caveats
Section titled “@runtime_checkable caveats”from typing import Protocol, runtime_checkable
@runtime_checkableclass Closeable(Protocol): def close(self) -> None: ...
class Conn: def close(self) -> None: pass
class Liar: close = 0 # not callable
class WrongSignature: def close(self, force: bool) -> str: # needs an argument, returns str return "closed"
print(isinstance(Conn(), Closeable), isinstance(Liar(), Closeable))print(isinstance(WrongSignature(), Closeable), isinstance(open, Closeable))True TrueTrue False| Caveat | Detail |
|---|---|
| without the decorator | isinstance() raises TypeError: Instance and class checks can only be used with @runtime_checkable protocols |
| checks only | that each member name exists on the object |
| does not check | signatures, return types, attribute types, even callable() |
| protocols with data members | issubclass() raises TypeError: Protocols with non-method members don't support issubclass(). Non-method members: 'name'. |
| speed | slower than a normal isinstance(): it inspects every member |
| a protocol itself | Closeable() raises TypeError: Protocols cannot be instantiated |
| the safer run-time check | callable(getattr(obj, "close", None)) |
collections.abc
Section titled “collections.abc”| ABC | Abstract methods you write | Mixin methods you get | isinstance() is True for |
|---|---|---|---|
Iterable |
__iter__ |
— | list, tuple, str, dict, set, range, files, generators |
Iterator |
__next__ |
__iter__ |
generators, iter(x), files, map(), zip() |
Generator |
send, throw |
close, __iter__, __next__ |
generator objects |
Sized |
__len__ |
— | anything with __len__ |
Container |
__contains__ |
— | anything with __contains__ |
Hashable |
__hash__ |
— | int, str, tuple, frozen dataclasses; not list, dict, set |
Callable |
__call__ |
— | functions, methods, classes, objects with __call__ |
Collection |
__len__, __iter__, __contains__ |
— | list, tuple, str, dict, set |
Sequence |
__getitem__, __len__ |
__contains__, __iter__, __reversed__, index, count |
list, tuple, str, range, bytes |
MutableSequence |
the above + __setitem__, __delitem__, insert |
append, extend, pop, remove, reverse, += |
list, deque, bytearray |
Set |
__contains__, __iter__, __len__ |
<=, &, |, -, ^, isdisjoint |
set, frozenset, dict.keys() |
MutableSet |
the above + add, discard |
remove, pop, clear, |=, &= |
set |
Mapping |
__getitem__, __len__, __iter__ |
__contains__, keys, items, values, get, __eq__ |
dict, MappingProxyType, ChainMap |
MutableMapping |
the above + __setitem__, __delitem__ |
pop, popitem, setdefault, update, clear |
dict, defaultdict, OrderedDict, Counter |
Awaitable, AsyncIterable, AsyncIterator |
__await__, __aiter__, __anext__ |
— | coroutines, async generators |
The one-trick ABCs (Iterable, Iterator, Reversible, Sized, Container, Collection, Hashable, Callable, Generator, the async ones and Buffer) check by structure: a class with __len__ is Sized without inheriting. Sequence and Mapping need inheritance or register().
from collections.abc import Hashable, Iterable, Iterator, Mapping, Sequence, Sized
class Bag: def __len__(self) -> int: return 3
checks = { "list is Sequence": isinstance([], Sequence), "dict is Sequence": isinstance({}, Sequence), "dict is Mapping": isinstance({}, Mapping), "str is Iterable": isinstance("ab", Iterable), "list is Iterator": isinstance([], Iterator), "Bag is Sized": isinstance(Bag(), Sized), "list is Hashable": isinstance([], Hashable),}for name, ok in checks.items(): print(f"{name:<18}{ok}")list is Sequence Truedict is Sequence Falsedict is Mapping Truestr is Iterable Truelist is Iterator FalseBag is Sized Truelist is Hashable FalseOther ready-made interfaces:
| Interface | Module | Means |
|---|---|---|
os.PathLike |
os |
has __fspath__; pathlib.Path is one |
contextlib.AbstractContextManager |
contextlib |
has __enter__ and __exit__ |
numbers.Number, Real, Integral |
numbers |
the numeric tower: isinstance(3, numbers.Real) is True |
SupportsInt, SupportsFloat, SupportsIndex, SupportsAbs |
typing |
runtime-checkable protocols for conversions |
io.IOBase, io.TextIOBase |
io |
real file objects |
Buffer |
collections.abc (3.12+) |
supports the buffer protocol: bytes, bytearray, memoryview |
Which one?
Section titled “Which one?”| ABC | Protocol | Duck typing | |
|---|---|---|---|
| Relation | nominal: must inherit (or register) |
structural: matching methods | none |
| Checked by | Python, at Cls() |
mypy or pyright, before running | the call itself |
| Error for a missing method | TypeError when you create the object |
a type-checker error | AttributeError at the call |
| Shares code | yes, concrete methods | no (methods with bodies are only defaults for explicit subclasses) | no |
| Works with third-party classes | only with register() |
yes | yes |
isinstance() |
yes, real | only with @runtime_checkable, names only |
hasattr() / callable(getattr(...)) |
| Signatures checked | no | yes (by the type checker) | no |
| Need | Choose |
|---|---|
| a quick script, standard library style | duck typing |
| your own family of classes that share code | ABC with concrete methods |
| plugins that must implement a method, with an early clear error | ABC |
| a function parameter that accepts objects you do not own | Protocol |
| a test double without inheriting from the real class | Protocol |
| a small interface per caller (interface segregation) | several small Protocols |
| a run-time branch on capability | collections.abc or callable(getattr(...)) |
| both: shared code and structural typing | an ABC for implementers, a Protocol for callers |
Gotchas
Section titled “Gotchas”@abstractmethodwithoutABC. Symptom: an incomplete subclass is created without error. Fix: inherit fromABCor usemetaclass=ABCMeta.- Wrong decorator order. Symptom: an abstract property or class method is not enforced, or
AttributeErrorat class creation. Fix: put@abstractmethodinnermost, directly abovedef. - ABCs check names only. Symptom:
def get(self)with the wrong parameters counts as an implementation. Fix: run mypy; write tests for each implementation. - Late error. Symptom: an incomplete subclass imports fine and fails only at
Cls(). Fix: create one instance of each implementation in a test. register()trusts you. Symptom:isinstance()isTrue, thenAttributeError. Fix: useregister()only for classes that really implement the interface.- Runtime protocol checks are shallow. Symptom:
isinstance(obj, Closeable)isTrueforclose = 0or the wrong signature. Fix: rely on mypy; at run time also checkcallable(). isinstance()with a plain Protocol. Symptom:TypeError: Instance and class checks can only be used with @runtime_checkable protocols. Fix: add@runtime_checkable, or do not check at run time.- Protocol with data members and
issubclass(). Symptom:TypeError: Protocols with non-method members don't support issubclass(). Non-method members: …. Fix: useisinstance()on an instance. - Positional-only mismatch. Symptom: mypy rejects
io.StringIOfor yourread(self, size)protocol. Fix: mark parameters positional-only with/when callers pass them positionally. isinstance(x, Iterable)misses old-style iterables. Symptom: a class with only__getitem__is iterable but notIterable. Fix: tryiter(x)and catchTypeError.stris aSequenceofstr. Symptom: a function for “a list of names” accepts"ada"and loops over letters. Fix: checkisinstance(x, str)first.- A fat interface. Symptom: implementations raise
NotImplementedErrorfor half the methods. Fix: split into small protocols.
Learn more
Section titled “Learn more”- Lesson: Inheritance and polymorphism (ABCs, Protocols) and its cheat sheet
- Type hints and Protocols: Type hints and its cheat sheet
- Container protocols from the other side: Dunder methods
- Interface segregation: Design patterns