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()
.
__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 ClassThe 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:
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:
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 ClassWhen 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:
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:
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.
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.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This is really helpful article for me…
- vikas shrivastava
Very useful. Thanks.
- Laeeq Khan
Good article. Thanks!
- Parth_Patel
QUOTE: I used str() to create __str__()
- Francisco
Who is responsible for calling the __repr__() and __str__()
- Shashikant Thakur
No one, it is implicit
- Advaitva
Hi Pankaj - I still dont understand the difference between the __str__ and __repr__. From your notes you mentioned Python __repr__() function returns the object representation. It could be any valid python expression such as tuple, dictionary, string etc, whereas __str__() represent string representation of the Object. I tried added an expression (return “{firstName:” + self.fname + “, lastName:” + self.lname + “, age:” + str(self.age) + “}”) in __str__() method and returned it to main function, it didnt throw any error. When both __str__() and __repr__() can return only strings or string expressions i am not sure what exactly is the difference. Any inputs would be helpful
- jagan
Jagan __str__() and __repr__() are almost similar Diff is to return or print only strings str() can be used but if you are going to use any expression for example str(value[-1]) the string can’t process this input values so at that kind of situations repr() is used it can handle string and also expressions
- Akash
Sorry, but this is an awful article. The difference between __repr__ and __str__ is that __repr__ is meant for developers (eg. debugging) and __str__ is used for users. You didn’t explain this simple difference and instead wrote many very or slightly wrong things - You write in the summary “__str__ must return string object whereas __repr__ can return any python expression.” which is wrong! - __repr__ needs to return string as well, as you showed earlier! You use class variables and override them with instance variable, why? thats just not needed and beginners will think it is needed (perhaps you think its necessary?) You call the dunder methods directly (eg `p.__str__()`) instead of using the proper builtins (`str(p)` and `repr(p)`) You use camelCase arguments when the python style is snake_case (underscores) You write there is no fallback for missing __repr__ but you clearly show the fallback (Python shows the type and id in hex). Not having a fallback would be something like raising NotImplementedError. There is a convention (but not really necessary) to have repr return a *string* that looks like the constructor for the object, so one can copy paste the repr outout to get identical copy. eg. a proper example would be: ``` class Person: def __init__(name, age): self.name = name self.age = age def __repr__(self): return f"““Person(name=”{self.name}”, age={self.age})“”" # developer friendly def __str__(self): return f"{self.name} is {self.age} years old" # use friendly ``` I don’t normally bash random people for being wrong, but this article is at the top of the Google search results for repr vs str in python, and a lot of beginners will read this.
- Iftah
1. None of these methods are to be used directly by users. The article just shows the difference between them, don’t suggest to use it in the code. 2. __repr__ can return anything, as shown in the code where it’s returning dict. BUT, when we call the repr() function, it calls __repr__, and that time, it has to return the string. I think you didn’t get this very minute difference. 3. This article is not meant to explain class and instance variables, it’s kept simple so that everyone can easily understand and don’t get into the complexities of the code. Please refer to this for class variables: https://www.journaldev.com/14628/python-classes-objects 4. I agree that the variable names should use underscores, not camel case. I will fix it. 5. The meaning of “fallback” is that if “this” is missing, I will use “that”. When __str__ is missing, __repr__ is used. But, if __repr__ is missing, it doesn’t look for any other method. Finally, I don’t usually reply to junk comments but it looked like you have good knowledge of Python. I hope my answer clarifies all your doubts.
- Pankaj
Thank you for replying and thank you for posting my comment as is, I appreciate both very much. 1. The same way as x.__len__() is meant to be used by using the builtin len(x), then x.__repr__ and x.__str__ are meant to be used by str(x) and repr(x). It very much requires some mention in an introductory article about this. For completeness, you can mention __format__ and what happens when you do print(x) or f"{x:bla}", as that is where these methods will be called implicitly, but really talking about methods __repr__/__str__ without mentioning the builtin repr/str is missing an important part of the story of these methods. 2. __repr__ can return anything, *just as much as __str__ can return anything*. both act exactly the same way in this regard. It’s only when they will be used by Python (eg. to convert to a string by a str/print/format functions) or by the debugger (repr is used eg. to show the value of a variable when stopped in breakpoint) THEN it will throw an exception - there is no difference between repr and str in this matter. Again, I can implement __str__ to return a dictionary and call it just fine with x.__str__(). but print(x) will fail. It is the same for both __str__ and __repr__, you should not return anything other the str types from them, or else they will crash when used, just like you can return a dictionary from __len__ it will work if you call x.__len__() but it will crash when you use len(x). 3. Exactly, so why complicate the example and write class variables that you will not use? you can delete them from your example and it will not change anything. Beginners reading this will use it as an example so it better not confuse them. As you understand, I’m not new to Python, I’ve been developing in it for 12 years now and read quite a few books about it. A colleague of mine who is new to Python was confused about the difference between __str__ and __repr__ and I was horrified to see him write __repr__ method that returned dictionary instead of a string, which apparently he learned from this article. Again, I appreciate your reply and that you posted my comment, when it was easy to delete and ignore. It shows great character and I salute you for this. I am not writing this to have an ego war with a stranger on the internet. I am writing this with hope that you will edit your article, for the sake of new developers reading.
- Iftah
1. I got your point, added a small section not to use these methods directly. 2. I got the point and confusion created by the wording of the article, I have removed some unwanted sections and made is more clear now. 3. You are right, I didn’t look at the example more clearly. I have edited the code to remove unwanted variables. Thanks for your comments, it helped in making the article better. I will look forward to your comments in the future too. PS: We don’t spam even if you type your real email id, I have met some good folks through some of the comments left by them on the blog. Once a very popular person from the Java area left a comment, later on, we got connected over Twitter and we became good friends. :)
- Pankaj
Epic
- James
“Sorry, but this is an awful article.” What an awful way to start a comment. I hope one day you’ll be as passionate about manners as you are about programming.
- Anon
Pankaj Thanks for this article. It is excellently done. As far as the comments from Iftah goes. People who are quick to articulate on attack anything and everything but their own shortcomings are people the world can do without
- AoxmoxoA
Thanks for the article!
- Sandro
and hence as you said using: print(str(p)) print(repr(p)) is better than: print(p.__str__()) print(p.__repr__())
- Bhasha
Good articles keep it up!
- Elias