Object-oriented programming · lesson 14 of 17
Parts in this lesson
Aclass Lendable(Protocol)what an object must be able to do
Bitem: Lendableany object of the right shape
Cmypy loans.pychecks the shape before running
D@runtime_checkableisinstance, by names only

Protocols

Last updated

Duck typing lets a function take any object that has the right methods, but nothing in the code says which methods those are. In this lesson you'll write that down as a protocol: a list of what an object must be able to do, which a class fits just by having those things, without inheriting anything. You'll see Python run a program that breaks the protocol, let mypy catch it, learn what isinstance can and can't check, and decide between an abstract class and a protocol.

By the end of this lesson you can

  • Write a protocol with typing.Protocol, and use it as a type hint
  • Explain structural typing: a class fits a protocol by its shape, not its family
  • Use mypy to find a class that's missing something a protocol needs
  • Say what @runtime_checkable checks, and choose between an abstract class and a protocol

Duck typing, written down

In lesson 4.10, a function worked with any object that had the right methods, with no shared parent. Here's one more. receipt_line takes a book or a DVD, and the two classes aren't related at all.

Step 1 code main.py
Edit the code, then run it again

It works, because both objects have a title and a loan_days(). But look at line 17: def receipt_line(item):. Nothing there says what item needs. To find out, you have to read the body on line 18 and spot item.title and item.loan_days(). In a longer function, or one that passes item on to other functions, that gets hard.

Type hints (lesson 2.11) could say. But which type? Book is wrong, because a DVD works too. The true answer is "anything with a title and a loan_days()", and Python has a way to write that down.

typing.Protocol

A protocol is a class that lists what an object must have, and nothing else. Line 4 makes Lendable one, by naming Protocol from the typing module as its parent.

  • Line 5, title: str, says a Lendable has a title that's text. It's written like a dataclass field (lesson 3.6): a name and a type, with no value.
  • Lines 7 and 8 say it has a loan_days() method that gives back an int. The body is pass, as for an abstract method in lesson 4.13. The protocol says what, never how.

Line 28 uses the protocol as a type hint: item: Lendable. Now the first line of receipt_line tells you exactly what it needs.

A protocol, and two classes that match it without inheriting from it
100%
«protocol» Lendable
  • +title: str
  • +loan_days(): int
Book
  • +title: str
  • +__init__(title: str)
  • +loan_days(): int
Laptop
  • +title: str
  • +charger: bool
  • +__init__(title: str, charger: bool)
  • +loan_days(): int
  • Protocol Lendable; attributes: title; methods: loan_days.
  • Class Book; attributes: title; methods: __init__, loan_days.
  • Class Laptop; attributes: title, charger; methods: __init__, loan_days.
Step 2 code main.py
Edit the code, then run it again

Neither Book nor Laptop mentions Lendable. They don't inherit from it, and they don't import it. They fit because they have a title and a loan_days() that gives back an int. The library lends laptops too, and a Laptop has its own extra charger attribute on line 22, which the protocol doesn't care about.

A protocol changes nothing when the program runs. Python reads Lendable and the hint, and runs the program exactly as in step 1. The protocol is there for people reading the code, and for mypy.

Matching by shape, not by family

There are two ways a class can count as a kind of thing.

Two ways to fit a type
By familyBy shape
A class fits whenIt names the parent: class Book(LibraryItem)It has the right attributes and methods
CalledNominal typing: by nameStructural typing: by shape
Used byisinstance with your own classes, abstract classesProtocols, and duck typing

Abstract classes, as in lesson 4.13, work by family: a Book is a LibraryItem because its class line says so. If it doesn't name the parent, it isn't one, whatever methods it has.

Protocols work by shape: Book is a Lendable because it has everything Lendable lists. This is called structural typing. It's duck typing from lesson 4.10, but written down where a tool can check it. You met the same idea at the end of lesson 4.13: Sized from collections.abc recognised a Shelf by its __len__.

Matching by shape means you can describe what a function needs without touching the classes that fit. That matters most for classes you didn't write and can't change, such as a class from someone else's module that happens to have a title and a loan_days().

Checking with mypy

Here a Magazine is lent. It has a title but no loan_days(), so it doesn't fit Lendable. Line 25 passes it to lend anyway. Press Run.

Step 4 code main.py
Edit the code, then run it again

Wrong way: it runs, with no error. lend only reads item.title on line 22, and a magazine has one. The missing loan_days() is waiting in the list loans for the day someone asks when the magazine is due. Add print(loans[0].loan_days()) at the end and run it: AttributeError, far from line 25, where the mistake really was.

