PEP 342 misunderstanding

Discussion in 'Python' started by metamoof@gmail.com, Oct 8, 2006.

  1. Guest

    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)
    ....
    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
    , Oct 8, 2006
    #1
    1. Advertising

  2. wrote:

    >>>> def printrange():

    > ... for x in range(10):
    > ... x = yield x
    > ... print x
    > ...
    >>>> g = printrange()
    >>>> for x in g:

    > ... 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>
    Fredrik Lundh, Oct 8, 2006
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Kurt Bonne
    Replies:
    1
    Views:
    522
    John Timney \(Microsoft MVP\)
    Aug 8, 2003
  2. Christoph Becker-Freyseng

    PEP for new modules (I read PEP 2)

    Christoph Becker-Freyseng, Jan 15, 2004, in forum: Python
    Replies:
    3
    Views:
    362
    Gerrit Holl
    Jan 16, 2004
  3. Jean-Paul Calderone

    Re: PEP 342 misunderstanding

    Jean-Paul Calderone, Oct 8, 2006, in forum: Python
    Replies:
    0
    Views:
    495
    Jean-Paul Calderone
    Oct 8, 2006
  4. Ville Vainio
    Replies:
    6
    Views:
    351
    Ville M. Vainio
    Jul 26, 2009
  5. Gunnar
    Replies:
    3
    Views:
    253
    Robert Klemme
    May 3, 2005
Loading...

Share This Page