Pythonic OOP String Conversion: .__repr__() vs .__str__()

Dan Bader
Dan Bader 7 Lessons 13m intermediate python

In this tutorial series you’ll do a deep dive on how Python’s to-string conversion using the .__repr__() and .__str__() “magic methods” works and how you can implement them in your own classes and objects.

When you define a custom class in Python and then try to print one of its instances to the console (or inspect it in an interpreter session) you get a relatively unsatisfying result. The default “to string” conversion behavior is basic and lacking in detail.

By default all you get is a string containing the class name and the id of the object instance (which is the object’s memory address in CPython). That’s better than nothing, but it’s also not very useful.

The solution here is adding the .__str__() and .__repr__() “dunder” methods (some call them “magic methods”) to your class.

They are the Pythonic way to control how objects are converted to strings in different situations.

In this tutorial series I’ll do a deep dive on how Python’s to-string conversion works and how you can add it to your own custom classes.

I’ll walk you through the .__str__() and .__repr__() methods, when to use each, and some tips on how to use them in real world scenarios.

Just remember:

  • The result of .__str__() should be readable.

  • The result of .__repr__() should be unambiguous.

  • Always add a .__repr__() to your classes. The default implementation for .__str__() just calls .__repr__(), so you get the best of both worlds.

What’s Included:

Related Learning Paths:

About Dan Bader

Dan Bader is the owner and editor in chief of Real Python and the main developer of the learning platform. Dan has been writing code for more than 20 years and holds a master's degree in computer science.

» More about Dan

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Participant Comments

Avatar image for François 江戸 D

François 江戸 D on Sept. 21, 2021

No sooner said than used, my last piece of code got cleaner :)

Avatar image for jeffersongarciaor

jeffersongarciaor on Jan. 29, 2021

Just amazing to learn new stuffs. Thank you Dan for this tutorial.

Avatar image for Idris Diba

Idris Diba on Aug. 3, 2020

I learned a lot from this tutorial. Thank you Dan for your excellent method of teaching.

Avatar image for michelnakhla

michelnakhla on July 20, 2019

Very brief and nice.

« Browse All Courses