State Machines in Python

Roy Smith roy at panix.com
Sat Sep 4 19:58:00 CEST 2010


In article <mailman.443.1283608243.29448.python-list at python.org>,
 "D'Arcy J.M. Cain" <darcy at druid.net> wrote:

> On Sat, 4 Sep 2010 14:36:38 +0100
> Jack Keegan <whatsjacksemail at gmail.com> wrote:
> > Just joined the group. I'm new to Python but been picking it up pretty easy.
> 
> Welcome aboard.
> 
> > 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
> 
> There's no switch statement because there's no real need for one.
> Check out the following sample code and see if it gives you some ideas.
> 
> #! /usr/bin/env python
> # -*- coding: utf-8 -*-
> 
> # Sample state machine
> 
> import sys
> 
> data = dict(counter = 0, flag = False)
> 
> def state1(d):
>     d['counter'] += 1
>     print "In state 1, counter = %(counter)d" % d
>     if d['flag']: sys.exit(0)
>     return state2
> 
> def state2(d):
>     d['counter'] += 1
>     print "In state 2, counter = %(counter)d" % d
>     return state3
> 
> def state3(d):
>     d['counter'] += 1
>     d['flag'] = True
>     print "In state 3, counter = %(counter)d" % d
>     return state1
> 
> state = state1
> while True:
>     state = state(data)

This is the pattern I've always used.  Simple and effective for any 
state machine which is small enough to code by hand.  I generally have 
my state methods return (next_state, output) tuples, but that's a detail.



More information about the Python-list mailing list