`__repr__` vs `__str__`
__repr__ is the unambiguous developer representation of an object, used by the REPL and repr(). __str__ is the readable user representation, used by print and str(). If __str__ is missing, Python falls back to __repr__.
Detailed Explanation
Every object can explain itself in two tones. __repr__ is for you, the programmer. It should say what the object is and how you might reconstruct it. Order(sku='A-1', qty=2) is a good repr. __str__ is for logs and UIs that do not want the class name. A-1 × 2 is a good str.
repr(x) calls x.__repr__(). str(x) calls x.__str__() if it exists, else __repr__. print(x) uses str. The interactive REPL uses repr for the value of an expression. f-strings use str by default and repr with {x!r}.
The documented ideal is that eval(repr(obj)) equals obj for simple types. That is true for lists, dicts, and many builtins. It is a guideline, not a requirement. For your classes, a repr that includes the class name and the fields that define identity is enough. If reconstruction is impossible (a socket, a thread), put ... and useful ids in the repr, and never pretend it is eval-able.
__repr__ should not be expensive and should not raise. A repr that hits the network or walks a huge graph will make debugging worse. Truncate collections. Use !r when embedding other objects so nested strings stay quoted.
Dataclasses generate both. The default dataclass repr lists fields. You can disable it per field with repr=False for secrets and huge blobs.
__format__ is a third hook for format(obj, spec) and f-string specs. Implement it when the object has a natural format language (dates, money). Otherwise __str__ is enough.
If you implement only one, implement __repr__. You get a decent print for free, and the REPL stays informative. Implementing only __str__ leaves the REPL showing <Order object at 0x...>.
Code Examples
class Order:
def __init__(self, sku: str, qty: int):
self.sku = sku
self.qty = qty
def __repr__(self) -> str:
return f"Order(sku={self.sku!r}, qty={self.qty})"
def __str__(self) -> str:
return f"{self.sku} × {self.qty}"
line = Order("A-1", 2)
print(repr(line)) # Order(sku='A-1', qty=2)
print(str(line)) # A-1 × 2
print(f"{line} / {line!r}") # A-1 × 2 / Order(sku='A-1', qty=2)# Missing __str__ falls back to __repr__.
class Sku:
def __init__(self, code: str):
self.code = code
def __repr__(self) -> str:
return f"Sku({self.code!r})"
print(Sku("A-1")) # Sku('A-1')Common Gotchas
Putting secrets in `__repr__`
the REPL, logs, and exception messages will print them. Mark dataclass fields `repr=False`.
A slow or recursive `__repr__`
containers call `repr` on elements. Guard self-references and cap length.
`__str__` that returns a non-str
Python raises `TypeError`. Always return `str`.
`!r` in f-strings is `repr`
use it in log lines when you need quotes around strings so spaces are visible.