Welcome, guest | Sign In | My Account | Store | Cart

A very simple idiom for implementing a state machine.

Python, 39 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
'''a very simple idiom for a state machine'''

from random import random
from time import sleep


# Each of the state functions below performs some action and then implements
# logic to choose next state.  Each state function returns the next state.

def state0():
    print "state0"
    # delay and decision path to simulate some application logic
    sleep(.5)
    if random()>.5:
        return state1
    else:
        return state2

def state1():
    print "state1"
    # delay and decision path to simulate some application logic
    sleep(.5)
    if random()>.5:
        return state0
    else:
        return state2

def state2():
    print "state2"
    # delay and decision path to simulate some application logic
    sleep(.5)
    if random()>.5:
        return state0
    else:
        return None

state=state0    # initial state
while state: state=state()  # launch state machine
print "Done with states"

I wanted to do a state machine and thought through a few more complicated structures but found myself drawn to the simplicity of this.

I have the actions and decisions in common functions but one could easily separate them if it seems right to do so.

I find the simplicity of this very appealing. There is no SM class involved or even a variable named next_state.