eval(repr(object)) hardly ever works

Donn Cave donn at u.washington.edu
Wed Sep 13 12:19:53 EDT 2006


In article <1158157045.593941.64050 at i42g2000cwa.googlegroups.com>,
 "Hardcoded Software" <hardcoded.software at gmail.com> wrote:
> Matthew Wilson wrote:
> > I understand that idea of an object's __repr__ method is to return a
> > string representation that can then be eval()'d back to life, but it
> > seems to me that it doesn't always work.
> >
> > For example it doesn't work for instances of the object class:
> >
> > In [478]: eval(repr(object()))
> > ------------------------------------------------------------
> >    File "<string>", line 1
> >      <object object at 0xf233e8>
> >      ^
> > SyntaxError: invalid syntax
> >
> > It seems to work for types like integers and dictionaries and lists,
> > but not for much else.

> I don't think that repr() is for eval(). repr() is for outputting a
> string that represent the object and is not ambiguous. Example: print
> 'foo' == print u'foo' but print repr('foo') != print repr(u'foo')

Right, but that eval() idea dies hard.  The document excerpt
quoted in an earlier followup, for __repr__, now admits that it
might not be possible ... but then the documentation for __str__
right below it says "differs from __repr() in that it does not
have to be a valid Python expression".  There's plenty of evidence
in the standard libraries that people understand these two functions,
but they certainly have arrived at that understanding from some
other route than reading the documentation.

   Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list