__repr__ is a Python special method that returns an official, unambiguous string representation of an object. Use it primarily for debugging and development, especially when inspecting instances in an interactive console. Ideally, the returned text resembles valid Python instantiation code and can recreate an equivalent object. section 8.4.2 section 8.4.3
Implement and use __repr__ with these practical rules:
- Define it as an instance method and return a string containing the information needed to represent the instance. section 8.4.2
- Use repr(instance), rather than Class.__repr__(instance), to invoke it directly. section 8.4.2
- Use !r for string attributes in an f-string so their quotes remain part of the representation and the result can be parsed as Python code. section 8.4.3
- Prefer implementing both __str__ and __repr__; if only one is implemented, choose __repr__ because Python uses it when __str__ is absent. section 8.4.4
Representing a Task instance
class Task: def __init__(self, title, desc, urgency): self.title = title self.desc = desc self.urgency = urgency def __repr__(self): return f"Task({self.title!r}, {self.desc!r}, {self.urgency})" task = Task("Laundry", "Wash clothes", 3) print(repr(task)) # Task('Laundry', 'Wash clothes', 3) The quoted strings preserve valid constructor syntax. Without !r, eval(repr(task)) raises a SyntaxError because the string values are not quoted. section 8.4.2 section 8.4.3
Listing 8.11 Overriding __repr__ in a class
class Task:
def __init__(self, title, desc, urgency):
self.title = title
self.desc = desc
self.urgency = urgency
def __str__(self):
return f"{self.title}: {self.desc}, urgency level {self.urgency}"
def __repr__(self):
return f"Task({self.title!r}, {self.desc!r}, {self.urgency})" #1
Inspect the complete Task implementation, including the contrasting __str__ method and the !r conversions. section 8.4.2


