Identity dictionnary
Bob Ippolito
bob at redivi.com
Sat Feb 28 21:31:40 EST 2004
On 2004-02-28 21:05:48 -0500, Jean-Sebastien Roy <js at jeannot.org> said:
> I'm trying to create an object to be used as a key in a dictionary,
> where comparison (for key retrieval) would be done by 'is' instead of
> __eq__.
> (__eq__ is defined in this object, but serve another purpose and does
> not return a boolean).
>
> Is defining __hash__ as id(self) sufficient to guarantee that __eq__
> will never be called by the dict implementation ? (it seems to work in
> practice)
> If not, how to ensure __eq__ will never be called ?
I don't believe your assumption about dict is correct. A typical dict
is not going to have 2**32 slots in it, so you will eventually get a
collision, which will call __eq__ unless the key you're getting happens
to be the first item in that slot (it think uses object identity first
as an optimization and for sanity, though I have not looked at the
source).
What you might want is a special kind of container, not a special kind
of object to use as keys to a dict:
class identitymap(object):
def __init__(self):
self._dict = {}
def __getitem__(self, item):
return self._dict[id(item)][1]
def __setitem__(self, item, value):
self._dict[id(item)] = (item, value)
... etc.
I have used a data structure such as this before for similar reasons
(an attempt at pure python transparent object persistence..).
-bob
More information about the Python-list
mailing list