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:
- __repr__ should be unambiguous (and possibly machine-readable)
- __str__ should be human-readable
- __repr__ is a fallback for __str__ if __str__ is missing
- Calling
print()
uses __str__
--> 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.