
The repr() Function in Python
Today, we'll discuss Python's repr() function.
repr()
This built-in Python function returns a string that represents the object passed to it.
The purpose of repr() is to provide a representation of the object, ideally in the form of valid Python code that can recreate the object.
If that's not possible, the string should still be informative and clearly describe the object's state. For instance, it can be used for logging information or debugging the program.
Let's look at some practical examples to better understand how repr() works.
Example 1: Basic Objects
Consider a simple object like an integer:
x = 42
Now, use repr() with the variable x as the argument.
print(repr(x))
The function returns the same value as a string.
'42'
As we can see, `repr()` provides a string representation that includes quotes, whereas the variable itself holds an integer.
Example 2: Lists and Dictionaries
Let's see how `repr()` works with more complex data structures like lists and dictionaries:
Create a list with some numeric and alphanumeric values.
lista = [1, 2, 3, "quattro"]
If you use repr() with the list as an argument, it returns the content as a string.
print(repr(lista))
Output: '[1, 2, 3, 'quattro']'
This way, if you want to create another list with the same contents, you can do so easily.
You can achieve the same result with a dictionary.
dizionario = {"a": 1, "b": 2}
Again, repr() returns the dictionary's content as a string.
print(repr(dizionario))
'{'a': 1, 'b': 2}'
In these cases, repr() provides a string that clearly shows the structure and content of lists and dictionaries.
Example 3: Objects and Classes
Now let's see an example with a custom object.
Suppose you have a class `Person`:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name={self.name!r}, age={self.age!r})"
This class implements the special method `__repr__()`.
This method is automatically called when you use the repr() function on an instance of the class.
For example, create an instance of the class:
p = Person("Tom", 25)
Then use the repr() function with the object as an argument.
print(repr(p))
In this case, the function calls the object's __repr__ method and prints the custom string.
'Person(name='Tom', age=25)'
The returned string provides a clear representation of the `Person` object.
Difference between repr() and str(). It's important to distinguish between these two functions. Both return a string. However, repr() accesses the object's `__repr__` attribute, while the str() function accesses the object's `__str__` attribute. Generally, repr() is used by developers, while str() is intended to return a readable, user-friendly string for end users.
I hope this guide has clarified how and when to use the repr() function.