Python __repr__() Magic Method

Rate this post

Syntax

object.__repr__(self)

The Python __repr__ method returns a string representation of the object on which it is called. It implements the built-in repr() function. If you call print(x) an object x, Python internally calls x.__str__() to determine the string representation of object x. If this isn’t implemented, Python calls x.__repr__().

We call this a “Dunder Method” for Double Underscore Method” (also called “magic method”). To get a list of all dunder methods with explanation, check out our dunder cheat sheet article on this blog.

Background repr()

Python’s built-in repr(x) function returns the standard (canonical) representation of an object.

Python repr() Function – A Helpful Guide with Example
>>> repr(42)
'42'
>>> repr('42')
"'42'"
>>> repr([1, 2, 3])
'[1, 2, 3]'
>>> repr({'Alice': 'Bob', 'Bob': 'Alice'})
"{'Alice': 'Bob', 'Bob': 'Alice'}"
>>> repr(object)
"<class 'object'>"
>>> repr(repr)
'<built-in function repr>'

Example Custom __repr__

Do you want to implement a custom string representation when using the repr(object) function on your custom object?

To accomplish this, overwrite the object.__repr__() method when defining the class and return the desired string representation of the given object.

💡 Note that if __str__() is defined, it takes precedence over __repr__(). The latter is only used as a fallback that’s implemented per default for any object.

Let’s have a look at an example where both dunder methods are defined:

class Car:
    def __init__(self, color, brand):
        self.color = color
        self.brand = brand

    def __str__(self):
        return 'Your car has color ' + self.color + ' and brand ' + self.brand

    def __repr__(self):
        return '123'

    
porsche = Car('black', 'porsche')
tesla = Car('silver', 'tesla')

print(str(porsche))
print(str(tesla))

The output is:

Your car has color black and brand porsche
Your car has color silver and brand tesla

Note how __str__ takes precedence over __repr__.

No __str__() but __repr__() defined

If you skip the definition of the __str__ method, it’ll take the string returned by the __repr__ method:

class Car:
    def __init__(self, color, brand):
        self.color = color
        self.brand = brand

    def __repr__(self):
        return '123'

    
porsche = Car('black', 'porsche')
tesla = Car('silver', 'tesla')

print(str(porsche))
print(str(tesla))

The output now is:

123
123

Thus, if you define the __repr__ dunder method but not the __str__ dunder method, the built-in str() function falls back to the __repr__() output.

__repr__ vs __str__

The difference between __str__() and __repr__() methods is that __str__() is expected to return a human-readable format, whereas __repr__() is expected to return a formal string representation of the object that should be sufficient to reconstruct the object (e.g., including object state variables).

Here’s an example:

import datetime
now = datetime.datetime.now()

print(now.__str__())
# 2021-12-06 11:14:56.285055

print(now.__repr__())
# datetime.datetime(2021, 12, 6, 11, 14, 56, 285055)

💡 The first output is a human-readable format, whereas the second output could be use to reconstruct the original object, e.g., by passing the output string into the eval() function.

However, the methods are closely related and they can even call each other if one of them is not implemented:

Python uses the __str__() method as a priority when being forced to convert an object to a string.

If __str__() is not defined, it attempts to call __repr__().

Only if this is not defined as well, it uses the default string representation of any object with the memory address and the name and location of the object’s class definition.

Here’s what happens if you define __repr__ but not __str__:

class Data:
    def __repr__(self):
        return 'finxter'


a = Data()

print(str(a))
# finxter

And here’s what happens if both methods are defined __str__() and __repr__()—Python prioritizes the definition of the __str__() method:

class Data:
    def __repr__(self):
        return 'finxter'

    def __str__(self):
        return 'python'


a = Data()

print(a)
# python

The __str__() method has some more powerful arguments—you can learn about them in our detailed blog tutorial here.

References:

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!