Python never checks a protocol, just as it never checks any type hint. mypy does. Save the program as loans.py and run mypy on it, as in lesson 2.11:

(.venv) > mypy loans.py
loans.py:25: error: Argument 1 to "lend" has incompatible type "Magazine"; expected "Lendable"  [arg-type]
loans.py:25: note: "Magazine" is missing following "Lendable" protocol member:
loans.py:25: note:     loan_days
Found 1 error in 1 file (checked 1 source file)

mypy points at line 25, the call that's wrong, and the notes name what's missing: loan_days. It found this without running anything. Give Magazine a loan_days() that returns 14, and mypy is happy:

(.venv) > mypy loans.py
Success: no issues found in 1 source file

mypy only checks code with type hints. On the receipt_line(item) from step 1, with no hints, it says nothing. That's why the protocol and the hint item: Lendable go together.

@runtime_checkable and its limits

Sometimes a program needs to ask, as it runs, whether an object fits. isinstance won't take a protocol on its own. It needs the decorator @runtime_checkable on the protocol, as on line 4.

Step 5 code main.py
Edit the code, then run it again
  • Line 30: a Book has a title and a loan_days, so True.
  • Line 31: a Magazine has no loan_days, so False.
  • Line 32: True, though Fake is nothing like a library item. Its title on line 26 is a number, and its loan_days on line 27 is text, not a method.

That's the limit. isinstance with a protocol only checks that each name exists. It doesn't check what kind of value is there, what a method takes, or what it gives back. A "yes" from it means "the names are there", nothing more. mypy, which reads the types, would reject Fake wherever a Lendable is expected.

Delete line 4 and run it again: TypeError: Instance and class checks can only be used with @runtime_checkable protocols. Python makes you ask for the weaker check on purpose.

Abstract class or protocol?

Both say what an object must be able to do. They differ in who has to agree to it, and who checks.

Which to use
Abstract base classProtocol
How a class joinsIt inherits: class Book(LibraryItem)It doesn’t: having the right attributes and methods is enough
Who checksPython, when an object is mademypy, before the program runs. Python never does
Shared codeYes: children inherit methods like due_dateNo: a class that only fits it gets nothing
isinstanceWorks, and checks the familyOnly with @runtime_checkable, and checks names only
Best forA family you write yourself, with code to shareSaying what a function needs, from any class, even ones you didn’t write

A rule of thumb:

  • When you're writing a family of classes yourself, and the parent has code to share, use an abstract class. LibraryItem, with its due_date that every child uses, is one.
  • When a function needs certain methods and shouldn't care where its objects came from, use a protocol as the hint. receipt_line and its Lendable is one.

They work together. In the loan desk project, Book, DVD and Magazine inherit from the abstract LibraryItem, and they also fit Lendable, so a laptop can be lent through the same code without joining the family.

In other languages

This step is optional. It's for anyone who will meet Java or Rust later.

Saying what an object must do, in three languages
PythonJavaRust
Writing down what’s neededclass Lendable(Protocol)interface Lendabletrait Lendable
How a class signs upIt doesn’t: the right methods are enoughIt says so: class Book implements LendableIt says so: impl Lendable for Book
A function that takes onedef lend(item: Lendable)void lend(Lendable item)fn lend(item: &impl Lendable)
Who checksmypy, if you run itThe compiler, alwaysThe compiler, always
A class someone else wroteFits if it has the methodsFits only if its author wrote implements LendableYou can write impl Lendable for it yourself

Java's interfaces and Rust's traits work by family: a class or type fits only if it says so, and the compiler checks every call before the program runs. C# works like Java. A Python protocol works by shape, and is checked only if you run mypy. Go's interfaces are the closest match to protocols: a type fits just by having the methods. Simple Rust 4.3 writes fn lend(item: &impl Lendable) the Rust way.

Check what you learned

Three questions. Pick an answer, then check it.

This Room is added to the program from step 2, and passed to receipt_line(item: Lendable). What does mypy say?
class Room:
    def __init__(self, title: str) -> None:
        self.title = title

    def loan_days(self) -> int:
        return 1


print(receipt_line(Room("Study room 2")))
A class is missing a method its protocol lists, and an object of it is passed to a function with the protocol as a hint. What does Python do when the program runs?
Your function must accept items from someone else's module, which you can't change. They have a title and a loan_days(), but no shared parent. What should the hint be?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Python