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.
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 Mechanism | Inheritance Required? | Enforcement Timing | Runtime Cost | Primary Strength |
|---|---|---|---|---|
typing.Protocol (PEP 544) | No (structural) | Static CI type check (mypy / pyright) | Zero unless @runtime_checkable | Decouples callers from third-party SDKs & enables trivial test fakes |
abc.ABC + @abstractmethod | Yes (nominal) | Runtime TypeError on missing abstract method during cls() | Negligible MRO / ABCMeta check on instantiation | Enforces 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 import | Plugin auto-registration & subclass field validation without metaclass conflicts |
Custom type Metaclass | Yes (metaclass=Meta) | Class construction / type.__new__ | Complex MRO / metaclass layout conflicts | Framework 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.
pythonfrom collections.abc import Sequencefrom typing import Protocol, runtime_checkable@runtime_checkableclass EmbeddingProvider(Protocol):@propertydef dimensions(self) -> int: ...async def embed_batch(self, texts: Sequence[str]) -> list[list[float]]: ...# Third-party client or test fake NEVER inherits from EmbeddingProviderclass MockEmbedder:@propertydef dimensions(self) -> int:return 384async 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 onlyreturn 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.ProtocolInterfaces: Zero inheritance lock-in, works seamlessly onhttpx.AsyncClientor 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.ABCBase 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 triggeringABCMeta/SQLAlchemy/Pydantic metaclass layout collisions.
Failure modes and misconceptions
- Believing
@runtime_checkableValidates Method Signatures: Callingisinstance(obj, EmbeddingProvider)succeeds even ifembed_batchtakes zero arguments or returnsstrinstead oflist[list[float]]. Always pair Protocols withpyrightormypy --strictin CI. - Defining Protocols Using Mutable Parameter Types (
list[str]instead ofSequence[str]): Passing atuple[str, ...]orlist[SpecialDoc]against a parameter typedlist[BaseDoc]raises invariant type errors in Pyright/mypy. Accept read-onlySequenceorIterableabstractions in Protocol method signatures. - Custom
typeMetaclass Conflicts Across Frameworks: Inheriting from both a PydanticBaseModel(or SQLAlchemyDeclarativeBase) and a custom metaclass raisesTypeError: 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. - Protocol Method Signatures Using Concrete
selfAnnotations or Instantiating Protocols: CallingEmbeddingProvider()raisesTypeError: Protocols cannot be instantiated, and omitting...bodies or misspelling default argument compatibility causes structural subtyping mismatches when implementations rename keyword parameters.
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 (
Sequencevslist) 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).