Using python coroutines to implement easy of use state machines

M. Dietrich mdt at emdete.de
Mon May 26 13:53:32 CEST 2008


On Mon, May 26, 2008 at 11:24:28AM +0800, Guillaume Chereau wrote:
> This is a question for Mickey, who seems to know python quite well :
> 
> I am having a look at the python-ophoned code, and I see that it
> relies a lot on call back functions to implement some sort of state
> machines. (I am not really sure of the real mathematical term I
> should use)
> 
> Something like this :
> 
> def process():
> 	print "start process"
> 	# start an asynchronous function 
> 	call_asynchronous(an_other_process, call_back = process_next)
> 
> def process_next(value)
> 	print "an_other_process returned", value
> 
> 
> Well, there is a python trick that is getting popular now that can
> ease a lot the implementation of such functions. The idea is to use
> the yield keyword to write coroutines (functions that can be exited
> and restarted at any internal point).
> 
> The previous example could be written like this :
> 
> def process():
> 	print "start process"
> 	value = ( yield call_asynchronous(an_other_process) )
> 	print "an_other_process returned", value
> 
> Although it looks like a single function, the yield keyword makes it
> in fact working like two different functions (or a single function
> with two entry points) So it looks much cleaner, and it is a very
> clever way of writing complicated state machines in python.
> 
> See the PEP written by Guido van Rossum  :
> http://www.python.org/dev/peps/pep-0342/
> 
> The use example number 3 is particularly interesting.
> 
> The people from PyGtk are also already using this thing :
> http://www.gnome.org/~gjc/gtasklet/gtasklets.html
> 
> So my question is : Shouldn't we use this as well ? It is the
> current trend in python programs, and it makes the code much much
> simpler. The only problem is that many people are not familiar with
> coroutine, since it doesn't exist in C, and they are not used
> to write software that rely on this.

i played around with yield in the current flavor that python brings
and integrated it with glib to achieve a reversion of control as you
describe. for now i saw no benefit in the area of my pygsmd. the
future implementation of "yield" in python may be better suited for my
needs and i will check again if it goes to mainstream.

best regards,
	michael



More information about the smartphones-standards mailing list