The __repr__()
is used to get a machine-friendly string representation of an object. Compared to the __str__() method which returns a human-friendly string representation , the __repr__()
method should provide a more complete representation of the object. This method gets called indirectly when we use the builtin repr()
function.
On a call to print an object, the print()
function calls the __repr__()
method if the object involved does not have __str__()
method overridden.
Typically, any Python object have the __repr__()
method defined by default. However, the value returned is usually a general summary of the object, the name of the class it belongs to, or some other information that provides an easy way to identify the object. In the case with buitin data types, the function usually returns the value held by the object.
Example with builtin data types
#Example with list
L = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(ascii(L.__repr__())) #same as print(L)
#Example with tuples
T = ("Pynerds", "Python", "Django", "Flask")
print(T.__repr__()) #same as print(T)
D = {1: "One", 2: "Two", 3: "Three"}
print(D.__repr__())#Same as print(D)
Example with other objects
#Example with a function
def add(a, b):
return a + b
print(add.__repr__())#Same as print(func)
#Example with class instances
class Example:
pass
e = Example()
print(e.__repr__()) #Same as print(e)
Overriding the __repr__() method for custom objects
We can override the __repr__()
methods for a class instance to make the value returned more relevant and meaningful.
The print() function will call the __repr__ method if the default __str__ method is not overriden.
#overriding __repr__() method for objects
class Example:
def __repr__(self):
return "This is an Example instance"
e = Example()
#The __str__() is not defined, the print() function will use __repr__ instead
print(e)
When we define an instance method named __repr__()
in a class(as in above), it effectively overrides the default method.
It is worth noting that the method should strictly return a string. It should also not define any additional required arguments apart from the compulsory "self
", Otherwise a TypeError
will be raised on an attempt to print the object.
let us look at another example with a class inherited from the builtin list()
class.
class MyList(list):
def __init__(self, *args):
super().__init__(args)
#Override the default way a list is represented
def __repr__(self):
S = ", ".join([str(i) for i in self])
return "< %s> "%S
L = MyList(1, 2, 3, 4)
L1 = MyList(*range(10))
L2 = MyList("Pynerds", "Python", "Django", "Flask")
print(L)
print(L1)
print(L2)
# a nested MyList Object
L3 = MyList(MyList(1, 2), MyList(3, 4, 5), MyList(6, 7, 8, 9))
print(L3)
As you can see above, we have effectively overridden the way a list is represented using the custom class MyList
. The example includes some advanced stuff but it is easy to understand if we break it as follows:
MyList(list)
: Create a class MyList that is a subclass of the built-in list class :def __init__(self, *args)...
- Create an __init__ instance method that takes in the values given at instantiation and perform the necessary list initialization.-
def __repr__(self)....
- Override the built-in__repr__
method to change how the list is represented when printed.
The difference between __repr__() and __str__() methods
In literal language the __repr__ ()
method returns the “official” string representation of an object. The string returned is used when printing the object or informing the user of the object state. Thus the returned string needs to capture the object's state more accurately and in an unambiguous way.
On the other hand, the __str__()
method usually returns “informal” string representation of an object. This method is used for display purposes and usually produces a more user-friendly string representation than __repr__()
. It is the method that gets called when we use the builtin function, str().
In most cases the two methods usually returns similar values but they do not need to be always the same.
Conclusion:
- The
__repr__()
method returns the printable representation of an object. - All objects have the
__repr__()
method defined by default. - This is the method that is typically called when printing an object using the builtin
print()
function. - We can override the method for custom objects to make the printed value more specific and meaningful.
- The
__repr__()
method should strictly return a string, it should also not define any required argument apart fromself
. - While the
__repr__()
function returns the "official" representation of an object, the__str__
method returns a more user friendly representation of an object.