What Magic Methods Are
Python’s special methods let objects control their string representation. Two of the most common are __repr__ and __str__, each called by built‑in functions or interactive prompts.
__repr__ – the developer’s view
The goal of __repr__ is to provide an unambiguous, machine‑readable representation. Ideally it returns a string that could be used with eval() to recreate the object, or at least contains enough detail to identify the instance.
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f"Point({self.x!r}, {self.y!r})"
p = Point(3, 4)
print(repr(p)) # Point(3, 4)
__str__ – the user’s view
When an object is printed or converted to a string for display, __str__ is used. It should be concise and friendly, prioritizing readability over precision.
class Point:
def __str__(self):
return f"({self.x}, {self.y})"
print(p) # (3, 4)
Fallback Behavior
If __str__ is missing, Python falls back to __repr__. If both are absent, the default representation includes the object’s memory address, which is rarely useful to end users.
When to Implement Each
Implement __repr__ on every class that benefits from debugging clarity. Implement __str__ only when you need a nicer display for users, such as in command‑line tools or logs.
Takeaway: Use __repr__ for debugging and __str__ for user‑friendly output.
People also ask
Can __repr__ return a human‑readable string?
Yes, but it should still be unambiguous and ideally eval‑able.
What happens if I define only __repr__?
print() will display the __repr__ string, so debugging output will also be user‑friendly.
Is __repr__ always called in the REPL?
Yes, the interactive prompt uses __repr__ to display the last expression’s value.
Inspired by a public discussion on Stack Overflow. This article is an original explanation for learners.