PEP 342 misunderstanding

M

metamoof

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:
.... for x in range(10):
.... x = yield x
.... print x
........ g.send(x*2)
....
0
1
None
4
3
None
8
5
None
12
7
None
16
9
None
Now, I was expecting that to be 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20.

What am I missing here?

Moof
 
F

Fredrik Lundh

... for x in range(10):
... x = yield x
... print x
...
... g.send(x*2)
...
0
1
None
4
3
None
8
5
None
12
7
None
16
9
None

Now, I was expecting that to be 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20.

What am I missing here?

the output doesn't match your sample program; I assume you left out a
print statement or two from the second loop.

what you seem to be missing is that "next" (which is called by the
for-in loop) is basically the same thing as "send(None)". in other
words, you end up pulling two items from the generator for each iteration.

</F>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top