Python __str__ and __repr__
__repr__ and __str__ are dunder methods that turn an object into text.
A repr for developers
A repr should show exactly what the object holds. Paste it back into Python, and you rebuild the object.
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def __repr__(self):
return f"Book({self.title!r}, {self.pages})"
book = Book("Dune", 412)
print(repr(book))A str for readers
print() and str() use __str__ when you define it. The text can read like a normal sentence.
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def __repr__(self):
return f"Book({self.title!r}, {self.pages})"
def __str__(self):
return f"{self.title}, {self.pages} pages"
book = Book("Dune", 412)
print(book)
print(str(book))Force the repr in an f-string
Add !r just inside the braces. The f-string then asks for the repr, not the str.
print(f"Logged: {book!r}")
print(f"Shown: {book}")Lists show the repr
Containers never ask items for their str. A list shows the repr of each item inside it.
print([book])
print((book,))Example
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
def __repr__(self):
return f"Book({self.title!r}, {self.author!r}, {self.pages})"
def __str__(self):
return f"{self.title} by {self.author}"
book = Book("Dune", "Frank Herbert", 412)
print(book)
print(f"For the log: {book!r}")
print([book, Book("Emma", "Jane Austen", 474)])Key points
- Dunder: a special name with double underscores on both sides, like __repr__
- Use __repr__ to return an exact string that shows what the object holds
- Use __str__ to return a friendly string for people to read
- Use !r in an f-string to choose the repr for one value
- Containers display their items with repr, never with str
In this example, Book stores a title, an author, and a page count. __repr__ builds an exact string with !r around the text fields. __str__ builds a friendly line with the title and author. print(book) uses __str__, so you see the friendly line. The f-string uses !r, so you see the exact repr. The list shows the repr of both books inside it.
Note
Write __repr__ first if you write only one, because print() and str() both fall back to it.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does print([book]) show for each book in the list?