[Python-Dev] misbehaving __contains__

Raymond Hettinger python at rcn.com
Wed Jan 23 02:19:08 CET 2008


>> And, would we lose the nice relationship expressed by:
>>
>>     for elem in container:
>>         assert elem in container


[Steven Bethard]
>We've already lost this if anyone really wants to break it::
>
>    >>> class C(object):
>    ...     def __iter__(self):
>    ...         return iter(xrange(3))
>    ...     def __contains__(self, item):
>    ...         return False

I think this is in the same category as writing a __hash__ that doens't match __eq__.  It is explicitly shooting yourself in the foot.  

I'm more concerned about introducing an API where well-meaning attempts to code a __contains__ override will implicitly shoot the toes off of client code that innocently assumes a somewhat sensible invariant relation between looping over elements in a container and those elements being in the container.  The code for sets and frozensets makes that assumption, for example.  And, when the code does break, the errors will be darned hard to find.


Raymond



More information about the Python-Dev mailing list