There’s a bit of buzz on the python-ideas mailing list about Greg Ewing’s proposal for a new keyword “yield from“. He has made a draft PEP and patch for python 2.6.1.
On short it adds syntactic sugar for generator decomposition and adds a “return value” statement in generators (the underlying mechanism for that is a StopIteration(value) exception).
Here’s a straightforward example:
>>> def g1(): ... print "Starting g1" ... yield "g1 ham" ... result = yield from g2() ... print "Got result: %r from g2" % result ... yield "g1 eggs" ... print "Finishing g1" ... >>> def g2(): ... print "Starting g2" ... yield "g2 spam" ... yield "g2 more spam" ... print "Finishing g2" ... return "foobar" ... >>> for x in g1(): ... print "Yielded", x ... Starting g1 Yielded g1 ham Starting g2 Yielded g2 spam Yielded g2 more spam Finishing g2 Got result: 'foobar' from g2 Yielded g1 eggs Finishing g1
There are a bunch of other examples and tests bundled with Greg’s patch.
I got the patch and it works :). Had to manually rebuild the parser – make didn’t do it by itself and I had to run “make Parser/pgen & make Python/graminit.c & make“. I wonder why.