Understanding repr in Python
The repr function in Python is a built-in function that returns a string representation of an object. This representation is intended to be unambiguous and, ideally, should allow the object to be recreated using the eval() function. The repr function is particularly useful for debugging, as it provides a detailed description of the object, which can be used to understand its structure and content.
Usage of repr
The repr function can be applied to almost any Python object to convert it into a string representation. This is especially useful when dealing with complex data types or when you need to ensure that the string representation of an object is unambiguous and informative.
Example with Lists
Lists are one of the complex data types in Python that can be converted to a string representation using repr. Here is an example demonstrating how repr can be used with lists:
repr([1, 2, 3])
# [Output: '[1, 2, 3]'](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-6/145)
x = [1]
x.append(2)
x.append([3, 4])
'the list x is ' + repr(x)
# [Output: 'the list x is [1, 2, [3, 4]]'](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-6/145)
In this example, the repr function is used to convert the list x to a string representation. This string is then concatenated with another string to form the final output. Without using repr, attempting to concatenate a list directly with a string would result in an error, as Python would not know how to handle such an operation.
Example with Built-in Functions
The repr function can also be used with built-in Python functions to obtain a string that describes the function. For instance:
repr(len)
# [Output: '<built-in function len>'](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-6/143)
In this case, Python returns a string—<built-in function len>—that describes the len function. Although it does not provide the code that implements the function, it gives a clear indication of what the function is.
Overriding __repr__ in a Class
In Python, the __repr__ method is a special method used to define a string representation of an object that is primarily intended for debugging and development purposes. This representation should ideally be unambiguous and, if possible, match the syntax necessary to recreate the object using the eval() function.
To illustrate how __repr__ can be overridden in a class, consider the following example:
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
#1 !r requests the __repr__ method to be used for string interpolation.
In this Task class, the __repr__ method is defined to return a string that includes the class name and the values of its attributes. The !r conversion flag is used for title and desc to ensure that their __repr__ methods are called, which includes quotation marks around string literals. This is crucial for making the string representation evaluable by eval().
Purpose and Usage of __repr__
The primary purpose of __repr__ is to provide a string that can be used to recreate the object. This is particularly useful for developers during debugging. For example:
task = Task("Laundry", "Wash clothes", 3)
task_repr = repr(task)
task_repr_eval = eval(task_repr)
print(type(task_repr_eval))
# [Output: <class '__main__.Task'>](https://livebook.manning.com/book/python-how-to/chapter-8/243)
print(task_repr_eval)
# [Output: Laundry: Wash clothes, urgency level 3](https://livebook.manning.com/book/python-how-to/chapter-8/243)
In this example, the repr() function is used to obtain the string representation of the task object, which can then be evaluated back into a Task object using eval().
Importance of the !r Flag
The !r flag is used in the __repr__ method to ensure that string attributes are represented with quotation marks. This is important because without the !r flag, the string representation would not include the necessary quotation marks, making it impossible to recreate the object using eval(). Consider the following example without the !r flag:
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}, {self.desc}, {self.urgency})"
task = Task("Laundry", "Wash clothes", 3)
print(repr(task))
# [Output: Task(Laundry, Wash clothes, 3)](https://livebook.manning.com/book/python-how-to/chapter-8/243)
In this case, the output lacks quotation marks around the string literals, which leads to a SyntaxError when attempting to evaluate the string:
eval(repr(task))
# [ERROR: SyntaxError: invalid syntax. Perhaps you forgot a comma?](https://livebook.manning.com/book/python-how-to/chapter-8/243)
The absence of quotation marks means that the string literals are interpreted as variable names, which are undefined, resulting in an error. Therefore, using the !r flag is essential for ensuring that the __repr__ output is a valid Python expression.
| Book Title | Usage of repr | Technical Depth | Connections to Other Concepts | Examples Used | Practical Application |
|------------|---------------|-----------------|-------------------------------|---------------|-----------------------|
| [The Quick Python Book, Fourth Edition](https://www.manning.com/books/the-quick-python-book-fourth-edition) | Discusses `repr` as a tool for obtaining a formal string representation of objects, useful for debugging. [more](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-6/143) | Provides a basic understanding of `repr` and its utility in converting complex data types to strings. [more](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-6/143) | Connects `repr` to its role in debugging and understanding object structures. [more](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-6/143) | Includes examples with lists and built-in functions to demonstrate `repr` usage. [more](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-6/145) | Highlights `repr`'s role in debugging and ensuring unambiguous string representations. [more](https://livebook.manning.com/book/the-quick-python-book-fourth-edition/chapter-6/143) |
| [Python How-To](https://www.manning.com/books/python-how-to) | Focuses on the `__repr__` method for defining string representations of objects, emphasizing its role in debugging. [more](https://livebook.manning.com/book/python-how-to/chapter-8/243) | Explores overriding `__repr__` in classes and the importance of the `!r` flag for evaluable string representations. [more](https://livebook.manning.com/book/python-how-to/chapter-8/243) | Compares `__repr__` with `__str__`, highlighting their different purposes. [more](https://livebook.manning.com/book/python-how-to/chapter-8/243) | Provides class-based examples to illustrate `__repr__` usage and the significance of the `!r` flag. [more](https://livebook.manning.com/book/python-how-to/chapter-8/243) | Demonstrates how `__repr__` can be used to recreate objects using `eval()`, showcasing its practical utility in development. [more](https://livebook.manning.com/book/python-how-to/chapter-8/243) |
FAQ (Frequently asked questions)
How can you override the repr method in a Python class?
What is the purpose of overriding the repr method in a class?
What does the '!r' in the repr method do?
What is the purpose of the repr function in Python?
How does repr help in debugging?
What does repr return for complex objects?
What does repr([1, 2, 3]) return?