Difference between __str__ and __repr__ in Python

Patrick Loeber

Learn what's the difference between the __str__ and __repr__ methods in Python.

Both are special methods (also known as "dunder methods") that return strings based on the state of the object. For built-in classes these methods are already implemented, and it's good practice to implement them ourselves when creating a custom class.

Let's look at the docs:

object.__str__(self) (Link)

Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object. The return value must be a string object. [...]

object.__repr__(self) (Link)

Called by the repr() built-in function to compute the “official” string representation of an object. [...] . If a class defines __repr__() but not __str__(), then __repr__() is also used when an “informal” string representation of instances of that class is required.

This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.

So to summarize we can say:

--> If you can only write one, start with __repr__.

Another rule of thumb: __repr__ is for developers, __str__ is for customers.

Let's look at an example:

>>> import datetime >>> today = datetime.datetime.now() >>> str(today) '2021-08-12 20:17:04.066084' >>> repr(today) 'datetime.datetime(2021, 8, 12, 20, 17, 4, 66084)' >>> print(today) # __str__ is used '2021-08-12 20:17:04.066084' >>> today # __repr__ is used 'datetime.datetime(2021, 8, 12, 20, 17, 4, 66084)'

As we can see, using __str__ displays the dateobject in a clean date string while __repr__ also shows information about the module.

FREE VS Code / PyCharm Extensions I Use

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link *

* This is an affiliate link. By clicking on it you will not have any additional costs, instead you will support me and my project. Thank you! 🙏

Check out my Courses