Introduction
In this article, you’ll learn about the special methods __str__()
and __repr__()
that are defined in the Python data model. The __str__()
and __repr__()
methods can be helpful in debugging Python code by logging or printing useful information about an object.
Python special methods begin and end with a double underscore and are informally known as dunder methods. Dunder methods are the underlying methods for Python’s built-in operators and functions. You should avoid calling dunder methods directly, and instead implement the dunder methods in your class and then use the built-in functions that call them, such as str()
and repr()
.
What’s the difference between __str__()
and __repr__()
?
The __str__()
method returns a human-readable, or informal, string representation of an object. This method is called by the built-in print()
, str()
, and format()
functions. If you don’t define a __str__()
method for a class, then the built-in object implementation calls the __repr__()
method instead.
The __repr__()
method returns a more information-rich, or official, string representation of an object. This method is called by the built-in repr()
function. If possible, the string returned should be a valid Python expression that can be used to recreate the object. In all cases, the string should be informative and unambiguous.
In general, the __str__()
string is intended for users and the __repr__()
string is intended for developers.
__str__()
and __repr__()
Examples Using a Built-In Class
The examples in this section call the __str__()
and __repr__()
methods directly for demonstration purposes.
The datetime.datetime
class is a built-in Python class which has a default implementation of the __str__()
and __repr__()
methods.
The following example code shows the strings returned by the default implementation of the __str__()
and __repr__()
methods for a datetime.datetime
object:
import datetime
mydate = datetime.datetime.now()
print("__str__() string: ", mydate.__str__())
print("str() string: ", str(mydate))
print("__repr__() string: ", mydate.__repr__())
print("repr() string: ", repr(mydate))
The output is:
Output__str__() string: 2023-01-27 09:50:37.429078
str() string: 2023-01-27 09:50:37.429078
__repr__() string: datetime.datetime(2023, 1, 27, 9, 50, 37, 429078)
repr() string: datetime.datetime(2023, 1, 27, 9, 50, 37, 429078)
The output shows that the str()
function calls __str__()
and returns a human-friendly string, while the repr()
function calls __repr__()
and returns a more information-rich string that can be used to recreate the object. In fact, you can use the repr()
function with the eval()
function to create a new object from the string:
import datetime
mydate1 = datetime.datetime.now()
mydate2 = eval(repr(mydate1))
print("mydate1 repr() string: ", repr(mydate1))
print("mydate2 repr() string: ", repr(mydate2))
print("the values of the objects are equal: ", mydate1==mydate2)
The output is:
Outputmydate1 repr() string: datetime.datetime(2023, 1, 26, 9, 43, 24, 479635)
mydate2 repr() string: datetime.datetime(2023, 1, 26, 9, 43, 24, 479635)
the values of the objects are equal: True
The preceding example code creates the mydate2
object from the repr()
string for mydate1
, and then verifies that the values of both objects are equal.
__str__()
and __repr__()
Examples Using a New Class
When you create a class, you should implement at least the ___repr__()
method so that useful information is returned when built-in functions use __repr__()
.
The following class doesn’t implement the __str__()
or __repr()__
methods:
class Ocean:
def __init__(self, sea_creature_name, sea_creature_age):
self.name = sea_creature_name
self.age = sea_creature_age
c = Ocean('Jellyfish', 5)
print(str(c))
print(repr(c))
The output when you use str()
and repr()
is:
Output<__main__.Ocean object at 0x102892860>
<__main__.Ocean object at 0x102892860>
The preceding example demonstrates that the default implementation of __repr()__
for the object returns a string with only the class and the object id
in hexadecimal format, which is not very useful. Note that str()
and repr()
return the same value, because str()
calls __repr__()
when __str__()
isn’t implemented.
Update the Ocean class with implementations of the __str__()
and __repr__()
methods:
class Ocean:
def __init__(self, sea_creature_name, sea_creature_age):
self.name = sea_creature_name
self.age = sea_creature_age
def __str__(self):
return f'The creature type is {self.name} and the age is {self.age}'
def __repr__(self):
return f'Ocean(\'{self.name}\', {self.age})'
c = Ocean('Jellyfish', 5)
print(str(c))
print(repr(c))
The output is:
OutputThe creature type is Jellyfish and the age is 5
Ocean('Jellyfish', 5)
The implementation of __str__()
in the preceding example returns an easy-to-read string that provides the relevant details of the object for a user. The implementation of __repr__()
returns a string that’s a valid Python expression which could be used to recreate the object: Ocean('Jellyfish', 5)
. The example uses f-string formatting for the strings, but you can format the strings using any format supported by Python.
Conclusion
In this article, you explored the differences between the __str__()
and the __repr__()
methods and implemented these special methods in a class, so that you didn’t need to call them directly. Learn more about working with strings in Python through our Python string tutorials.
Source:
https://www.digitalocean.com/community/tutorials/python-str-repr-functions