Note

Python - Magic Method __repr__ - Define object debug representations


Understanding the Python __repr__ Magic Method / Dunder Method with Examples

The magic method __repr__ provides a way to return a string that represents an instance of a class. Unlike __str__, which is meant to give a human-readable description, __repr__ is used to provide a string that could ideally be used to recreate the object.


class MyClass:
    def __init__(self, my_int):
        self.my_int = my_int

    def __repr__(self) -> str:
        return f'MyClass(my_int={self.my_int})'


my_class_instance = MyClass(1)

print(repr(my_class_instance))  # Output: MyClass(my_int=1)
print(my_class_instance.__repr__())  # Output: MyClass(my_int=1)

Output:

MyClass(my_int=1)
MyClass(my_int=1)

Purpose of __repr__

The __repr__ method needs to return a string that could be used to recreate the object. This often involves including the class name and its attributes. For example, if we had a class representing a point in a 2D space, the __repr__ string might look like Point(x=1, y=2).

The goal is to make debugging easier by giving developers clear information on how to recreate given object.


Here you can take a look at a more practical example:

class Product:
    def __init__(self, name: str, price: float) -> None:
        self.name = name
        self.price = price

    def __repr__(self) -> str:
        return f"Product(name='{self.name}', price={self.price:.2f})"  # :.2f specifies precision of float number

product = Product("Laptop", 999.99)

print(repr(product))  # Product(name="Laptop", price=999.99)

Output:

Product(name="Laptop", price=999.99)

Please notice how the output - Product(name="Laptop", price=999.99) could be used to directly recreate this object.

I hope you found this helpful! If you have any feedback, questions or requests, please reach out to me through Contact page!

Thank You Image


You might also be interested in: