Python consists of several special methods. The names of these special methods are preceded and followed by two underscore characters – __methodname__(). With these special methods, we can initialize, compare or print objects. These methods can be called when the objects are created. In this article, we shall be talking about one such special method in by – the repr method, which is represented by __repr__().
What is the repr method?
The repr method in python is used to generate a string representation of a given object. When the repr() method is invoked, it will automatically call the object’s __repr__() function. It will return a string which would be a printable representation of the given object.
The syntax of the repr() method is:
repr(obj)
It accepts only one argument which is the object whose string representation has to be printed.
We can also override the __repr__() method to change the working of the repr() function.
Working of the repr function
Let us now understand how the repr function works in python.
Here, we will try to print a variable ‘city’ containing the string value ‘Chicago’ enclosed in single quotes. First, we shall print the ‘city’ variable.
city = 'Chicago'
print(city)
The output will be the variable data without any quotes.
Chicago
But, if we use the repr function, it will return ‘Chicago’ after wrapping it in double quotes.
city = 'Chicago'
repr(city)
Output:
''Chicago''
If we use print() along with the repr() function, then it will print the expression as it was passed. Here, the string ‘Chicago‘ will be printed in single quotes.
print(repr(city))
Output:
'Chicago'
For numeric values also, the repr() function will return a printable representation for that variable.
x = 11
repr(x)
Output:
'11'
This will hold true for boolean values also.
x = True
repr(x)
Output:
'True'
Using repr to call class objects
The repr() function can also be called by class objects.
Let us take a user-defined class named ‘Product’. There will be two variables in the product class – ‘name’ and ‘price’. We will initialize the variables in the __init__() function first.
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
Now, after creating the class Product, we shall create an object of the Product class. We shall pass two values to the object.
obj = Product('Bread', 50)
After creating the object, we shall pass the object as the argument to the repr() function. The repr() function will convert object to strings as and when required. We shall now print the repr() function’s output.
print(obj)
The output is:
<__main__.Product object at 0x7fb6351fc750>
Here we received the object of Product class inside angular brackets. It contains the name and location of the object. To print the actual object values, we shall override the __repr__() function.
So, we shall override the __repr__() function to print the ‘name’ and ‘price’ of the object of Product class. It shall return a formatted string containing the name and age.
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def __repr__(self):
return f'Product Details : name = {self.name}, price = {self.price}'
Now, after creating the class Product, we shall create an object of Product class. We shall pass two values to the object.
obj = Product('Bread', 50)
We shall now print the repr() function’s output.
print(obj)
The output is:
Product Details : name = Bread, price = 50
The Entire Code is:
#Without overriding
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
obj = Product('Bread', 50)
print(obj)
#With overriding
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def __repr__(self):
return f'Product Details : name = {self.name}, price = {self.price}'
obj = Product('Bread', 50)
print(obj)
__repr__() vs __str__()
We use both the special functions – __repr__() and __str__() for obtaining string representation of a given object. The difference between the two is that the __str__() function will return a value which is user friendly whereas the __repr__() function will return a value in its unambiguous form.
Suppose if we take a string ‘python’ and pass it to both the functions. Then, __str__() will print the string as it is passed by the user whereas the __repr__() function will pass the string as it is represented in the string format.
For __str__():
x = 'python'
str(x)
Output:
'python'
For __repr__():
repr(x)
Output:
''python''
For printing date, the __str()__ function will only print the current date. For that, we will import datetime and print it for the current time.
import datetime
date = datetime.datetime.now()
str(date)
The output will be:
'2021-06-15 11:15:53.494880'
But, if we use the repr() function, then it will print the official form of representation of the ‘date’ object.
import datetime
date = datetime.datetime.now()
repr(date)
Output:
'datetime.datetime(2021, 6, 15, 11, 15, 53, 494880)'
FAQ’s
Which function is better, actually depends upon you and your requirements. If your aim is to use it for the users, then __str__() is ideal. But if you want to use it for developers to aid in debugging, then __repr__() is preferred.
That was all for repr in python. If you have any questions, let us know in the comments below.
Until next time, Keep Learning!