Table of contents
1.
Introduction
2.
What is repr() in Python?
2.1.
Python repr() Function Syntax
2.2.
Python repr() Function Parameters
2.3.
Python repr() Function Return Value
3.
How repr() Works in Python?
3.1.
Example 1: Using repr() with Built-in Types      
4.
Python
4.1.
Example 2: Using repr() with User-defined Classes
5.
Python
6.
Python __repr__ Implementation
6.1.
Example 1
6.2.
Python
6.3.
Example 2
6.4.
Python
7.
Magic Methods
8.
Frequently Asked Questions
8.1.
How __repr__ can be used for logging and debugging?
8.2.
How __repr__ can be used for serializing and deserializing?
8.3.
What does repr mean?
8.4.
What is __repr__ and __str__ in Python?
8.5.
Does print use __repr__ or __str__?
9.
Conclusion
Last Updated: Jan 22, 2025
Easy

Python __repr__

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Python programming, understanding the __repr__ method is akin to unlocking a powerful tool for object representation and debugging. Often overshadowed by its sibling method __str__, __repr__ plays a crucial role in defining how Python objects are represented as strings. Whether you're a novice programmer or a seasoned developer, mastering __repr__ can significantly enhance your ability to inspect and understand Python objects.

Python __repr__

What is repr() in Python?

The repr() function in Python returns a string representation of an object that is unambiguous and primarily intended for debugging. It calls the object's __repr__ method, which should provide a detailed and developer-friendly description. The goal is to produce a string that, if passed to eval(), can recreate the object (when feasible).

Python repr() Function Syntax

repr(object)
  • object: The object for which you want the string representation.

Python repr() Function Parameters

  • object (required): Any Python object (e.g., int, list, string, custom objects).

Python repr() Function Return Value

  • Returns a string that is a valid Python expression representing the given object. For built-in types, it shows a precise, unambiguous representation. It depends on the implementation of the __repr__ method for user-defined types.

How repr() Works in Python?

The repr() function in Python calls an object’s __repr__() method to obtain its string representation. For built-in types, Python provides a default __repr__ implementation that outputs a developer-friendly, unambiguous representation of the object. For user-defined classes, you can override the __repr__ method to customize the output.

Example 1: Using repr() with Built-in Types      

  • Python

Python

# Using repr() with different objects
print(repr(123))
print(repr(3.14))
print(repr("Hello, world!"))
print(repr([1, 2, 3]))
You can also try this code with Online Python Compiler
Run Code

Output:

'123'
'3.14'
"'Hello, world!'"
'[1, 2, 3]'

Example 2: Using repr() with User-defined Classes

  • Python

Python

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def __repr__(self):
return f"Person(name='{self.name}', age={self.age})"

# Create an instance of Person
person = Person("Rahul", 30)

# Use repr()
print(repr(person))
You can also try this code with Online Python Compiler
Run Code

Output:

Person(name='Rahul', age=30)

Python __repr__ Implementation

In this section of the article “Python __repr__”, we will see the implementation of the __repr__() method.

Example 1

In this example, we will implement __repr__ in python by creating a class “Car”.

Code

  • Python

Python

# Creating class "Car"
class Car:

   # Creating __init__ method to initialize the instance variables
   def __init__(self, name, model):
       self.name = name
       self.model = model
     
   # Creating __repr__ method to represent the object of class "Car"
   def __repr__(self):
       rep = 'Car(' + self.name + ', ' + self.model + ')'
       return rep

# Creating the objects "car1" and "car2" of class "Car"
car1 = Car("BMW", "i7")
car2 = Car("Mercedes", "S-Class")

# Representation of objects "car1" and "car2" by printing them using repr() method
print(repr(car1))
print(repr(car2))
You can also try this code with Online Python Compiler
Run Code

Output

output 1

Explanation

In the above code, we created a class called “Car”, in which two magic methods are present. One magic method is the __init__() method, which will be called automatically for the initialization. The second magic method is __repr__() method which is called for the representation of the object of this class, there is a string returned as the result of this method. After that, two objects are created whose names are “car1” and “car2”, which is then passed to the repr() method, and the printing is done.

Example 2

Let's take one more example to understand better In this example, we will create a class called “College”, where we will represent its object using the __repr__ method. Here is the code for the same:

Code

  • Python

Python

# Creating class "College"

class College:

   # Creating __init__ method to initialize the instance variables

   def __init__(self, name, country, salary):

       self.name = name

       self.country = country

       self.salary = salary

   # Creating __repr__ method to represent the object of class "College"

   def __repr__(self):

       return str(self.name)+' | '+str(self.country)+' | '+str(self.salary)

# Creating the objects "clg1", "clg2" and "clg3" of class "Collge"

clg1 = College("IIT Delhi", "India", "17 LPA")

clg2 = College("IIT Bombay", "India", "20 LPA")

clg3 = College("IIM Bangalore", "India", "23 LPA")

# Representation of objects "car1", "car2" and "car3" by printing them using repr() method

print(repr(clg1))

print(repr(clg2))

print(repr(clg3))

You can also try this code with Online Python Compiler
Run Code

 

Output

output 2

Explanation

In the above code, we created a class called “College”, in which two magic methods are present. One magic method is the __init__() method, which will be called automatically for the initialization. The second magic method is __repr__() method which is called for the representation of the object of this class, there is a string returned as the result of this method. After that, three objects are created whose names are “clg1”, “clg2”, and “clg3”, which is then passed to the repr() method, and the printing is done.

Magic Methods

Magic Methods, also known as Dunder methods, contain two underscores in the prefix and suffix, and Dunder means Double Underscores. Few types of magic methods are: 

  • __init__() method: There are constructors in several languages such as C++, C#, and Java. Similarly, this method used for initialization without any call.
     
  • __add__() method: It is a magic method that is used to add two objects that returns the third object.
     
  • __len__() method: It is a magic method that is used to determine the length of objects passed to this method.
     
  • __repr__() method: This method is used to represent a class’s objects and returns a string

Frequently Asked Questions

How __repr__ can be used for logging and debugging?

If there are any errors in the application created using Python, then the __repr__ method can be used to print the error or meaningful message about the object.

How __repr__ can be used for serializing and deserializing?

The __repr__ method can be used for converting objects to JSON or XML and converting them back to objects which are known as serializing and deserializing.

What does repr mean?

repr stands for "representation." It provides an unambiguous string representation of an object, useful for debugging and logging, often invoking __repr__().

What is __repr__ and __str__ in Python?

__repr__ provides a developer-friendly representation, while __str__ provides a user-friendly one. repr() calls __repr__, and str() or print() calls __str__.

Does print use __repr__ or __str__?

print() uses __str__ if available; otherwise, it defaults to __repr__. The goal is to display a readable string for users.

Conclusion

Magic Methods, also known as Dunder methods, contain two underscores in the prefix and suffix. Here __repr__ method is one of the magic methods that can be used to represent the class’s object. 

In this article, we discussed what are the magic methods, and we also discussed one of the magic methods called __repr__ along with its implementation. Here are more articles that are recommended to read:

You can also consider our paid courses such as DSA in Python to give your career an edge over others!

Happy Learning!

Live masterclass