-->

__str__ vs __repr__ in Python

By: Priya Philip 1 month ago

Both __repr__ and __str__ are used to represent objects in different ways.The default implementation of __repr__ for a str value can be called as an argument to eval, and the return value would be a valid string object.


>>>repr(y)
"'a string'"
>>>y2=eval(repr(y))
>>>y==y2
True

Lets see how to implement these two methods:


class Book:
    name = ""
    publish = 0

    def __init__(self, Bookname, Bookpublished):
        self.name = Bookname
        self.publish = Bookpublished

  
    def __repr__(self):
        return {'Bookname':self.name, 'Bookpublished':self.publish}

    
    def __str__(self):
        return 'Book(Bookname='+self.name+', Bookpublished='+str(self.publish)+ ')'

Python __str__():

__str__ goal is to be readable. This method returns the string representation of the object. when  print()  ,  formatstr.format, or str function is invoked on an object the __str__  method will be called if and only if a  __str__  method is defined for the class , otherwise it will use the built-in object implementation which actually calls  __repr__ method .

Example of str(): 


p = Book('Pride and Prejudice', 1813)

# __str__() example
print(p)
print(p.__str__())

s = str(p)
print(s)

Output:


Book(bookName=Pride and Prejudice, publish=1813)
Book(bookName=Pride and Prejudice, publish=1813)
Book(bookName=Pride and Prejudice, publish=1813)

Python __repr__():

The goal of __repr__() is to be unambiguous. __repr__() also returns valid python expression such as dictionary, tuple, string etc. It is called when repr() is invoked on the object, in that case, __repr__()  must return a String otherwise error will be thrown.

Example of repr():


p = Book('Pride and Prejudice', 1813)
# __repr__() example
print(p.__repr__())
print(type(p.__repr__()))
print(repr(p))

Output:


{'bookName': 'Pride and Prejudice', 'publish': 1813}
<type 'dict'>
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-26-2405c8d5cc59> in <module>()
      2 print(p.__repr__())
      3 print(type(p.__repr__()))
----> 4 print(repr(p))

TypeError: __repr__ returned non-string (type dict)

Since the __repr__ method is returnning dict and not string, the repr() function is throwing a TypeError. Edit the  __repr__ method with the below code and let's see what happends.


def __repr__(self):
        return '{bookName:'+self.name+', publish:'+str(self.publish)+ '}'

Output:


{Bookname:Pride and Prejudice, Bookpublished:1813}
<type 'str'>
{Bookname:Pride and Prejudice, Bookpublished:1813}

Conclution:

Define __repr__ for objects you write so you and other developers have a reproducible example when using it as you develop. Define __str__ when you need a human readable string representation of it.

Comments

Wish to hire us?

We take the vision which comes from dreams and apply the magic of science and mathematics, adding the heritage of our profession and our knowledge to create a design.