Python · Concurrency & Runtime

__str__() vs __repr__()

Mediumstrreprdunderoop

Interview question

What is the difference between __str__ and __repr__?

How to answer

The short answer

Both customize how an object becomes text, but they target different audiences.

__repr__

  • Unambiguous, developer-oriented representation.
  • Ideal goal: string that could recreate the object (eval-able when practical).
  • Used by the interactive console and when containers print elements.

__str__

  • Readable, user-facing description.
  • Used by str(obj) and print(obj).
  • If __str__ is missing, Python falls back to __repr__.
Python
class User:
    def __init__(self, user_id: int, name: str):
        self.user_id = user_id
        self.name = name

    def __repr__(self) -> str:
        return f"User(user_id={self.user_id!r}, name={self.name!r})"

    def __str__(self) -> str:
        return f"{self.name} (#{self.user_id})"

u = User(7, "Asha")
print(str(u))    # Asha (#7)
print(repr(u))   # User(user_id=7, name='Asha')
print([u])       # uses repr inside containers

Interview mnemonic: repr for developers/debugging; str for humans/display.

Lock it in with a real drill

You remember an answer longer once you have used it. Try a hands-on problem on this concept.

Open related drill