finding object using IS instead of ==
Andrew Dalke
adalke at mindspring.com
Thu Aug 28 12:13:17 EDT 2003
Mark Hahn:
> If I have a large collection (list, tuple, or dict) of objects, can I
locate
> one quickly that matches a given object using the IS equivalence operator
> instead of the value == operator?
If you write your own code then, yes, you can do it for list. Here's
some untested code.
def is_index(data, x):
for term in data:
if term is x:
return term
raise ValueError("not in data")
This would work for dicts if you have data == dict.iterkeys(), but
that won't take advantages of the hash lookup properties.
I don't know any way you can leverage 'is' tests over '==' for
dict's "__in__" searching. I tried
>>> class CmpIs:
... def __init__(self, obj):
... self.obj = obj
... def __hash__(self):
... return hash(self.obj)
... def __cmp__(self, other):
... x = cmp(id(self), id(other))
... if x == 0:
... self.match = other
... return x
...
but that doesn't work because the == test inside of the
dict's linear search of the hash chain appears to do
if term_in_dict == object_to_find
giving __cmp__ precedence to the object already in the
dictionary and so never getting to my overridden __cmp__.
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list