[Python-Dev] Simple coroutines?

Greg Ewing greg at cosc.canterbury.ac.nz
Tue Aug 24 07:57:18 CEST 2004


> My comment about "coroutines" was more that Guido previously
> expressed distaste for adding such a communication mechanism to
> generators as abusing the concept of a generator just being a way to
> implement complex iterators.

This makes me think that maybe we want another kind of object, similar
to a generator, but designed to be used for side effects rather than
to produce values.

For want of a better term, let's call it a "cooperator" (so it ends in
"ator" like "generator" :-). Actually there will be two objects, a
cooperator-function (analogous to a generator-function) and a
cooperator-instance (analogous to a generator-iterator).

Calling a cooperator-function will return a cooperator-instance, which
will obey the cooperator protocol. This protocol consists of a single
function run(), which causes the cooperator-instance to perform some
amount of work and then stop. If there is more work remaining to be
done, run() returns a true value, otherwise it returns a false value.

There will be a new statement:

    suspend

for use inside a cooperator-function. The presence of this statement
is what distinguishes a cooperator-function from an ordinary function
(just as the presence of 'yield' distinguishes a generator from an
ordinary function). Execution of 'suspend' will cause the run() method
to return with a true value. The next time run() is called, execution
will resume after the 'suspend'.

This is really all that's needed, but one further piece of syntax may
be desirable to make it easier for one cooperator to invoke another:

    do another_coop()

would be equivalent to

    co = another_coop()
    while co.run():
        suspend

(Because it implies a 'suspend', the presence of 'do' would also mark
a function as a cooperator-function).

Something to note is that there's no requirement for a cooperator-
instance to be implemented by a cooperator-function, just as an
iterator can be implemented in ways other than a generator.  This
sidesteps some of the difficulties of mixing Python and C calls, since
a Python cooperator-function could invoke a cooperator implemented in
C which in turn invokes another Python cooperator- function, etc. The
only requirement is that all the objects on the way down obey the
cooperator protocol.

The drawback is that you always have to know when you're calling
another cooperator and use 'do'. But that's no worse than the current
situation with generators, where you always have to know you're using
an iterator and use 'for... yield'.

What think ye all?

Greg Ewing, Computer Science Dept, +--------------------------------------+
University of Canterbury,	   | A citizen of NewZealandCorp, a	  |
Christchurch, New Zealand	   | wholly-owned subsidiary of USA Inc.  |
greg at cosc.canterbury.ac.nz	   +--------------------------------------+


More information about the Python-Dev mailing list