Reading history

Python Protocols and Duck Typing

6 min read 1 views

Learn duck typing in Python, plug classes into built-in tools with special methods, and describe required methods with typing.Protocol.

Python cares about what an object can do, not what class it belongs to. If an object has a pay() method, you can ask it to pay. This idea is called duck typing: “if it walks like a duck and quacks like a duck, treat it as a duck”. The typing.Protocol class lets you write that idea down, so editors and type checkers can find mistakes before the program runs.

In this lesson you will learn

  • What duck typing is and why Python uses it
  • How special methods let your objects work with len, in and sorted
  • Describing required methods with typing.Protocol
  • @runtime_checkable and isinstance
  • When to choose a Protocol and when to choose an abstract base class

You should know classes and objects, type hints and abstract classes.

Duck Typing in Action

# Duck typing: "if it walks like a duck..." Python checks behaviour, not type.
class Bkash:
    def pay(self, amount):
        return f"Paid {amount} taka with bKash"

class Card:
    def pay(self, amount):
        return f"Charged {amount} taka to card"

class Cash:
    def pay(self, amount):
        return f"Received {amount} taka in cash"

def checkout(method, amount):
    # No isinstance check: any object with a pay() method works
    print(method.pay(amount))

for m in [Bkash(), Card(), Cash()]:
    checkout(m, 450)

# Built-in "protocols": define special methods and Python's own tools work
class Playlist:
    def __init__(self, *songs):
        self.songs = list(songs)
    def __len__(self):
        return len(self.songs)
    def __iter__(self):
        return iter(self.songs)
    def __contains__(self, song):
        return song in self.songs

p = Playlist("Ami Banglay Gaan Gai", "Purano Sei Diner Kotha", "Ekusher Gaan")
print(len(p), "songs")
print("Ekusher Gaan" in p)
print(sorted(p))

# When the behaviour is missing, the error appears only when it is used
class Voucher:
    pass

try:
    checkout(Voucher(), 100)
except AttributeError as e:
    print("AttributeError:", e)

Output

Paid 450 taka with bKash
Charged 450 taka to card
Received 450 taka in cash
3 songs
True
['Ami Banglay Gaan Gai', 'Ekusher Gaan', 'Purano Sei Diner Kotha']
AttributeError: 'Voucher' object has no attribute 'pay'
  • Bkash, Card and Cash share no parent class. checkout works with all three, because each one has a pay method.
  • This makes code flexible. A new payment method only needs a pay method; checkout does not change.
  • Python’s own tools work the same way. Give a class __len__, __iter__ and __contains__, and len(), in, for and sorted() all accept it.
  • The weak point: a missing method is only found when that line runs. Voucher has no pay, and the error appears at run time.

Writing It Down With Protocol

from typing import Protocol, runtime_checkable

# A Protocol describes the methods an object must have.
# Classes do NOT need to inherit from it.
@runtime_checkable
class PaymentMethod(Protocol):
    def pay(self, amount: int) -> str: ...

class Nagad:
    def pay(self, amount: int) -> str:
        return f"Paid {amount} taka with Nagad"

class Coupon:
    def redeem(self) -> str:
        return "coupon used"

def checkout(method: PaymentMethod, amount: int) -> None:
    print(method.pay(amount))

checkout(Nagad(), 300)

# isinstance works with @runtime_checkable (it checks method names only)
print("Nagad is a PaymentMethod?", isinstance(Nagad(), PaymentMethod))
print("Coupon is a PaymentMethod?", isinstance(Coupon(), PaymentMethod))

# A type checker such as mypy would flag this call before the program runs:
#     checkout(Coupon(), 300)   # error: "Coupon" has no attribute "pay"

# A Protocol with an attribute and a method
class Shape(Protocol):
    name: str
    def area(self) -> float: ...

class Square:
    def __init__(self, side: float):
        self.name = "square"
        self.side = side
    def area(self) -> float:
        return self.side ** 2

class Circle:
    def __init__(self, r: float):
        self.name = "circle"
        self.r = r
    def area(self) -> float:
        return 3.14159 * self.r ** 2

def report(shapes: list[Shape]) -> None:
    for s in shapes:
        print(f"{s.name:7} {s.area():7.2f}")

report([Square(4), Circle(2)])

Output

Paid 300 taka with Nagad
Nagad is a PaymentMethod? True
Coupon is a PaymentMethod? False
square    16.00
circle    12.57
  • A Protocol lists the methods (and attributes) an object must have. The ... body means “no code here, this is only a description”.
  • Nagad never mentions PaymentMethod, yet it fits, because it has a matching pay method. This is called structural typing: the shape of the class is what counts.
  • The type hint method: PaymentMethod tells a type checker such as mypy what checkout needs. The checker reports checkout(Coupon(), 300) as an error before you run anything. Python itself does not check type hints while running.
  • @runtime_checkable lets you use isinstance with a Protocol. It only checks that the method names exist, not their parameters.
  • A Protocol can also require attributes, like name: str in Shape.

Protocol or Abstract Base Class?

ProtocolAbstract base class (ABC)
Must classes inherit from it?NoYes
Checked byType checkers (and isinstance if runtime checkable)Python, when you create an object
Can share code with subclassesNot usuallyYes
Works with classes you cannot editYesNo
Good forDescribing what a function needsA family of classes that share code

Use a Protocol when you want to accept “anything that can do X”, including classes from other libraries. Use an abstract base class when you are designing a family of classes yourself and want them to share code.

Common Mistakes

  1. Expecting Python to enforce a Protocol at run time. Without a type checker, a wrong object only fails when its missing method is called.
  2. Trusting isinstance too much. With @runtime_checkable it checks that the names exist, not that the parameters or return types match.
  3. Creating an object from a Protocol. PaymentMethod() raises TypeError; a Protocol is a description, not a real class to use.
  4. Checking types with type(x) == Card everywhere. It breaks duck typing; ask for behaviour instead.

Practice Exercises

Exercise 1. Write a Protocol Notifier with a method send(message: str) -> None, and two classes, SMS and Email, that fit it without inheriting from it.

Show answer
from typing import Protocol

class Notifier(Protocol):
    def send(self, message: str) -> None: ...

class SMS:
    def send(self, message: str) -> None:
        print("SMS:", message)

class Email:
    def send(self, message: str) -> None:
        print("Email:", message)

def alert_all(channels: list[Notifier], text: str) -> None:
    for c in channels:
        c.send(text)

alert_all([SMS(), Email()], "Exam starts at 10 am")

Exercise 2. Which special method must a class have so that len(obj) works?

Show answer

__len__, which must return a whole number of 0 or more.

Frequently Asked Questions

Do I need a type checker to use Protocol?

No, the code runs without one. But the main benefit of a Protocol is that tools such as mypy or Pyright, and editors like VS Code, can warn you about wrong objects as you type.

Which Python version added Protocol?

typing.Protocol arrived in Python 3.8. The list[Shape] style of hint used here needs Python 3.9 or later.

Summary

  • Duck typing: an object is accepted if it has the methods the code uses.
  • Special methods such as __len__ and __iter__ plug your classes into Python’s built-in tools.
  • Protocol describes required methods without inheritance, so type checkers can catch mistakes early.
  • Use a Protocol to describe needs; use an abstract base class to share code.

Next: Python Multiprocessing.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *