Unexpected behavior with dictionary keys containment and a user-defined class
James Stroud
jstroud at mbi.ucla.edu
Mon Jan 12 22:56:19 EST 2009
Rob Clewley wrote:
> 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).
Never.
> 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?
Well, the only conclusion is that dict uses the hash of an object to
test containment while lists use id.
James
More information about the Python-list
mailing list