Tutorial

How To Use the __str__() and __repr__() Methods in Python

Updated on January 28, 2023
authorauthor

Pankaj and Andrea Anderson

How To Use the __str__() and __repr__() Methods in Python

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:

Output
mydate1 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:

Output
The 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.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author


Default avatar

Technical Editor


Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
March 3, 2022

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

- Nono

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    December 10, 2021

    Good articles keep it up!

    - Elias

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      August 17, 2021

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

      - Bhasha

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        July 9, 2021

        Thanks for the article!

        - Sandro

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          December 20, 2020

          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

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            July 7, 2020

            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

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              April 22, 2020

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

              - Shashikant Thakur

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                February 2, 2020

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

                - Francisco

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  January 1, 2020

                  Good article. Thanks!

                  - Parth_Patel

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    January 21, 2019

                    Very useful. Thanks.

                    - Laeeq Khan

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Become a contributor for community

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      DigitalOcean Documentation

                      Full documentation for every DigitalOcean product.

                      Resources for startups and SMBs

                      The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                      Get our newsletter

                      Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                      New accounts only. By submitting your email you agree to our Privacy Policy

                      The developer cloud

                      Scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Get started for free

                      Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                      *This promotional offer applies to new accounts only.