// Tutorial //

Python __str__() and __repr__() functions

Published on August 3, 2022
Default avatar
By Pankaj
Developer and author at DigitalOcean.
Python __str__() and __repr__() functions

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

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 = datetime.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):
        self.name = 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):
        self.name = person_name
        self.age = person_age

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

    def __repr__(self):
        return f'Person(name={self.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.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up
About the authors
Default avatar


Developer and author at DigitalOcean.

Still looking for an answer?

Was this helpful?

Thanks, great help. I think could mention @dataclass too

- Nono

    Good articles keep it up!

    - Elias

      and hence as you said using: print(str(p)) print(repr(p)) is better than: print(p.__str__()) print(p.__repr__())

      - Bhasha

        Thanks for the article!

        - Sandro

          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

            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

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

              - Shashikant Thakur

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

                - Francisco

                  Good article. Thanks!

                  - Parth_Patel

                    Very useful. Thanks.

                    - Laeeq Khan