Understanding the Difference Between `__str__` and `__repr__` in Python

3 min read .

In Python, the __str__ and __repr__ methods are crucial for customizing how objects are represented as strings. These methods are often confused, but they serve distinct purposes and are used in different contexts. Understanding the difference between __str__ and __repr__ is essential for effective debugging and user-friendly output in your Python applications. We’ll explore what __str__ and __repr__ are, how they differ, and when to use each.

1. What is __str__?

The __str__ method is used to define a human-readable string representation of an object. Its primary purpose is to provide a readable and informative string for end-users or for display purposes. When you use the print() function or str() to convert an object to a string, Python calls the __str__ method.

Example:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"Person(name={self.name}, age={self.age})"

p = Person("Alice", 30)
print(p)  # Output: Person(name=Alice, age=30)

In this example, the __str__ method provides a user-friendly string representation of the Person object.

2. What is __repr__?

The __repr__ method is intended to provide an unambiguous and detailed string representation of an object, mainly for debugging and development purposes. The goal of __repr__ is to generate a string that, when passed to eval(), would produce an object with the same state (if possible). When you use the repr() function or inspect an object in an interactive session, Python calls the __repr__ method.

Example:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

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

p = Person("Alice", 30)
print(repr(p))  # Output: Person(name='Alice', age=30)

In this example, the __repr__ method provides a detailed string representation of the Person object that is useful for debugging.

3. Key Differences Between __str__ and __repr__

  • Purpose:

    • __str__: Provides a readable, user-friendly string representation.
    • __repr__: Provides an unambiguous, detailed string representation for debugging.
  • Default Behavior:

    • If you only define __repr__ and not __str__, Python will use __repr__ for both print() and str(). This is because __str__ falls back to __repr__ if __str__ is not defined.

Example:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

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

p = Person("Alice", 30)
print(p)       # Output: Person(name='Alice', age=30)
print(str(p))  # Output: Person(name='Alice', age=30)
  • Use Case:
    • __str__: Use it to define how the object should be displayed to users, focusing on readability and clarity.
    • __repr__: Use it to define a detailed string that provides a clear view of the object’s internal state for debugging.

4. Best Practices for Implementing __str__ and __repr__

  • Implement Both Methods: If you need both user-friendly output and detailed debugging information, implement both __str__ and __repr__ methods in your classes.
  • Keep __repr__ Unambiguous: Ensure that the output of __repr__ is unambiguous and, where possible, could be used to recreate the object.
  • Test Your Methods: Verify that your __str__ and __repr__ methods provide the expected output in different contexts, such as printing and debugging.

5. Example: Customizing String Representation

Here’s an example that demonstrates both methods in a single class:

class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

    def __str__(self):
        return f"'{self.title}' by {self.author}"

    def __repr__(self):
        return f"Book(title='{self.title}', author='{self.author}')"

b = Book("1984", "George Orwell")
print(b)        # Output: '1984' by George Orwell
print(repr(b))  # Output: Book(title='1984', author='George Orwell')

In this example, __str__ provides a reader-friendly format for displaying the book, while __repr__ offers a detailed representation suitable for debugging.

6. Conclusion

Understanding the difference between __str__ and __repr__ in Python is essential for creating well-defined and user-friendly object representations. By using __str__ for clear, readable output and __repr__ for detailed, unambiguous information, you can enhance both the usability and debuggability of your code. Implementing these methods effectively helps in maintaining clean, maintainable, and professional Python code.

Tags:
Python

See Also

chevron-up