Using python coroutines to implement easy of use state machines

Guillaume Chereau charlie at openmoko.org
Mon May 26 05:24:28 CEST 2008


Hello,
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.

cheers,

- Charlie


-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part
URL: <http://lists.linuxtogo.org/pipermail/smartphones-standards/attachments/20080526/ac5055cd/attachment.pgp>


More information about the smartphones-standards mailing list