Python repr() Function
The repr()
function returns a printable representation of an object.
The repr()
function calls the underlying __repr__()
method of the object.
This representation is intended to be unambiguous and, if possible, should be a valid Python expression that could be used to recreate the object by using the eval()
function.
Syntax
repr(obj)
repr() Parameters
Python repr()
function parameters:
Parameter | Condition | Description |
---|---|---|
obj | Required | The object whose printable representation has to be returned |
repr() Return Value
Python repr()
function returns a string that is the printable representation of the object.
Examples
Example 1: Representation of an integer
x = 10
repr_str = repr(x)
print(repr_str) # Output: 10
print(type(repr_str)) # Output: <class 'str'>
output
10
<class 'str'>
Example 2: Representation of a String
s = 'Hello World!'
repr_str = repr(s)
print(repr_str) # Output: 'Hello World!'
print(type(repr_str)) # Output: <class 'str'>
output
'Hello World!'
<class 'str'>
Example 3: Representation of a List
my_list = [1, 2, 3]
repr_str = repr(my_list)
print(repr_str) # Output: [1, 2, 3]
print(type(repr_str)) # Output: <class 'str'>
output
[1, 2, 3]
<class 'str'>
Example 4: Representation of a Set
my_set = {1, 2, 3}
repr_str = repr(my_set)
print(repr_str) # Output: {1, 2, 3}
print(type(repr_str)) # Output: <class 'str'>
output
{1, 2, 3}
<class 'str'>
Example 5: Representation of a Tuple
my_tuple = (1, 2, 3)
repr_str = repr(my_tuple)
print(repr_str) # Output: (1, 2, 3)
print(type(repr_str)) # Output: <class 'str'>
output
(1, 2, 3)
<class 'str'>
Example 5: Implementing __repr__()
for Custom Objects
To use the repr()
function with you custom objects, you need to implement the __repr__()
function in your class.
This because the repr()
built-in function calls the __repr__()
method to get the string representation.
For example, consider the following Person
class in which the __repr__()
method is implemented:
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})"
Then, you can use the repr()
function on instances of Person
class:
person = Person("Tom", 25)
print(repr(person)) # Output: Person(name='Tom', age=25)
output
Person(name='Tom', age=25)