[Zope-dev] Please help - Persistent dictionary keys
John D. Heintz
jheintz@isogen.com
Thu, 21 Sep 2000 08:00:29 -0500
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.
Why do the Python class instances naturally act as dictionary keys while
the ExtensionClass instances don't?
Thanks for the time,
John
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}
> >>>
>
> --
> Martijn Pieters
> | Software Engineer mailto:mj@digicool.com
> | Digital Creations http://www.digicool.com/
> | Creators of Zope http://www.zope.org/
> ---------------------------------------------
--
John D. Heintz
DataChannel, Inc.
Senior Engineer
512-633-1198
jheintz@isogen.com