Python repr()


Python repr() is a built-in function that returns a string containing a printable representation of an object.

python repr()

In Python, both str() and repr() return the printable representation of given object. We will learn about the difference between str() and repr() in a bit.

Python repr() Syntax

repr(object)

repr() rakes only one parameter as an argument.

  • object (required) – whose printable representation has to be returned

Python repr() Example

>>> repr(5)
'5'

>>> #repr() with list
>>> repr([1,2])
'[1,2]'

>>> #repr() with tuple
>>> repr((3,4))
'(3,4)'

>>> #repr() with dictionary
>>> repr({'x':1,'y':2})
"{'x': 1, 'y': 2}"

>>> #repr() with strings
>>> repr('Python')
"'Python'"

As you can see in above example, for many types, repr() makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object.

Behind the scenes, repr() function utilizes __repr__() method of the given object to return the printable representation.

A class can be used to control what repr() returns for its instances by defining a __repr__() method.

Customizing __repr__() for  custom objects

>>> class Example:
      def __repr__(self):
          return 'bar'

>>> repr(Example())
'bar'

Now that you know about repr() function, you might be wondering what exactly is the difference between this Python repr() function and str() function as both returns the string containing the printable representation of an object.

Python repr() vs Python str()

Here are some of the things that are different about repr() and str() functions in Python.

  • Behind the scenes, repr() uses the built-in  method __repr__() of the object to return the printable string representation while str() uses __str__() method of an object
  • The goal of using str() function is to return a printable string that is easy for user to read, while repr() function is mainly used for debugging and development and it has all the information about the object