Revised suggestion

Raymond Hettinger othello at javanet.com
Thu Jan 17 10:18:25 EST 2002


I would like to solicit comments on my revised suggestion for generators.

Currently, a generator can use 'yield expression' to send data to the caller
which gets the data as a return value from 'gen.next()'.  My goal is to
augment the syntax to let the caller send some data back --  Full two-way
communication.

The implementation ought to be easy because the current version of 'yield'
already does almost all of the work except passing back a value.

Here's the idea in a nutshell:
1.  Let .next()  take an optional argument
2.  Have yield return that value to the generator.

def mygen():
    ...
    val = yield None
    print val

g = mygen()
g.next()
g.next(3)

Notes:
1.  As far as I can tell, 'lambda' is the only other statement that can
return
an assignable value, viz:  f = lambda x: x*2
2.  The first call to .next() can't use a value because the first call to
.next()
starts at the top of the generator code.  A 'var = yield None' is not
encountered
until the second call and after.
3.  A further idea (not essential to this suggestion) is to augment .next()
with
another method, gen.throw(anException, [data]) which can raise an exception
inside the generator.
4.  This idea is backward compatible -- doesn't break code or use up a
keyword.
5.  Something similar can already be achieved by passing the data in via
global (yuck) variables.


Raymond Hettinger
othello at javanet.com


> >
> > 'yield' suspends execution and sends back a value.
> > 'accept' suspends execution and waits to take-in a value.
> > 'yield' makes it easy to write lazy producers.
> > 'accept' makes it easy to write steam-like, lazy consumers.
>
> Neil Schemenauer spent a good chunk of time playing with stuff "like this"
> when first implementing generators, but eventually dropped it as too
little
> bang for the highly-more-convoluted buck.  I expect more in this area will
> eventually get done, but can't predict what it will look like in the end.
> Keep playing with it!
>






More information about the Python-list mailing list