repr(x) == repr(y) <=> x == y AND eval(repr(x)) == x

Chermside, Michael mchermside at ingdirect.com
Wed Oct 23 16:30:44 EDT 2002


>>> A wise man once said to me:
>>> ,---
>>> | You're FAR more likely to meet objects where you can't count on
>>> | eval(repr(x)) == x, than non-hashable objects.
>>> `---
>>
>> Trust your wise friend.
>
>He's not my friend but I trust anyone who knows Python better than
>me. I was just curious, /why/ and /when/.

Ah! Then I can help.

ALL objects will support __repr__. However, it will often just default
to returning __str__. Or it will return something that is nice and
descriptive, but may not actually re-generate the object properly
when fed to eval(). The idea that eval(repr(x)) == x is a really nice
idea, but in practice, for most types you will find it is quite hard
to do, and not worth the effort. So the trivial types, like int, float,
and list will all satisfy eval(repr(x))==x, but lots of the built-in
things WON'T, and you should expect that most of the time it won't
work out.

On the other hand, supporting __hash__ is usually trivial. The default
implementation (based on id()) is actually good enough for lots of
kinds of objects. __hash__ works for essentially ALL built-in or
standard library classes for which it makes sense (ie, things that
aren't mutable), and it's very easy to support it properly on new
classes that you write. So you should expect that most of the time
it WILL work.

Finally, what you really wanted to do here was to take an object
and put it in some form other than the "live" object (a string) from
which it could be re-generated later. That's called "serialization",
and in Python it's supported by the pickle module, not by repr()
and eval(). The nice thing about pickle is that you don't have to
write ANYTHING to make your objects picklable[1], it happens
automagically for you.


-- Michael Chermside

[1] - Well, for some really special kinds of objects you may need
to do special things while marshalling or unmarshalling for the
pickling. If so, these can be written. But such special cases
are quite rare and involve weird things like pickling an object
that contains an open file or something like that.





More information about the Python-list mailing list