Friday, October 2, 2009

Python State Machine

State machines are handy during software development to help visualize the changing states of either a single instance, or a group of instances over time. Modeling state machines is also useful for visualizing the events that cause instances to change state. It is for this reason that the UML includes states and state machines.

State machines aren't limited to visualizations. They can also be directly implemented. The StatePy Python package provides a basic set of abstractions that developers can use to implement such a state machine. The elements include states and machines. Also included are events that trigger state transitions. There is currently no support for defining composite states but this package seems to be early on in development. Below is a simple example of how to setup a state machine.
#Example; Creating Python States.

#Do imports.
from statepy.state import State, Machine, Event

#Printing state.
class StatePrinting(State):

#Constructor. Initialize the State.
def __init__(self, *args, **kw):
State.__init__(self, *args, **kw)

#On state entry.
def enter(self):
print "Printing..."

#On state exit.
def exit(self):
print "Finished printing..."

#Sorting state.
class StateSorting(State):

#Constructor. Initialize the State.
def __init__(self, *args, **kw):
State.__init__(self, *args, **kw)

#On state entry.
def enter(self):
print "Sorting..."

#On state exit.
def exit(self):
print "Finished sorting..."

#Provided state transitions.
@staticmethod
def transitions():
return {"FINISHED_SORTING":StatePrinting}

#Building state.
class StateBuilding(State):

#Constructor. Initialize the State.
def __init__(self, *args, **kw):
State.__init__(self, *args, **kw)

#On state entry.
def enter(self):
print "Building..."

#On state exit.
def exit(self):
print "Finished building..."

#Provided state transitions.
@staticmethod
def transitions():
return {"FINISHED_BUILDING":StateSorting}

#Main.
if __name__=="__main__":

#Initialize the machine.
machine_obj=Machine()

#Start the machine in a building state.
machine_obj.start(StateBuilding)

#Pass the transition events to the machine.
machine_obj.injectEvent(Event("FINISHED_BUILDING"))
machine_obj.injectEvent(Event("FINISHED_SORTING"))

No comments :

Post a Comment