Define a def __str__(self) -> str: method on your class returning a clean, human-readable string representation—which Python automatically calls inside print(obj), str(obj), and f-strings (f"{obj}")—and pair it with __repr__(self) -> str: for unambiguous developer/debugging output inside REPL sessions, tracebacks, and containers ([obj]).
Basic Example
class Product:
def __init__(self, sku: str, name: str, price: float) -> None:
self.sku = sku
self.name = name
self.price = price
# 1. User-facing display string: used by print(obj), str(obj), and f"{obj}"
def __str__(self) -> str:
return f"{self.name} (${self.price:.2f})"
# 2. Developer/debug string: used by repr(obj), REPL, and inside lists/dicts
def __repr__(self) -> str:
return f"Product(sku={self.sku!r}, name={self.name!r}, price={self.price!r})"
item = Product("KB-01", "Mechanical Keyboard", 89.5)
print(item) # Calls __str__ -> Output: Mechanical Keyboard ($89.50)
print(f"Item: {item}") # Calls __str__ -> Output: Item: Mechanical Keyboard ($89.50)
print([item]) # Calls __repr__ -> Output: [Product(sku='KB-01', name='Mechanical Keyboard', price=89.5)]
print(f"{item!r}") # Forces __repr__-> Output: Product(sku='KB-01', name='Mechanical Keyboard', price=89.5)
Key Details & Edge Cases
- Printing a list or dict of objects calls
__repr__, NOT__str__:- When you run
print([item])orprint({"first": item}), Python callsrepr(item)on every element inside the container—never__str__. If you only define__str__without__repr__, printing a list still outputs.
- When you run
- Fallback hierarchy (
__str__falls back to__repr__, never the reverse):- If a class defines only
__repr__,print(obj)andstr(obj)automatically fall back to__repr__. - If a class defines only
__str__,repr(obj)and container printing still show<ClassName object at 0x...>. Therefore, always implement__repr__first, and add__str__whenever end-user output should differ from the developer representation.
- If a class defines only
__str__MUST return an exactstrinstance (or raiseTypeError):- Returning
None, anint, or abytesobject from__str__raisesTypeError: __str__ returned non-string (type NoneType). Always ensure every code path returns astr.
- Returning
- Avoid infinite recursion inside
__str__:- Calling
str(self)orf"{self}"inside__str__triggersRecursionError: maximum recursion depth exceeded. Format individual attributes directly (self.name,self.price) instead.
- Calling
- Automatic
__repr__generation with:- Decorating a class with
auto-generates a clean__repr__out of the box (and__str__falls back to it automatically), letting you override only__str__when you want custom user-facing formatting.
- Decorating a class with
Comparison of String Representation Dunder Methods in Python
| Method | Triggered By | Target Audience | Fallback Behavior | Best Used When |
|---|---|---|---|---|
__str__(self) |
print(x), str(x), f"{x}" |
End users, logs, UI messages | Falls back to __repr__ if undefined |
Formatting readable summaries (e.g., "Mechanical Keyboard ($89.50)"). |
__repr__(self) |
repr(x), f"{x!r}", REPL, [x] |
Developers, debuggers, tracebacks | Falls back to <Cls object at 0x...> |
Unambiguous constructor-style string (Product(sku='KB-01', ...)). |
__format__(self, spec) |
f"{x:spec}", format(x, spec) |
Custom format specifiers | Falls back to str(x) when spec == "" |
Supporting custom format codes like f"{product:short}" or f"{money:EUR}". |
You must log in or register to comment.
