1

I am trying to understand difference between __str__ and __repr__ and following Difference between __str__ and __repr__ in Python

In the answer it says __repr__'s goal is to be unambiguous, I am confused what that really means. Another answer says: __repr__: representation of python object usually eval will convert it back to that object, so I have read that eval function let execute the python code in it.

Can someone please explain these terms in simple language:

  • What is object reconstruction?
  • What is __repr__?
  • What is the connection between eval and __repr__?
Community
  • 1
  • 1

1 Answers1

4

Perhaps a simple example will help clarify:

class Object:

    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return 'Object({0.a!r}, {0.b!r})'.format(self)

This object has two parameters defined in __init__ and a sensible __repr__ method.

>>> o = Object(1, 2)
>>> repr(o)
'Object(1, 2)'

Note that the __repr__ of our object now looks exactly like how we created it to begin with; it's legal Python code that supplies the same values. As the data model documentation puts it:

If at all possible, [__repr__] should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment).

That's where eval comes in:

>>> x = eval(repr(o))
>>> x.a
1
>>> x.b
2

Because the representation is Python code, we can evalulate it and get an object with the same values. This is "reconstructing" the original object o.

However, as pointed out in the comments, this is just an illustration and doesn't mean that you should rely on repr(eval(x)) when trying to create a copy of x.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • It would be useful to note "this is how you'd typically write `repr(..)` if writing one and definitely not how `repr(..)` and `eval` should be used". I remember someone using this combination to clone objects.. – UltraInstinct Oct 03 '16 at 07:11