DEV Community

Cover image for typing.Protocol or abc.ABC for Python Ports? A Drifting Fake Shows What Each Catches
Gabriel Anhaia
Gabriel Anhaia

Posted on Edited on AI-assisted

typing.Protocol or abc.ABC for Python Ports? A Drifting Fake Shows What Each Catches


You add one keyword argument to a port. OrderRepository.save now takes idempotency_key, because the payment provider retries its webhooks and you are done cleaning up duplicate orders. You update the SQLAlchemy adapter. You update the use case that calls it. The in-memory fake in tests/fakes.py still has the old signature, and nobody touched it.

What tells you? That depends on two choices made months ago: whether the port is an abc.ABC or a typing.Protocol, and whether your type checker, mypy or pyright, looks inside tests/. Python itself never compares method signatures at runtime, in either style.

I haven't run these snippets through both checkers for this post. The error codes, settings and message formats come from the mypy, pyright and CPython docs and source, linked where they appear. The code targets Python 3.12 or later.

The port, the change, and the stale fake

Here is the ABC version of the port after the change:

# app/ports.py
from abc import ABC, abstractmethod
from dataclasses import dataclass

@dataclass
class Order:
    id: str
    total_cents: int

class OrderRepository(ABC):
    @abstractmethod
    def save(
        self, order: Order, *, idempotency_key: str
    ) -> None: ...

    @abstractmethod
    def get(self, order_id: str) -> Order | None: ...
Enter fullscreen mode Exit fullscreen mode

The fake nobody updated:

# tests/fakes.py
from app.ports import Order, OrderRepository

class InMemoryOrderRepository(OrderRepository):
    def __init__(self) -> None:
        self.rows: dict[str, Order] = {}

    def save(self, order: Order) -> None:  # stale
        self.rows[order.id] = order

    def get(self, order_id: str) -> Order | None:
        return self.rows.get(order_id)
Enter fullscreen mode Exit fullscreen mode

And the use case, with a validation branch before the write:

# app/place_order.py
from app.ports import Order, OrderRepository

class PlaceOrder:
    def __init__(self, repo: OrderRepository) -> None:
        self.repo = repo

    def __call__(self, order: Order, key: str) -> None:
        if order.total_cents <= 0:
            raise ValueError("empty order")
        self.repo.save(order, idempotency_key=key)
Enter fullscreen mode Exit fullscreen mode

The Protocol version of the port has the same two methods, and implementers don't inherit from it:

# app/ports.py, Protocol style
from typing import Protocol

# Order: the same dataclass as above

class OrderRepository(Protocol):
    def save(
        self, order: Order, *, idempotency_key: str
    ) -> None: ...

    def get(self, order_id: str) -> Order | None: ...
Enter fullscreen mode Exit fullscreen mode

With this port, the fake is the same class with (OrderRepository) dropped from its header. Same stale save.

What Python checks at runtime

ABC first. The abc docs state the whole contract: a class with an ABCMeta-derived metaclass "cannot be instantiated unless all of its abstract methods and properties are overridden." Overridden means a method with that name exists on the subclass. The docs say nothing about parameters, so InMemoryOrderRepository() builds fine with its stale save.

The ABC check does pay off for a different drift. Delete get from the fake and construction fails with a TypeError. On current CPython the message follows the format string from a November 2022 change: "Can't instantiate abstract class InMemoryOrderRepository without an implementation for abstract method 'get'".

The stale save stays quiet until the use case runs self.repo.save(order, idempotency_key=key). Then Python raises a TypeError about an unexpected keyword argument, from inside PlaceOrder.__call__, in whichever test reaches that line. This pytest test never reaches it:

# tests/test_place_order.py
import pytest

from app.place_order import PlaceOrder
from app.ports import Order
from tests.fakes import InMemoryOrderRepository

def test_rejects_empty_order():
    place = PlaceOrder(InMemoryOrderRepository())
    with pytest.raises(ValueError):
        place(Order("o-1", 0), key="k-1")
Enter fullscreen mode Exit fullscreen mode

It passes with the stale fake, because validation raises before the write. Every test that only covers rejection paths keeps passing.

Protocol at runtime checks less. A plain Protocol has no runtime check at all; the fake is an ordinary class. A missing get shows up as an AttributeError when something calls it. Adding @runtime_checkable lets you write isinstance(fake, OrderRepository), and the typing docs are blunt about what that does: it "will check only the presence of the required methods or attributes, not their type signatures or types."

# app/ports.py, Protocol style, decorated
from typing import Protocol, runtime_checkable

# Order: the same dataclass as above

@runtime_checkable
class OrderRepository(Protocol):
    def save(
        self, order: Order, *, idempotency_key: str
    ) -> None: ...

    def get(self, order_id: str) -> Order | None: ...

# in a test, with the stale fake:
# assert isinstance(fake, OrderRepository)  -> passes
Enter fullscreen mode Exit fullscreen mode

mypy's protocol docs say the same: "signatures of methods are not checked."

A plug with the right outline but the wrong pins held up to a hexagonal socket, while an inspector traces only the outline
A runtime check sees the method names. The parameters are invisible to it.

So runtime Python reports missing names (ABC, at construction) and bad calls (both styles, once the call runs). For a parameter that drifted, the earliest signal comes from the type checker.

What mypy and pyright report, and on which line

Both checkers catch the stale save in both styles. They report it in different places, and one mypy default decides whether you see it at all.

