String Representation: __str__ vs. __repr__
In Python, every object has a string representation. By default, custom objects look like a cryptic memory address: <__main__.Car object at 0x7f...>. To make your objects professional and easy to debug, you must override the “Magic Methods” responsible for string output.
The Python Data Model provides two distinct methods for this: __str__ and __repr__.
1. __str__: The “User” View
Section titled “1. __str__: The “User” View”The __str__ method is meant to be informal and readable. Its primary goal is to provide a clear summary for an end-user.
- Triggered by:
print(obj),str(obj), and f-strings{obj}. - Goal: To be pretty.
class Book: def __init__(self, title, author): self.title = title self.author = author
def __str__(self): return f"'{self.title}' by {self.author}"
my_book = Book("1984", "George Orwell")print(my_book) # Output: '1984' by George Orwell2. __repr__: The “Developer” View
Section titled “2. __repr__: The “Developer” View”The __repr__ (Representation) method is meant to be unambiguous and formal. Its primary goal is to provide enough information to recreate the object.
- Triggered by: The interactive console,
repr(obj), and inside collections (like lists). - Goal: To be precise.
class Book: # ... __init__ ...
def __repr__(self): return f"Book(title='{self.title}', author='{self.author}')"
# In a list, Python uses __repr__library = [Book("1984", "Orwell"), Book("Dune", "Herbert")]print(library)# Output: [Book(title='1984', author='Orwell'), Book(title='Dune', author='Herbert')]3. The Fallback Mechanism
Section titled “3. The Fallback Mechanism”What happens if you only define one of them?
- If you define only
__repr__: Python uses it for bothprint()and the console. - If you define only
__str__: Python uses it forprint(), but the console/lists will still show the ugly<__main__...>address.
Best Practice: Always define __repr__ first. It’s the “fallback” that ensures your objects are always debuggable.
4. Under the Hood: Evaluation vs. Display
Section titled “4. Under the Hood: Evaluation vs. Display”The distinction between these two comes from the philosophy that an object has an Identity (how the computer sees it) and a Value (how the human sees it).
__repr__answers: “What is this object?”__str__answers: “What information does this object hold?”
When you use the REPL, Python calls repr() on every result to show you the “Raw” object. When you use print(), Python calls str() to give you a “Pretty” version.
5. Summary Table
Section titled “5. Summary Table”| Feature | __str__ | __repr__ |
|---|---|---|
| Intended Audience | End User | Developer / Debugger |
| Output Style | Informal / Pretty | Formal / Unambiguous |
| Default Fallback | object.__repr__ | object.__repr__ |
| Best Practice | Optional. | Highly Recommended. |