For...in statement and generators
duncan.booth at invalid.invalid
Tue Dec 22 12:28:02 CET 2009
"Gabriel Genellina" <gagsl-py2 at yahoo.com.ar> wrote:
> En Mon, 21 Dec 2009 11:39:46 -0300, Lucas Prado Melo
><lukepadawan at gmail.com> escribió:
>> Is there a way to send() information back to a generator while using
>> for...in statement?
> No. You have to write the iteration as a while loop.
You *can* use send() to a generator while using a for loop, but it's
probably more effort than it's worth.
The caveats include: You have to construct the generator outside the
loop so you can refer to it from inside the loop. The generator has to
distinguish between the for loop iteration and additional values sent
in. When using send() that call mustn't terminate the iteration (or if
it does you have to be prepared to catch the StopIteration).
Here's a silly example which counts up to some limit and each time
yields double the current count but you can reset the counter using
>>> def doubler(n, limit):
while n < limit:
m = yield 2*n
if m is not None:
n = m
n += 1
>>> d = doubler(1, 20)
>>> for n in d:
print "sent", n+3, d.send(n+3)
sent 5 ok
sent 13 ok
sent 29 ok
>>> for n in doubler(1, 20):
Duncan Booth http://kupuguy.blogspot.com
More information about the Python-list