inverse of __repr__ ?

Thomas Wouters thomas at xs4all.net
Thu Jan 13 07:19:31 EST 2000


On Thu, Jan 13, 2000 at 03:42:13AM -0800, Thien-Thi Nguyen wrote:

> i've looked through _programming python_ for the inverse of __repr__, but
> could not find anything.  perhaps i'm missing some clue?

> 	read : write
> 	??   : __repr__

> or is there no way to extend the reader in a python repl?

What do you want the inverse __repr__ to do, re-instantiate the object ? You
can use 'eval' for that, if the __repr__ function of that particular object
allows it. The basic types do, for instance, but for items like file and
socket objects it's impossible. Some standard python classes implement it,
but usually only those who do not rely on on other objects or
unrepresentable data (like filehandles, locks, etc.) When doing such tricks
you also have to make sure you imported the right modules the right way, so
that the eval(__repr__) actually makes sense.

Basically, your read/write analogy isn't functional. __repr__ isn't like
write, it's more like read, and the 'write' side of the equation is simply
typing in the code in an editor/python prompt. __repr__ is more or less a
way to 'print' an object with some technical info attached. __str__ is
usually used to produce 'user-friendly' output.

If you want to reliably dump an object into a file or string and be able to
reinstantiate it, take a look at the shelve and pickle modules (and
cPickle.) They do such work.
-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list