Created
November 12, 2012 15:01
-
-
Save asemt/4059845 to your computer and use it in GitHub Desktop.
A simple, stupid (as in KISS) state maschine
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class InvalidStateException(Exception): | |
pass | |
class MissingStateMachineConfigurationException(Exception): | |
pass | |
from types import DictionaryType | |
class StateMachine(object): | |
def __init__(self, configuration, logger): | |
''' | |
Example of a valid state machine configuration: | |
state_machine_configuration =\ | |
{ | |
'<current_state>' : | |
{ | |
'<transition_event>' : '<next_state_to_enter>', | |
}, | |
<another_current_state> ... | |
} | |
Where each state is a method that executes the code/action(s) associated with that state. Inside the method | |
an expression: | |
own_method_name = inspect.stack()[0][3] | |
could be used to capture the method name aka state name. Then the *last* statement of that method must be: | |
# do transition to configured state | |
return getattr(self, self.sm.sm(own_method_name, event))() | |
''' | |
if (type(configuration) == DictionaryType) and (len(configuration) != 0): | |
self.configuration = configuration | |
else: | |
raise MissingStateMachineConfigurationException( | |
"Missing required State Machine configuration (dict required)!") | |
self.log = logger | |
def sm(self, current_state, event): | |
try: | |
next_state = self.configuration[current_state][event] | |
self.log.debug(">> sm: %s --- %s --> %s" % (current_state, event, next_state)) | |
return next_state | |
except KeyError: | |
missing_key_tuple = (current_state, event) | |
raise InvalidStateException("Unknown state! Missing key tuple was: '(%s,%s)'" % | |
(missing_key_tuple[0],missing_key_tuple[1])) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment