__str__ vs. __repr__
Toby Dickenson
htrd90 at zepler.org
Sun Nov 7 09:13:45 EST 1999
"Tim Peters" <tim_one at email.msn.com> wrote:
>Let me back off to what repr and str "should do":
>
>repr(obj) should return a string such that
> eval(repr(obj)) == obj
I don't understand the motivation for this requirement. Why would
anyone want to pass such a string to eval? If you anticipate the need
for reconstructing the object from a textual representation, then
surely pickle is a better option?
Alternatively, most classes could implement __repr__ as :-)
def __repr__(self):
return "pickle.loads(%s)" % repr(pickle.dumps(self))
>repr() currently cheats in another way: for purely aesthetic reasons,
>repr(float) and repr(complex) don't generate enough digits to allow exact
>reconstruction of their arguments (assuming high-quality float<->string in
>the platform libc). This is a case where an argument appropriate to str()
>was applied to repr(), not because it makes *sense* for repr, but because so
>much output goes thru an *implicit* repr() now and you didn't want to see
>all those "ugly" long float strings <0.50000000000000079 wink>.
OK, so repr as it stands today is clearly not suitable for formatting
for people, and is less than ideal for formatting for the machine.
However there is a third audience for who it is ideal, the programmer,
who need a representation for use in development tools such as
debuggers, or the interactive mode.
Tim's Rat class is a good example of how __repr__ should not be
implemented, because it exposes the internal representation of the
object, not the external value.
However, using a small number of digits for repr(float) does make
sense because it still provides sufficient precision for most
programmers.
Toby Dickenson
More information about the Python-list
mailing list