Skip to content

Instantly share code, notes, and snippets.

@bwicklund
Created August 13, 2018 16:40
Show Gist options
  • Save bwicklund/01a0c655f7d7af3c0279649e700310c6 to your computer and use it in GitHub Desktop.
Save bwicklund/01a0c655f7d7af3c0279649e700310c6 to your computer and use it in GitHub Desktop.
Simple Python State Machine
class InitializationError(Exception): pass
class StateMachine:
def __init__(self):
self.handlers = []
self.startState = None
self.endStates = []
def add_state(self, handler, end_state=0):
self.handlers.append(handler)
if end_state:
self.endStates.append(handler)
def set_start(self, handler):
self.startState = handler
def run(self, cargo=None):
if not self.startState:
raise InitializationError,\
"must call .set_start() before .run()"
if not self.endStates:
raise InitializationError, \
"at least one state must be an end_state"
handler = self.startState
while 1:
(newState, cargo) = handler(cargo)
if newState in self.endStates:
newState(cargo)
break
elif newState not in self.handlers:
raise RuntimeError, \
"Invalid target %s" % newState
else:
handler = newState
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment