← Back to Python, page 1

python-0006 · Medium mid

How do __str__ and __repr__ differ, and which one should every class define?

__repr__ gives an unambiguous, developer-facing representation, ideally one that looks like code to recreate the object; it is used by the REPL, debuggers and containers. __str__ gives a readable, user-facing text used by print() and str(). If only __repr__ is defined, str() falls back to it, so __repr__ is the one to define first.

Full answer
python
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __repr__(self):
        return f"Point(x={self.x}, y={self.y})"
    def __str__(self):
        return f"({self.x}, {self.y})"

p = Point(1, 2)
print(p)
print(repr(p))
print([p])
print(f"{p!r}")

class Plain:
    def __repr__(self):
        return "Plain()"
print(str(Plain()))

Output:

text
(1, 2)
Point(x=1, y=2)
[Point(x=1, y=2)]
Point(x=1, y=2)
Plain()

print(p) and str(p) use __str__; repr(p) and the list display use __repr__, which is why the list shows Point(x=1, y=2) rather than the friendly text. The f-string !r conversion also calls __repr__, which is handy in log messages.

The Plain class defines only __repr__, and str() falls back to it. The reverse is not true: a class with only __str__ still shows the default <__main__.X object at 0x...> in lists and the REPL.

Dataclasses generate a good __repr__ automatically, which is one of their conveniences.

python
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __repr__(self):
        return f"Point(x={self.x}, y={self.y})"
    def __str__(self):
        return f"({self.x}, {self.y})"

p = Point(1, 2)
print(p)
print(repr(p))
print([p])
print(f"{p!r}")

class Plain:
    def __repr__(self):
        return "Plain()"
print(str(Plain()))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • __repr__ is for developers
  • __str__ is for users
  • Containers use __repr__ for items
  • str falls back to __repr__
  • Dataclasses generate __repr__

Common mistakes

  • Defining only __str__ and getting unhelpful debug output
  • Returning non-string values

Follow-ups

  • What does the !r conversion do in f-strings?
  • How does a dataclass build its repr?

Tips

  • Define __repr__ first