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"
Similar Reads
Python repr() Function
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.' enclose
4 min read
Python range() function
The Python range() function returns a sequence of numbers, in a given range. The most common use of it is to iterate sequences on a sequence of numbers using Python loops. Example In the given example, we are printing the number from 0 to 4. [GFGTABS] Python for i in range(5): print(i, end="
7 min read
Python str() function
The str() function in Python is an in-built function that takes an object as input and returns its string representation. It can be used to convert various data types into strings, which can then be used for printing, concatenation, and formatting. Let’s take a simple example to converting an Intege
4 min read
Python Functions
Python Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it ov
10 min read
Function Wrappers in Python
Wrappers around the functions are also knows as decorators which are a very powerful and useful tool in Python since it allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of the wrapped function, without perman
2 min read
type() function in Python
The type() function is mostly used for debugging purposes. Two different types of arguments can be passed to type() function, single and three arguments. If a single argument type(obj) is passed, it returns the type of the given object. If three argument types (object, bases, dict) are passed, it re
5 min read
Python min() Function
Python min() function returns the smallest of the values or the smallest item in an iterable passed as its parameter. Example: Find Python min integer from the list [GFGTABS] Python numbers = [23,25,65,21,98] print(min(numbers)) [/GFGTABS]Output 21Python min() Function Syntaxmin(a, b, c, ..., key=fu
4 min read
Python len() Function
len() function returns number of items in an object that can be characters, words, or elements in a sequence. Let’s start with a simple example to understand the len() functions with strings: [GFGTABS] Python s = "GeeksforGeeks" # Use len() to find the length of the string length = len(s)
2 min read
Python - all() function
The Python all() function returns true if all the elements of a given iterable (List, Dictionary, Tuple, set, etc.) are True otherwise it returns False. It also returns True if the iterable object is empty. Sometimes while working on some code if we want to ensure that user has not entered a False v
3 min read
Python pow() Function
Python pow() function returns the result of the first parameter raised to the power of the second parameter. Syntax of pow() Function in Python Syntax: pow(x, y, mod) Parameters : x : Number whose power has to be calculated.y : Value raised to compute power.mod [optional]: if provided, performs modu
2 min read
Python oct() Function
Python oct() function takes an integer and returns the octal representation in a string format. In this article, we will see how we can convert an integer to an octal in Python. Python oct() Function SyntaxSyntax : oct(x) Parameters: x - Must be an integer number and can be in either binary, decimal
2 min read
Python map() function
The map() function is used to apply a given function to every item of an iterable, such as a list or tuple, and returns a map object (which is an iterator). Let's start with a simple example of using map() to convert a list of strings into a list of integers. [GFGTABS] Python s = ['1', '
4 min read
sum() function in Python
The sum of numbers in the list is required everywhere. Python provides an inbuilt function sum() which sums up the numbers in the list. [GFGTABS] Python arr = [1, 5, 2] print(sum(arr)) [/GFGTABS]Output8 Sum() Function in Python Syntax Syntax : sum(iterable, start) iterable : iterable can be anything
3 min read
Python open() Function
The Python open() function is used to open internally stored files. It returns the contents of the file as Python objects. Python open() Function SyntaxThe open() function in Python has the following syntax: Syntax: open(file_name, mode) Parameters: file_name: This parameter as the name suggests, is
3 min read
Python | fmod() function
fmod() function is one of the Standard math library function in Python, which is used to calculate the Module of the specified given arguments. Syntax: math.fmod( x, y ) Parameters: x any valid number (positive or negative). y any valid number(positive or negative). Returns: Return a floating point
2 min read
Wand sharpen() function - Python
The sharpen() function is an inbuilt function in the Python Wand ImageMagick library which is used to sharpen the image. Syntax: sharpen(radius, sigma) Parameters: This function accepts four parameters as mentioned above and defined below: radius: This parameter stores the radius value of the sharpn
2 min read
Python input() Function
Python input() function is used to take user input. By default, it returns the user input in form of a string. input() Function Syntax: input(prompt)prompt [optional]: any string value to display as input message Ex: input("What is your name? ") Returns: Return a string value as input by the user.
4 min read
Python | math.sin() function
In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.sin() function returns the sine of value passed as argument. The value passed in this function should be in radians. Syntax: math.sin(x) Parameter: x : value to be passed to s
1 min read
Python print() function
The python print() function as the name suggests is used to print a python object(s) in Python as standard output. Syntax: print(object(s), sep, end, file, flush) Parameters: Object(s): It can be any python object(s) like string, list, tuple, etc. But before printing all objects get converted into s
2 min read