Python Protocols: structural typing with Protocol (3.8)
What you’ll learn
Section titled “What you’ll learn”- What structural subtyping (“static duck typing”) means and how it differs from inheriting from an ABC.
- How to define a protocol, and what a type checker verifies (names, parameters and return types).
- What
@runtime_checkableadds, and why itsisinstance()check is shallow. - Generic protocols, callback protocols, protocol inheritance and explicit opt-in subclassing.
- How protocols make dependencies swappable in real code and in tests, and when an ABC is still the right tool.
Summary
Section titled “Summary”typing.Protocol, added in Python 3.8 by PEP 544, defines an interface by its shape. A class satisfies a protocol if it has the required methods and attributes with compatible types, whether or not it inherits from the protocol. The check is done by static type checkers such as mypy or pyright; at run time a protocol does nothing unless you decorate it with @runtime_checkable, which enables a presence-only isinstance() check. Protocols are fully current in Python 3.14.
The problem it solves
Section titled “The problem it solves”Python code has always relied on duck typing: if an object has a send() method, you can call it. Type annotations made that harder, because the obvious way to describe “has a send() method” was an abstract base class, and an ABC only accepts classes that inherit from it (or are registered with it). Third-party classes, classes that already have a base class and simple test doubles do not.
Running the samples: each sample is a complete script. Save it as a .py file and run it with Python 3.14 (python3 sample.py), then type-check it with mypy sample.py. Outputs were produced with CPython 3.14.6 and mypy 2.4.1 (the file names in the mypy output are the names the samples were saved under). Type checkers are separate tools, installed with pip install mypy or similar.
from abc import ABC, abstractmethodfrom typing import Protocol
# Before: an ABC only accepts classes that inherit from it.class NotifierABC(ABC): @abstractmethod def send(self, to: str, message: str) -> bool: ...
# After: a Protocol accepts anything with a matching send().class Notifier(Protocol): def send(self, to: str, message: str) -> bool: ...
# A third-party class: we cannot make it inherit from anything.class VendorMailClient: def send(self, to: str, message: str) -> bool: print(f"Mail to {to}: {message}") return True
def notify_abc(n: NotifierABC, to: str) -> bool: return n.send(to, "Order ORD-1001 shipped")
def notify(n: Notifier, to: str) -> bool: return n.send(to, "Order ORD-1001 shipped")
notify_abc(VendorMailClient(), "ada@example.test") # works, but a type errornotify(VendorMailClient(), "ada@example.test") # works and type-checksRun output, then mypy output:
Mail to ada@example.test: Order ORD-1001 shippedMail to ada@example.test: Order ORD-1001 shippedbefore_after.py:25: error: Argument 1 to "notify_abc" has incompatible type "VendorMailClient"; expected "NotifierABC" [arg-type]Found 1 error in 1 file (checked 1 source file)Both calls run, because Python itself never checked the annotation. The difference is what the type checker accepts: the ABC demands inheritance (nominal typing), the protocol demands only the right shape (structural typing).
How it works
Section titled “How it works”A protocol is a class that lists Protocol among its bases. Its methods usually have ... as the body; annotated class attributes become required attributes. A type checker compares each member’s name, parameters and return type against the candidate class.
from typing import Protocol
class Notifier(Protocol): def send(self, to: str, message: str) -> bool: ...
class BrokenClient: def send(self, to: str) -> None: # wrong parameters and return type pass
class Repository[T](Protocol): # generic protocol (3.12 syntax) def get(self, key: str) -> T | None: ...
class PriceRepo: def get(self, key: str) -> float | None: return {"MUG-01": 8.5}.get(key)
class Retry(Protocol): # callback protocol def __call__(self, attempt: int, *, delay: float) -> bool: ...
def backoff(attempt: int, *, delay: float) -> bool: return attempt < 3
def bad_backoff(attempt: int) -> bool: return attempt < 3
def notify(n: Notifier) -> None: ...def lookup(repo: Repository[float], sku: str) -> float | None: return repo.get(sku)def run(policy: Retry) -> None: ...
notify(BrokenClient())print(lookup(PriceRepo(), "MUG-01"))run(backoff)run(bad_backoff)Run output is 8.5. The mypy output:
static_check.py:31: error: Argument 1 to "notify" has incompatible type "BrokenClient"; expected "Notifier" [arg-type]static_check.py:31: note: Following member(s) of "BrokenClient" have conflicts:static_check.py:31: note: Expected:static_check.py:31: note: def send(self, to: str, message: str) -> boolstatic_check.py:31: note: Got:static_check.py:31: note: def send(self, to: str) -> Nonestatic_check.py:34: error: Argument 1 to "run" has incompatible type "Callable[[int], bool]"; expected "Retry" [arg-type]static_check.py:34: note: "Retry.__call__" has type "def __call__(self, attempt: int, *, delay: float) -> bool"Found 2 errors in 1 file (checked 1 source file)- Signatures matter statically. A method with the right name but the wrong parameters or return type does not satisfy the protocol.
- Generic protocols take type parameters.
class Repository[T](Protocol)uses the Python 3.12 syntax; for 3.11 and older, writeclass Repository(Protocol[T])with aTypeVar. - Callback protocols define
__call__. They describe callables thatCallable[...]cannot express, such as keyword-only parameters or overloads.
Run-time behavior
Section titled “Run-time behavior”from typing import Protocol, runtime_checkable, is_protocol, get_protocol_members
@runtime_checkableclass Notifier(Protocol): def send(self, to: str, message: str) -> bool: ...
@runtime_checkableclass HasOrderId(Protocol): order_id: str # a data member, not a method
class MailClient: def send(self, to: str, message: str) -> bool: return True
class BrokenClient: def send(self) -> None: # wrong signature, same name pass
class Order: def __init__(self, order_id: str): self.order_id = order_id
# isinstance() only checks that the names exist.print(isinstance(MailClient(), Notifier), isinstance(BrokenClient(), Notifier))print(isinstance(Order("ORD-1"), HasOrderId), isinstance(object(), HasOrderId))
# issubclass() refuses protocols that have data members.try: issubclass(Order, HasOrderId)except TypeError as exc: print("TypeError:", exc)
# Protocols cannot be instantiated.try: Notifier()except TypeError as exc: print("TypeError:", exc)
# Introspection helpers (Python 3.13+).print(is_protocol(Notifier), is_protocol(MailClient), sorted(get_protocol_members(HasOrderId)))
# Explicit subclassing is allowed and inherits default implementations.class Auditable(Protocol): def audit_id(self) -> str: return f"{type(self).__name__}:{id(self) % 1000}"
class Refund(Auditable): # nominal: opts in to the default passprint(Refund().audit_id().startswith("Refund:"))
# A subclass of a protocol is a regular class unless it lists Protocol again.class LoudNotifier(Notifier): passclass LoudNotifierProto(Notifier, Protocol): def shout(self) -> None: ...print(is_protocol(LoudNotifier), is_protocol(LoudNotifierProto))Output:
True TrueTrue FalseTypeError: Protocols with non-method members don't support issubclass(). Non-method members: 'order_id'.TypeError: Protocols cannot be instantiatedTrue False ['order_id']TrueFalse True@runtime_checkableis presence-only.BrokenClientpassesisinstance()because it has asend; the documentation calls these “simple-minded” checks that ignore signatures and types. Without the decorator,isinstance()against a protocol raisesTypeError.- Data members limit
issubclass(). A class cannot prove it has an instance attribute, so protocols with non-method members only supportisinstance(). - Opting in is allowed. A class can inherit from a protocol explicitly to get default method bodies and an early error from the type checker if it drifts; it then behaves like an ordinary subclass.
- Protocol-ness is not inherited. A subclass is a protocol only if it lists
Protocolin its bases again; otherwise it is a regular (abstract-looking) class. - Speed. The documentation warns that
isinstance()against a runtime-checkable protocol can be surprisingly slow; preferhasattr()in hot paths.
Realistic example
Section titled “Realistic example”OrdersPortal’s checkout service needs a payment gateway and somewhere to write receipts. The protocols live next to the code that uses them, so the production adapter, a test fake and even io.StringIO all fit without inheriting from anything. A @runtime_checkable protocol guards the one boundary where objects arrive dynamically.
import ioimport sysfrom dataclasses import dataclass, fieldfrom decimal import Decimalfrom typing import Protocol, runtime_checkable
# The protocols live next to the code that USES them, not the implementations.class PaymentGateway(Protocol): def charge(self, order_id: str, amount: Decimal, currency: str) -> str: """Charge the customer and return a payment reference.""" ...
@runtime_checkableclass ReceiptSink(Protocol): def write(self, text: str, /) -> object: ...
@dataclassclass CheckoutService: gateway: PaymentGateway receipts: ReceiptSink
def checkout(self, order_id: str, amount: Decimal) -> str: if amount <= 0: raise ValueError("amount must be positive") ref = self.gateway.charge(order_id, amount, "EUR") self.receipts.write(f"{order_id} paid {amount} EUR ref={ref}\n") return ref
# Production adapter (would call the payment provider over HTTPS).class CardGateway: def __init__(self, base_url: str) -> None: self.base_url = base_url
def charge(self, order_id: str, amount: Decimal, currency: str) -> str: return f"pay_{order_id.lower()}" # network call omitted
# Test double: no inheritance, no mocking library.@dataclassclass FakeGateway: charges: list[tuple[str, Decimal, str]] = field(default_factory=list)
def charge(self, order_id: str, amount: Decimal, currency: str) -> str: self.charges.append((order_id, amount, currency)) return f"fake-{len(self.charges)}"
fake = FakeGateway()buffer = io.StringIO() # io.StringIO already has write()service = CheckoutService(fake, buffer)print(service.checkout("ORD-3001", Decimal("42.50")))print(fake.charges, repr(buffer.getvalue()))
live = CheckoutService(CardGateway("https://pay.example.test"), sys.stdout)live.checkout("ORD-3002", Decimal("19.99"))
# Plugin boundary: validate a dynamically loaded object at run time.def load_sink(obj: object) -> ReceiptSink: if not isinstance(obj, ReceiptSink): raise TypeError(f"{type(obj).__name__} cannot receive receipts") return obj
try: load_sink(["not", "a", "sink"])except TypeError as exc: print("TypeError:", exc)Output (and mypy reports Success: no issues found in 1 source file):
fake-1[('ORD-3001', Decimal('42.50'), 'EUR')] 'ORD-3001 paid 42.50 EUR ref=fake-1\n'ORD-3002 paid 19.99 EUR ref=pay_ord-3002TypeError: list cannot receive receiptsThe ReceiptSink protocol is deliberately small: one method, with the text parameter positional-only (/) and the return type object, so any file-like object that returns a character count, or nothing at all, still fits. Keeping protocols narrow is what makes them easy to satisfy.
Common mistakes
Section titled “Common mistakes”- Expecting run-time enforcement. A plain protocol is invisible at run time; passing the wrong object fails only when the missing method is called. Run a type checker in CI.
- Trusting
isinstance()with a runtime-checkable protocol. It confirms names exist, not that signatures or types match. Use it at boundaries as a sanity check, not as validation. - Forgetting to repeat
Protocolin a sub-protocol.class Loud(Notifier)is a concrete class, not a protocol. Writeclass Loud(Notifier, Protocol). - Fat protocols. A protocol that copies every method of one implementation is an ABC in disguise, and every fake must implement all of it. Define the few members the consumer actually calls.
- Ignoring parameter names. A caller holding the protocol type may pass arguments by keyword, so a renamed parameter in an implementation can break at run time. Checkers differ on whether they report it (mypy 2.4.1, for example, accepts a renamed parameter without a warning). Make parameters positional-only with
/in the protocol when names should not matter. - Monkey-patching a runtime-checkable protocol. Since Python 3.12 its members are frozen when the class is created; adding attributes later has no effect on
isinstance().
When to use it and when not to
Section titled “When to use it and when not to”Use a protocol when the consumer cares about behavior, not ancestry: dependency injection, plugins, accepting third-party or standard-library objects, and test doubles. Use an ABC when you want to share implementation, force subclasses to register intent, or validate at instantiation time (an ABC refuses to instantiate a subclass with missing abstract methods).
| Need | typing.Protocol |
abc.ABC |
collections.abc ABCs |
|---|---|---|---|
| Accept classes you do not control | Yes | Only via register() |
Yes, for the one-method ABCs such as Iterable and Sized |
| Checked by type checkers | Structurally | Nominally | Yes |
Run-time isinstance() |
Only with @runtime_checkable, presence-only |
Yes | Yes |
| Shared default methods | Only for explicit subclasses | Yes | Yes (mixin methods) |
| Error when a method is missing | Static only | At instantiation | At instantiation |
Compatibility
Section titled “Compatibility”| Version | Change |
|---|---|
| 3.8 | typing.Protocol and @runtime_checkable added (PEP 544). Use typing_extensions on older versions. |
| 3.12 | Generic class syntax class P[T](Protocol); runtime checks use inspect.getattr_static; runtime-checkable members are frozen at class creation. |
| 3.13 | typing.is_protocol() and typing.get_protocol_members() added. |
| 3.14 | Current release, no protocol-specific changes. |
| 3.15 (in development) | isinstance() against a non-runtime-checkable protocol that inherits from a runtime-checkable one is deprecated, to become a TypeError in 3.20. |
Interview questions
Section titled “Interview questions”1. What is the difference between nominal and structural subtyping, and which does Python use?
Nominal subtyping relates types by declared inheritance; structural subtyping relates them by their members. Python’s run time is duck-typed, classes and ABCs are nominal for type checkers, and Protocol adds structural subtyping to the static type system.
2. A class passes isinstance(obj, MyProtocol) but crashes when called. How?
@runtime_checkable only checks that the member names exist. The method may have a different signature, or an attribute may have the wrong type. The static type checker is the tool that compares signatures.
3. Why can’t you use issubclass() with a protocol that declares order_id: str?
Instance attributes are usually set in __init__, so they are not visible on the class. Python raises TypeError for issubclass() against protocols with non-method members; isinstance() still works because it inspects the instance.
4. Senior scenario: OrdersPortal’s domain package imports a third-party payment SDK only to type-hint charge() calls, and every test needs that SDK installed. How do you restructure it?
Apply dependency inversion with a protocol. Define a narrow PaymentGateway protocol inside the domain package, containing only the methods checkout uses, with domain types (Decimal, order IDs) rather than vendor types. Put a vendor adapter in an infrastructure module that satisfies the protocol structurally, and inject it at the composition root. Tests use a small fake class with no SDK dependency, and mypy guarantees both the adapter and the fake still match. Do not make the protocol runtime-checkable unless objects arrive dynamically, and keep it small so adding a second provider is cheap.
Key takeaways
Section titled “Key takeaways”- A protocol describes required members; any class with compatible members satisfies it, with no inheritance.
- Checking is static;
@runtime_checkableadds only a presence check forisinstance(). - Keep protocols small and define them where they are consumed.
- Sub-protocols must list
Protocolagain; explicit subclassing is allowed and inherits defaults. - Prefer an ABC when you need shared implementation or instantiation-time enforcement.
Related pages
Section titled “Related pages”- Type hints: the annotation system protocols plug into.
- typing_extensions: newer typing features, including protocols, on older Pythons.
- Magic methods: the dunder methods behind built-in protocols such as
__len__and__iter__. - dataclasses: simple classes that make convenient protocol implementations and fakes.
- Metaclasses: the machinery behind ABCs and
Protocol’s run-time checks. - Python type hints basics: a gentler introduction to annotations.