For...in statement and generators

Duncan Booth duncan.booth at invalid.invalid
Tue Dec 22 06:28:02 EST 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 
the
>> 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 
send().

>>> def doubler(n, limit):
	while n < limit:
		m = yield 2*n
		if m is not None:
			n = m
			yield "ok"
		else:
			n += 1

			
>>> d = doubler(1, 20)
>>> for n in d:
	print n
	print "sent", n+3, d.send(n+3)

	
2
sent 5 ok
10
sent 13 ok
26
sent 29 ok
>>> 
>>> for n in doubler(1, 20):
	print n

	
2
4
6
8
10
12
14
16
18
20
22
24
26
28
30
32
34
36
38
>>> 

-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list