[Zope-dev] Please help - Persistent dictionary keys

Martijn Pieters mj@digicool.com
Thu, 21 Sep 2000 17:07:17 +0200


On Thu, Sep 21, 2000 at 08:00:29AM -0500, John D. Heintz wrote:
> Thanks for the reply Martijn,
> 
> I do want the objects of Test2 class to be compared by identity, like
> I'm assuming Test1 objects are.  
> 
> If I have to define __cmp__ and __hash__ then I will basically be making
> them up because the object in question are mutable - except for their
> identity.

I don't think that in this case __cmp__ has to be implemented; you just
use the default behaviour of object identity comparison. All you need to
do is then implent a __hash__() method that will return a 32-bit integer
that is unique to the object. You could base this on repr(self).

> Why do the Python class instances naturally act as dictionary keys while
> the ExtensionClass instances don't?

ExtensionClasses pretend to be Python classes, but are not succeeding
everywhere. I am not that deeply knowledgable about Extension Classes, so
I cannot tell you why exactly you see this difference.

> Martijn Pieters wrote:
> > 
> >From the Python Library Reference:
> 
>   """A dictionary's keys are almost arbitrary values. The only types of
>   values not acceptable as keys are values containing lists or
>   dictionaries or other mutable types that are compared by value rather
>   than by object identity."""
> 
> <...>
> 
> > So, if you want to be able to use a Persistent based object as keys to a
> > dictionary, implement __cmp__ and __hash__ methods on that class:
> > 
> > >>> import ZODB
> > >>> from Persistence import Persistent
> > >>> class Test1:
> > ...     pass
> > ...
> > >>> class Test2(Persistent):
> > ...   def __cmp__(self): return 1
> > ...   def __hash__(self): return 1
> > ...
> > >>> dict = {}
> > >>> t1 = Test1()
> > >>> t2 = Test2()
> > >>> dict[t1] = 1
> > >>> dict[t2] = 2
> > >>> dict
> > {<Test2 instance at 80b3aa0>: 2, <__main__.Test1 instance at 80a3e78>: 1}
> > >>>
> 
> -- 
> John D. Heintz
> DataChannel, Inc.
> Senior Engineer
> 512-633-1198
> jheintz@isogen.com

-- 
Martijn Pieters
| Software Engineer  mailto:mj@digicool.com
| Digital Creations  http://www.digicool.com/
| Creators of Zope   http://www.zope.org/
---------------------------------------------