__str__ vs. __repr__
Thomas A. Bryan
tbryan at python.net
Sat Nov 6 03:27:10 EST 1999
Donn Cave wrote:
> repr is used
> in lots of places, like the interactive interpreter,
I think that was Tim's point. Earlier he said:
"""For that matter, why is repr implied at an interactive prompt given
a raw expression? Seems that friendly strings would be more
He wants str to be used at the interpreter since it's supposed to be
the human readable form. One of Guido's complaints was that then
1 and '1' then look the same.
> On the contrary, it's str() that's intended for the machine, and
> repr() for the human.
>From the library reference:
Return a string containing a printable representation of an object.
This is the same value yielded by conversions (reverse quotes). It
is sometimes useful to be able to access this operation as an
ordinary function. For many types, this function makes an attempt
to return a string that would yield an object with the same value
when passed to eval().
Return a string containing a nicely printable representation
of an object. For strings, this returns the string itself.
The difference with repr(object) is that str(object) does not
always attempt to return a string that is acceptable to eval();
its goal is to return a printable string. """
The problem is that this thread is the first time many of us have
ever thought about the problem. I've never noticed those two lines
in the library reference, and I haven't seen the str/repr distinction
clearly made anywhere else. Furthermore, since the interactive i
nterpreter *does* use repr(), many of us make __repr__ return the
human readable form so that we can easily test our classes.
So, what I'm hearing is:
1. __str__ *should* be a human readable string
2. __repr__ *should* be a representation that can be eval'd back to the
3. This convention is not widely known, but
3b. the interactive interpreter discourages the convention by using
repr to show the result of an expression
Therefore, we could switch the convention for str and repr, which breaks
things that are currently following the convention.
Or we could switch the interactive interpreter to use str to encourage
class writers to follow the convention. Of course, any class writers
who intentionally switched __repr__ and __str__ to get nice interactive
behavior will have to switch the mehtods back.
Since Tim voted for the second option, that's probably what Guido will
decide. ;) Either way, Guido still has to deal with non-printing
characters, string-vs-number distinctions, and other insanity in the
More information about the Python-list