eval(repr(x)) == x

Kragen Sitaker kragen at pobox.com
Mon Jan 28 21:24:17 EST 2002


Oren Tirosh <oren-py-l at hishome.net> writes:
> On Sun, Jan 27, 2002 at 08:33:28AM -0500, François Pinard wrote:
> > I wonder if `repr' could not be made to produce a string which includes
> > a non-binary pickle of a complex object, combined with a modification to
> > the standard Python reading device understanding the convention, and able
> > to recreate the original from the pickle data in the string.
> 
> No need to modify Python for this.  It all depends on you and how you write
> your object. Just make sure the entire object state can be reconstructed 
> using the arguments to its constructor and write a __repr__ method that 
> prints out this constructor call.  As long as your objects are purely
> hierarchical it can even work recursively.

That only works for types you write, eh?

> > Yes, it traversed my mind that `repr' of a complex object, containing
> > a representation of it, could use a lot of characters, maybe enough to
> > kill legibility.  I was probably hoping a miracle :-).  Some happen!
> 
> C'est un miracle! The pprint module!

See also htmlstr(), which is at 
http://lists.canonical.org/pipermail/kragen-hacks/2002-January/000291.html

It generates stylable HTML output which, even in its default display,
is far more readable than repr()'s; and for any Python object where
eval(repr(obj)) == obj, the text parts of the HTML (as cut-and-pasted
from Mozilla, anyway) evaluate to the original object.

> Even without such miracles, repr output is far more legible than pickle.  
> I don't think repr can be or should be a general purpose replacement for 
> pickling, but there are some places where it can serve a similar function.

I wish repr were a general-purpose replacement for pickle.dumps, and
that there was an equivalent undump function (other than eval).  Lisp
is nice this way.




More information about the Python-list mailing list