Lesson · Python Data Model & Special Methods
String Representations
55 min readString Representations
`__repr__` targets developers and debugging, while `__str__` targets readable display. Good representations make objects easier to inspect without hiding important state.
Learning goals
- Explain the audience each method serves:
__repr__for developers and debugging,__str__for readable display. - Predict which method
print(point),repr(point), and the interactive echo each use for the worked example'sPoint. - Use
!rinside an f-string and say why it keeps field values unambiguous. - Describe the fallback rule:
str()andprint()fall back to__repr__, butrepr()never calls__str__. - Explain why a container shows its elements with
__repr__even when__str__exists.
Mental model
The two methods answer two audiences, and the routing is one-way. In the worked example the same Point prints as (2, 3) through print, which uses __str__, and as Point(x=2, y=3) through repr, which keeps the fields in their own repr form. If __str__ is missing, str() and print() fall back to __repr__; nothing falls back the other way.
Mental model
read it top to bottom
print and str() → __str__, readable (falls back to __repr__) repr() and REPL echo → __repr__, unambiguous list, dict, tuple → always the elements' __repr__
Core idea
Representations answer different audiences with different contracts: __repr__ gives an unambiguous developer-facing description whose fields show their own types, while __str__ gives readable display. Python routes repr() and interactive echo to __repr__, and str() and print() to __str__, falling back to __repr__ when the friendly form is absent. Getting both right lets the worked example's Point stay readable on screen and still unambiguous in a log.
__repr__
__repr__ should provide an unambiguous developer-oriented representation when practical. A good representation includes the state that explains object identity or configuration.
__str__
__str__ is the friendly text representation used by str() and commonly by print(). If it is absent, Python can fall back to __repr__.
Developer vs user-facing representations
__repr__ speaks to developers: it should identify the object and show its state unambiguously, ideally in a form that could rebuild it. __str__ speaks to users: it favors short, readable display, usually built from the raw fields. The split exists so logs stay precise while screens stay readable, and the one-way fallback means a class with only __repr__ still has a working display path.
Walkthrough
Point.__init__storesxandy;__repr__returns an f-string that wraps each field with!r, so strings and nested objects appear in their own repr form instead of being flattened into text.__str__returnsf"({self.x}, {self.y})", a short display form:print(point)uses it and shows(2, 3).repr(point)bypasses__str__and showsPoint(x=2, y=3), the form you could paste back into a REPL to rebuild the object.- Predict before running: which line uses
__str__, and whatprint(point)would show if__str__were deleted.
Experiments to try
- Delete
__str__and rerun both lines: confirm thatprint(point)falls back to__repr__, then restore the method. - Add a string field such as
label="origin"and compare!ragainst plain formatting inside__repr__; note exactly where the ambiguity disappears. - Put two
Pointobjects in a list and print the list; explain why it shows the repr form of each point even though__str__exists. - Run
eval(repr(point))and compare the rebuilt object'sxandywith the original's; explain what makes the repr string usable this way.
Common mistakes
- Providing only
__str__and expectingrepr(), the REPL echo, or container display to use it; those paths read__repr__and fall back the other way. - Dropping
!rfrom__repr__: a string field then formats without quotes, soPoint('2', 3)andPoint(2, 3)produce the same text. - Returning a non-string from
__repr__or__str__, which raisesTypeErrorat the moment Python uses the result. - Adding side effects (printing, network or disk access) inside a representation, because
__repr__runs in debuggers, logs, and error messages where side effects distort the tooling.
Practice: Easy
- Run the worked example and record which line prints
(2, 3)and which printsPoint(x=2, y=3), then name the method behind each. - Delete
__str__, rerun both lines, and explain the new output with the fallback rule. - Create
Point("a", "b")and note how!rkeeps the string fields quoted in the repr output.
Practice: Medium
- Extend
Pointwith an__eq__comparing the(x, y)pair soeval(repr(point)) == pointworks; explain why the repr'sPoint(x=2, y=3)shape is what makes the round trip possible. - Write a
Money(amount, currency)class whose__str__formats as10.00 USDand whose__repr__showsMoney(amount=10.0, currency='USD'); check bothprintandrepr. - Create a class without
__repr__and put it in a list next toPointobjects; explain why the default<... object at 0x...>output makes a list of several objects unreadable.
Practice: Hard
- Design a
Node(value, children)whose__repr__renders the whole nested structure in one expression, such asNode(1, [Node(2, []), Node(3, [])]); verify a singlereprcall shows the full tree. - Build a failure lab with three reproductions: a
__repr__returning a number and theTypeErrorit causes; a__repr__that prints as a side effect and scrambles log output; a class with only__str__whose list display is unreadable. Explain each mechanism and its fix. - Connect this lesson to f-strings: explain what
f"{point}",f"{point!r}", andf"{point!s}"each call, using the worked example's class as the test object.
Lesson checklist
- I can say which method
print,repr, and the interactive echo each use. - I can write a
__repr__that shows every field unambiguously, with!rwhere the type must stay visible. - I can explain the one-way fallback from
__str__to__repr__. - I can explain why containers display elements with their repr forms.
Remember
`__repr__` and `__str__` split representation by audience: an unambiguous, field-showing form for developers and a readable form for display. Python routes `repr()` and the interactive echo to `__repr__`, `str()` and `print()` to `__str__`, and falls back to `__repr__` when the friendly form is absent. In the worked example the same point reads as `(2, 3)` on screen and as `Point(x=2, y=3)` in a log, which is the split working as designed.
Interview angles
What is the main purpose of **__repr__**?+
__repr__ should provide an unambiguous developer-oriented representation when practical. A good representation includes the state that explains object identity or configuration.
What should you pay attention to when using **__str__**?+
__str__ is the friendly text representation used by str() and commonly by print(). If it is absent, Python can fall back to __repr__.
How does **Developer vs user-facing representations** fit into this lesson?+
__repr__ speaks to developers: it identifies the object and shows its state unambiguously, ideally in a form that could rebuild it. __str__ speaks to users: it favors short, readable display. The split exists so logs stay precise while screens stay readable, and a missing __str__ falls back to __repr__.
What does `!r` change inside `__repr__`, and why does it matter for a string field?+
!r applies repr() to the field, so a string value keeps its quotes and shows as '2' instead of 2. Without it, Point('2', 3) and Point(2, 3) produce the same text and the representation no longer identifies the object's actual state.