Complete guide to Python's repr function covering basic usage, custom objects, and practical examples of string representations.
Last modified April 11, 2025
This comprehensive guide explores Python’s repr function, which returns a string representation of an object. We’ll cover basic usage, custom objects, and practical examples of creating unambiguous object representations.
The repr function returns a string containing a printable representation of an object. It aims to be unambiguous and often looks like valid Python code to recreate the object.
Key characteristics: meant for debugging, often returns valid Python code, used by Python when printing objects in containers, and calls the object’s repr method.
Here’s simple usage with different built-in types showing how repr creates string representations of common Python objects.
basic_repr.py
print(repr(42)) # ‘42’ print(repr(3.14)) # ‘3.14’
print(repr(‘hello’)) # “‘hello’” print(repr(“world”)) # ‘“world”’
print(repr([1, 2, 3])) # ‘[1, 2, 3]’ print(repr({‘a’: 1})) # “{‘a’: 1}”
This example shows repr with different built-in types. For numbers, it returns the number as a string. For strings, it adds quotes.
The string representation includes the quotes themselves, making it clear it’s a string. For containers, it shows the complete syntax to recreate them.
This example demonstrates the key differences between repr and str representations of objects.
repr_vs_str.py
import datetime
now = datetime.datetime.now()
print(str(now)) # ‘2025-04-11 14:30:15.123456’ print(repr(now)) # ‘datetime.datetime(2025, 4, 11, 14, 30, 15, 123456)’
class Example: def str(self): return “User-friendly string”
def __repr__(self):
return "Example()"
e = Example() print(str(e)) # ‘User-friendly string’ print(repr(e)) # ‘Example()’
The datetime example shows str provides a readable format while repr shows how to recreate the object. The custom class shows the same distinction.
repr is meant for developers while str is for end users. When printing containers, Python uses repr for elements.
You can make custom objects work properly with repr by implementing the repr special method.
custom_repr.py
class Point: def init(self, x, y): self.x = x self.y = y
def __repr__(self):
return f"Point({self.x}, {self.y})"
def __str__(self):
return f"({self.x}, {self.y})"
p = Point(3, 4) print(repr(p)) # ‘Point(3, 4)’ print(str(p)) # ‘(3, 4)’ print([p]) # [Point(3, 4)]
The Point class implements both repr and str. repr shows how to recreate the object while str shows a simplified version.
When the point is in a list, Python uses repr for its representation, demonstrating why repr is important.
This example shows how repr can be useful for debugging by providing more detailed object information.
debugging.py
data = { ’name’: ‘Alice’, ‘age’: 30, ‘scores’: [95, 88, 92], ‘active’: True }
print(“Debug output:”) print(repr(data))
user_input = “Hello\nWorld” print(“User input representation:”) print(repr(user_input)) # Shows the newline character: ‘Hello\nWorld’
The dictionary example shows how repr displays the complete structure with all types visible. This is invaluable for debugging.
The string example demonstrates how repr makes special characters visible, unlike regular printing which would show an actual newline.
While repr generally works with all objects, this example shows edge cases and how to handle them.
errors.py
class BadRepr: def repr(self): raise Exception(“Broken repr”)
try: print(repr(BadRepr())) except Exception as e: print(f"Error in repr: {e}")
class NoRepr: pass
print(repr(NoRepr())) # Shows default object representation
The first example shows what happens when repr raises an exception. The second shows the default representation when no repr is defined.
The default representation includes the class name and memory address, which is better than nothing but not as useful as a custom implementation.
Implement repr: For all classes you create
Make it unambiguous: Representation should clearly show object state
Aim for recreatable: Ideal repr is valid Python code to recreate object
Include all state: Don’t omit important attributes
Differentiate from str: repr for developers, str for users
My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.
List all Python tutorials.