Difference between __repr__ and __str__ in Python

When implementing a class in Python, you usually implement the __repr__ and __str__ methods.

  1. __str__ should print a readable message
  2. __repr__ should print a message that is unambigous (e.g. name of an identifier, class name, etc).

You can see __str__ as a method for users and __repr__ as a method for developers.

Here is an implementation example for a class that simply stores an attribute (data).

class Length():
    def __init__(self, data):
        self.data = data

__str__ is called when a user calls the print() function while __repr__ is called when a user just type the name of the instance:

>>> l = Length([1,2,3])
>>> print(l)    # should call __str__ if it exists
<__main__.Length at 0x7faf240acc18>
>>> l
<__main__.Length object at 0x7faf240acc18>

By default when no __str__ or __repr__ methods are defined, the __repr__ returns the name of the class (Length) and __str__ calls __repr__.

Now, let us define the __repr__ method ourself to be more explicit:

class Length():
    def __init__(self, data):
        self.data = data
    def __repr__(self):
        return "Length(%s) " % (len(self.data))

we could use it as follows:

>>> l = Length([1,2,3])
>>> print(l)     # calls __str__
Length(3)
>>> l            # calls __repr__
Length(3, 140175447410224)

When using the print() function in Python, the __str__ is called (if found) and otherwise, __repr__.

class Length():
    def __init__(self, data):
        self.data = data
    def __repr__(self):
        return "Length(%s, %s) " % (len(self.data), id(self))
    def __str__(self):
        return "Length(%s) " % (len(self.data))

so now __repr__ and __str__ have different behaviours:

>>> l = Length([1,2,3])
>>> print(l)     # calls __str__
Length(3)
>>> l            # calls __repr__
Length(3, 140175447410224)
Please follow and like us:
This entry was posted in Python and tagged , . Bookmark the permalink.

3 Responses to Difference between __repr__ and __str__ in Python

Leave a Reply

Your email address will not be published. Required fields are marked *