[Python-ideas] Cofunctions - A New Protocol

Terry Reedy tjreedy at udel.edu
Wed Nov 2 01:05:56 CET 2011


On 11/1/2011 6:24 AM, Greg Ewing wrote:
...
> Cofunctions
> -----------
>
> There will be a special form of Python function called a "cofunction",
> defined
> using the new keyword ``codef`` in place of ``def``.

Is this really needed? The presence of 'coyield' signals 'cofunction', 
just as 'yield' signals 'generator'. Does a cofunction without a suspend 
point make sense? (And if it did, 'if False: coyield' or 'coyield' after 
'return' could serve as a signal.)

 > A cofunction
> provides a
> convenient way of creating an object obeying the coroutine protocol.
> (This is
> similar to how a generator provides a convenient way of creating an object
> obeying the iterator protocol).
>
> Suspension of a cofunction is achieved using the expression
>
> ::
>
> ``coyield`` [value]
>
> This is analogous to a ``yield`` expression in a generator, and like
> ``yield``,
> it can both provide and receive a value. However, unlike ``yield``, it
> is *not*
> restricted to communicating with the immediate caller. It communicates
> directly
> with the ``resume`` method of the coroutine, however deep the nesting of
> calls
> is between the ``resume`` call and the ``coyield``.
>
> There are some restrictions, however:
>
> * A ``coyield`` is only allowed in the body of a cofunction (a function
> defined
> with ``codef``), not in any other context.
>
> * A cofunction can only be called from the body of another cofunction,
> not in
> any other context.
>
> Exceptions are raised if any of these restrictions are violated.

Except that an initial 'call' from a coroutine.resume is needed to get 
the first cofunction started ;-).

-- 
Terry Jan Reedy




More information about the Python-ideas mailing list