Protocols are a kind of inheritance or typing mechanism that lets you define interfaces through structural typing. They follow the duck typing philosophy: if it quacks like a duck, looks like a duck, and walks like a duck, then it is a duck. To see it clearly, let us start with a simple example: a payment gateway.
Traditional Approach with ABC
With ABC (Abstract Base Classes), we can define a base class to inherit from. Here we define PaymentGateway and an abstract method that every payment gateway must implement. If we want to include Stripe, PayPal, a bank, or any other provider, every class must inherit from this base class and implement the methods it defines, just like in a traditional interface.
In this approach, the Stripe class implements communication with that provider (simulated in the example), and PayPal does the same. Once those implementations are in place, we can define another class with the application-specific methods to process the charge. That is, here is the logic to talk to the payment gateway and run the charge, not the business logic.
If the system sells books, courses, or any other product, operations to record the sale or deduct inventory live in a class like CheckoutService, which receives PaymentGateway (the abstract interface that concrete classes later implement). To use it, just call the service from the main application flow and run the charge.
01_payments_abc.py
from abc import ABC, abstractmethod
class PaymentGateway(ABC):
@abstractmethod
def pay(self, amount: float) -> bool:
pass
class StripeGateway(PaymentGateway):
def pay(self, amount: float) -> bool:
print(f"Charge of ${amount:.2f} processed with Stripe.")
return True
class PayPalGateway(PaymentGateway):
def pay(self, amount: float) -> bool:
print(f"Charge of ${amount:.2f} processed with PayPal.")
return True
class CheckoutService:
def __init__(self, gateway: PaymentGateway) -> None:
self.gateway = gateway
def checkout(self, amount: float) -> bool:
return self.gateway.pay(amount)
# Usage
service = CheckoutService(StripeGateway())
service.checkout(49.99)$ uv run pyright 01_payments_abc.py- If, when running the code, we change the method name on the interface or concrete implementation—for instance, renaming the method to
pay2without updating the rest—the program will fail because the defined contract is not met. WithABC, the base class sets the mandatory template that subclasses must override, and non-compliance is caught when instantiating or running.
The Protocol Approach and Structural Typing
What about protocols? It is another typing mechanism—lightweight typing based on structural compatibility. Comparing both implementations side by side, instead of using ABC, we define the interface by inheriting from Protocol.
In the Protocol version, the Stripe class or a client like LegacyBankClient does not explicitly inherit from PaymentGateway. Unlike the traditional approach, where the concrete class had to declare inheritance from the base class, there is no explicit inherited link here.
Business logic still lives in CheckoutService or in the service responsible for recording sold products, calling the pay method defined in the contract. When running the code, behavior works the same way: if a class implements the methods and signatures expected by the protocol, it satisfies the contract implicitly.
01_payments_protocol.py
from typing import Protocol
class PaymentGateway(Protocol):
def pay(self, amount: float) -> bool:
...
class StripeGateway:
def pay(self, amount: float) -> bool:
print(f"Charge of ${amount:.2f} processed with Stripe.")
return True
class LegacyBankClient:
# Does not inherit from PaymentGateway or import your domain layer
def pay(self, amount: float) -> bool:
print(f"Transfer of ${amount:.2f} sent to legacy bank.")
return True
class CheckoutService:
def __init__(self, gateway: PaymentGateway) -> None:
self.gateway = gateway
def checkout(self, amount: float) -> bool:
return self.gateway.pay(amount)
# Usage
service = CheckoutService(LegacyBankClient())
service.checkout(120.00)$ uv run pyright 01_payments_protocol.pyCoupling, Type Checkers, and Runtime Behavior
A key point is understanding what happens at runtime versus static analysis. Python at runtime does not stop you from calling a method if the object has it, and type annotations do not block execution on their own. So if we rename a method to pay2 and run the script directly in Python, it can keep running until the nonexistent or incompatible method is called.
This is where static type checkers like mypy or pyright come in. These tools analyze code without running it and inspect type annotations and protocols. For example, with Pyright, if a class does not match the protocol's expected signature—say the method is missing or returns a type other than bool, a String, or another method name—the checker flags the error right away.
uv run pyright 01_payments_protocol.py
01_payments_protocol.py:31:27 - error: Argument of type "LegacyBankClient" cannot be assigned to parameter "gateway" of type "PaymentGateway" in function "__init__"
"LegacyBankClient" is incompatible with protocol "PaymentGateway"
"pay" is an incompatible type
Type "(amount: str) -> bool" is not assignable to type "(amount: float) -> bool"
Parameter 1: type "float" is incompatible with type "str"
"float" is not assignable to "str" (reportArgumentType)
1 error, 0 warnings, 0 informationsIn the ABC approach, coupling is tighter and the nominal relationship is explicit: whatever the base class declares must be strictly fulfilled. In the Protocol approach, coupling is looser and structural: the service depends on the protocol abstraction, and concrete classes fit if they match the required signature, without inheriting from a shared base class.
Practical Use Cases in Clean Code
In Clean Code and Clean Architecture, abstractions help keep impact localized, isolate changes, and separate business logic from external details (such as SDKs, HTTP clients, or databases). Protocols are especially helpful in large or modern projects with multiple modules and layers:
- Integrating external or legacy code without touching it: If you work with a third-party SDK or class you cannot modify that already exposes the expected method (such as
pay(amount: float) -> bool), withProtocolit fits directly without needing a wrapper class just to inherit from anABC.from abc import ABC, abstractmethod class PaymentGateway(ABC): @abstractmethod def pay(self, amount: float) -> bool: ... class ThirdPartySDK: # External code you cannot modify def pay(self, amount: float) -> bool: print(f"External SDK charged ${amount:.2f}") return True class ThirdPartySDKAdapter(PaymentGateway): # Mandatory wrapper from inheritance def __init__(self, sdk: ThirdPartySDK) -> None: self.sdk = sdk def pay(self, amount: float) -> bool: return self.sdk.pay(amount)- With Protocol (fits directly without a wrapper):
from typing import Protocol class PaymentGateway(Protocol): def pay(self, amount: float) -> bool: ... class ThirdPartySDK: # Does not inherit from PaymentGateway or get modified def pay(self, amount: float) -> bool: print(f"External SDK charged ${amount:.2f}") return True def process_order(gateway: PaymentGateway, amount: float) -> bool: return gateway.pay(amount) # Works directly with mypy/pyright without a wrapper class process_order(ThirdPartySDK(), 25.0)
- Avoiding circular dependencies and layer mixing: By defining the contract (for example, a port or interface in the application layer) with a
Protocol, external implementations do not need to import classes from inner layers to inherit from them, reducing cross-layer or circular dependencies.# --- Application layer (application/ports.py) --- from typing import Protocol class ChargePort(Protocol): def pay(self, amount: float) -> bool: ... # --- Infrastructure layer (infrastructure/stripe_client.py) --- # Notice: it does not need to import `ChargePort` from `application/ports.py` class StripeClient: def pay(self, amount: float) -> bool: print(f"Charge of ${amount:.2f} on Stripe") return True # --- Use case (application/checkout.py) --- def checkout(port: ChargePort, total: float) -> bool: return port.pay(total)
- Less rigidity in class hierarchies: Avoids forcing classes into rigid inheritance hierarchies when they already have their own structure (for instance, a class that already inherits from a document generator but also satisfies an archiving protocol).
from typing import Protocol class Archivable(Protocol): def archive(self) -> None: ... class DocumentGenerator: def render(self) -> str: return "content" class PdfReportExporter(DocumentGenerator): # Keeps its own hierarchy and also satisfies `Archivable` def archive(self) -> None: print("PDF archived to cold storage") def archive_item(item: Archivable) -> None: item.archive() archive_item(PdfReportExporter())
- Lighter tests: To test a use case or service, we can create a simple fake or mock that implements only the needed method (for example, recording charges in a test), without inheriting from an abstract class or implementing methods the test does not use.
- With ABC (the fake must implement every abstract method even if unused):
from abc import ABC, abstractmethod class PaymentGateway(ABC): @abstractmethod def pay(self, amount: float) -> bool: ... @abstractmethod def refund(self, transaction_id: str) -> bool: ... @abstractmethod def get_balance(self) -> float: ... class FakeGatewayABC(PaymentGateway): def pay(self, amount: float) -> bool: return True # Forced to define them so FakeGatewayABC can be instantiated def refund(self, transaction_id: str) -> bool: raise NotImplementedError def get_balance(self) -> float: return 0.0- With Protocol (the fake only implements what the use case needs):
from typing import Protocol class Charger(Protocol): def pay(self, amount: float) -> bool: ... class FakeCharger: def __init__(self) -> None: self.charges: list[float] = [] def pay(self, amount: float) -> bool: self.charges.append(amount) return True def charge_user(charger: Charger, amount: float) -> bool: return charger.pay(amount) # In your test: fake = FakeCharger() assert charge_user(fake, 15.0) is True assert fake.charges == [15.0]
Both ABC and Protocol have their place: ABC remains useful when you want explicit inheritance, shared behavior, or runtime hierarchy validation, while Protocol brings flexibility and loose coupling backed by static typing.
Importance in Clean Code
In Clean Code (and in Clean Architecture, which often goes hand in hand), using interfaces, abstractions, and approaches like Protocol or ABC serves a central goal: writing code that is easy to read, understand, change, and test without breaking the rest of the system.
Beyond the pattern itself, it is used for these practical reasons day to day:
1. Hiding Implementation Details (Real Abstraction)
When reading a service or use case, you do not care at that moment whether the charge runs through Stripe, PayPal, an HTTP request, or a local database. Depending on an abstraction (PaymentGateway / Protocol) lets business code express what it needs to do, not how it is done underneath. That reduces cognitive noise.
2. Isolating Changes (Avoiding the Domino Effect)
In Clean Code, the goal is keeping a change's impact localized. If the payment library, email delivery method, or database engine changes tomorrow, business rules should not need to be rewritten because the integration connects through the defined contract.
3. Keeping Functions and Classes Small and Focused
By defining small contracts (for example, a Protocol with only what a component needs), you avoid "swiss-army-knife" classes or giant interfaces that force other objects to carry methods they do not use. Each piece serves a clear responsibility.
4. Enabling Fast, Deterministic Tests
Good Clean Code is easy to test without depending on the internet, external APIs, or real databases. By depending on an abstraction, you can easily swap out the real implementation for an in-memory fake or mock to test business logic in milliseconds.
5. Making System Boundaries Explicit
In a real project, not all code has the same value or stability:
- Business / domain logic: changes due to business rules; must stay stable and clean.
- External details (frameworks, SDKs, APIs, databases): change due to tools, versions, or providers.
Using abstractions (Protocol or ABC) marks that boundary: the core of the system is not tied to a specific library or provider.
An Important Nuance in Clean Code
Using Protocol or ABC does not make code "Clean Code" on its own. If behind a Protocol there are huge functions, confusing names, duplicated logic, or abstractions created "just in case" for a single class that will never change, the code is still hard to maintain. In Clean Code, abstraction is justified when it clarifies design, isolates external dependencies, or makes testing easier—not as architectural decoration.