__str__() and __repr__()

Methods that define an object’s text appearance: readable for the user (__str__) and technical for the programmer (__repr__).

Returns
Both methods must return a string (str).
On this page

Example

#
Python
class Student:
    def __init__(self, name, points):
        self.name = name
        self.points = points

    def __str__(self):
        return f"{self.name} ({self.points} pts)"

    def __repr__(self):
        return f"Student({self.name!r}, {self.points})"

emma = Student("Emma", 250)

print(emma)
print(f"Leader: {emma}")
print(repr(emma))
print([emma, Student("Jack", 90)])
Resultsaved result, you can check it
Emma (250 pts)
Leader: Emma (250 pts)
Student('Emma', 250)
[Student('Emma', 250), Student('Jack', 90)]

Definition and usage

#

Without these methods, print(object) shows something like <__main__.Student object at 0x...>, which says very little. The __str__ method returns a readable description of the object meant for the user. It is used by print(), str(), and f-strings.

The __repr__ method returns a technical description, useful when debugging. A good representation looks like the code that creates the same object, e.g. Student("Emma", 250). It is used by the repr() function, the interactive console when you type a variable name, and printing a collection: a list of objects in print() shows the repr of each element.

If a class has only __repr__, Python also uses it in place of a missing __str__. So when you write only one of these methods, start with __repr__. In an f-string, you force the technical version with the !r suffix, e.g. f"{object!r}". Inside __repr__ itself, this suffix adds quotes around strings.

Syntax

#
Syntax
class Name:
    def __str__(self):
        return "description for the user"

    def __repr__(self):
        return "Name(...)"

More examples

#
An object’s default appearance
Python
class Course:
    def __init__(self, title):
        self.title = title

print(Course("Python"))
Result
Click Run to see the result.

The result looks something like <__main__.Course object at 0x104f3a2d0>. The memory address changes on every run.

__repr__ alone covers both
Python
class Badge:
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return f"Badge({self.name!r})"

badge = Badge("7-day streak")
print(badge)
print(str(badge) == repr(badge))
print(f"Earned: {badge!r}")
Resultsaved result, you can check it
Badge('7-day streak')
True
Earned: Badge('7-day streak')

Good practices

#
  • If you write only one of these methods, choose __repr__. It also works as __str__, and it helps a lot when debugging.
  • In __repr__, format strings with !r so the result includes quotes and looks like code: f"Student({self.name!r})".
  • @dataclass generates __repr__ automatically based on the class’s fields.

Related entries

#

Spotted a mistake or missing an example? Write to us.