If you aren't programming with state machines, you should be.
statemachine
offers a simple and easy-to-use finite-state machine that can adapted into almost any code base.
To create a state machine, mix in the statemachine.Machine
class. The only requirement is an initial state, which are represented as strings.
import statemachine
class TrafficLight(statemachine.Machine):
initial_state = 'red'
This machine won't do much, but we can get the current state
>>> stoplight = TrafficLight()
>>> stoplight.state
'red'
We can add state transitions using the event
decorator. These functions return an iterable of transitions. A transition is just a two-tuple. The first element is an iterable of states, the wilcard '*', or a single state. The second element is the target state.
import statemachine
class TrafficLight(statemachine.Machine):
initial_state = 'red'
@statemachine.event
def cycle(self):
yield 'red', 'green'
yield 'green', 'yellow'
yield 'yellow', 'red'
Calling the cycle
method will transition the machine into the next state.
>>> stoplight = TrafficLight()
>>> stoplight.state
'red'
>>> stoplight.cycle()
>>> stoplight.state
'green'
You can listen for transition events using the before_transition
and after_transition
decorators`.
import statemachine
class TrafficLight(statemachine.Machine):
initial_state = 'red'
@statemachine.event
def cycle(self):
yield 'red', 'green'
yield 'green', 'yellow'
yield 'yellow', 'red'
@statemachine.after_transition('red', 'green')
def announce(self):
print "GO GO GO"
Initiate the transition by calling cycle
>>> stoplight = TrafficLight()
>>> stoplight.cycle()
'GO GO GO'
If you only care about where you're coming from (or where you're going), use the transition_from
and transition_to
decorator
import statemachine
class TrafficLight(statemachine.Machine):
initial_state = 'red'
@statemachine.event
def cycle(self):
yield 'red', 'green'
yield 'green', 'yellow'
yield 'yellow', 'red'
@transition_to('yellow')
def safety(self):
print "SLOW DOWN"
@transition_from('red')
def announce(self):
print "GO GO GO"
$ pip install statemachine