Skip to the solution
EasyDSA9 min read

What is the difference between __repr__ and __str__?

453 views

The problem

Question presented to candidate: "Python classes can define both __repr__ and __str__. What is the difference between them, when does Python call each one, and if you only had time to write one, which would it be?"

What a strong answer should cover:

  • __str__ is the readable, end-user text (print(x), str(x), f"{x}"); __repr__ is the unambiguous, developer-facing text (repr(x), the REPL, debuggers, logs).
  • Containers such as lists and dicts show the repr of their elements, even when you print the container.
  • The fallback rule: if __str__ is missing, str() uses __repr__; the reverse is not true, so __repr__ is the one to write first.
  • Convention: for simple value types repr looks like a constructor call, ideally so that eval(repr(x)) == x; otherwise use the <ClassName ...> style.
  • !r and the f"{x=}" debugging form (Python 3.8+) use repr; both methods must return a str.
  • dataclasses generate __repr__ for you; reprlib.recursive_repr guards self-referencing objects.

Code / implementation expected: Yes β€” a small class with both methods, showing print, repr, a list of the objects and an f-string with !r.

  • dunder
  • repr
  • str

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonMoney: str for users, repr for developers, and the fallback rule
PythonBuilt-ins, dataclasses, recursive reprs and reprlib

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 23 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextEasy

How does the in operator work in Python?

Continue