Skip to content

Effortlessly Understand __repr__ in Python

[

When Should You Use .repr() vs .str() in Python?

In Short: Use .repr() for Programmers vs .str() for Users

Python classes have a number of special methods, and two of them are repr() and str(). These methods provide string representations of objects, but they serve different purposes:

  • repr() is used to provide the official string representation of an object, targeted at programmers.
  • str() is used to provide the informal string representation of an object, targeted at users.

Let’s dive deeper into the differences between these two methods and explore when to choose repr() vs str().

How Can You Access an Object’s String Representations?

To access an object’s string representations, you can use the built-in functions str() and repr(). The str() function invokes the str() method, while the repr() function invokes the repr() method.

Here’s an example to illustrate this:

class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def __repr__(self):
return f"Car('{self.make}', '{self.model}', {self.year})"
def __str__(self):
return f"{self.year} {self.make} {self.model}"
my_car = Car("Toyota", "Camry", 2020)
print(str(my_car)) # Output: 2020 Toyota Camry
print(repr(my_car)) # Output: Car('Toyota', 'Camry', 2020)

As you can see, the str() method provides a more user-friendly representation of the Car object, while the repr() method provides a detailed and unambiguous representation for programmers.

Should You Define .repr() and .str() in a Custom Class?

In general, it’s a good practice to define both repr() and str() methods in your custom classes. By doing so, you can control how your objects are represented in different contexts.

Here are some guidelines for choosing when to use repr() vs str() in your classes:

  • Use repr() to provide a complete and unambiguous representation of the object. This allows programmers to recreate the object if needed.
  • Use str() to provide a user-friendly representation of the object that focuses on important details.

It’s important to note that if str() is not defined for a class, Python will use the repr() method as a fallback.

Conclusion

In this tutorial, you learned about the differences between repr() and str() in Python. You also learned how to access an object’s string representations using the str() and repr() functions. Remember to define both repr() and str() methods in your custom classes to provide meaningful representations of your objects.

By understanding when to use repr() vs str(), you can make your code more readable, maintainable, and user-friendly. Keep these concepts in mind as you develop and maintain your Python programs. Happy coding!