State Machines in Python

D'Arcy J.M. Cain darcy at druid.net
Sat Sep 4 15:49:53 CEST 2010


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)


-- 
D'Arcy J.M. Cain <darcy at druid.net>         |  Democracy is three wolves
http://www.druid.net/darcy/                |  and a sheep voting on
+1 416 425 1212     (DoD#0082)    (eNTP)   |  what's for dinner.



More information about the Python-list mailing list