What is the difference between __str__ and __repr__
· Category: Python Programming
What is the difference between str and repr
Core Difference
__str__ is for the end user: readable, informal, and concise. __repr__ is for the developer: unambiguous and ideally valid Python code that could recreate the object.
Implementation Example
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Point({self.x}, {self.y})"
def __repr__(self):
return f"Point({self.x!r}, {self.y!r})"
p = Point(2, 3)
print(str(p)) # Point(2, 3)
print(repr(p)) # Point(2, 3)
When to Define Each
Always define __repr__. If __str__ is missing, Python falls back to __repr__. Use __str__ only when you need a separate, more user-friendly display. For logging, prefer __repr__ because it preserves type information.
If you are building custom types frequently, review Python classes and objects for OOP fundamentals, and consider adding Python type hints to make your repr output even more informative during debugging.