Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Classes and Special Methods

__str__() and __repr__()

Reference for Python __str__() and __repr__(): readable versus developer strings, what print, f-strings and containers use, !r, and writing a good repr.

__repr__() returns the "official" string for an object, meant for developers: ideally unambiguous and, when practical, valid Python that would recreate the object. __str__() returns the "informal" string meant for users.

str(obj), print(obj) and f"{obj}" use __str__(). The interactive prompt, repr(obj), !r in f-strings and the display of items inside lists, tuples and dicts use __repr__(). If you define only __repr__(), it is used for both.

Python
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __repr__(self):
        return f"Point({self.x}, {self.y})"

Try it

Python Which one is called where

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Fallbacks and mistakes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
class C:
    def __str__(self) -> str: ...
    def __repr__(self) -> str: ...
    def __format__(self, spec: str) -> str: ...
Method Called by
__repr__() repr(), the interactive prompt, !r, %r, items inside containers, the fallback for __str__().
__str__() str(), print(), format() with an empty spec, !s, %s.
__format__(spec) format(obj, spec) and f-strings with a format spec; the default calls str(obj) when the spec is empty and raises TypeError otherwise.

Return value: all three must return a str.

Raises: TypeError ("__str__ returned non-string") if a method returns another type.

Usage notes

  • Always write __repr__() first. It helps in debugging, logs and tracebacks; add __str__() only if users need a friendlier form.
  • Aim for recreatable output. Point(1, 2) is better than <Point object at 0x...>. When that is impossible, use the <ClassName ...> style with useful details.
  • Containers always use repr() of their items. That is why a list of objects with only __str__() still shows the default form.
  • The default __repr__() shows the class name and an address; the default __str__() calls __repr__().
  • Use !r for quoted values inside your own repr, so strings are quoted and escaped: f"User({self.name!r})".
  • Do not raise exceptions or do I/O in these methods; debuggers call them freely.
  • @dataclass generates __repr__() for you.
  • Bytes. __bytes__() is a separate hook used by bytes(obj).