Direct answer
A Protocol fits when you own the call site and want any object with the right shape to satisfy it. An ABC fits when you own the implementations and want a shared nominal base with a registration point and partial defaults. PEP 544 defines protocols as a way to express structural typing relationships, so a protocol match is a static conclusion about the shape a value has. A runtime isinstance check against a protocol is a separate question and does not follow from the static match. The concrete win is decoupling a caller from a concrete class it never needed to name. The concrete loss is that a protocol says nothing about behavior, so two structurally identical implementations can behave differently at runtime and the type system will not notice.
The review order matters. Map the implementations and the call sites first, then decide which side of the contract the abstraction should live on. Ask Claude Code to inventory callers and the attributes they use, not to pick an abstraction for you. The choice between structural and nominal typing is a design decision that depends on who owns the interface.
Why the wrong abstraction costs refactor time
Pick a Protocol when the interface should be open to objects you do not control. Pick an ABC when the interface should be a deliberate family with a single base. Choosing wrong shows up later as friction in one direction. A Protocol used where a shared base was needed leaves each implementation reinventing defaults. An ABC used where openness was needed forces every caller to subclass or register, including third-party objects that cannot be modified.
The cost is a refactor that touches every implementation or every call site. Neither abstraction is cheaper in general; they optimize for different ownership boundaries. A team that names the boundary before writing the interface spends an hour deciding. A team that guesses spends a week moving code.
There is a review angle too. A refactor that swaps an ABC for a Protocol changes what the type checker accepts without changing any runtime statement. It is exactly the kind of change that looks cosmetic in a diff and is not. Reviewers need to know whether the intent is to widen what callers may pass or to narrow it.
Evidence and its limits
Official, F003: PEP 544: Protocols defines protocols as a way to express structural typing relationships in Python. The definition this post builds on is structural. The canonical PEP page was not full-page fetched within the research budget, so recheck the exact passage before citing it further.
Official: The standard library page for typing.Protocol documents the runtime class behind static structural typing, and the mypy cheat sheet documents how a static checker treats protocol matching.
Official, agent loop: Claude Code best practices recommends a pass-or-fail check for the agent to close its loop. In an interface refactor the check is the static checker plus the existing test suite, run before and after. Claude Code common workflows covers iterating an edit against a command.
Derived, F004: Distinguishing static structural typing from explicit runtime protocol checks is a review recommendation. It does not imply runtime equivalence between protocols and ABCs, and it is not a rule that one abstraction is better.
This post claims no performance result for either abstraction. This post does not claim a type checker guarantees runtime behavior.
Structural vs nominal typing
Structural typing asks whether a value has the members a context requires. Nominal typing asks whether a value was declared as a member of a named type. The two answer different questions, and Python supports both.
An ABC is nominal. A class is a Drawable because it inherits from Drawable or registers against it. The relationship is explicit and visible in the class definition. Visibility is a feature when the family is small and deliberate, and a cost when it forces unrelated classes into a shared hierarchy.
A Protocol is structural. A class satisfies a protocol because it has the required attributes with compatible signatures, regardless of inheritance. The relationship is inferred at the use site. Inference is a feature when callers should accept any conforming object, and a cost when the set of conforming objects should be a closed, reviewed list.
| Question | Protocol answer | ABC answer |
|---|---|---|
| Who defines conformance | The use site | The base class |
| Inheritance required | No | Yes, or explicit registration |
| Works on third-party classes | Yes, unmodified | Only via registration |
| Runtime check via isinstance | Only with explicit runtime protocol | Yes, native |
| Best when | Callers should accept any conforming object | Implementations form a deliberate family |
Read the table as a routing rule. Choose the row that matches who owns the boundary.
When a Protocol fits
A Protocol fits when the caller is the owner of the requirement. A function that renders any object with a to_dict method, or a repository layer that accepts any object with save and load, is expressing a shape it needs rather than a family it curates. Declaring a Protocol at that call site names the requirement without forcing producers to inherit from anything.
Protocols also fit when third-party objects must conform. A caller that accepts a Protocol accepts any object from any library that happens to have the right shape. An ABC would require modifying or registering those objects, which is often impossible for code you do not own.
The limit is behavior. A Protocol states the members a value has, not what they do. Two implementations with identical member signatures can differ in side effects, ordering, or error behavior. The type system will accept both. The Claude Code generated tests oracle bias guide covers the related trap where generated artifacts define their own standard; a protocol match is not a behavioral standard either.
When an ABC fits
An ABC fits when the implementations form a family with shared policy. A plugin system where every plugin must register through a known base, or a set of storage backends that share default methods in the base, benefits from a nominal root. The base can provide partial implementations, and the family is visible in the class definitions.
An ABC also fits when a runtime isinstance check is genuinely part of the contract. A dispatch that routes on type membership needs a nominal type to check against. A Protocol used with isinstance requires an explicit runtime protocol declaration, which is a separate decision from the static match.
The limit is openness. Every conforming class must inherit or register. Third-party objects cannot satisfy the interface without modification, and unrelated classes get pulled into a hierarchy they may not belong in. The Claude Code legacy code guide covers the complementary question of whether similar code should share a base or stay independent; the same ownership question applies to ABC membership.
Map implementations and call sites
Start from the code, not from the abstraction. Two lists decide the choice: every implementation that would satisfy the interface, and every call site that consumes it.
# list candidate call sites by the members they use
rg -n "def (save|load|close)\(" src/
rg -n "\.to_dict\(" src/For each call site, record the members it uses and whether it cares about behavior. A call site that only needs save and load and does not inspect concrete types is a Protocol candidate. A call site that dispatches on type or relies on a shared default is an ABC candidate.
| Call site | Members used | Cares about concrete type | Abstraction lean |
|---|---|---|---|
render(view) |
to_dict |
No | Protocol |
Repo.save(obj) |
save, validate |
No | Protocol |
PluginHost.register(p) |
registration + shared base | Yes | ABC |
Storage.dispatch(backend) |
isinstance dispatch | Yes | ABC |
The table is the artifact that makes the refactor reviewable. A row that says Protocol on a call site that dispatches on type is a defect in the map, and catching it here is cheaper than catching it after the interface exists.
Claude Code can draft this inventory by searching the repository, and the draft needs review. The agent reads the members used at each site but does not know the ownership intent behind the interface. Review each row against the question the table asks.
Separate static and runtime checks
The distinction in F004 is the one reviewers miss. A static structural match means the type checker accepts the value. An explicit runtime protocol check means isinstance(value, MyProtocol) returns True at execution time. The first does not imply the second.
A Protocol used only in annotations is a static construct. Adding isinstance against it requires the protocol to declare itself as a runtime-checkable protocol, which is a deliberate change to the class. An ABC supports isinstance natively because it is a real class.
| Check | What it answers | Static or runtime | Protocol | ABC |
|---|---|---|---|---|
| Annotation compatibility | Will the checker accept this value | Static | Yes | Yes |
isinstance membership |
Is this value a member at runtime | Runtime | Only if runtime-checkable | Yes, native |
| Behavioral equivalence | Do two conforming values behave the same | Neither | No | No |
Neither abstraction answers the third row. Behavioral equivalence is a testing question, not a typing question. The Claude Code generated tests guide covers stating an invariant and searching for the input that breaks it, which is the narrower tool for behavioral claims about conforming implementations.
Reviewing the static checker output alongside the test suite is the pass condition for an interface refactor. The static checker confirms the shape contract. The tests confirm the behavior the shape does not.
Refactor the interface boundary
Make the change in three steps, each independently reviewable. First, introduce the abstraction at the call site without changing any implementation. Second, run the static checker and the tests. Third, decide whether any implementation needs adjustment now that the contract is named.
from typing import Protocol
class SupportsSave(Protocol):
def save(self) -> None: ...
def persist(obj: SupportsSave) -> None:
obj.save() # static structural match, no inheritance requiredThe first step is where the win lives: the call site now names the shape it needs, and any conforming object satisfies it. The producer did not change. The type checker accepts objects from anywhere that have a compatible save.
An ABC applies the same three steps with the base class as the artifact. Introduce the base, run the checks, then move implementations onto it one at a time if the family is deliberate.
Ask Claude Code to produce the diff in this order and to report the checker and test results at each step. The Claude Code verification guide covers asking what changed, what proves it, and what was not checked. A report that omits the runtime side of the distinction in F004 is incomplete, because the static match is the part the agent can verify and the runtime behavior is the part it cannot.
Review compatibility consequences
An interface refactor changes what the type checker accepts, which is a compatibility change even when no runtime statement moves. Review three consequences.
The first is widening. Replacing an ABC parameter with a Protocol parameter accepts more values. Callers that previously had to subclass now conform structurally. Usually that is the intent, but it is a public contract change if the function is part of a published API.
The second is narrowing. Replacing a Protocol parameter with an ABC parameter accepts fewer values, since producers must now inherit or register. Third-party callers that conform structurally but do not inherit will fail the static check.
The third is runtime check breakage. Existing code that called isinstance(value, OldABC) and the refactor removes the ABC, that check fails at runtime even though the static types still line up. Search for isinstance against the removed name before deleting it.
| Consequence | Detect it by | Fix |
|---|---|---|
| Widened acceptance | Published API consumers now pass more types | Confirm the widening is intended |
| Narrowed acceptance | Third-party structural conformers fail checks | Keep a Protocol at the boundary |
| Broken isinstance | Search for the removed base name | Keep the ABC or update call sites |
The compatibility review is the part an agent cannot do from the diff alone. It requires knowing which consumers are outside the repository. On the versioning side of a public contract change, the Claude Code code review guide covers what happens when a contract change outpaces the review that has to accept it.
Checklist before you merge an interface refactor
Run this list against the diff. Each row is a pass condition.
| Check | Pass condition | If it fails |
|---|---|---|
| Ownership | The interface owner is named in the change record | Decide ownership before merging |
| Call-site map | Every consumer has a row with members used | Complete the map |
| Abstraction choice | Choice follows the ownership row, not preference | Revisit the choice |
| Static checker | Checker output matches the intended widening or narrowing | Fix the interface |
| Test suite | Existing behavior tests pass | Investigate before merging |
| isinstance search | No runtime check against a removed base | Keep or update the check |
| Consumer impact | Out-of-repo consumers reviewed for widening or narrowing | Record the impact |
Worked example: a rendering call site
Suppose a commit adds a render(view) function that calls view.to_dict(). Three classes in the repository have to_dict, and one comes from a vendored library. The current parameter annotation is a concrete class, which rejects the vendored object even though it has the member.
The call-site map has one row: members used is to_dict, cares about concrete type is no. The row leans Protocol. Introducing a SupportsToDict protocol at the call site accepts all four implementations without touching any of them.
The record after the change looks like this.
| Implementation | Satisfies protocol statically | Runtime isinstance needed | Behavior verified by |
|---|---|---|---|
CartView |
Yes | No | Existing render tests |
InvoiceView |
Yes | No | Existing render tests |
ExportView |
Yes | No | Not run, no scheduled-job fixture |
vendored ForeignView |
Yes | No | Structural match only, no behavior test |
The fourth row is the honest part. The vendored object satisfies the shape, so the type checker accepts it, but no test exercises its to_dict. The static match is a shape conclusion, not a behavior conclusion. Record the gap rather than reading the green checker as proof.
The concrete win is that a vendored object the function never named now satisfies the contract without modification. The concrete loss is the fourth row: a structurally conforming object with unverified behavior is now accepted by design.
Working with Claude Code on the refactor
Give the agent two inputs: the call-site map and the intended ownership boundary. Ask for the interface introduction as a separate step from any implementation change, and ask for checker and test output at each step. The agent session works best when the verification is a command that returns pass or fail, which is the shape the official best-practices guidance recommends.
Ask the agent to report three things. The interface it introduced and where. The implementations it considers conforming and the members it matched. The runtime checks it searched for and whether any broke. A report that claims a protocol guarantees behavior is wrong and should be returned for revision.
Reviewing the ownership decision is the reviewer’s job. The agent reads members and call sites, but whether the conforming objects should form a closed family is a design call. The Claude Code overengineering guide describes how a small interface request can produce a large diff; ask for the interface only and keep producer changes out of the same commit unless they are required.
Related reading in this batch
Interface boundaries sit next to other contract work in this batch. Dictionary-shaped API boundaries are covered by the Python TypedDict boundaries guide covers separating required from optional keys. Third-party typing surfaces are covered by the Python stub drift guide covers auditing .pyi stubs against runtime signatures, including the warning that mypy’s stubtest imports and executes the packages it checks.
On the packaging side of a Python contract, the Python dependency groups vs extras guide covers separating published metadata from local workflow requirements.
Other ecosystems are covered by the TypeScript project references guide covers source ownership and declaration boundaries, and the Go module compatibility guide covers keeping API changes inside an import contract.
Data gap and future update
The distinction behind F004 is a review recommendation, not a measured result. This post makes no claim about the performance of protocols versus ABCs, the frequency of each in real codebases, or the defect rate of either choice. The research pass behind this post did not collect such measurements, and none of the cited documentation provides them.
PEP 544 and the standard library typing page were not full-page fetched within the research budget, so the exact passage behind F003 carries a recheck caveat. A future update should verify the canonical wording and add any runtime-checkable protocol details the current text does not cover.
Repository-specific data is absent: no Python version, checker version, or codebase size was inspected. The refactor routine is derived from the documented typing distinctions.
One AI API Key option for OpenAI-format agents
Claude Code uses an Anthropic-format route, so the One AI free model IDs are not a Claude Code model source. The packet records Claude IDs as unavailable on 2026-11-27.
OpenAI-format agents have a separate route: One AI API Key offers https://api.oneaiapikey.com/v1, one key, and 46 live free IDs. It is a different client and request format, not a workaround for Claude Code authentication. Check the free model list and eligibility notes before choosing an agent route, or use the cost calculator to compare hosted options.
FAQ
Does a Protocol guarantee an object behaves correctly at runtime?
No. A Protocol is a static shape contract. PEP 544 defines it as a way to express structural typing relationships, which is a conclusion about members, not behavior. Two conforming objects can differ in side effects or error handling. Behavior needs tests.
Can I use isinstance with a Protocol?
Only if the protocol is declared runtime-checkable, which is a deliberate change to the class. A protocol used only in annotations is a static construct. An ABC supports isinstance natively. Treat the runtime check as a separate decision from the static match.
Should I replace every ABC with a Protocol?
No. Replace an ABC when the interface should be open to objects that cannot inherit from it. Keep an ABC when the implementations form a deliberate family with a shared base or a runtime membership check. Replacing every ABC is the specific overreach this post warns against.
Are mypy and other checkers interchangeable here?
No. This post does not present type checkers as interchangeable. Each checker has its own protocol handling and error reporting. Verify the behavior of the checker your repository uses rather than assuming another checker’s result transfers.
What proves my interface refactor is safe?
Three things together: the static checker accepts the intended widening or narrowing, the existing behavior tests pass, and a search confirms no runtime isinstance against a removed base. None of the three alone proves safety, and none of them verifies the behavior of a structurally conforming third-party object.
Related reading in this batch
This post is one of six language and build-system guides written together. The other five cover the same contract-boundary question from different angles: Python Dependency Groups vs Extras, Python TypedDict Boundaries, Python Stub Drift, Go Module Compatibility, and Go Workspace Boundaries.
Interface boundaries have close cousins in build systems and code generation. Go Module Graph Pruning covers the dependency-graph version of a contract, and Cargo Feature Unification covers which optional APIs a build exposes. Cargo Build Scripts covers the generated-artifact contract, and TypeScript Project References covers source and declaration ownership across projects.
Generated-code contracts in the batch cover C# Source Generators, OpenAPI Generator Customization, and GraphQL Code Generator Client Presets. Schema-level compatibility is covered by Protocol Buffer Reserved Fields and sqlc Query Annotations. Generated-code contracts in the batch cover C# source generators, OpenAPI generator customization, and GraphQL code generator client presets. Build-system and dependency boundaries cover Cargo feature unification, Gradle constraints vs dependencies, and NuGet central package management. Dependency-install risks that sit outside contract design, Claude Code dependency install side effects covers what an install can do beyond adding files, and Claude Code hallucinated packages covers a package that does not exist. Framework maintenance guides including Django deprecation runway and Angular update guide apply the same consumer-impact reasoning to framework versions.
More from this batch
- Python Dependency Groups vs Extras: A Claude Code Migration Map
- Python TypedDict Boundaries: Stop Model Drift With Claude Code
- Python Stub Drift: Audit Third-Party Types With Claude Code
- Go Module Compatibility: Keep API Changes Inside the Contract
- Go Workspace Boundaries: Decide What Belongs in go.work
More Claude Code troubleshooting
- Cargo Profile Boundaries: Keep Debug and Release Behavior Aligned
- Cargo Workspace Inheritance: Centralize Metadata Without Hiding Crates
- Gradle Capability Conflicts: Resolve Competing Components With Claude Code
- Gradle Variant Attributes: Match Consumers to the Right Artifact
- Maven Optional Dependencies: Keep Transitive Expectations Explicit
- .NET Multi-Targeting: Separate Framework Dependencies for Claude Code
- CMake Presets: Give Claude Code Reproducible Configure Inputs
- CMake find_package vs FetchContent: Choose a Dependency Boundary
- Conan CMakeDeps: Keep Consumer Targets Stable for Claude Code
- pnpm Peer Diagnostics: Read Resolution Reports Before Claude Code Pins
- Rails Upgrade Sequence: Order Major Changes With Claude Code
Sources
- Official: PEP 544: Protocols, supporting the definition of protocols as structural typing relationships (F003). Carries a passage-recheck caveat.
- Official: Python Standard Library: typing.Protocol, reference for the runtime class behind static structural typing (F004 context).
- Official: mypy Documentation: Type Hints Cheat Sheet, reference for how a static checker treats protocol matching.
- Official: Claude Code Docs: Best Practices, supporting the pass-or-fail verification loop.
- Official: Claude Code Docs: Common Workflows, reference for iterating an edit against a command.