Skip to content

Instantly share code, notes, and snippets.

@Karn
Created July 29, 2017 07:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Karn/188603e62c5fda66a42995e11b3653bc to your computer and use it in GitHub Desktop.
Save Karn/188603e62c5fda66a42995e11b3653bc to your computer and use it in GitHub Desktop.
Python State Machine - States
class State(object):
"""
We define a state object which provides some utility functions for the
individual states within the state machine.
"""
def __init__(self):
print 'Processing current state:', str(self)
def on_event(self, event):
"""
Handle events that are delegated to this State.
"""
pass
def __repr__(self):
"""
Leverages the __str__ method to describe the State.
"""
return self.__str__()
def __str__(self):
"""
Returns the name of the State.
"""
return self.__class__.__name__
# Start of our states
class LockedState(State):
"""
The state which indicates that there are limited device capabilities.
"""
def on_event(self, event):
if event == 'pin_entered':
return UnlockedState()
return self
class UnlockedState(State):
"""
The state which indicates that there are no limitations on device
capabilities.
"""
def on_event(self, event):
if event == 'device_locked':
return LockedState()
return self
# End of our states.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment