Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #95181
| Newsgroups | comp.lang.python |
|---|---|
| Date | 2015-08-09 02:06 -0700 |
| Message-ID | <88256581-75d4-4f77-81f0-9e3e25baecbc@googlegroups.com> (permalink) |
| Subject | Iterators membership testing |
| From | Pierre Quentel <pierre.quentel@gmail.com> |
The documentation at https://docs.python.org/3.5/reference/expressions.html#not-in says :
"For user-defined classes which do not define __contains__() but do define
__iter__(), x in y is true if some value z with x == z is produced while
iterating over y. If an exception is raised during the iteration, it is as if
in raised that exception."
However, if I define a class with
class A:
def __init__(self, x):
self.x = x
self.counter = -1
def __iter__(self):
return self
def __next__(self):
self.counter += 1
if self.counter >= self.x:
raise StopIteration
return self.counter
and test for membership with
iterator = A(10)
for i in iterator:
assert i in iterator, '%s not found' %i
I get an assertion error. Setting a trace on __next__ suggests that for
membership testing, the interpreter consumes the iterator until the searched
value is found (or until exhaustion), then it resumes iteration at this point.
For instance :
>>> iterator = A(10)
>>> for i in iterator:
... print(i)
... assert i+1 in iterator
...
0
2
4
6
8
>>>
If this is correct, should the documentation mention it ?
Back to comp.lang.python | Previous | Next — Next in thread | Find similar | Unroll thread
Iterators membership testing Pierre Quentel <pierre.quentel@gmail.com> - 2015-08-09 02:06 -0700
Re: Iterators membership testing Chris Angelico <rosuav@gmail.com> - 2015-08-09 19:24 +1000
Re: Iterators membership testing Pierre Quentel <pierre.quentel@gmail.com> - 2015-08-09 02:55 -0700
Re: Iterators membership testing Chris Angelico <rosuav@gmail.com> - 2015-08-09 20:13 +1000
Re: Iterators membership testing Pierre Quentel <pierre.quentel@gmail.com> - 2015-08-09 04:00 -0700
Re: Iterators membership testing Chris Angelico <rosuav@gmail.com> - 2015-08-09 21:10 +1000
Re: Iterators membership testing Laura Creighton <lac@openend.se> - 2015-08-09 13:30 +0200
Re: Iterators membership testing Mark Lawrence <breamoreboy@yahoo.co.uk> - 2015-08-09 14:49 +0100
Re: Iterators membership testing Chris Angelico <rosuav@gmail.com> - 2015-08-09 23:11 +1000
Re: Iterators membership testing Tim Chase <python.list@tim.thechases.com> - 2015-08-09 08:09 -0500
Re: Iterators membership testing Mark Lawrence <breamoreboy@yahoo.co.uk> - 2015-08-09 14:45 +0100
Re: Iterators membership testing Tim Chase <tim@thechases.com> - 2015-08-09 08:09 -0500
csiph-web