Understanding `__str__` vs `__repr__` in Python
Python provides __str__() and __repr__() so classes can control how their instances appear as text. They serve related but different audiences.
__str__: Human-Friendly Output
str(obj) and usually print(obj) use __str__():
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}, age {self.age}"
person = Person("Alice", 30)
print(person)Output:
Alice, age 30Use __str__() when you want a concise representation aimed at users or normal application output.
__repr__: Developer-Oriented Representation
repr(obj) uses __repr__():
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name={self.name!r}, age={self.age!r})"The !r conversion uses repr() for the attribute value, which makes strings and other values less ambiguous:
Person(name='Alice', age=30)A good __repr__() should be unambiguous and useful during debugging. When practical, it may resemble valid Python code that could recreate an equivalent object, but that is a guideline rather than a strict requirement.
Define Both Together
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name={self.name!r}, age={self.age!r})"
def __str__(self):
return f"{self.name}, age {self.age}"Then:
person = Person("Alice", 30)
print(str(person))
print(repr(person))What If __str__ Is Missing?
If a class does not define __str__(), Python falls back to __repr__() for str(obj):
class Item:
def __repr__(self):
return "Item()"
print(str(Item())) # Item()That is why implementing __repr__() is often the more important minimum for developer-facing classes.
Containers Usually Use repr
When an object appears inside a list or dictionary, Python normally uses its repr() representation:
people = [Person("Alice", 30)]
print(people)This makes __repr__() especially useful in logs, debugging sessions, and test failures.
Dataclasses
For data-oriented classes, @dataclass automatically generates a useful __repr__():
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: intYou only need a custom implementation when the generated representation is not suitable.
Conclusion
Use __str__() for readable user-facing text and __repr__() for precise developer-facing diagnostics. If you only implement one, a useful __repr__() is usually the better default because Python can fall back to it for string conversion.