[Python-ideas] __iter__ implies __contains__?

Antoine Pitrou solipsis at pitrou.net
Sun Oct 2 21:57:43 CEST 2011


On Mon, 03 Oct 2011 06:31:08 +1100
Steven D'Aprano <steve at pearwood.info> wrote:
> 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.

Hello?
The issue is not that walking over an iterator changes the state of the
iterator, it is that "x in A" iterates over A at all.





More information about the Python-ideas mailing list