In Python, __str__
and __repr__
are special methods used to define string representations of objects, but they serve different purposes:
1. __repr__
(Official/String Representation)
- Purpose:
- Meant for unambiguous debugging and developer clarity.
- Ideally returns a string that is a valid Python expression to recreate the object.
- Used by
repr()
and displayed in the interactive interpreter when you type the object. - Example:
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def __repr__(self):
return f"Date({self.year}, {self.month}, {self.day})" # Valid Python code
d = Date(2023, 10, 5)
print(repr(d)) # Output: Date(2023, 10, 5)
2. __str__
(User-Friendly/String Representation)
- Purpose:
- Returns a readable, informal string for end-users.
- Used by
str()
andprint()
. - Example:
class Date:
def __str__(self):
return f"{self.year}-{self.month}-{self.day}"
d = Date(2023, 10, 5)
print(d) # Output: 2023-10-5 (simpler for users)
Key Differences
Feature | __repr__ | __str__ |
---|---|---|
Audience | Developers (debugging) | End-users (readability) |
Use Case | repr(obj) , interactive shell | print(obj) , str(obj) |
Goal | Unambiguous, recreate the object | Human-readable |
Fallback Behavior | If __str__ is missing, uses __repr__ | No fallback to __repr__ |
3. When to Implement Each
- Always define
__repr__
:
Provides a clear debugging representation. If__str__
is undefined,__repr__
is used as a fallback. - Define
__str__
for user-friendly output:
Optional but recommended for better user experience.
Example with Both Methods
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def __repr__(self):
return f"Date({self.year}, {self.month}, {self.day})"
def __str__(self):
return f"{self.year}-{self.month:02d}-{self.day:02d}"
d = Date(2023, 10, 5)
print(repr(d)) # Output: Date(2023, 10, 5) (debugging)
print(d) # Output: 2023-10-05 (user-friendly)
4. Built-in Behavior
For many objects (e.g., lists, dictionaries), __repr__
and __str__
return the same string by default. For example:
lst = [1, 2, 3]
print(str(lst)) # [1, 2, 3]
print(repr(lst)) # [1, 2, 3] (same here)
But for strings, they differ:
s = "hello"
print(str(s)) # hello
print(repr(s)) # 'hello' (includes quotes)
Summary
- Use
__repr__
for unambiguous debugging. - Use
__str__
for user-friendly output. - If in doubt, define
__repr__
(it’s a best practice).