In Python, the repr() function is used to obtain the string representation of an object. This string is a valid expression that can be used to recreate the object. The function is commonly used for debugging and logging purposes.
Ideally, the return value of the repr() function can be used to reconstruct the object:
lst = [1, 2, 3]
lst2 = eval(repr(lst))
print(lst == lst2) # True
Difference from the str() function
The str() function returns a user-friendly, readable string; whereas repr() returns a precise representation that is developer-friendly.
The __repr__() method
The repr() function actually calls the object's __repr__() method:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Person: {self.name}, {self.age}"
def __repr__(self):
return f"Person('{self.name}', {self.age})"
p = Person("Alice", 30)
print(str(p)) # Person: Alice, 30
print(repr(p)) # Person('Alice', 30)
p2 = eval(repr(p))
print(p2.name) # Alice
The value returned by __repr__() should be a valid expression that can be used to reconstruct the object.