Understanding “__repr__” and “__str__” in Python

Learning Python’s string conversion methods

Vishal Sharma
The Startup
3 min readJun 5, 2020

--

Photo by Dlanor S on Unsplash

Python says “__repr__” is used to get a string representation of object while __str__” is used to find the “informal” string representation of an object. But, why do we need two different representations?

Let’s say we are working with code. We have introduced a class named “Animal” and we have built an object “a” for it.

Now, when this program runs, it will return something unreadable like this.

The common workaround for this is that we call class attributes directly and get the results “Dog” and “Pomeranian” in our case.

But, actually, there is a convention in Python that handles all of the above “printing” piece of code that we wrote. I want to explain how that works and how __repr__ and __str__ works. It is also one of the most asked questions in interviews. So, stay tuned.

__str__

Let’s take the same Animal class to ease things up. So, I have just added a dunder str method in the class.

Basically what my dunder method does here is that whenever we call the class, it returns us a string output “A Pomeranian Dog” instead of the object id in the memory.

However, if you just inspect the object, you will still get the memory address.

So, inspecting the Animal object still gives the memory address but when we printed the object, we got a different result based on the __str__ method.

So, to overcome this, you can also do something like this.

It will also return you the string output. Basically, you are forcing an object to convert to string. And, it will call the dunder str method to do that.

__repr__

We just learned about __str__. Now, the second one is called __repr__. Let’s understand how it is different from __str__.

The piece of code below will make you understand the whole scenario of __str__ and __repr__ happening under the hood.

When we just inspected the object, __repr__was called while when we used the print method, __str__ was called.

In another example, I called both the “str” and “repr” method on a datetime object.

Using str converted the object to string and made it human readable. While repr should be unambiguous and is more meant for internal use and debugging.

Conclusion

__str__ or str() is used for creating output that is human-readable are must be for end-users. But, repr() or __repr__ must serve the purpose of debugging and development.

Peace!

--

--