[Python-ideas] Implementing Coroutines (was Cofunctions - Back to Basics)

Mark Shannon mark at hotpy.org
Fri Oct 28 14:09:03 CEST 2011


Yuval Greenfield wrote:
> I'm sorry, I still don't understand what the problem here is. I didn't 
> have any trouble making a python implementation for the wikipedia 
> coroutine example:
> 
> http://codepad.org/rEgg4GzW

Where is the yield method?

You need to be able to call Coroutine.co_yield() from *anywhere* not 
just in a generator.

Suppose we have a Tree class with a walk method which takes a callback 
function:

class Tree:

     class Node:

         def visit(self, callback):
	    if self.left: self.left.visit(callback)
	    if self.right: self.right.visit(callback)
             callback(self.value)

     def walk(self, callback):
         '''Recursively walks the tree calling callback(node)
            for each node'''
	self.root.visit(callback)


We can then use Coroutine to create a tree iterator,
with something like:

def tree_callback(node):
     Coroutine.co_yield(node)

#Make an iterator from a coroutine
def tree_iterator(tree):
     co = Coroutine(tree.walk)
     yield co.resume(tree_callback)
     while True:
         yield co.resume(None)	

(I am glossing over questions like: Should a stopping coroutine raise an 
exception from the resume method or just return a value.
Should a stopped coroutine that is resumed raise a StopIteration 
exception, a GeneratorExit exception or some new exception, etc, etc...)
	
The important point here is that Tree.walk()  is recursive and knows 
nothing of generators or coroutines, yet can be made to drive a generator.


> 
> 
> 
> On Fri, Oct 28, 2011 at 12:16 PM, Mark Shannon <mark at hotpy.org 
> <mailto:mark at hotpy.org>> wrote:
> 
>     Errata to previous email.
> 
> 
>      >
>      >    def co_yield(value):
>      >        'Yields (returns) value back to caller of resume() method.'
> 
>     Should have been
> 
>        @staticmethod
> 
>        def co_yield(value):
>            'Yields (returns) value back to caller of resume() method.'
> 
>     Cheers,
>     Mark.
>     _________________________________________________
>     Python-ideas mailing list
>     Python-ideas at python.org <mailto:Python-ideas at python.org>
>     http://mail.python.org/__mailman/listinfo/python-ideas
>     <http://mail.python.org/mailman/listinfo/python-ideas>
> 
> 




More information about the Python-ideas mailing list