Sub topic 2
Making objects printable: __repr__ and __str__
This chapter assumes you can define classes with __init__ and regular methods, and that you know how print(), f-strings and lists behave. It covers the two methods that control how an object turns into text, and the __format__ hook behind f-string format specs.
Why Python has two text forms
Every object can be converted to text in two ways, and each has its own audience.
__repr__is for developers. It should be unambiguous and useful in a debugger, a log line or a traceback.__str__is for end users. It should be readable, and it may leave out detail.
Without either method, Python falls back to the inherited object.__repr__:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
print(p) # <__main__.Point object at 0x7f...> (address varies)
print(repr(p)) # same textThe output names the class and a memory address. It says nothing about the data inside, so it is almost useless for debugging.
Writing __repr__
By convention, a good __repr__ looks like the expression that would rebuild the object. Use !r on each field so strings keep their quotes and nested objects use their own repr. Use type(self).__name__ instead of a hard-coded name so subclasses report the right class.
class Temperature:
def __init__(self, degrees):
self.degrees = degrees
def __repr__(self):
return f'{type(self).__name__}({self.degrees!r})'
class Celsius(Temperature):
pass
print(repr(Temperature(21.5))) # Temperature(21.5)
print(repr(Celsius(21.5))) # Celsius(21.5)Some objects cannot be rebuilt from their fields, such as an open connection or a file handle. For these, use the angle-bracket form, which signals that the text is a description and not valid code:
class Connection:
def __init__(self, host, port):
self.host = host
self.port = port
def __repr__(self):
return f'<{type(self).__name__} {self.host!r}:{self.port}>'
print(Connection('db.local', 5432)) # <Connection 'db.local':5432>print() shows this output because __str__ is not defined and falls back to __repr__.
Writing __str__
Add __str__ only when users should see something different from the developer form. If you define __str__ and no __repr__, Python does not use __str__ for the repr. The fallback runs one way only: a missing __str__ falls back to __repr__.
class Temperature:
def __init__(self, degrees):
self.degrees = degrees
def __repr__(self):
return f'{type(self).__name__}({self.degrees!r})'
def __str__(self):
return f'{self.degrees}°C'
t = Temperature(21.5)
print(t) # 21.5°C
print(repr(t)) # Temperature(21.5)
print([t]) # [Temperature(21.5)]
print(f'{t}') # 21.5°C
print(f'{t!r}') # Temperature(21.5)The list line shows an important rule. Containers such as list, tuple, dict and set always use repr for their elements, even when you print the container with str(). This is why __repr__ matters more than __str__.
Which method runs where
| Expression | Method used |
|---|---|
| `print(x)`, `str(x)` | `__str__` (falls back to `__repr__`) |
| `repr(x)` | `__repr__` |
| `f'{x}'`, `format(x)` | `__format__`, which by default uses `__str__` |
| `f'{x!r}'`, `'%r' % x` | `__repr__` |
| `f'{x!s}'`, `'%s' % x` | `__str__` |
| `f'{x=}'` | `__repr__` |
| Interactive prompt echo | `__repr__` |
| Elements inside a list, dict or set | `__repr__` |
The call goes through the object's type, not the instance. Assigning obj.__repr__ = lambda: 'x' on an instance has no effect on repr(obj), because Python looks the method up on the class.
Controlling format specs with __format__
An f-string such as f'{x:>10}' passes the part after the colon to __format__. The default object.__format__ accepts only an empty spec and raises TypeError for anything else. That is why f'{Temperature(21.5):>10}' fails unless you handle it.
The simplest approach is to format the str result, and to add custom specs only when you need them:
class Temperature:
def __init__(self, degrees):
self.degrees = degrees
def __repr__(self):
return f'{type(self).__name__}({self.degrees!r})'
def __str__(self):
return f'{self.degrees}°C'
def __format__(self, spec):
if spec == 'f':
return f'{self.degrees * 9 / 5 + 32:.1f}°F'
return format(str(self), spec)
t = Temperature(21.5)
print(f'{t}') # 21.5°C
print(f'[{t:>8}]') # [ 21.5°C]
print(f'{t:f}') # 70.7°FCommon mistakes
- Returning a non-string. Both methods must return a
str. Returning a number or a tuple raisesTypeErrorwhen the method is called throughrepr()orstr(). - Defining only
__str__. Lists, logs and debugger views show the ugly default. Define__repr__first and add__str__only if you need it. - Printing inside the method.
__repr__should return text, not callprint(). A method that prints and returnsNonefails withTypeError. - Raising exceptions or doing slow work. Debuggers and error reports call
repron objects in odd states, such as half-built instances. A__repr__that touches a database or a missing attribute makes debugging harder. Read only attributes that always exist. - Infinite recursion with cycles. If two objects mention each other in their reprs, the call never ends. Built-in lists handle this by printing
[...]. For your own classes, usereprlib.recursive_repr:
import reprlib
class Node:
def __init__(self, name):
self.name = name
self.friend = None
@reprlib.recursive_repr()
def __repr__(self):
return f'Node({self.name!r}, friend={self.friend!r})'
a = Node('a')
b = Node('b')
a.friend = b
b.friend = a
print(a) # Node('a', friend=Node('b', friend=...))- Leaking secrets. Reprs end up in logs and tracebacks. Leave passwords, tokens and personal data out of them.
Summary of the working model
repr(x)callstype(x).__repr__(x). It is the developer-facing form, and containers use it for their elements.str(x)callstype(x).__str__(x), and a missing__str__falls back to__repr__.format(x, spec)calls__format__, which defaults tostr(x)when the spec is empty.- Both text methods must return a
str, and neither should raise or have side effects.
Exercise
A class Person defines only __str__, which returns the person's name. What does print([Person('Ann')]) show, and what is the smallest change that makes it show something useful?
Show answer
It shows the default form, such as [<__main__.Person object at 0x...>]. A list uses repr for its elements, and __str__ is not used as a fallback for repr. Add a __repr__ that returns something like f'Person({self.name!r})', and the output becomes [Person('Ann')].
Exercise
Why does f'{Temperature(21.5):>8}' raise TypeError when the class defines __str__ but not __format__, and how do you fix it?
Show answer
The default object.__format__ rejects any non-empty format spec. Define __format__(self, spec) and return format(str(self), spec), which applies the width and alignment to the string form.