Back to results for “Operator Overloading”
Python › Magic Methods & Operator Overloading

What is the difference between __str__ and __repr__?

Beginner

Answer

__str__ should return a readable, user-facing string (used by print() and str()), while __repr__ should return an unambiguous, ideally eval-able representation useful for debugging (used by the REPL and repr()). If __str__ is not defined, Python falls back to __repr__ for str() and print().
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(str(p))   # (1, 2)
print(repr(p))  # Point(x=1, y=2)
Real-world example In a debugging session, a list of custom objects printed in the console shows each item's __repr__, making it crucial to implement a clear, informative __repr__ for every domain model class.

Common follow-ups: What does Python use when only __repr__ is defined?;Why should __repr__ ideally be eval-able?