Coding a simple state machine in python

Roy Smith roy at panix.com
Mon Feb 24 20:54:06 EST 2014


In article <65ac9612-fd48-472a-b077-c802be96ece3 at googlegroups.com>,
 Ronaldo <abhishek1899 at gmail.com> wrote:

> How do I write a state machine in python? I have identified the states and 
> the conditions. Is it possible to do simple a if-then-else sort of an 
> algorithm? Below is some pseudo code:
> 
> if state == "ABC":
>    do_something()
>    change state to DEF
> 
> if state == "DEF"
>    perform_the_next_function()

There's lots of ways to code state machines in Python.  The last time I 
did one, I made each state a function.  Each function returned a 
(next_state, output) tuple.  I don't know if that's the best way, but it 
worked and seemed logical to me.  Here's a trivial example with just two 
states:

class StateMachine:
    def __init__(self):
        self.state = self.start

    def process(self, input):
        for item in input:
            self.state, output = self.state(item)
            print output

    def start(self, item):
        if item > 5:
            return self.end, "done"
        else:
            return self.start, "still looking"

    def end(self, item):
        if item < 3:
            return self.start, "back to the beginning"
        else:
            return self.end, "still stuck at the end"

sm = StateMachine()
sm.process([1, 2, 6, 4, 2, 2])


When you run it, it should print:

still looking
still looking
done
still stuck at the end
back to the beginning
still looking



More information about the Python-list mailing list