State Machines in Python

Stefan Behnel stefan_ml at behnel.de
Sat Sep 4 16:41:46 CEST 2010


Jack Keegan, 04.09.2010 15:36:
> Hi girls&  guys,
>
> Just joined the group. I'm new to Python but been picking it up pretty easy.
> I love it!

Welcome to the group.


> I'm hoping to use it to make a controlling application for an
> experiment. Basically I want to use it to interface with some data
> acquisition (DAQ) hardware to accept incoming signals and respond sending
> signals to the outputs. I'm looking for an efficient State Machine algorithm
> as I need the timing to be as good as possible.
> As there is no switch statement in Python, I've been looking around for a
> good implementation. Most of the algorithms I've come across seem to be
> based on parsing applications. I'd like something more suited to my needs.
> I'd like to avoid excessive use of 'if-elif-else' statements as each would
> have to be checked to find the right conditions which would have an time
> overhead involved. I have seen an implementation of the switch using
> dictionaries but someone had commented that creating and throwing away
> dictionaries also comes at a cost.
> I was wondering if any of you could advise or point me in the right
> direction.

Dictionaries are a common way to do it, and there are different recipes. A 
second way is a class that dispatches to its methods. A third (IMHO rather 
beautiful) way is coroutines:

http://gnosis.cx/publish/programming/charming_python_b5.html
http://www.dabeaz.com/coroutines/Coroutines.pdf

However, you'll have to do some benchmarking if you care about performance. 
Dictionaries are fast and likely the fastest way to do it, but coroutines 
are a lot more versatile. Stackless Python might also be worth a look in 
this context, it's fast *and* versatile.

You should also be aware that there are various event driven frameworks 
(like Twisted, eventlet and others) that make asynchronous event handling 
fast and easy, and that use much higher-level abstractions than pure state 
machines.

Stefan




More information about the Python-list mailing list