Python, properly · Chapter 28 of 42

Protocols and ABCs

By the end of this chapter you can explain duck typing, make a family of classes promise a method with an abstract base class, describe "any object with these methods" with a Protocol, and check it with isinstance and with mypy. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Objects
  • 3 tasks
  • Python
  • In the all labs plan

The first 2 chapters of Python, properly are free. This one comes with the all labs plan.

Why you need this

DabbaDrop sends its daily report through several exporters: a CSV file for Rafiq, a one-line WhatsApp message for Farah. The report function does not care what class an exporter is, only that it can export:

class CsvExport:
    def export(self, rows):
        return "\n".join(",".join(r) for r in rows)


class WhatsAppExport:
    def export(self, rows):
        return " | ".join(r[0] for r in rows)


class Rider:
    def __init__(self, name):
        self.name = name


def send_report(exporter, rows):
    print(exporter.export(rows))


rows = [("D0101", "delivered"), ("D0102", "cancelled")]
send_report(CsvExport(), rows)
send_report(WhatsAppExport(), rows)
send_report(Rider("Ganesh"), rows)
D0101,delivered
D0102,cancelled
D0101 | D0102
Traceback (most recent call last):
  File "/workspace/chapters/28-protocols-and-abcs/ducks.py", line 23, in <module>
    send_report(Rider("Ganesh"), rows)
    ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
  File "/workspace/chapters/28-protocols-and-abcs/ducks.py", line 17, in send_report
    print(exporter.export(rows))
          ^^^^^^^^^^^^^^^
AttributeError: 'Rider' object has no attribute 'export'

That flexibility is Python's strength, and the last call is its weakness: the mistake shows up only when the line runs, in the middle of the evening report. Kunal wants the rule "an exporter has export" written down, so Python or a tool can check it before it matters.

What you build: 3 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    payments.py: every payment must know how to pay

    Write an abstract base class Payment (it inherits from ABC) with an abstract method pay(amount), and a normal method charge(amount) that raises ValueError when amount is 0 or less and otherwise returns self.pay(amount).

    Then three subclasses: Upi(vpa), whose pay(240) returns "UPI Rs 240 from ravi@okaxis" for Upi("ravi@okaxis"); Cash(), whose pay(240) returns "Cash Rs 240"; and Card(last4), whose pay(240) returns "Card Rs 240 ending 4242" for Card("4242").

    Payment() raises TypeError, and so does making the check's own subclass of Payment that has no pay.

  2. Task 2

    notify.py: anything that can send is a Notifier

    Write Notifier, a Protocol with one method send(self, text: str) -> None, that isinstance can check. Then broadcast(text, targets): call send(text) on every target that is a Notifier, skip every other target, and return how many were sent.

    The check uses its own classes that never inherit from Notifier: isinstance(SmsSender(), Notifier) is True for a class with send, False for a class without one, and broadcast("D0101 is on its way", [SmsSender(), Rider(), MailSender(), 42, "text"]) sends to the two senders and returns 2. broadcast with no targets returns 0.

  3. Task 3 · interview question

    Interview: tiffin.py, a Collection without inheriting

    Write a class Tiffin with nothing in brackets after its name. Tiffin(dishes) keeps a list of dish names and works with len, for (any number of times) and in: for Tiffin(["Chole", "Roti"]), len is 2, the loop gives Chole and Roti, and "Roti" in it is True.

    A Tiffin must pass isinstance with collections.abc's Sized, Iterable, Container and Collection. Then count_all(things) returns the total length of every item that is Sized and counts nothing for the others: count_all([Tiffin(["Chole", "Roti", "Dal Tadka"]), "abc", 5, [1, 2], None]) returns 8.

What you will learn

  • Duck typing: an object is accepted for what it can do, not what it inherits.
  • Abstract base classes (abc.ABC, @abstractmethod): a parent that forces every subclass to write a method.
  • Protocols (typing.Protocol): "any object with these methods", no inheritance needed, checked by mypy and, with @runtime_checkable, by isinstance.
  • collections.abc: how isinstance(x, Sized) says yes to a class that never inherited.

More in Objects

Build "Protocols and ABCs" yourself

DabbaDrop, a Mumbai tiffin startup, runs on Excel and WhatsApp. You are its first Python developer. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of Python, properly are free. This one comes with the all labs plan.