Python __str__() and __repr__() functions

Filed Under: Python

We will look into two important python object functions that are very helpful in debugging python code by logging useful information regarding the object.

Python __str__()

This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object.

This method must return the String object. If we don’t implement __str__() function for a class, then built-in object implementation is used that actually calls __repr__() function.

Python __repr__()

Python __repr__() function returns the object representation in string format. This method is called when repr() function is invoked on the object. If possible, the string returned should be a valid Python expression that can be used to reconstruct the object again.

You should always use str() and repr() functions, which will call the underlying __str__ and __repr__ functions. It’s not a good idea to use these functions directly.

What’s the difference between __str and __repr__?

If both the functions return strings, which is supposed to be the object representation, what’s the difference?

Well, the __str__ function is supposed to return a human-readable format, which is good for logging or to display some information about the object. Whereas, the __repr__ function is supposed to return an “official” string representation of the object, which can be used to construct the object again. Let’s look at some examples below to understand this difference in a better way.

Python __str__ and __repr__ examples

Let’s look at a built-in class where both __str__ and __repr__ functions are defined.

>>> import datetime
>>> now =
>>> now.__str__()
'2020-12-27 22:28:00.324317'
>>> now.__repr__()
'datetime.datetime(2020, 12, 27, 22, 28, 0, 324317)'

It’s clear from the output that __str__() is more human friendly whereas __repr__() is more information rich and machine friendly and can be used to reconstruct the object. In fact, we can use repr() function with eval() to construct the object.

>>> now1 = eval(repr(now))
>>> now == now1

Both of these functions are used in debugging, let’s see what happens if we don’t define these functions for a custom object.

class Person:

    def __init__(self, person_name, person_age): = person_name
        self.age = person_age

p = Person('Pankaj', 34)



<__main__.Person object at 0x10ff22470>
<__main__.Person object at 0x10ff22470>

As you can see that the default implementation is useless. Let’s go ahead and implement both of these methods.

class Person:

    def __init__(self, person_name, person_age): = person_name
        self.age = person_age

    def __str__(self):
        return f'Person name is {} and age is {self.age}'

    def __repr__(self):
        return f'Person(name={}, age={self.age})'

p = Person('Pankaj', 34)



Person name is Pankaj and age is 34
Person(name=Pankaj, age=34)

Earlier we mentioned that if we don’t implement __str__ function then the __repr__ function is called. Just comment the __str__ function implementation from the Person class and print(p) will print {name:Pankaj, age:34}.


Both __str__ and __repr__ functions return string representation of the object. The __str__ string representation is supposed to be human-friendly and mostly used for logging purposes, whereas __repr__ representation is supposed to contain information about object so that it can be constructed again. You should never use these functions directly and always use str() and repr() functions.

You can checkout the complete python script and more Python examples from our GitHub Repository.


  1. Iftah says:

    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): = name
    self.age = age
    def __repr__(self):
    return f”””Person(name=”{}”, age={self.age})””” # developer friendly
    def __str__(self):
    return f”{} 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.

    1. Pankaj says:

      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:

      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.

      1. Iftah says:

        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.

        1. Pankaj says:

          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. 馃檪

          1. Iftah says:

            Thanks for updating the article, I think it is perfect now

            and added my real email in case you want to continue the dialog in private 馃檪

          2. Pankaj says:

            Awesome. I will look forward to your comments in other articles too. And thanks for providing the real email id, will connect with you soon. 馃檪

    2. Anon says:

      “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.

  2. jagan says:

    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

    1. Akash says:

      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

  3. Shashikant Thakur says:

    Who is responsible for calling the __repr__() and __str__()

    1. Advaitva says:

      No one, it is implicit

  4. Francisco says:

    QUOTE: I used str() to create __str__()

  5. Parth_Patel says:

    Good article. Thanks!

  6. Laeeq Khan says:

    Very useful. Thanks.

  7. vikas shrivastava says:

    This is really helpful article for me…

Leave a Reply

Your email address will not be published. Required fields are marked *

Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages