The __repr__() Method in Python: A Complete Guide (Examples)

In Python, you can specify a textual representation of an object by implementing the __repr__() method into the class.

For example, let’s create a Fruit class with a textual representation method:

class Fruit:
    def __init__(self, name):
        self.name = name
    
    def __repr__(self):
        return f'Fruit("{self.name}")'

When you print a Fruit object, the __repr__() method is called and the text description of the object shows up in the console.

banana = Fruit("Banana")
print(banana)

Output:

Fruit("Banana")

In this guide, you learn how and why to use the __repr__() method. You also learn about an alternative method called __str__().

The __repr__() Method in Python

In Python, it is possible to override the default description of a custom object by specifying the __repr__() method in the class.

You might want to do this because, by default, the textual representation of a Python object might look rather verbose.

The Problem

Let’s see an example that shows the verbose output of printing an object in Python. Say you have a class Fruit class that looks like this:

class Fruit:
    def __init__(self, name):
        self.name = name

Let’s create a couple of Fruit objects with this class:

banana = Fruit("Banana")
apple = Fruit("Apple")

Now, let’s print these objects into the console:

print(banana)
print(apple)

Output:

<__main__.Fruit object at 0x7f0e2089b4c0>
<__main__.Fruit object at 0x7f0e208008b0>

This output is not useful as it makes no sense to you as a developer, other than it’s a fruit object at some memory address.

Where Does The Description Come From?

To fix the problem, you can customize the default description to something more readable. But before going there, let’s inspect where this description originates in the first place.

When you call the print() function on any Python object, you are calling a method called __repr__() behind the scenes. In your own class, it’s the default implementation of the __repr__() method which returns an unclear description of the string like this:

<__main__.Fruit object at 0x7f0e2089b4c0>
<__main__.Fruit object at 0x7f0e208008b0>

The Solution: __repr__() Method

You can get rid of the default object description by overriding the __repr__() method.

Changing the default textual representation is useful if you want to make sense of your objects, for example when debugging the code.

According to best practices, if you override the __repr__() method, you should return a string that describes exactly how the object was created.

So for example, if you use to create objects with the following syntax:

Fruit("Banana")

The overridden __repr__() method should exactly the same as a string:

Fruit("Banana")

You will learn why in just a bit. Before that, let’s take a look at an example.

Example

Let’s override the __repr__() method into a Fruit class to change the description of Fruit objects when printed:

class Fruit:
    def __init__(self, name):
        self.name = name
    
    def __repr__(self):
        return f'Fruit("{self.name}")'

Now, let’s create two Fruit objects and print them out:

banana = Fruit("Banana")
apple = Fruit("Apple")

print(banana)
print(apple)

This results in the following output in the console:

Fruit("Banana")
Fruit("Apple")

Now you have successfully replaced the default description of an object with something you can make sense of!

Call repr() Instead of __repr__()

In Python, you can call the built-in repr() function on an object instead of using the __repr__() method. This is because, by design, the repr() method calls the __repr__() method under the hood.

For example, let’s call the repr() method on the Fruit objects from the previous example:

banana = Fruit("Banana")
apple = Fruit("Apple")

print(repr(banana))
print(repr(apple))

This gives the same result as calling the __repr__() would.

Fruit("Banana")
Fruit("Apple")

Next, let’s talk about why the repr() method should return a string that describes how the object was created.

The eval() Function in Python

In Python, there is a built-in function called eval() that turns the code from a string into executable Python code.

For example:

eval("print(1 + 2)")

Output:

3

The eval() function runs the code inside the string argument. Now, this code could be anything. For example, you can create a new Fruit object using the eval() function:

pineapple = eval('Fruit("Pineapple")')

Thus, it’s practical to return a string that describes how the object was created from the __repr__() method. This makes it possible to call eval() on the string representation of the object to build another equal object.

For example:

banana = Fruit("Banana")
otherbanana = eval(repr(banana))

print(otherbanana)

Output:

Fruit("Banana")

In this code:

  • The repr(banana) returns a string Fruit(“Banana”).
  • This is passed into the eval() function.
  • The eval() function then executes the code inside the string. This creates another equal banana object.

This only works if the __repr__() method returns a string that describes how the object was created.

Wonderful! Now you understand how to modify the description of a custom object by overriding the __repr__() method.

The __str__() Method in Python

Another very similar method to __repr__() in Python is the __str__() method. It also returns a textual description of the object on which it’s called. However, the description returned by __str__() method should be something end users can understand.

Have a look at this output that was returned by the __repr__() method in the previous section:

Fruit("Banana")

The output is ambiguous for someone who does not know how to code. For example, you do not want to show this kind of string representation for an end-user.

The easiest solution would be to modify the __repr__() method to be more user-friendly. But you don’t want to do that because calling the eval() function on the objects wouldn’t work anymore.

A better solution is to specify another related method, __str__(). This should return a clear description of an object—something you could show to non-technical end users.

Now, let’s implement the user-friendly __str__() method into the Fruit class:

class Fruit:
    def __init__(self, name):
        self.name = name
    
    def __str__(self):
        return f"A Fruit object called {self.name}"
    
    def __repr__(self):
        return f'Fruit("{self.name}")'

Similar to how you can call __repr__() using the repr() function, you can call __str__() method using the built-in str() function. Or even better, you can call the print() function. When you do this,

  • The print() function checks if the object has a __str__() method.
    1. If it does, that method gets called.
    2. If it doesn’t, then __repr__() is called instead.

If you create a Fruit object and print it to the console, the __str__() method gets called first, which shows a user-friendly string representation of the object:

banana = Fruit("Banana")
print(banana)

Output:

A Fruit object called Banana

If the __str__() method wasn’t there, the description would come from the __repr__() method.

Conclusion

Today you learned what is the __repr__() method in Python.

To recap, the __repr__() method specifies how an object is described as a string. It is advised to implement this method such that it returns a “developer-friendly” string that describes how the object was created. This is to make it possible to call eval() on the representation to build an identical object.

eval(repr(obj)) = obj

Another method used to represent the object as a string is the __str__() method. This is a more “user-friendly” way to describe an object.

When you call the print() function on an object, it first tries to call the __str__() method of the object. If that method is not implemented, it then proceeds to call the __repr__() method.

Thanks for reading. Happy coding!

Further Reading

50 Python Interview Questions