Python Repr() with Examples

In this article, we will talk about the repr() function. The name “repr” stands for representation. According to official Python documentation, the repr() function is used to get a printable string representation of an object and the string can often yield an object when evaluated using the eval() function.

repr() is a Python built-in function and when called, it invokes the __repr__() method. We can use it when we want to debug or to know information about an object. It takes one object as its argument and returns a legal string representation of the passed object.

Example of Python Repr()

website = "PythonGeeks"
result = repr(website)
print(result)
print(type(result))

Output

‘PythonGeeks’

<class ‘str’>

From the above sample code, we can understand the following:

Syntax

repr(object)

Parameters

Number of parameters: 1 (One)

    Required: 1 (One)

    Optional: 0 (zero)

Parameter type: Object  [Required] 

Do remember that in Python, almost everything is an object. So you can pass almost everything (int, char, iterable, function, class, etc.) to repr(). 

Return

repr() returns a printable string representation of the passed object.

Return type:  String

Working of repr() Function in Python

Whenever we initialize a class in Python, it automatically inherits an object class. This means every class is a subclass of an object class in Python.

This is shown in the below code.

Python Repr() Example

class Website:
  pass

print(issubclass(Website, object))

Output

True

All classes inherit a few methods from the object class called Magic Methods or Dunder Methods.

We can see those methods in the below code.

Example of Magic Method in Python

print(dir(Website))

Output

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

When we run a repr() function, it internally invokes the __repr__() method which is already present in the class as seen in the above code.

When a class is passed to the repr() function, it returns a string containing the name of the passed class and the id of the passed class’s instance.

Python repr Function Example:

print(repr(Website()))

Output:

<__main__.Website object at 0x104411ac0>

We can use this to our advantage and override the __repr__() method to make it return a string of our choice and create custom objects.

Overriding __repr__() Method to Create a Custom Object

Since Python is an object-oriented programming language, it gives us the ability to override methods.

All we need to do is define a method in child class with the same name as a method in the parent class.

Example of Overriding repr() Method

class Website:
  
   def __repr__(self):
       return "PythonGeeks"
  
print(repr(Website()))

Output:

PythonGeeks

Now unlike before, repr() returns a string of our choice.

We can also make it a bit dynamic like in the below code.

Code:

class Website:
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return f"Website name is {self.name}"

website1 = Website("PythonGeeks")
website2 = Website("Google")

print(repr(website1))
print(repr(website2))

Output:

Website name is PythonGeeks
Website name is Google

In this way, we can create custom objects which can return custom strings.

How is repr() different from str()

If you’ve ever encountered the str() function, you might now wonder, how the str() function is different from the repr() function. Well, look no further because we got it covered.

Although repr() and str() both return a similar-looking string, the style of the content within the string is different.

str() returns an easily readable unofficial string while repr() returns an official univocal string.

We say official because the string produced by the repr() function can be later used as an argument for the eval function.

This is explained in detail in the following code.

Code:

website = "PythonGeeks"
print(eval(repr(website)))

Output:

PythonGeeks

In the above code, repr() returned a string which when passed to eval() returned an object.   

Code:

print(eval(str(website)))

Output:

Traceback (most recent call last):  

    File “/Users/apple/PythonGeeks/repr.py”, line 3, in <module>

        print(eval(str(website)))

    File “<string>”, line 1, in <module>

NameError: name ‘PythonGeeks’ is not defined

As seen in the above code, the string returned by str() can not be passed to eval() unlike repr() function.

Since repr() is univocal and legal, it is a better choice for debugging than str().

repr() and str() invoke two different magic methods. You can see the same in below example:

Code:

class Website:

   def __init__(self, name, domain):
       self.name = name
       self.domain = domain

   def __repr__(self):
       return f"Website({self.name}, {self.domain})"

   def __str__(self):
       return f"Website is {self.name}.{self.domain}"

website1 = Website("PythonGeeks", "com")
print(repr(website1))
print(str(website1))

Output:

Website(PythonGeeks, com)

Website is PythonGeeks.com

In the above code, repr() invoked __repr__() method and str() invoked _str__() method. 

repr() vs str()

