PEP 342 misunderstanding
Jean-Paul Calderone
exarkun at divmod.com
Sun Oct 8 15:50:36 EDT 2006
On 8 Oct 2006 12:33:02 -0700, metamoof at gmail.com wrote:
>So I've been reading up on all the new stuff in PEP 342, and trying to
>understand its potential. So I'm starting with a few simple examples to
>see if they work as expected, and find they dont.
>
>I'm basically trying to do the following:
>
>for x in range(10):
> print x*2
>
>but coroutine-style.
>
>My initial try was:
>
>>>> def printrange():
>... for x in range(10):
>... x = yield x
>... print x
>...
>>>> g = printrange()
>>>> for x in g:
>... g.send(x*2)
>...
Try this instead:
>>> x = None
>>> while 1:
... if x is None:
... send = None
... else:
... send = x * 2
... try:
... x = g.send(send)
... except StopIteration:
... break
...
0
2
4
6
8
10
12
14
16
18
>
>Now, I was expecting that to be 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20.
>
>What am I missing here?
Your code was calling next and send, when it should have only been calling
send.
Jean-Paul
More information about the Python-list
mailing list