🐍 Python Q30 / 170

What is __str__ and __repr__?

AI-Powered Answer ✓ Answered

In Python, `__str__` and `__repr__` are special methods (often called dunder methods) used to define string representations of objects. While both convert an object into a string, they serve distinct purposes and are intended for different audiences: `__str__` for readability, and `__repr__` for unambiguous representation.

`__str__` (String Representation for Humans)

The __str__ method is designed to return an 'informal' or 'nicely printable' string representation of an object. Its primary goal is readability for end-users. It's invoked by the built-in str() function and implicitly by the print() statement/function.

python
class MyObject:
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return f"MyObject with value: {self.value}"

ob = MyObject(10)
print(ob) # Calls ob.__str__() -> "MyObject with value: 10"
print(str(ob)) # Calls ob.__str__() -> "MyObject with value: 10"

`__repr__` (Developer-Friendly Representation)

The __repr__ method is intended to return an 'official' or 'unambiguous' string representation of an object. Its primary goal is to provide enough information for a developer to recreate the object or understand its state, useful for debugging. It's invoked by the built-in repr() function and when an object is displayed in the interactive interpreter (e.g., in a console or debugger).

The convention is that __repr__ should, if possible, return a string that would yield an object with the same value when passed to eval(). If not possible, it should return a useful description typically enclosed in angle brackets <...>. The !r f-string format specifier is useful here to ensure the value itself is represented by its repr.

python
class MyObject:
    def __init__(self, value):
        self.value = value

    def __repr__(self):
        return f"MyObject(value={self.value!r})" # !r calls repr() on self.value

ob = MyObject(10)
print(repr(ob)) # Calls ob.__repr__() -> "MyObject(value=10)"

ob_string = MyObject("hello")
print(repr(ob_string)) # Calls ob_string.__repr__() -> "MyObject(value='hello')"

# In an interpreter, just typing `ob` would implicitly call ob.__repr__()

Key Differences

Feature`__str__``__repr__`
AudienceEnd-users, human-readableDevelopers, unambiguous
PurposePretty print, informal displayDebugging, official representation, recreation
Invoked by`str()`, `print()``repr()`, interactive interpreter, debuggers
FallbackFalls back to `__repr__` if `__str__` is not definedIf not defined, uses default `object` repr (e.g., `<__main__.MyObject object at 0x...>`)

When to Use Which

  • Always implement __repr__ for your custom classes. This provides a useful debugging representation and is considered good practice.
  • Implement __str__ if you need a user-friendly, readable output that is different from your __repr__. If your __repr__ is already perfectly human-readable, you might not need __str__.
  • If you only implement __repr__ and not __str__, then str() (and print()) will fall back to using __repr__'s output. This is often an acceptable default behavior, especially for simple objects.