Python repr()

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

The syntax of repr() method is:

repr(obj)

repr() Parameters

The repr() method takes a single parameter:

  • obj - object whose printable representation has to be returned

Return value from repr()

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

It returns a string that would yield an object with the same value when passed to eval().

eval(repr(obj)) = obj (approximation that holds true for most of built-in types)

Example 1: How repr() works in Python?

var = 'foo'

repr(var)

When you run the program, the output will be:

"'foo'"

Here, we assign a value 'foo' to var.

The repr() method returns "'foo'", 'foo' inside double quotes.

It is important to that 'foo' is a string so it's represented by the single quotes. 'foo' without the quotes would assign var to foo variable.

This is important because, repr() returns a string that would be of same value as passed to eval().

If we have to pass 'foo' to eval() as string, it should be passed in double quotes to escape the internal single quotes, eval("'foo'") which is same as the output of repr().


Example 2: Implement __repr__() for custom objects

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

You can easily implement/override the __repr__() method to use your own value for the repr() output.

class Person:
    name = 'Adam'

    def __repr__(self):
        return repr(self.name)

repr(Person())

When you run the program, the output will be:

"'Adam'"