Sub topic 2
Making objects printable: __repr__ and __str__
This chapter assumes you can define classes with __init__ and instance attributes, and that you know f-strings and the built-in list type.
Why the default output is not useful
A class with no string methods prints an object's type and memory address.
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
print(Vector(1, 2)) # <__main__.Vector object at 0x7f...>The address tells you nothing about the data. Two special methods fix this: __repr__ and __str__.
Two audiences, two methods
__repr__is for developers. It is called byrepr(obj), by the interactive prompt, in debuggers, and when the object appears inside a list, dict, or tuple.__str__is for end users. It is called bystr(obj),print(obj), andf"{obj}".
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f'Vector({self.x!r}, {self.y!r})'
def __str__(self):
return f'({self.x}, {self.y})'
v = Vector(1, 2)
print(v) # (1, 2)
print(repr(v)) # Vector(1, 2)
print(f'{v}') # (1, 2)
print([v]) # [Vector(1, 2)]Note the last line. A list formats its items with repr, even when you call print on the list.
Which method does Python pick?
str() looks for __str__ first. If the class does not define it, Python falls back to __repr__. The reverse does not happen: repr() never uses __str__.
Because of this fallback, the practical rule is: always write __repr__, and add __str__ only when a friendlier display is useful.
Writing a good __repr__
Aim for output that looks like the code that would recreate the object, as in Vector(1, 2). When that is not possible, use the form <ClassName ...> with the key fields.
Use the !r conversion on each field. It calls repr() on the value, so strings keep their quotes and you can tell Vector('1', '2') from Vector(1, 2).
class User:
def __init__(self, name):
self.name = name
def __repr__(self):
return f'{type(self).__name__}({self.name!r})'
class Admin(User):
pass
print(Admin('ana')) # Admin('ana')Using type(self).__name__ instead of a hardcoded name means subclasses print their own name.
Common errors
- Returning a non-string. Both methods must return a
str, or Python raisesTypeError. - Printing secrets.
__repr__appears in logs and tracebacks, so leave out passwords and tokens. - Calling
repr(self)inside__repr__through a field that refers back to the object. This causes infinite recursion.
Exercise
A class defines only __str__, returning 'point'. What does print([obj]) show, and why?
Show answer
It shows something like [<__main__.Point object at 0x...>]. A list formats its items with repr(), and the class has no __repr__, so Python uses the default. repr() never falls back to __str__.