Browse Engineering journal
Languages & design

Design a Python protocol from its caller

On this page

A clock used by a lease needs one operation and one behavioural guarantee. Python can check only part of that contract.

Programming Languages & Paradigms · Dec 4, 2026 · 2 min read

A lease expires when elapsed time reaches a deadline. Its clock could expose time zones, dates and formatting, but the lease uses precisely one operation. Naming that operation at the call site gives a test clock and a production clock room to differ.

from typing import Protocol

class Clock(Protocol):
    def seconds(self) -> float: ...

class ManualClock:
    def __init__(self, now: float):
        self.now = now

    def seconds(self) -> float:
        return self.now

def expired(clock: Clock, deadline: float) -> bool:
    return clock.seconds() >= deadline

clock = ManualClock(4.0)
assert not expired(clock, 5.0)
clock.now = 5.0
assert expired(clock, 5.0)

ManualClock inherits no clock base class. A static checker can establish compatibility from the method signature. PEP 544 introduced this form of structural subtyping for Python 3.8. An implementation supplied by another package can satisfy the contract without importing the application. PEP 544, defining and using protocols.

The annotation leaves one question open

What does the number measure? A wall clock and a monotonic clock can both return a float. A caller can accidentally mix deadlines from one clock with readings from the other. Make deadline construction and checking share a clock instance. Keep the units in the operation name and specify which direction time can move. Test the instant at the deadline, since a choice between greater-than and greater-than-or-equal changes ownership of that instant.

A runtime protocol check only inspects the presence of members. It cannot establish these timing guarantees. A shared base class would still require behavioural tests. Choose one when implementations also share lifecycle or state, and give consumers a small protocol when they need interchangeable behaviour. Python’s runtime protocol checks.

How to replace a renderer while invoices keep shippingA migration seam makes two renderers interchangeable. A comparison contract tells you when switching is safe.Where to draw a service boundaryFollow a seat reservation through two concurrent requests before deciding which components should deploy independently.

Search ObjectFAQ