repr() str()
Clearer and unambiguous More easily readable
Better choice for debugging Typically not preferred for debugging
Can be passed to eval() Passing to eval() raises an error
Invokes __repr__() Invokes __str__()

str() invokes __repr__() method

In Python, overriding only _repr__() method causes str() function to invoke __repr__() method instead of __str__() method. This can be seen in the below code

Code:

class Vehicle:
   def __repr__(self):
       return "Invoked __repr__()"

car = Vehicle()
print(repr(car))
print(str(car))

Output:

Invoked __repr__()
Invoked __repr__()

In the above code, we’ve overridden __repr__() method. This caused the str() function to call __repr__() method instead of __str__() method.

Seeing this, we may think if we override only __str__() method, then repr() invokes __str__() but this is not the case.

repr() function always invokes __repr__() method as in below example.

Code

class Vehicle:
   def __str__(self):
       return "Invoked __str__()"

car = Vehicle()
print(repr(car))
print(str(car))

Output

<__main__.Vehicle object at 0x10d5ce8b0>Invoked __str__()

In the above code, we’ve overridden __str__() method but still repr() invoked __repr__() method unlike str(). Thus, repr() always invokes __repr__() method.

When to use Python repr() function

Since we learned what is repr() and how to use it, now it is time to learn when to use it.

1. repr() returns a string that is clear and univocal, and due to these characteristics, repr() is an excellent yet simple tool to debug a program when needed.

2. When working with eval()

3. When working with data files such as .csv.

4. When we need to extract flat data from a file.

Points to Remember

1. repr() is a built-in function.
2. It takes one object.
3. It returns a printable string representation of the passed object
4. The string returned by repr() can be passed to eval()
5. We can make repr() return the string of our choice by overriding the __repr__() method of the passed object.
6. repr() is more univocal whereas str() is easily readable.
7. Debugging is better with repr() than str()
8. repr() invokes __repr__() whereas str() invokes _str__()
9. repr() is used to extract flat data from a file and when working with other data files.

Python repr() Interview Questions

Q1. What is the output of the following code?

Code

class Computer:
   def __repr__(self):
       return "Class name Computer"

my_comp = Computer()

if repr(my_comp) == str(my_comp):
   print("Both return same")
else:
   print("Both return different")

Ans 1. The output of the given code is

Both return same

Q2. Complete the code.

Sample Input

smith 18

Sample Output

Smith is 18 years old.
Person(smith, 18)

Code

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

   # Your Code Here

p_name, p_age = input().split()
p1 = Person(p_name, p_age)

print(str(p1))
print((repr(p1)))

Answer 2:

Code

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

    # Your Code Here

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

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


p_name, p_age = input().split()
p1 = Person(p_name, p_age)

print(str(p1))
print((repr(p1)))

Input

ram 24

Output

Ram is 24 years old.
Person(ram, 24)

Q3. What is the output of the following code?

Code

number = 24

print(repr(number))
print(eval(repr(number)))

if repr(number) == eval(repr(number)):
   print("True")
else:
   print("False")

Answer 3: The output is

24
24
False

Q4. What is the output of the following code?

Code

website = "PythonGeeks"

if type(repr(website)) == str:
   print(f"{repr(website)} is type String.")
else:
   print(f"{repr(website)} is not type String.")

if type(eval(repr(website))) == str:
   print(f"{eval(repr(website))} is type String.")
else:
   print(f"{eval(repr(website))} is not type String.")

if repr(website) == eval(repr(website)):
   print("Both are same")
else:
   print("Both are different")

Answer 4. The output of the given code is

‘PythonGeeks’ is type String.

PythonGeeks is type String.

Both are different

Q5. Give an example of the repr() function.

Answer 5.

Code

a = "Hello World"
print(repr(a))

Output

‘Hello World’

Python Repr() Quiz

Conclusion

In this article, we learned about the repr() function and how to use it. We have discussed how the repr() function works and how to change it whenever needed. We have also learned the difference between repr() and str() functions.

Furthermore, if you have any queries, please feel free to share them with us in the comment section.

We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google | Facebook


Leave a Reply

Your email address will not be published. Required fields are marked *