FAQ: __str__ vs __repr__
donn at u.washington.edu
Wed Jun 15 18:53:38 CEST 2005
In article <42b021ba$1 at griseus.its.uu.se>,
Jan Danielsson <jan.danielsson at gmail.com> wrote:
> Sorry, but I Just Don't Get It. I did search the 'net, I did read the
> FAQ, but I'm too dumb to understand.
> As far as I can gather, __str__ is just a representation of the
No, it is not. It is a conversion to string. The result has
no trace of the original object, per se -- in principle, many
different kinds of object could yield the same result. Suppose
str(x) -> "42". Is x an int? a string? an XMLParseResult?
AnswerToLifeTheUniverseAndEverything? You don't want to know,
that's why you use str().
The "friendly" idea is vacuous if you look hard enough at it,
and won't really help.
> However, I don't understand what __repr__ should be. There's a phrase
> in the documentation which makes it highly confusing for a beginner like
> me: "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).". What does that mean?
It's kind of a bad idea that the Python world isn't ready to
let go of yet.
repr() is really the representation of the object. If you
look at the result of repr(x), you should indeed see some
clue to the original object. I guess this is what gives
people the idea that str() is friendly, because as a rule
users are not interested in the original object -- but
there are exceptions, for example you may find the quotes
useful around a string, depending on the situation. The
object information also leads to the marshalling idea, but
of course this isn't (and can't be) implemented for many
objects so we can't expect this to work reliably with
random objects. The price we pay for the notion is mostly
in the "fix" for float repr, which now displays the float
in all its imprecise glory and routinely confounds people
who don't understand what that's about.
Donn Cave, donn at u.washington.edu
More information about the Python-list