You are currently viewing Python difference between __str__ and __repr__?

What is the difference between __str__ and __repr__ in Python? The __str__ and __repr__ methods are two commonly used “dunder” (double underscore) methods that can be used to define how an object is represented as a string.

Advertisements

Both methods, str and repr, generate a string representation of an object, but they serve different purposes and people use them in different contexts.

In this article, we will explore the differences between __str__ and __repr__, when to use each method, and provide examples of how to implement them in your Python code.

1. Examples of str() and repr()

Before getting into the details of __str__ and __repr__ , let’s see where it can be useful. The str() function returns a string representation of the object that is meant to be human-readable

The repr() function, on the other hand, returns a string representation of the object that is meant to be unambiguous and complete.


my_list = [1, 2, 3]
print(str(my_list)) 
# '[1, 2, 3]'

print(repr(my_list)) 
# '[1, 2, 3]'

In the example above you have seen how these two methods, give the same output. But there are some differences between these two, which we will see in the upcoming section.

2. What is __str__ in Python?

The __str__ method is a special method in Python that defines a human-readable string representation of an object. It is called automatically when the object is printed or passed to the str() function.

The purpose of the __str__ method is to provide a concise and easy-to-understand string representation of the object, intended for humans rather than machines.

See the following Example of using the __str__ method:


class ProgrammingLanguage:
    def __init__(self, name, year, designed_by):
        self.name = name
        self.designed_by = designed_by

    def __str__(self):
        return f"{self.name} by {self.designed_by}"

object= ProgrammingLanguage("Python", "Guido van Rossum")
print(python)  

# Output: "Python by Guido van Rossum"

In the above example the __str__ method is used to convert a Python Object to a string representation. We have overridden the __str__ method.

3. What is __repr__ in Python?

The __repr__ is also used to define a string representation of an object, typically for debugging or logging purposes. This method is called “repr” which stands for “representation”. It returns a string representation of an object that can be used to recreate the object.

The __repr__ method is called when the repr() function is used on an object or when the object is printed in the Python REPL. The string returned by the __repr__ method should be a valid Python expression that, when evaluated, would create an object identical to the original object.


class ProgrammingLanguage:
    def __init__(self, name, year, designed_by):
        self.name = name
        self.designed_by = designed_by
    
    def __repr__(self):
        return f"ProgrammingLanguage('{self.name}' ,'{self.designed_by}')"

python = ProgrammingLanguage("Python","Guido van Rossum")
print(repr(python)) 
# Output: "ProgrammingLanguage('Python', 'Guido van Rossum')"

4. Difference Between __str__ and __repr__

Both the __str__ and __repr__ methods in Python are used to define string representations of objects, but they serve slightly different purposes.

  • __str__ is for making objects readable to humans, while __repr__ is for making objects unambiguous to the computer.
  • __str__ is used when you want to display an object to a user, while __repr__ is used when you want to display an object to the computer, such as when debugging.
  • __str__ can return a simplified representation of the object, while __repr__ should return a complete representation that can be used to recreate the object.

The following Table summarizes the differences between __str__ and __repr__ in Python:

__str____repr__
PurposeHuman-readableFormal and unambiguous
When calledstr() functionrepr() function, object printed in REPL
String representationReadable but incompleteComplete and valid Python expression
FormatShould be easy to read by humansDoes not need to be easy to read by humans
Example“ProgrammingLanguage(name=’Python’)”__main__.ProgrammingLanguage object at 0x…
UsageUsed for user-friendly display of an objectUsed for debugging, logging, and re-creating an object
ReturnsA string representing the object’s state or valuesA string that, when evaluated, can be used to re-create the object
CustomizationCan be customized to improve object representationCan be customized to improve object representation or debugging output
FallbackIf __str__ is not defined, uses __repr__If __repr__ is not defined, uses a default representation of the object
__str__ vs __repr__

5. Examples of __str__ and __repr__

Some examples of when you might want to use __str__:

5.1 Example 1

A class that represents a user profile, you might want to define __str__ and __repr__ to return the user’s name, email, and a short bio.


class UserProfile:
    def __init__(self, name, email, bio):
        self.name = name
        self.email = email
        self.bio = bio
    
    def __str__(self):
        return f"{self.name} ({self.email}): {self.bio}"
    
    def __repr__(self):
        return f"UserProfile(name={self.name}, email={self.email}, bio={self.bio})"

5.2 Example 2

If you have a class that represents a book, you might want to define __str__ and __repr__ to return the book’s title, author, and publication date.


class Book:
    def __init__(self, title, author, publication_date):
        self.title = title
        self.author = author
        self.publication_date = publication_date
    
    def __str__(self):
        return f"\"{self.title}\" by {self.author} ({self.publication_date})"
    
    def __repr__(self):
        return f"Book(title={self.title}, author={self.author}, publication_date={self.publication_date})"

5.3 Example 3

If you have a class that represents a product, you might want to define __str__ and __repr__ to return the product’s name, price, and description.


class Product:
    def __init__(self, name, price, description):
        self.name = name
        self.price = price
        self.description = description
    
    def __str__(self):
        return f"{self.name}: ${self.price} - {self.description}"
    
    def __repr__(self):
        return f"Product(name={self.name}, price={self.price}, description={self.description})"

6. Summary and Conclusion

In conclusion, the difference between __str__ and __repr__ is an important concept in Python to understand. You use str to define a human-readable string representation of an object, and you use repr to define a formal and unambiguous string representation of an object.

Remember, str is for human-readable string representations, while repr is for unambiguous and machine-readable string representations. If you have any questions leave them in the comment section.

Happy coding!