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
mypyto find a class that's missing something a protocol needs - Say what
@runtime_checkablechecks, 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.
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 aLendablehas atitlethat'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 anint. The body ispass, 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.
- +title: str
- +loan_days(): int
- +title: str
- +__init__(title: str)
- +loan_days(): int
- +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.
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.
| By family | By shape | |
|---|---|---|
| A class fits when | It names the parent: class Book(LibraryItem) | It has the right attributes and methods |
| Called | Nominal typing: by name | Structural typing: by shape |
| Used by | isinstance with your own classes, abstract classes | Protocols, 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.
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 filemypy 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.
- Line 30: a
Bookhas atitleand aloan_days, soTrue. - Line 31: a
Magazinehas noloan_days, soFalse. - Line 32:
True, thoughFakeis nothing like a library item. Itstitleon line 26 is a number, and itsloan_dayson 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.
| Abstract base class | Protocol | |
|---|---|---|
| How a class joins | It inherits: class Book(LibraryItem) | It doesn’t: having the right attributes and methods is enough |
| Who checks | Python, when an object is made | mypy, before the program runs. Python never does |
| Shared code | Yes: children inherit methods like due_date | No: a class that only fits it gets nothing |
isinstance | Works, and checks the family | Only with @runtime_checkable, and checks names only |
| Best for | A family you write yourself, with code to share | Saying 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 itsdue_datethat 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_lineand itsLendableis 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.
| Python | Java | Rust | |
|---|---|---|---|
| Writing down what’s needed | class Lendable(Protocol) | interface Lendable | trait Lendable |
| How a class signs up | It doesn’t: the right methods are enough | It says so: class Book implements Lendable | It says so: impl Lendable for Book |
| A function that takes one | def lend(item: Lendable) | void lend(Lendable item) | fn lend(item: &impl Lendable) |
| Who checks | mypy, if you run it | The compiler, always | The compiler, always |
| A class someone else wrote | Fits if it has the methods | Fits only if its author wrote implements Lendable | You 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.
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.
- typing: Protocol
- typing: runtime_checkable: checks only that the names exist, not their types
- Glossary: duck-typing
- PEP 544: Protocols: Structural subtyping (static duck typing)
- OMG Unified Modeling Language (UML) 2.5.1: the standard the class diagrams follow
- The Java Tutorials: Defining an Interface: what a Java class must have, signed up with implements
- The Rust Programming Language: Traits: Defining Shared Behavior: what a Rust type must have, signed up with impl