Python __repr__ Method
Last modified November 18, 2026 Python 3.15
The __repr__ method returns the official string representation of
an object. It is used by repr(), by the interactive interpreter,
and as the fallback when __str__ is missing. A good
representation is unambiguous and, where practical, looks like an expression
that could recreate the object. This article covers the basic method, its
relationship with __str__, the !r flag, debugging
output, inheritance, containers and round-tripping through
eval().
A basic __repr__
The method returns a string. Printing the result of
repr() shows the representation; printing the object itself uses
the same method when no __str__ is defined.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Point({self.x}, {self.y})"
p = Point(3, 4)
print(repr(p))
print(p)
Both calls produced the same text. The representation includes the class
name and the values, which makes it much more informative than the default
<__main__.Point object at 0x...>.
$ python basic_repr.py Point(3, 4) Point(3, 4)
__repr__ versus __str__
__repr__ aims at developers and should be precise;
__str__ aims at end users and should be readable. When only
__repr__ exists, str() falls back to it.
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __repr__(self):
return f"Book({self.title!r}, {self.author!r})"
def __str__(self):
return f"{self.title} by {self.author}"
book = Book("Python Crash Course", "Eric Matthes")
print(repr(book))
print(str(book))
print(f"{book}")
print(f"{book!r}")
A plain f-string uses __format__, which falls back to
__str__; the !r flag forces __repr__.
The quoted values in the representation come from the !r
conversion inside the method itself.
$ python repr_vs_str.py
Book('Python Crash Course', 'Eric Matthes')
Python Crash Course by Eric Matthes
Python Crash Course by Eric Matthes
Book('Python Crash Course', 'Eric Matthes')
The !r conversion flag
Using !r when interpolating values automatically calls
repr() on them. This preserves quotes and escapes, which makes
output unambiguous and is safer than adding quote characters by hand.
class Label:
def __init__(self, text):
self.text = text
def __repr__(self):
return f"Label({self.text!r})"
for value in ("plain", "it's quoted", "line\nbreak"):
print(repr(Label(value)))
print(f"{'raw'} vs {'represented'!r}")
Python chose double quotes for the string containing an apostrophe and escaped the newline. Hand-written quote characters would have produced a broken or misleading representation in those cases.
$ python r_flag.py
Label('plain')
Label("it's quoted")
Label('line\nbreak')
raw vs 'represented'
Unambiguous debugging output
For a container-like object, the representation should show all stored
values. Reusing the built-in repr() of those values keeps nested
structures accurate.
class ShoppingCart:
def __init__(self):
self.items = []
def add_item(self, product, quantity):
self.items.append((product, quantity))
def __repr__(self):
contents = ", ".join(repr(item) for item in self.items)
return f"ShoppingCart([{contents}])"
cart = ShoppingCart()
cart.add_item("Apple", 3)
cart.add_item("Banana", 5)
print(repr(cart))
The full state — every product and quantity — is visible at a glance. Using
repr() on each tuple rather than formatting it manually keeps the
quotes and structure correct.
$ python debugging_repr.py
ShoppingCart([('Apple', 3), ('Banana', 5)])
Inheritance
A representation should name the actual class, not a hard-coded parent.
Using self.__class__.__name__ makes the method work for
subclasses without changes.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"{self.__class__.__name__}({self.name!r}, {self.age})"
class Employee(Person):
def __init__(self, name, age, employee_id):
super().__init__(name, age)
self.employee_id = employee_id
def __repr__(self):
return (f"{self.__class__.__name__}({self.name!r}, "
f"{self.age}, {self.employee_id!r})")
emp = Employee("John Doe", 30, "E12345")
print(repr(emp))
The subclass includes the parent's fields plus its own, and the class name
is Employee. Reusing the parent's method would have omitted the
employee ID.
$ python inheritance_repr.py
Employee('John Doe', 30, 'E12345')
Custom containers
A container should follow the conventions of built-in containers: show the class name and the elements in a comma-separated list inside brackets or parentheses.
class TaggedList:
def __init__(self, tag, *items):
self.tag = tag
self.items = list(items)
def __repr__(self):
items_repr = ", ".join(repr(item) for item in self.items)
return f"{self.__class__.__name__}({self.tag!r}, {items_repr})"
def __str__(self):
return f"{self.tag}: {', '.join(str(item) for item in self.items)}"
tags = TaggedList("Numbers", 1, 2, 3, 4)
print(repr(tags))
print(tags)
The representation looks like a constructor call, while the user-facing string is a short description. Having both is common for library classes.
$ python container_repr.py
TaggedList('Numbers', 1, 2, 3, 4)
Numbers: 1, 2, 3, 4
Round-tripping with eval()
When the representation looks like a valid constructor call,
eval(repr(obj)) can recreate the object. This is a useful quality
check, though it requires the class to be importable in the evaluating
scope.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Point({self.x!r}, {self.y!r})"
p = Point(3, 4)
text = repr(p)
clone = eval(text)
print(text)
print(clone.x, clone.y)
print(type(clone).__name__)
The text was evaluated back into a Point with identical
coordinates. Not every class can support this — objects tied to external
resources usually cannot — but it is a good goal for simple value types.
$ python roundtrip.py Point(3, 4) 3 4 Point
Best practices
A few rules keep __repr__ useful:
- Include the class name and all attributes needed to identify the object.
- Use
!ron interpolated values so quotes and escapes are preserved. - Prefer a representation that could be evaluated back into the object.
- Use
self.__class__.__name__so subclasses are described correctly. - Write
__str__separately when users need a friendlier message.
Source
object.__repr__ - Python documentation
Format string syntax - Python documentation
In this article we have implemented the __repr__ method. We have
covered the basic representation, the difference from __str__,
the !r flag, debugging output, inheritance, containers and
round-tripping with eval(). For related topics, see
Python __str__ method,
Python __format__ method, and
Python f-strings.
Author
List all Python tutorials.