[Python-Dev] Return from generators in Python 3.2

Guido van Rossum guido at python.org
Fri Aug 27 02:25:51 CEST 2010


On Thu, Aug 26, 2010 at 5:05 PM, Yury Selivanov <yselivanov at gmail.com> wrote:
> On 2010-08-26, at 8:04 PM, Greg Ewing wrote:
>> Even with your proposal, you'd still have to use a 'creepy
>> abstraction' every time one of your coroutines calls another.
>> That's why PEP 380 deals with 'more than just return'.
>
> Nope.  In almost any coroutine framework you have a scheduler
> or trampoline object that basically does all the work of calling,
> passing values and propagating exceptions.  And many other things
> that 'yield from' won't help you with (cooperation, deferring to
> process/thread pools, pausing, etc.)  Being a developer of one
> of such frameworks, I can tell you, that I can easily live without
> 'yield from', but dealing with weird return syntax is a pain.

That's not my experience. I wrote a trampoline myself (not released
yet), and found that I had to write a lot more code to deal with the
absence of yield-from than to deal with returns. In my framework,
users write 'raise Return(value)' where Return is a subclass of
StopIteration. The trampoline code that must be written to deal with
StopIteration can be extended trivially to deal with this. The only
reason I chose to use a subclass is so that I can diagnose when the
return value is not used, but I could have chosen to ignore this or
just diagnose whenever the argument to StopIteration is not None.

> Especially when you use decorators like @bus.method, or
> @protocol.handler, that transparently wrap your callable be it
> generator or regular function.  And after that you have to use
> different return syntax for them.

Until PEP 380 is implemented, you have to use different return syntax
in generators. You have some choices: raise StopIteration(value),
raise SomethingElse(value), or callSomeFunction(value) -- where
callSomeFunction raises the exception. I like the raise variants
because they signal to tools that the flow control stops here -- e.g.
in Emacs, python-mode.el automatically dedents after a 'raise' or
'return' but not after a call (of course).

-- 
--Guido van Rossum (python.org/~guido)


More information about the Python-Dev mailing list