With the ABC, the fake subclasses the port, so the checker compares each method with the one it overrides. mypy reports an [override] error on the fake's save. pyright reports it under reportIncompatibleMethodOverride, which its configuration docs list as an error in standard and strict mode and as off in basic. standard is pyright's default. The error sits on the fake's class, whether or not any test uses the fake.

With the Protocol, the fake has no base class, so there is nothing to compare at its definition. The check happens where the fake meets the port type: PlaceOrder(InMemoryOrderRepository()), because PlaceOrder.__init__ declares repo: OrderRepository. mypy reports an [arg-type] error in the shape its protocol docs show, Argument 1 to "takes_box" has incompatible type "IntBox"; expected "Box", plus a note listing the members that conflict. In this post's code the names are PlaceOrder, InMemoryOrderRepository and OrderRepository, and the conflicting member is save. pyright files it under reportArgumentType, an error from basic mode up.

Look at the test header again: def test_rejects_empty_order(): has no annotations, which is how most pytest tests are written. mypy's check_untyped_defs defaults to False, so mypy does not type-check the inside of functions without annotations. Under default mypy settings, the Protocol-style mismatch inside that test body is never reported. The ABC-style [override] error still is, because it lives on the fake's annotated class. pyright's analyzeUnannotatedFunctions defaults to true per the same configuration page, so pyright does check the test body.

A magnifying glass hovering over two blueprints, one marking a class definition and the other marking a call site
ABC-style fakes get checked where they are defined. Protocol-style fakes get checked where they are used.

The whole drift, side by side:

Signal ABC subclass Protocol, no base class
Method missing, runtime TypeError at construction AttributeError at the call
Parameter drifted, runtime TypeError at the call TypeError at the call
@runtime_checkable isinstance not applicable passes if the names exist
mypy [override] on the fake [arg-type] where it is passed
pyright reportIncompatibleMethodOverride reportArgumentType
mypy, unannotated test still reported not reported

Pin the fake to the port

If you pick Protocol, move the check to the fake's definition so it stops depending on how the tests are written. mypy's docs on subclassing protocols give two ways.

First, inherit from the protocol explicitly. Per those docs, a protocol as a base class "forces mypy to verify that your class implementation is actually compatible with the protocol." The fake stays a regular class. One runtime detail to know: a method you forget to write is inherited from the protocol, where its body is ..., so calling it returns None instead of failing. mypy flags instantiating that class as an abstract-class error; Python does not.

Second, keep the fake free of the base class and add one annotated assignment at module level, which mypy checks even with default settings:

# bottom of tests/fakes.py
_conforms: OrderRepository = InMemoryOrderRepository()
Enter fullscreen mode Exit fullscreen mode

A drifted fake now fails on that line as an [assignment] error. Then make sure the checker reads the tests folder at all:

# pyproject.toml
[tool.mypy]
files = ["app", "tests"]
check_untyped_defs = true

[tool.pyright]
include = ["app", "tests"]
typeCheckingMode = "standard"
Enter fullscreen mode Exit fullscreen mode

None of this checks behaviour. A fake can match the new signature and still ignore idempotency_key, which is the exact bug the parameter exists to prevent. A shared contract test, one pytest module parametrised over the fake and the real adapter, is what checks that. The type checker covers the shape. The contract test covers what the methods do.

Picking one: Protocol for ports you own, ABC for shared behaviour

Use Protocol when the core owns the port and adapters only need to match it. No adapter has to import a base class to be valid, and a third-party client you can't edit can satisfy the port as-is. PEP 544 put it this way: subclassing a protocol explicitly is possible, but "it's not necessary to do so for the sake of type-checking." The price is that all the checking happens in the type checker, so it has to run in CI over tests/ as well as app/.

Use an ABC when adapters should inherit behaviour from the port. A concrete helper written once on top of an abstract method is the usual case:

class OrderRepository(ABC):
    @abstractmethod
    def get(self, order_id: str) -> Order | None: ...

    def get_or_raise(self, order_id: str) -> Order:
        order = self.get(order_id)
        if order is None:
            raise LookupError(order_id)
        return order
Enter fullscreen mode Exit fullscreen mode

An ABC also fits implementations that load where no type checker looks, such as plugins discovered at runtime. There, the construction-time TypeError is the only check you get before the first call.

Skip @runtime_checkable as a conformance test in either case. It checks names, and the typing docs add that an isinstance check against a runtime-checkable protocol "can be surprisingly slow" next to one against a regular class.

Open your pyproject.toml and check whether tests is listed for both checkers. If it isn't, start there.


If this was useful

Ports, fakes and the line between the core and its adapters are what Hexagonal Architecture in Python is built around. The book takes one async FastAPI and SQLAlchemy 2 service and builds it five ways (Hexagonal, Clean, Onion, layered, vertical slice), then measures how each holds up. Every listing runs from the free companion repo, so you can read the ports and their fakes before you buy anything.

Hexagonal Architecture in Python by Gabriel Anhaia

Top comments (1)

Collapse
 
alexshev profile image
Alex Shev •

The stale fake is exactly the failure mode that makes a port boundary look healthier than it is. Beyond choosing Protocol or ABC, I would make contract checks run against every test double and adapter in CI, with tests included in the type-check scope. The important result is not that an abstract class can refuse instantiation; it is that a signature change cannot reach production while the fake still models an older protocol.