Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 15 / Topic 1 of 6

Protocol: structural typing

Part 9 used base classes and ABC to say "these classes share a contract" (nominal typing: it matters what a class is called / inherits from). A Protocol describes a contract by shape instead: "anything with a discount_price() method fits here", whether or not it inherits from anything in particular. This is called structural typing, often nicknamed "duck typing with a type checker watching". Think of a plug socket: any appliance with the right pins works, whatever brand name is printed on it.

from typing import Protocol

class Discountable(Protocol):
    def discount_price(self) -> float: ...

class Course:
    def __init__(self, name: str, price: float) -> None:
        self.name, self.price = name, price
    def discount_price(self) -> float:
        return round(self.price * 0.8, 2)

class Gadget:
    def __init__(self, name: str, price: float) -> None:
        self.name, self.price = name, price
    def discount_price(self) -> float:
        return round(self.price * 0.9, 2)

def total_after_discount(items: list[Discountable]) -> float:
    return round(sum(item.discount_price() for item in items), 2)

cart = [Course("Python for Beginners", 1999.0), Gadget("Mouse", 799.0)]
print(total_after_discount(cart))   # 2318.3

Neither Course nor Gadget imports or inherits from Discountable. mypy accepts both anyway, because their shape matches. A Protocol can also describe plain attributes, not only methods:

from typing import Protocol

class Nameable(Protocol):
    name: str

@runtime_checkable: using isinstance() on a shape

By default a Protocol is a static-only tool: isinstance(x, Discountable) raises TypeError at run time. Add @runtime_checkable to allow the check; it only confirms the names exist, not that their signatures match.

from typing import Protocol, runtime_checkable

@runtime_checkable
class Nameable(Protocol):
    name: str

class FreeWebinar:
    def __init__(self, title: str) -> None:
        self.title = title           # no "name" attribute

print(isinstance(Course("Python for Beginners", 1999.0), Nameable))   # True
print(isinstance(FreeWebinar("Intro to SQL"), Nameable))              # False

Checking isinstance(cart[0], Discountable) (no @runtime_checkable) raises:

TypeError: Instance and class checks can only be used with @runtime_checkable protocols
Tool Checks what Checked by Needs a shared base class?
ABC (Part 9) a class declares it implements the contract Python, at run time yes
Protocol a value's shape matches mypy, statically no
Protocol + @runtime_checkable names exist (not full signatures) Python, at run time no

🔍 Going deeper: collections.abc.Iterable, Sized, Callable and friends (Part 10/11) are themselves runtime-checkable Protocols baked into the standard library. Writing your own is the same idea, scoped to your own app.

Full program: examples/01_protocols.py.

Read more: the official typing.Protocol documentation.

Exercise 1: A billing Protocol

Scenario: A Pune shop's billing code has an Invoice class and a Subscription class, written by different people, with no shared base class. Both already have a total_due() method, so a Protocol can describe the shape they share. What to do: Inside main():

  1. Write a Protocol named Payable with one method: def total_due(self) -> float: ....
  2. Write Invoice(number, amount, paid) with total_due() returning 0.0 if paid else amount, and Subscription(customer, monthly_fee, months_due) with total_due() returning monthly_fee * months_due. Neither inherits from Payable.
  3. Write overdue_total(items: list[Payable]) -> float, the rounded sum of total_due() over a mixed list.
  4. Make a list bills of two Invoices (one paid, one not) and one Subscription; print "Overdue total: ₹" followed by the result of overdue_total(bills), with no space (sep=""), using:
    • Invoice("INV-1", 1760.0, paid=False)
    • Invoice("INV-2", 540.0, paid=True)
    • Subscription("Asha", 499.0, 2)
  5. Write a @runtime_checkable Protocol named HasEmail with the attribute email: str. Write Customer(email) (has email) and GuestCheckout (no attributes). Print whether an instance of each isinstance()-matches HasEmail.
  6. Inside a try/except TypeError, call isinstance(bills[0], Payable) (no @runtime_checkable) and print "Payable isinstance error:" with the error.

Sample output:

Overdue total: ₹2758.0
Customer has HasEmail      : True
GuestCheckout has HasEmail : False
Payable isinstance error: Instance and class checks can only be used with @runtime_checkable protocols

💡 Hint: INV-1 is unpaid, so it still owes 1760.0; INV-2 is paid, so it owes 0.0; the subscription owes 499.0 * 2 = 998.0. Total: 1760.0 + 0.0 + 998.0 = 2758.0.


Show the solution to Exercise 1
"""Exercise 1: A billing Protocol.

Shows: typing.Protocol for structural typing, and @runtime_checkable.

Run:   python ex01.py   (macOS/Linux: python3 ex01.py)
"""

from typing import Protocol, runtime_checkable


class Payable(Protocol):
    def total_due(self) -> float: ...


@runtime_checkable
class HasEmail(Protocol):
    email: str


class Invoice:
    def __init__(self, number: str, amount: float, paid: bool) -> None:
        self.number = number
        self.amount = amount
        self.paid = paid

    def total_due(self) -> float:
        return 0.0 if self.paid else self.amount


class Subscription:
    def __init__(self, customer: str, monthly_fee: float, months_due: int) -> None:
        self.customer = customer
        self.monthly_fee = monthly_fee
        self.months_due = months_due

    def total_due(self) -> float:
        return self.monthly_fee * self.months_due


def overdue_total(items: list[Payable]) -> float:
    return round(sum(item.total_due() for item in items), 2)


class Customer:
    def __init__(self, email: str) -> None:
        self.email = email


class GuestCheckout:
    pass


def main() -> None:
    bills: list[Payable] = [
        Invoice("INV-1", 1760.0, paid=False),
        Invoice("INV-2", 540.0, paid=True),
        Subscription("Asha", 499.0, 2),
    ]
    print("Overdue total: ₹", overdue_total(bills), sep="")

    print("Customer has HasEmail      :", isinstance(Customer("[email protected]"), HasEmail))
    print("GuestCheckout has HasEmail :", isinstance(GuestCheckout(), HasEmail))

    try:
        isinstance(bills[0], Payable)
    except TypeError as error:
        print("Payable isinstance error:", error)


if __name__ == "__main__":
    main()

Search the guide