Python
__str__
__repr__
string representation
programming languages

What is the difference between __str__ and __repr__?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In Python, the special methods __str__ and __repr__ are fundamental to customizing the way objects are represented as strings. Understanding when and how to use these methods is vital for creating readable and informative object representations, especially when debugging or logging.

Technical Explanation

Both __str__ and __repr__ are used for representing objects as strings, but they serve different purposes:

  • __repr__: Official string representation of an object. It should, ideally, be unambiguous, and if possible, the output of __repr__ should be valid Python code that can reconstruct the object. In simple terms, __repr__ is for developers.
  • __str__: Informal string representation of an object. It's meant to be readable and is used for creating output for end-users. While __str__ should return a user-friendly representation, __repr__ should focus on accurately representing the object for debugging.

Implementation

To better understand these methods, let's look at a basic example:

python
1class Book:
2    def __init__(self, title, author, pages):
3        self.title = title
4        self.author = author
5        self.pages = pages
6
7    def __repr__(self):
8        return f"Book('{self.title}', '{self.author}', {self.pages})"
9    
10    def __str__(self):
11        return f"'{self.title}' by {self.author}"

In the example above:

  • __repr__: The method provides an unambiguous string representation that could be used to recreate the object. Book('The Great Gatsby', 'F. Scott Fitzgerald', 180) suggests this is the constructor format.
  • __str__: The method returns a simplified, easily readable representation: 'The Great Gatsby' by F. Scott Fitzgerald.

Usage Contexts

  • When you print an object, Python attempts to call __str__. If __str__ is not defined, Python will use __repr__.
  • When using the Python interpreter (for instance, typing an object name in the shell), __repr__ is used.
  • Logging and debugging are ideal scenarios for __repr__.

Example Usage

python
1book = Book('The Great Gatsby', 'F. Scott Fitzgerald', 180)
2
3print(book)             # Output: 'The Great Gatsby' by F. Scott Fitzgerald
4print(str(book))        # Output: 'The Great Gatsby' by F. Scott Fitzgerald
5print(repr(book))       # Output: Book('The Great Gatsby', 'F. Scott Fitzgerald', 180)

A Closer Look

  1. Reusability: The output of __repr__ should ideally be a valid expression, meaning you can use it to instantiate the object.
  2. Error Scenarios: If an object does not define __str__, the default implementation inherited from the base class calls __repr__.
  3. Readable vs. Formal: While __str__ prioritizes readability, __repr__ provides insight into the object’s structure.
  4. Priority: For print or str(), if __str__ is not available, Python resorts to __repr__. However, the converse is not true.

Table of Differences

Aspectstrrepr
PurposeReadable for the userUnambiguous for developers
Ideal ContentSimplified, user-friendly informationComplete, precise object description
Fallback BehaviorFalls back to __repr__ if undefinedCannot fall back to __str__
Use Case ContextUser-facing messagesDebugging, logs, REPL interaction
Preferred FormatReadable proseExecutable string (like code)

Conclusion

Understanding the distinction between __str__ and __repr__ is foundational to writing better Python classes. It ensures that code remains flexible and communicative to both developers and end-users. Properly implementing these methods enhances debugging efficiency and user interaction, making the overall coding experience more seamless and productive.


Course illustration
Course illustration

All Rights Reserved.