__str__ vs. __repr__

Gordon McMillan gmcm at hypernet.com
Sun Nov 7 11:32:07 EST 1999


Toby Dickenson writes:

> "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?

It's not human editable. I guess you've never used 
 open('xxx.xxx','w').write(repr(dict))
and
 dict = eval(open('xxx.xxx','r'),read())

as a cheap config file.

> 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. 

For strings, ints, lists, tuples and dicts it is dandy for both 
right now. For longs it's good for machines; for some others 
it's OK for some users.

It doesn't make a whole lot of sense for low-level objects 
involving open resources, but it does make a great deal of 
sense for user objects which would represent a URL as a 
string, or a file as a (filename, mode). You can then make 
repr(object) yield a valid constructor and include high level 
objects in your config file, or cut and paste from interactive to 
a script.

Whether you use them or not, these are very valuable features 
that are promised (but not entirely fulfilled). 

> 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.
> 
There's been some debate about interactive mode. I would 
personally prefer that interactive mode err on the side of 
excess accuracy, (I find pprint to be a necessity for complex 
structures, and whether repr or str is used, that's not going to 
change). Debuggers should not be relying on either, but 
should pick apart the object through knowledge of Python 
internals.

> 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.

Tim's Rat class should provide a separate __str__ 
implementation.
 
> However, using a small number of digits for repr(float) does make
> sense because it still provides sufficient precision for most
> programmers.

For human consumption, I *always* use % formatting with 
floats - there's no way that float can know whether the human 
is a chemist or a bean-counter, (if the latter qualify at all).


- Gordon




More information about the Python-list mailing list