Python Special Methods
What you will learn
- What special methods (also called dunder methods) are
__str__and__repr__: the difference, and how to write both__len__,__getitem__,__contains__,__iter__,__bool__,__call____format__and the number-conversion methods__getattr__and context managers (__enter__,__exit__), briefly- Which operation calls which method
1. What are special methods?
A special method is a method whose name starts and ends with two underscores: __init__, __str__, __len__. The two underscores are called a "dunder" (double underscore), so these are also called dunder methods. You have already written one, __init__.
You almost never call them directly. Python calls them for you when you use a built-in function or operator:
| You write | Python calls |
|---|---|
Dog("Rex") |
__init__ (after creating the object) |
print(x), str(x) |
x.__str__() |
repr(x), showing x in a list |
x.__repr__() |
len(x) |
x.__len__() |
x[i] |
x.__getitem__(i) |
item in x |
x.__contains__(item) |
for a in x |
x.__iter__() |
bool(x), if x: |
x.__bool__() (or __len__) |
x(arg) |
x.__call__(arg) |
x == y, x + y, x < y |
__eq__, __add__, __lt__ (lesson 13.8) |
This is how your own classes can behave like built-in types. Never invent your own names with double underscores: that space belongs to Python.
Quick check: when you write `len(basket)`, which method does Python call?
basket.__len__().
2. repr and str
By default, an object prints as something unhelpful:
class P:
def __init__(self, x, y):
self.x, self.y = x, y
p = P(1, 2)
print(p)
print([p])
<__main__.P object at 0x0000011705536A50>
[<__main__.P object at 0x0000011705536A50>]
(The number after at varies.) There are two methods that control how an object is shown, for two audiences:
| Method | Audience | Used by | Goal |
|---|---|---|---|
__repr__ |
programmers | repr(x), the interactive prompt, debuggers, inside lists and dictionaries, !r in f-strings |
unambiguous; ideally looks like the code that creates the object |
__str__ |
end users | print(x), str(x), f"{x}" |
readable |
class S(P):
def __repr__(self):
return f"S(x={self.x!r}, y={self.y!r})"
def __str__(self):
return f"S at {self.x},{self.y}"
s = S(1, "a")
print(s)
print(repr(s))
print([s])
print({"k": s})
print(f"{s!r}", f"{s}")
S at 1,a
S(x=1, y='a')
[S(x=1, y='a')]
{'k': S(x=1, y='a')}
S(x=1, y='a') S at 1,a
print(s)uses__str__.- Containers (lists, dictionaries) show their items with
__repr__, even when you print the container. !rin an f-string asks forrepr.
The fallback rule
If a class has only __repr__, Python uses it for str as well. If it has only __str__, then repr stays the unhelpful default. So always write __repr__ first:
class Q(P):
def __repr__(self):
return f"Q({self.x}, {self.y})"
q = Q(1, 2)
print(q, repr(q), [q])
Q(1, 2) Q(1, 2) [Q(1, 2)]
One method, and everything looks right. Add __str__ only when users should see something different from the developer's view.
Writing a good repr
A good __repr__ shows the class name and the values, using !r for each (so that text gets its quotes). Ideally you could paste the result back into Python to make an equal object:
print(repr("it's"), repr(3.0), repr(None), repr([1, "a"]))
"it's" 3.0 None [1, 'a']
Built-in types already follow this idea. For your own classes, use f"ClassName({self.a!r}, {self.b!r})". (Use type(self).__name__ instead of the class name if subclasses should show their own name.) Lesson 13.11 shows that dataclasses write __repr__ for you.
3. Behaving like a collection
By defining a few special methods, an object can plug into len, indexing, in, for, sorted and if:
| Method | Enables |
|---|---|
__len__(self) |
len(x), and bool(x) (empty is false) |
__getitem__(self, i) |
x[i], slices x[1:], and (as a fallback) looping and in |
__contains__(self, item) |
item in x |
__iter__(self) |
for a in x, list(x), sum(x), sorted(x), max(x) |
__bool__(self) |
if x: (when you want truth to mean something else) |
class Basket:
def __init__(self, *items):
self.items = list(items)
def __len__(self):
return len(self.items)
def __getitem__(self, i):
return self.items[i]
def __contains__(self, x):
return x in self.items
def __iter__(self):
return iter(self.items)
def __repr__(self):
return f"Basket({', '.join(map(repr, self.items))})"
b = Basket("a", "b", "c")
print(len(b), b[0], b[-1], b[1:])
print("b" in b, "z" in b)
print(list(b), sorted(b, reverse=True), max(b))
print(bool(b), bool(Basket()))
print(b)
3 a c ['b', 'c']
True False
['a', 'b', 'c'] ['c', 'b', 'a'] c
True False
Basket('a', 'b', 'c')
Every built-in function works on a Basket because it follows the protocol.
Notice two things:
- With
__len__defined, an emptyBasket()is false and a non-empty one true, with no__bool__needed (lesson 5.3). b[1:]works because__getitem__simply passes the index on to the list, and a slice is also passed to it.
A class with only getitem
Python's rule is generous: if a class has only __getitem__, it is still iterable. Python tries x[0], x[1], ... until an IndexError:
class OnlyGetitem:
def __getitem__(self, i):
if i >= 3:
raise IndexError
return i * 10
g = OnlyGetitem()
print(list(g), g[2], 20 in g)
[0, 10, 20] 20 True
But it has no length: len(g) is TypeError: object of type 'OnlyGetitem' has no len(). Write __iter__ to be explicit and efficient.
4. Callable objects: call
A class with __call__ makes its objects behave like functions (lesson 11.7). Unlike a plain function, the object remembers data between calls:
class Adder:
def __init__(self, n):
self.n = n
def __call__(self, x):
return x + self.n
add3 = Adder(3)
print(add3(4), callable(add3))
print(list(map(add3, [1, 2])))
7 True
[4, 5]
5. Formatting and conversion
You can control how your object works with f-strings, int(...), float(...) and round(...):
| Method | Enables |
|---|---|
__format__(self, spec) |
f"{x:spec}" and format(x, spec) |
__int__, __float__ |
int(x), float(x) |
__round__(self, n=0) |
round(x) and round(x, n) |
__bool__ |
bool(x) |
class Money:
def __init__(self, amount):
self.amount = amount
def __str__(self):
return f"${self.amount:,.2f}"
def __format__(self, spec):
return format(self.amount, spec) if spec else str(self)
def __bool__(self):
return self.amount != 0
def __int__(self):
return int(self.amount)
def __float__(self):
return float(self.amount)
def __round__(self, n=0):
return round(self.amount, n)
m = Money(1234.5)
print(m, f"{m}")
print(f"{m:.1f}", f"{m:>10,.0f}|")
print(int(m), float(m), round(m), round(Money(2.567), 2))
print(bool(m), bool(Money(0)))
$1,234.50 $1,234.50
1234.5 1,234|
1234 1234.5 1234.0 2.57
True False
With no spec, f"{m}" uses str(m). With a spec such as .1f, the method passes it on to the number. (1,234 shows the usual tie-to-even rounding of 1234.5, lesson 3.3.)
6. getattr: missing attributes
__getattr__(self, name) is called only when normal lookup fails, that is when the attribute is not found in the object or the class. It lets you provide fallback or computed attributes:
class Temp:
def __getattr__(self, name):
return f"<no {name}>"
t = Temp()
t.real = 1
print(t.real, t.fake, t.other)
1 <no fake> <no other>
t.real was found normally, so __getattr__ was not used. t.fake was missing, so it was. Be careful: this makes typos silent (you get a string, not an AttributeError), so use it for a clear purpose, and raise AttributeError for names that really should not exist:
class Tracker:
def __init__(self):
object.__setattr__(self, "_data", {})
def __setattr__(self, name, value):
self._data[name] = value
def __getattr__(self, name):
try:
return self._data[name]
except KeyError:
raise AttributeError(name)
tr = Tracker()
tr.a = 1
tr.b = 2
print(tr.a, tr.b, tr._data)
1 2 {'a': 1, 'b': 2}
__setattr__ runs on every assignment, so inside it, never write self.x = ... (that calls itself again forever). The first line of __init__ avoids that by writing through object.__setattr__. Special methods like these are powerful and easy to get wrong: prefer plain attributes and properties (lesson 13.4) unless you need them.
7. Context managers: enter and exit
The with statement (chapter 14) calls __enter__ at the start and __exit__ at the end, even if an error happens. That makes cleanup automatic, for files, locks and timers:
class Ctx:
def __enter__(self):
print("enter")
return self
def __exit__(self, exc_type, exc, tb):
print("exit", exc_type.__name__ if exc_type else None)
return False
with Ctx() as c:
print("inside")
enter
inside
exit None
If the block raises an error, __exit__ still runs, and receives the error's details. Returning False lets the error continue to the caller:
try:
with Ctx():
raise ValueError("x")
except ValueError:
print("caught")
enter
exit ValueError
caught
8. Other special methods you will meet
| Method | Called | Use |
|---|---|---|
__new__(cls) |
before __init__, to create the object |
rare: singletons, immutable types |
__del__(self) |
when the object is about to be removed from memory | rare, unreliable timing; prefer with |
__hash__, __eq__ |
hash(x), x == y |
lesson 9.7 and 13.8 |
__lt__, __add__, ... |
comparison and arithmetic operators | lesson 13.8 |
__setitem__, __delitem__ |
x[i] = v, del x[i] |
mutable collections |
__enter__, __exit__ |
with |
lesson 14.6 |
__init_subclass__, __class_getitem__ |
class-level hooks | advanced |
You can list the special methods of a class with dir(ClassName), picking those that start and end with two underscores.
Worked example: a Playlist that behaves like a collection
A Playlist has a name and songs. We want it to print nicely, show a developer view, support len, indexing, in (ignoring case), looping, if, and be callable to "play" a song.
class Playlist:
def __init__(self, name, *songs):
self.name = name
self._songs = list(songs)
def add(self, song):
self._songs.append(song)
return self
def __repr__(self):
return f"Playlist({self.name!r}, {', '.join(map(repr, self._songs))})"
def __str__(self):
return f"{self.name} ({len(self)} songs)"
def __len__(self):
return len(self._songs)
def __getitem__(self, i):
return self._songs[i]
def __iter__(self):
return iter(self._songs)
def __contains__(self, song):
return song.lower() in (s.lower() for s in self._songs)
def __bool__(self):
return bool(self._songs)
def __call__(self, i):
return f"Now playing: {self._songs[i]}"
pl = Playlist("Road", "Alpha", "Beta").add("Gamma")
print(pl)
print(repr(pl))
print(len(pl), pl[0], pl[-1], pl[1:], "beta" in pl, "Delta" in pl)
print(list(pl), sorted(pl, reverse=True), bool(pl), bool(Playlist("Empty")), pl(1))
print([pl])
copy = eval(repr(pl))
print(copy.name, list(copy), copy is pl)
Road (3 songs)
Playlist('Road', 'Alpha', 'Beta', 'Gamma')
3 Alpha Gamma ['Beta', 'Gamma'] True False
['Alpha', 'Beta', 'Gamma'] ['Gamma', 'Beta', 'Alpha'] True False Now playing: Beta
[Playlist('Road', 'Alpha', 'Beta', 'Gamma')]
Road ['Alpha', 'Beta', 'Gamma'] False
| Special method | What it gives |
|---|---|
__repr__ |
the developer view; used inside the list [pl]; eval(repr(pl)) rebuilds an equal playlist |
__str__ |
the friendly line Road (3 songs) |
__len__, __getitem__, __iter__ |
len, indexing and slicing, list, sorted |
__contains__ |
a case-insensitive in |
__bool__ |
an empty playlist is false |
__call__ |
the playlist object can be "called" like a function |
(eval runs text as code, so use it only on text you trust; here it just shows what a good repr can do.) The song names are made up.
Common mistakes
- Writing only
__str__and getting an unhelpfulreprin lists and debugging output. Write__repr__first. - Returning a non-string from
__str__or__repr__: they must return text. - Calling
self.x = ...inside__setattr__, which recurses forever. - Defining
__getattr__and making typos silent. RaiseAttributeErrorfor unknown names. - Inventing your own
__name__-style methods. - Forgetting that
__len__also controls truth (an object withlen0 is false).
Key takeaways
- Special (dunder) methods are called by Python for built-in functions and operators; you rarely call them yourself.
__repr__is for programmers (unambiguous, shown in containers);__str__is for users (print); write__repr__first, sincestrfalls back to it.__len__,__getitem__,__contains__,__iter__and__bool__let your class work withlen,[],in,forandif.__call__makes objects callable;__format__,__int__,__float__and__round__control formatting and conversion.__getattr__handles missing attributes, and__enter__/__exit__powerwith; use the powerful ones sparingly.
Practice
1. Which method does print(obj) use, and which does [obj] use when printed?
Show answer
print(obj) uses __str__. Showing [obj] uses __repr__ for the item inside the list.
2. A class defines only __repr__. What does str(obj) give?
Show answer
The same as repr(obj): str falls back on __repr__ when __str__ is missing.
3. Make a class Bag support len(bag) and for x in bag.
Show answer
class Bag:
def __init__(self, *items):
self._items = list(items)
def __len__(self):
return len(self._items)
def __iter__(self):
return iter(self._items)
4. Why is an empty object with __len__ returning 0 false in an if?
Show answer
When there is no __bool__, Python uses __len__ for truth: a length of zero is false.
5. What goes wrong with self.x = v inside __setattr__?
Show answer
It calls __setattr__ again, which calls itself without end. Use object.__setattr__(self, "x", v) or store into self.__dict__.
6. What does __call__ allow?
Show answer
Calling an object with brackets, obj(args), like a function that can remember data.