Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the relationship between __repr__ and eval(), and what is the main purpose of __repr__? [closed]

I just came across this question Difference between __str__ and __repr__ in Python and its mentioned that the main purpose of the __repr__ is to be unambiguous. But I heard that the main purpose of the __repr__ is to generate a string such that eval() can reconstruct the python object later. Actually what is the main purpose of __repr__? Do any built-in functions or any default modules in python inherently use __repr__ to reconstruct the object? Will it mess up the execution if we just overwrite __repr__ such that it returns a constant string (e.g. "foo") always?

like image 902
RoboAlex Avatar asked Oct 19 '25 14:10

RoboAlex


1 Answers

For types that have a literal notation (str, int, float, list, etc.) the repr() returns a string that can be used to create the type again.

That is nice, but not a requirement.

The main purpose for __repr__ is to provide the developer with unambiguous information as to what object they have here, for debugging purposes.

Quoting from the __repr__ documentation:

Called by the repr() built-in function to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form <...some useful description...> should be returned.

but most of all:

This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.

Emphasis mine.

Returning a constant string from your custom type would not break anything technically, but would make your life as a developer harder.

like image 147
Martijn Pieters Avatar answered Oct 21 '25 02:10

Martijn Pieters