__repr__ vs __str__

Posted by Afsal on 21-Jul-2023

Hi Pythonistas!

Today we will learn about the difference between __repr__ and __str__ magic methods. Both of them gives idea both the class.The __repr__ is only a representation of the class. The __str__ is the human readable representation of the class. __repr__ is shown as the output in REPL or we can call using repr function. __str__ is shown then we use print, str, in string formatting.

Let us learn by an example

Code

>>> class Example:
... def __str__(self):
...     return "This is str"
... def __repr__(self):
...     return "This is repr"
...
>>> a = Example()
>>> a
This is repr
>>> print(a)
This is str
>>> print(repr(a))
This is repr
>>> print(str(a))
This is str
>>> print(f"{a}")
This is str
>>>

We can see the output of various situations. We can see another example python’s datetime module.

>>> import datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2023, 7, 18, 9, 16, 42, 696616)
>>> print(now)
2023-07-18 09:16:42.696616
>>>

We can see than __repr__ is class representation of the datetime object. But __str__ is readable representation of the object.

Note: If we does not provide __str__ then by default it show __repr__ of the class.

>>> class B:
... pass
...
>>> b = B()
>>> b
<__main__.B object at 0x7f55c0f6fe50>
>>> print(b)
<__main__.B object at 0x7f55c0f6fe50>
>>>

 

Every class have default __repr__ like this. 

Hope you have learned the difference between __repr__ and __str__ please share your valuable suggestions with afsal@parseltongue.co.in