What is the difference between `__repr__` and `__str__`, and what should each aim to return?
Answer
`__repr__` should return an unambiguous, developer-facing representation, ideally one that could be evaluated to recreate an equivalent object (like `Point(x=1, y=2)`), and it is what shows up in a REPL, in a list's printed contents, and in a debugger. `__str__` should return a readable, user-facing description, meant for `print()` and `str()` calls. If `__str__` is not defined, Python falls back to `__repr__` automatically, so it is good practice to always implement `__repr__` even if `__str__` is skipped.
Strong answer includes
- __repr__ is unambiguous and developer-facing, ideally re-creatable
- __str__ is readable and user-facing, used by print()
- Python falls back to __repr__ when __str__ is missing
Practical example
repr(datetime(2026, 1, 1))returns
"datetime.datetime(2026, 1, 1, 0, 0)", precise and re-creatable, while
str(datetime(2026, 1, 1))returns the friendlier `"2026-01-01 00:00:00"` .