[docs] documentation for 2.7.3 __repr__ and __str__

g1234 at arcor.de g1234 at arcor.de
Tue Mar 12 17:11:00 CET 2013


my name is Richard and I first want to compliment for the great thing of python and of course it's documentation.

I found an issue I would like to discuss in the description of the __repr__ attribute.

It says there about __repr__: "Called by the repr() built-in function ..."

And further: "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."

And about __str__ it says: "... by the print statement to compute the “informal” string representation of an object. This differs from __repr__() in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead."

At another place I read that __str__ is supposed to be human readable and that python falls back to __repr__ if there is no __str__ defined.

Lets say we have a Color class which holds the name of the color and it's RGB values, than I would interpret this as have the attributes return something like the following:

__repr__:  "{'name':'red', 'red':255, 'green':0, 'blue':0}"
__str__:    "Color: red [255, 0, 0]"

The first would be readable by a python program and convert to an instance of the Color class and the latter is information rich, compact and alot better human readable. This is supported by the real purpose of the repr() function which is meant to serialize data for persistent storage or to transmit across a wire.

In practice it is alot worse, many classes follow the documentation and have their __repr__ produce something like <xyz object at 0x94738237> which is in no way human readable and information rich. If this is "some useful description" at all, like the documentation asks for, I would deny.

But the documentation suggests for __repr__: "This is typically used for debugging..." Which is wrong from my point of view.

Especially, since I found out, that __repr__ is also, at least sometimes, used in comparison of objects.

Conclusion: I would like to suggest to move the line that starts with: "This is typically used for debugging ...", to the __str__ attribute, suggesting to developers of debugging tools do dispay information rich, compact and human readable information to humans and leave __repr__ for machine to machine communication.

Thanks for taking the time,


More information about the docs mailing list