Image for post
Image for post

Every now and then, when I go back to writing Python code after a break, a question comes to mind:

What message should I put into the __str__ and the __repr__ functions?

When you search for the difference between them, you will find out that __str__ should be human readable and __repr__ should be unambiguous (as explained in this StackOverflow question). It’s a great, detailed answer. But for some reason, it never really stuck with me. I’m not the smartest developer and sometimes to remember something, I need a very simple example. What I actually found helpful was written straight in the documentation of the repr() function:

For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval()

An excellent example of what it means, is the datetime module:

As you can see, the repr function returns a string that can be used to create an object with the same properties as now (not the same as now, but with the same properties). You can verify it by using the following code:

So how can you use it in your own classes? For instance, if you are writing a class Car that has the attributes color and brand and is initialized in the following way:

then this is what the __repr__ function for the car should return:

It’s not always possible to write the __repr__ function that can recreate a given object, but simply keeping in mind those examples with datetime and Car has helped me to remember the difference between the __repr__ and __str__.

Credits: I found out about this trick in “Python Tricks” book, by Dan Bader. If you haven’t heard of it, it’s a great source of intermediate-level pieces of knowledge about Python. I’m in no way associated with Dan, but his book was one of the most enjoyable Python technical reads I’ve had in a long time.

More credits: Image from Pexels

Originally published at on January 25, 2019.

Written by

Python consultant, freelancer, and trainer at Writes about productivity, tools, Python, and programming best practices.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store