What is the difference between __str__ and __repr__?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
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:
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
A Closer Look
- Reusability: The output of
__repr__should ideally be a valid expression, meaning you can use it to instantiate the object. - Error Scenarios: If an object does not define
__str__, the default implementation inherited from the base class calls__repr__. - Readable vs. Formal: While
__str__prioritizes readability,__repr__provides insight into the object’s structure. - Priority: For print or
str(), if__str__is not available, Python resorts to__repr__. However, the converse is not true.
Table of Differences
| Aspect | str | repr |
| Purpose | Readable for the user | Unambiguous for developers |
| Ideal Content | Simplified, user-friendly information | Complete, precise object description |
| Fallback Behavior | Falls back to __repr__ if undefined | Cannot fall back to __str__ |
| Use Case Context | User-facing messages | Debugging, logs, REPL interaction |
| Preferred Format | Readable prose | Executable 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.
Related reading
- What is the difference between , None, None and for the shape of a placeholder?
- What is the difference between a pandas Series and a single-column DataFrame?
- What is the difference between a string and a byte string?
- What is the difference between an expression and a statement in Python?
- What is the difference between dict.items and dict.iteritems in Python 2?
- What is the difference between flatten and ravel functions in numpy?
- What is the difference between is None and None
- What is the difference between iterator and iterable and how to use them?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.