What is the difference between `__str__` and `__repr__` in Python, and which should you implement first?
`__repr__` is the developer-facing representation — unambiguous, ideally eval-able back to the object. `__str__` is the user-facing string — readable and concise. When only `__repr__` is defined, Python falls back to it for `str()` as well, so implement `__repr__` first.
How to think about it
What’s really being asked
The interviewer wants to know if you understand that Python separates “show me the object for debugging” from “show me something a user would read.” They also want to see whether you know about the one-way fallback — str() falls back to repr(), but never the other direction.
The two audiences
| Hook | Called by | Audience | Goal |
|---|---|---|---|
__repr__ | repr(), interactive REPL, !r format | Developers | Unambiguous; ideally eval(repr(obj)) == obj |
__str__ | str(), print(), f-strings (no !r) | End users | Readable |
Think of it this way: __repr__ is what you’d want to see in a debugger or error log. __str__ is what you’d display in a UI or a report.
Building both from scratch
A Transaction class is a good example because the two audiences really do want different things. A developer debugging a payment pipeline wants to reconstruct the exact object. A customer reading a confirmation email just wants the readable summary.
The fallback chain
If __str__ is absent, Python calls __repr__. There is no reverse fallback — __repr__ never delegates to __str__. This means:
- Define only
__repr__→ bothstr(obj)andrepr(obj)work, with the same output. - Define only
__str__→repr(obj)falls back to the unhelpful<ClassName object at 0xADDR>.
That’s why the rule is: implement __repr__ first, then add __str__ only when you need a distinct user-facing format.