The Wayback Machine - https://web.archive.org/web/20250118002241/https://www.geeksforgeeks.org/python-repr-function/
Open In App

Python repr() Function

Last Updated : 03 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python repr() Function returns a printable representation of an object in Python. In other words, we can say that the Python repr() function returns a printable representation of the object by converting that object to a string.

Example

In the code, repr(s) returns the string ‘Hello, Geeks.’ enclosed in single quotes. repr(2.0/11.0) calculates the division of 2.0 by 11.0 and returns the result as a string without any formatting or rounding.

Python
s = 'Hello, Geeks.'
print (repr(s))
print (repr(2.0/11.0))

Output :

'Hello, Geeks.'
0.18181818181818182

Python repr() Function Syntax

Syntax: repr(object)

  • object: The object whose printable representation is to be returned.

Return: str, printable representation of the object.

How repr() works in Python?

Here we assign an integer value of 10 to a variable x and the repr() of x is returning the value 10 as a string class.

Python
x = 10
print(type(repr(x)))

Output :

<class 'str'>

repr() in Python Examples

Passing List to repr() in Python

In this example, we are using repr() on the list.

Python
print(repr(['a', 'b', 'c']))

Output :

['a', 'b', 'c']

Passing string object to repr() method

In this example, we are calling the repr() on the string object in Python.

Python
strObj = 'geeksforgeeks'

print(repr(strObj))

Output :

'geeksforgeeks'

Passing a set object to the repr() method

In this example, we have created a set. The set includes numbers from 1 to 5 and we are calling the repr() on the set.

Python
num = {1, 2, 3, 4, 5}

# printable representation of the set
printable_num = repr(num)
print(printable_num)

Output :

{1, 2, 3, 4, 5}

Implement __repr__() for custom objects

In this example, the Person class has a __repr__() method that returns a string representation of the Person object. The repr(person) call returns the string representation defined by the __repr__() method, which is then printed to the console.

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})"

person = Person("John", 25)
print(repr(person))

Output :

Person(name='John', age=25)

To know the difference between str and repr Click here.

Python repr() Function – FAQs

Can you provide an example of using repr() on a built-in data type?

The repr() function in Python returns a string representation of an object that is meant to be unambiguous and useful for debugging. Here’s how repr() works with a built-in data type:

# Example with a string
text = "Hello, World!"
print(repr(text)) # Output: "'Hello, World!'"

# Example with a list
numbers = [1, 2, 3, 4, 5]
print(repr(numbers)) # Output: '[1, 2, 3, 4, 5]'

# Example with a dictionary
data = {'name': 'Alice', 'age': 30}
print(repr(data)) # Output: "{'name': 'Alice', 'age': 30}"

How to customize the output of repr() for a custom class?

To customize the output of repr() for a custom class, override the __repr__() method in your class. This method should return a string that ideally includes information needed to recreate the object.

Example:

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

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

# Create an instance
p = Person("Alice", 30)
print(repr(p)) # Output: Person(name='Alice', age=30)

Why is repr() useful for debugging?

repr() is useful for debugging because it provides a detailed and unambiguous string representation of an object. Unlike str(), which is intended for human-readable output, repr() aims to provide a clear and accurate representation of the object’s internal state, which helps developers understand what is happening in the code.

How to override the __repr__() method in a class?

To override the __repr__() method, define it in your class to return a string that includes relevant details about the object.

Example:

class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year

def __repr__(self):
return f"Car(make={self.make!r}, model={self.model!r}, year={self.year!r})"

# Create an instance
my_car = Car("Toyota", "Corolla", 2020)
print(repr(my_car)) # Output: Car(make='Toyota', model='Corolla', year=2020)

What is the purpose of __repr__() compared to __str__()?

__repr__():

Purpose: Provides an unambiguous representation of the object. It is meant for developers and debugging.

Usage: The output of __repr__() should be a valid Python expression that could be used to recreate the object, if possible.

Example:

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

__str__():

Purpose: Provides a readable, human-friendly string representation of the object.

Usage: The output of __str__() is intended to be more user-friendly and suitable for display.

Example:

def __str__(self):
return f"{self.name} is {self.age} years old"


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg