Understanding Python’s __repr__ Method

Published on

in

,
Understanding Python's __repr__ Method

The __repr__ method is a special method in Python that is used to define a string representation for an object. It is intended to provide a clear and unambiguous representation of the object, primarily for debugging and development purposes. This is also called dunder method because of the double underscores before and after the name.

Without __repr__, when you print an object or inspect it in an interactive session, python will use a default representation that includes the object’s type and memory address, which is often not very informative. That’s where __repr__ comes in handy.

Why Do We Need __repr__?

Without __repr__, printing or inspecting an object shows only the default representation:

class MyCustomClass:
    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name

    def full_name(self):
        return f"{self.first_name} {self.last_name}"

custom_obj = MyCustomClass("John", "Doe")
print(custom_obj)  # Default representation without __repr__

The output will be something like:

<__main__.MyCustomClass at 0x1f045501d50>

This output tells you very little—it shows only the type and memory address.

Making Objects More Informative

To provide a more informative representation, you can implement the __repr__ method in your class:

class MyCustomClass:
    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name

    def full_name(self):
        return f"{self.first_name} {self.last_name}"
    
    def __repr__(self):
        return f"MyCustomClass(first_name='{self.first_name}', last_name='{self.last_name}')"

custom_obj = MyCustomClass("John", "Doe")
print(custom_obj)  # Now uses the __repr__ method

The output will be:

MyCustomClass(first_name='John', last_name='Doe')

Now the output clearly shows the object’s state, which is much more useful when debugging.

Advertisements

Whenever you call repr(custom_obj), it will return the string defined in the __repr__ method. This will common for all python objects, including built-in types like lists, dictionaries, and tuples, which have their own __repr__ implementations that provide useful information about their contents.

How __repr__ Helps in Debugging

Imagine you are debugging a program with a list of custom objects:

students = [
    MyCustomClass("Alice", "Smith"),
    MyCustomClass("Bob", "Johnson")
]
print(students)

Output with __repr__:

[MyCustomClass(first_name='Alice', last_name='Smith'),
 MyCustomClass(first_name='Bob', last_name='Johnson')]

This gives you an immediate snapshot of the list contents, saving time compared to printing each attribute manually. For example if you already familiar with django models, the __repr__ method is often used to provide a concise summary of model instances, which is invaluable during development and debugging.

Beyond __repr__: Rich Representations in Jupyter

In Jupyter notebooks, we have additional capabilities to customize the representation of objects using special methods like _repr_html_, _repr_json_, _repr_svg_, etc., which allow for rich representations in different formats.

For example, you may seen from scikit-learn library, when you create a model and display it in a Jupyter notebook, it often shows a nicely formatted HTML representation of the model, which is made possible by implemention of these special methods.

This special method _repr_*_ are called by Jupyter notebook to render the object in different formats, enhancing the user experience when working with complex objects.

from sklearn.linear_model import LogisticRegression
model = LogisticRegression()
model  # In a Jupyter notebook, this will display a rich HTML representation of the model

The output will be a nicely formatted HTML representation of the Logistic Regression model, showing its parameters and other relevant information in a user-friendly way.

Advertisements

👉 In the next part, we’ll explore the different representation methods that support Jupyter notebooks (such as _repr_html_, _repr_mimebundle_, and others) and learn when and how to use them.

Next Part: https://wearexplorer.com/2025/10/21/mastering-jupyters-special-repr-methods/

Reference Links:

  1. https://discuss.python.org/t/what-are-the-differences-between-str-and-repr-in-class-methods/44142
  2. https://docs.python.org/3/reference/datamodel.html#object.repr

👋

← Back

Thank you for your response. ✨

Rate your experience(required)

Leave a Reply


Join the Club

Stay updated with our latest tips and other news by joining our newsletter.

Advertisements

Discover more from WE ARE XPLORER

Subscribe now to keep reading and get access to the full archive.

Continue reading

Update cookies preferences