FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Python Protocols vs ABCs

Static structural subtyping with typing.Protocol vs nominal Abstract Base Classes.

Freshness: current•15 min read•Software and Web Engineering

Key Learning Outcomes

  • ✓Implement static duck typing with Protocols
  • ✓Compare structural and nominal interfaces
Full Technical Reference Document

Mental model

Python offers two formal mechanisms for modeling extensible software contracts: nominal subtyping via abc.ABC (requiring every implementation class to explicitly inherit from a shared base class) and structural subtyping via PEP 544 typing.Protocol (formalized static "duck typing," where any object providing matching attributes and method signatures satisfies the interface automatically without inheriting anything). Understanding when to prefer structural Protocol decoupling, nominal ABC runtime instantiation enforcement, or rare class-creation hooks (__init_subclass__ over full custom metaclasses) keeps large Python codebases modular, testable, and free of fragile diamond-inheritance traps.

Protocol Interface Definition
Unrelated Class Implementing Shape
Static Type Checker (Mypy / Pyright)
Structural Compatibility Verified
Conceptual teaching model synthesized from:python-docs,python-asyncio-docs

Theory

In large multi-team AI applications, concrete adapters (OpenAIClient, PgVectorStore, InMemoryFakeStore) often live in separate modules or third-party SDKs that you do not own. Requiring every adapter to subclass a framework base class creates brittle cross-package coupling—whereas defining a narrow Protocol right next to the consumer ("dependency inversion" in pure Python typing) lets existing classes and test fakes conform automatically.

Interface MechanismInheritance Required?Enforcement TimingRuntime CostPrimary Strength
typing.Protocol (PEP 544)No (structural)Static CI type check (mypy / pyright)Zero unless @runtime_checkableDecouples callers from third-party SDKs & enables trivial test fakes
abc.ABC + @abstractmethodYes (nominal)Runtime TypeError on missing abstract method during cls()Negligible MRO / ABCMeta check on instantiationEnforces shared template implementations & catches incomplete subclasses at boot
__init_subclass__ (PEP 487)Yes (standard subclassing)Class creation time (class Child(Plugin):)Zero runtime overhead after importPlugin auto-registration & subclass field validation without metaclass conflicts
Custom type MetaclassYes (metaclass=Meta)Class construction / type.__new__Complex MRO / metaclass layout conflictsFramework ORMs (DeclarativeBase) rewriting class attributes before construction

Variance, @runtime_checkable Pitfalls, and __init_subclass__

When authoring protocols, method return types behave covariantly (Sequence[str] safely fulfills Sequence[object]) while mutable container parameters behave invariant (list[str] cannot fulfill list[object] because callers could append an int). Declaring read-only properties via @property or abstract container arguments with Sequence[T]/Mapping[K, V] keeps Protocol interfaces broadly composable without covariance rejections. Notice also that @runtime_checkable inspects attribute existence only, not parameter/return signatures (isinstance(fake, VectorStore) returns True even if search() accepts wrong arguments), so treat runtime isinstance(..., Protocol) strictly as a coarse capability probe rather than a substitute for static checking. Meanwhile, 95% of historic metaclass use cases—like auto-registering tool handlers into a central dictionary—are better served by Python 3.6+ __init_subclass__, avoiding TypeError: metaclass conflict when mixing mixins or Pydantic models.

python
from collections.abc import Sequence
from typing import Protocol, runtime_checkable
​
@runtime_checkable
class EmbeddingProvider(Protocol):
@property
def dimensions(self) -> int: ...
​
async def embed_batch(self, texts: Sequence[str]) -> list[list[float]]: ...
​
# Third-party client or test fake NEVER inherits from EmbeddingProvider
class MockEmbedder:
@property
def dimensions(self) -> int:
return 384
​
async def embed_batch(self, texts: Sequence[str]) -> list[list[float]]:
return [[0.0] * 384 for _ in texts]
​
async def index_chunks(chunks: Sequence[str], embedder: EmbeddingProvider) -> int:
vectors = await embedder.embed_batch(chunks)
assert isinstance(embedder, EmbeddingProvider) # checks method/property presence only
return len(vectors)
​
# Clean alternative to heavy custom metaclasses for plugin/tool auto-registration:
class RegisteredTool:
registry: dict[str, type["RegisteredTool"]] = {}
​
def __init_subclass__(cls, *, tool_name: str, **kwargs: object) -> None:
super().__init_subclass__(**kwargs)
if tool_name in RegisteredTool.registry:
raise ValueError(f"Duplicate tool registration: {tool_name}")
RegisteredTool.registry[tool_name] = cls

Alternatives and trade-offs

  • typing.Protocol Interfaces: Zero inheritance lock-in, works seamlessly on httpx.AsyncClient or boto3 stubs you cannot modify, keeps dependencies inverted around consumer needs; relies on running Pyright or mypy in CI because Python ignores type hints at runtime by default.
  • abc.ABC Base Classes: Guarantees incomplete concrete subclasses fail immediately on instantiation even without running a type checker, and cleanly shares concrete template helper methods (super()); binds downstream packages tightly to the base module.
  • Class Decorators & __init_subclass__: Expressive declarative hooks for plugin registries and validation without triggering ABCMeta/SQLAlchemy/Pydantic metaclass layout collisions.

Failure modes and misconceptions

  1. Believing @runtime_checkable Validates Method Signatures: Calling isinstance(obj, EmbeddingProvider) succeeds even if embed_batch takes zero arguments or returns str instead of list[list[float]]. Always pair Protocols with pyright or mypy --strict in CI.
  2. Defining Protocols Using Mutable Parameter Types (list[str] instead of Sequence[str]): Passing a tuple[str, ...] or list[SpecialDoc] against a parameter typed list[BaseDoc] raises invariant type errors in Pyright/mypy. Accept read-only Sequence or Iterable abstractions in Protocol method signatures.
  3. Custom type Metaclass Conflicts Across Frameworks: Inheriting from both a Pydantic BaseModel (or SQLAlchemy DeclarativeBase) and a custom metaclass raises TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases. Replace custom metaclasses with __init_subclass__ or composition.
  4. Protocol Method Signatures Using Concrete self Annotations or Instantiating Protocols: Calling EmbeddingProvider() raises TypeError: Protocols cannot be instantiated, and omitting ... bodies or misspelling default argument compatibility causes structural subtyping mismatches when implementations rename keyword parameters.
Reflect before revealing the guide

Decision scenario

Your RAG platform supports pluggable vector backends (pgvector, Qdrant, Milvus) plus an ultra-fast deterministic fake in unit tests, and must let team squads wrap third-party SDK clients without monkey-patching or subclassing external library types. Define a narrow consumer-owned VectorIndexProtocol(Protocol) accepting Sequence[str] filters and returning read-only match records, enforce strict conformance across adapters in CI with Pyright, use abc.ABC strictly for internal framework hooks that must share stateful base lifecycle code, and replace an existing legacy metaclass registry with __init_subclass__ to stay compatible with Pydantic V2 models.

Learning outcomes

  • Contrast structural subtyping (typing.Protocol) against nominal subtyping (abc.ABC) and dependency inversion patterns.
  • Explain method/attribute variance rules (Sequence vs list) and the exact limits of @runtime_checkable.
  • Eliminate custom metaclass inheritance conflicts by applying __init_subclass__ or class decorators.
  • Enforce zero-runtime-overhead static interface guarantees across adapters and test fakes using Pyright/mypy.

Trade-offs

typing.Protocol yields clean, non-invasive interface decoupling across external SDKs and unit-test fakes with zero runtime cost, but shifts contract enforcement from Python runtime startup to strict CI static type checking (pyright / mypy).

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next