[Python-ideas] __iter__ implies __contains__?

Steven D'Aprano steve at pearwood.info
Sun Oct 2 21:31:08 CEST 2011


Devin Jeanpierre wrote:
>> Since iteration over elements is at the heart of containment tests, the same
>> reasoning applies to __contains__.
> 
> I was with you for the old-style sequence iteration API, but you've
> lost me here. I *can* imagine use-cases where "in" shouldn't work:
> pretty much any iterator. Doesn't it seem strange that `x in A` should
> succeed, but then `x in A` should fail?

No. That is implied by the iterator protocol, just like:

 >>> A = iter([1, 2, 3, 4])
 >>> sum(A)
10
 >>> sum(A)
0

If somebody is surprised that walking over an iterator for *any* reason 
changes the state of the iterator, they really haven't thought things 
through.



-- 
Steven



More information about the Python-ideas mailing list