Unexpected behavior with dictionary keys containment and a user-defined class

Rob Clewley rob.clewley at gmail.com
Mon Jan 12 22:41:00 EST 2009


Hi, the short version of my question is: when is a dictionary's
__contains__ method behavior different to using the 'in' idiom?
(because I have an example of a difference in my code).

Longer version: I have a user-defined class with a few overrides of
special methods, particularly __eq__ and __ne__. I also have a
dictionary keyed by instances of these classes, and I'm confused about
the unexpected behavior trying to test whether an instance is in the
dictionary's keys. The instance is i and the dictionary is d. I have
been using the idiom

i in d

which I understood to be the pythonic way to test the keys, but it
doesn't work. However, when I debug my code I see the instance in the
list of keys, and in fact

i in d.keys()  and  d.keys()[10] == i

both return True. But

d.__contains__(i)
d.has_key(i)
d.keys()[10] is i

return False. I put a print statement in my class's __eq__ method and
it is being called. It tests equality of some of my class instance's
attributes. I didn't realize there was any situation where you could
expect different results from   i in d   versus   i in d.keys()   --
am I misunderstanding something?

I'm not sure what other details to provide! Thanks a lot,
Rob



More information about the Python-list mailing list