Part 14 / Topic 2 of 11
The data model in depth
The data model is Python's set of rules for how objects work with the language. Built-in functions and operators do not do the work themselves: they call a dunder method (double underscore, like __len__) on the object's class. Write the dunder method, and your class works with the built-in. A group of dunder methods that together give one ability (like "can be looped over") is called a protocol.
Think of a wall socket: any device with the right plug works, whatever brand it is.
| You write | Python calls | Must return |
|---|---|---|
len(x) |
type(x).__len__(x) |
an int ≥ 0 |
x[key], x[1:3] |
__getitem__(key) |
the item |
for item in x |
__iter__() |
an iterator |
item in x |
__contains__(item) |
True/False |
bool(x), if x: |
__bool__() |
True/False |
x(args) |
__call__(args) |
anything |
x == y |
__eq__(y) |
True/False or NotImplemented |
hash(x), set/dict key |
__hash__() |
an int |
Real-world example: a playlist that behaves like a list.
class Playlist:
def __init__(self, songs):
self._songs = list(songs)
def __len__(self):
return len(self._songs)
def __getitem__(self, index):
return self._songs[index]
def __call__(self, word): # search by calling the object
return [s for s in self._songs if word in s]
trip = Playlist(["Kesariya", "Tum Hi Ho", "Jai Ho"])
print(len(trip)) # 3
print(trip[0], trip[-1]) # Kesariya Jai Ho
print(trip[1:]) # ['Tum Hi Ho', 'Jai Ho']
print("Jai Ho" in trip) # True (no __contains__: Python loops using __getitem__)
print(list(trip)) # ['Kesariya', 'Tum Hi Ho', 'Jai Ho'] (no __iter__ either)
print(bool(trip)) # True (no __bool__: Python uses __len__ != 0)
print(trip("Ho")) # ['Tum Hi Ho', 'Jai Ho']
Python has fallbacks when a method is missing:
bool(x):__bool__→ else__len__() != 0→ else alwaysTrue.in:__contains__→ else loop with__iter__→ else loop with__getitem__(0),(1), … untilIndexError.for:__iter__→ else__getitem__(0),(1), … untilIndexError.
Write __iter__ and __contains__ yourself when you can do better than a loop (for example a dict lookup).
The __hash__ / __eq__ rules
A hash is a number worked out from an object's value; sets and dicts use it to find items fast.
- Objects that are equal must have equal hashes.
- If you write
__eq__but not__hash__, Python sets__hash__toNone: the objects can no longer go in a set or be dict keys. - Hash only values that never change while the object is in a set or dict.
class Coupon:
def __init__(self, code):
self.code = code.upper()
def __eq__(self, other):
if not isinstance(other, Coupon):
return NotImplemented # "I don't know how to compare to that"
return self.code == other.code
print(Coupon.__hash__) # None
try:
{Coupon("DIWALI50")}
except TypeError as error:
print(error) # cannot use 'Coupon' as a set element (unhashable type: 'Coupon')
Coupon.__hash__ = lambda self: hash(self.code) # hash the field __eq__ uses
print(len({Coupon("diwali50"), Coupon("DIWALI50")})) # 1
(In a real class, write def __hash__(self): return hash(self.code) inside the class.)
🔍 Going deeper: built-ins look dunder methods up on the class, not the instance, so
obj.__len__ = ...on one object does not changelen(obj).@dataclass(frozen=True)(Part 9) writes__eq__and__hash__for you.
Full program: examples/02_data_model_protocols.py.
Read more: the official data model reference - the canonical list of every dunder.
Done here? The practice set for Part 14 — 8 exercises with solutions — is on the part page.