How do you customize how class instances print using __str__ in Python? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you customize how class instances print using str in Python?

message-square
0

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]) or print({"first": item}), Python calls repr(item) on every element inside the container—never __str__. If you only define __str__ without __repr__, printing a list still outputs [<__main__.Product object at 0x...>].
  • Fallback hierarchy (__str__ falls back to __repr__, never the reverse):
    • If a class defines only __repr__, print(obj) and str(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.
  • __str__ MUST return an exact str instance (or raise TypeError):
    • Returning None, an int, or a bytes object from __str__ raises TypeError: __str__ returned non-string (type NoneType). Always ensure every code path returns a str.
  • Avoid infinite recursion inside __str__:
    • Calling str(self) or f"{self}" inside __str__ triggers RecursionError: maximum recursion depth exceeded. Format individual attributes directly (self.name, self.price) instead.
  • Automatic __repr__ generation with @dataclass:
    • Decorating a class with @dataclass 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.

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}".