Coding a simple state machine in python
roy at panix.com
Tue Feb 25 02:54:06 CET 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":
> change state to DEF
> if state == "DEF"
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
self.state = self.start
def process(self, input):
for item in input:
self.state, output = self.state(item)
def start(self, item):
if item > 5:
return self.end, "done"
return self.start, "still looking"
def end(self, item):
if item < 3:
return self.start, "back to the beginning"
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 stuck at the end
back to the beginning
More information about the Python-list