[Python-ideas] Cofunctions PEP - Revision 4

Greg Ewing greg.ewing at canterbury.ac.nz
Fri Aug 13 05:48:52 CEST 2010

On 13/08/10 10:00, Nick Coghlan wrote:

> At the very least, a non-generator cofunction will need to offer
> close() and __del__() (or its weakref equivalent) to release resources
> in the event of an exception in any called cofunctions

But if it doesn't call any other cofunctions and doesn't
use any resources besides memory, there's no need for it
to provide a close() method.

> Providing dummy
> implementations of send() and throw() that ignore their arguments and
> devolve to next() is trivial,

But it seems perverse to force people to provide such
implementations, given that yield-from is defined in
such a way that the same effect results from simply
omitting those methods.

> PEP 342 is *called* "Coroutines via enhanced
> generators", and it still seems to me that the usage of send() and
> throw() is one of the key features distinguishing a cooperative
> scheduler from ordinary iteration.


I've just looked at that PEP, and I can now see where the
confusion is coming from.

PEP 342 talks about using yield to communicate
instructions to and from a coroutine-driving trampoline.
However, that entire technique is a *workaround* for
not having something like yield-from.

If you do have yield-from, then none of that is necessary,
and you don't *need* generators to be "enhanced" with a
send() facility in order to do coroutine scheduling --
plain next() is more than sufficient, as I hope my socket
example demonstrates.

A similar thing applies to throw(). The PEP 342 motivation
for it is so that the trampoline can propagate an
exception raised in an inner generator back up the
call stack, by manually throwing it into each generator
along the way. But this technique is rendered obsolete by
yield-from as well, because any exception occurring in
an inner generator propagates up the yield-from chain
automatically, without having to do anything special.


More information about the Python-ideas mailing list