Join our newsletter for the latest updates.

Python repr()

The repr() function returns a printable representation of the given object.

The syntax of repr() is:

repr(obj)

repr() Parameters

The repr() function takes a single parameter:

  • obj - the object whose printable representation has to be returned

Return value from repr()

The repr() function returns a printable representational string of the given object.


Example 1: How repr() works in Python?

var = 'foo'

print(repr(var))

Output

'foo'

Here, we assign a value 'foo' to var. Then, the repr() function returns "'foo'", 'foo' inside double-quotes.

When the result from repr() is passed to eval(), we will get the original object (for many types).

>>> eval(repr(var))
'foo'

Example 2: Implement __repr__() for custom objects

Internally, repr()function calls __repr__() of the given object.

You can easily implement/override __repr__() so that repr() works differently.

class Person:
    name = 'Adam'

    def __repr__(self):
        return repr('Hello ' + self.name )

print(repr(Person()))

Output

'Hello Adam'