Differences between Python special methods __str__ and __repr__
Description
__str__
and __repr__
are two special methods in Python used to define the string representation of an object. While these two methods serve similar roles, their purposes and usage contexts differ. Firstly, the name __str__
is derived from “string,” and it literally means returning the object or its value itself as a string. On the other hand, the name __repr__
comes from “representation,” and it returns a string that represents the object. Essentially, __repr__
returns a string that can recreate the object, whereas __str__
returns a string for user presentation. Ultimately, it depends on how the person defines them, but it is recommended that for any object obj
, eval(obj.__repr__())
should reproduce obj
.
Moreover, when obj
is input into a REPL, the resulting string is the output of __repr__
, and when print(obj)
is executed, the resulting string is the output of __str__
. Now, let’s define an object dt
containing date and time information as follows.
import datetime
dt = datetime.datetime(2025, 5, 28, 16, 53, 45)
dt.__str__()
presents the information contained within this object, namely May 28, 2025, 16:53:45, in a user-friendly manner.
>>> dt.__str__()
'2025-05-28 16:53:45'
>>> str(dt)
'2025-05-28 16:53:45'
>>> print(dt)
2025-05-28 16:53:45
In contrast, dt.__repr__()
displays a string that can recreate the object. Thus, executing eval(dt.__repr__())
would create an object identical to dt
.
>>> dt.__repr__()
'datetime.datetime(2025, 5, 28, 16, 53, 45)'
>>> repr(dt)
'datetime.datetime(2025, 5, 28, 16, 53, 45)'
>>> dt
datetime.datetime(2025, 5, 28, 16, 53, 45)
>>> eval(repr(dt)) == dt
True
However, note that this isn’t the case for all Python classes. For instance, in cases like numpy.array
or torch.tensor
, the __repr__
method does not return a string that allows the object to be recreated directly.
Environment
- OS: Windows11
- Version: Python 3.10.11