datarekha
Python Easy Asked at GoogleAsked at AmazonAsked at Meta

What is the difference between `__str__` and `__repr__` in Python, and which should you implement first?

The short answer

`__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

HookCalled byAudienceGoal
__repr__repr(), interactive REPL, !r formatDevelopersUnambiguous; ideally eval(repr(obj)) == obj
__str__str(), print(), f-strings (no !r)End usersReadable

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__ → both str(obj) and repr(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.

Learn it properly Dunder Methods

Keep practising

All Python questions

Explore further

Skip to content