Quickstart: Implement a state machine in a Python class
masterTo use transitions, import Machine and initialize it within your model class. You define states as a list and add transitions using add_transition. Transitions can be added via method calls or passed as a list of dictionaries to the Machine constructor. You can also use before and after callbacks to execute logic during transitions, and conditions to restrict transitions based on method returns.
from transitions import Machine
import random
class NarcolepticSuperhero(object):
# Define states
states = ['asleep', 'hanging out', 'hungry', 'sweaty', 'saving the world']
def __init__(self, name):
self.name = name
self.kittens_rescued = 0
# Initialize the state machine
# 'model=self' attaches the state and transition methods to this instance
self.machine = Machine(model=self, states=NarcolepticSuperhero.states, initial='asleep')
# Add transitions
# Using keyword arguments for trigger, source, and dest
self.machine.add_transition(trigger='wake_up', source='asleep', dest='hanging out')
# Using positional arguments for trigger, source, and dest
self.machine.add_transition('work_out', 'hanging out', 'hungry')
self.machine.add_transition('eat', 'hungry', 'hanging out')
# Using '*' as a source allows triggering from any state
self.machine.add_transition('distress_call', '*', 'saving the world',
before='change_into_super_secret_costume')
# Using 'after' to trigger logic after a successful transition
self.machine.add_transition('complete_mission', 'saving the world', 'sweaty',
after='update_journal')
# Using 'conditions' to check a property/method before allowing transition
self.machine.add_transition('clean_up', 'sweaty', 'asleep', conditions=['is_exhausted'])
self.machine.add_transition('clean_up', 'sweaty', 'hanging out')
self.machine.add_transition('nap', '*', 'asleep')
def update_journal(self):
self.kittens_rescued += 1
@property
def is_exhausted(self):
return random.random() < 0.5
def change_into_super_secret_costume(self):
print("Beauty, eh?")
# Usage
batman = NarcolepticSuperhero("Batman")
print(batman.state) # 'asleep'
batman.wake_up()
print(batman.state) # 'hanging out'
batman.distress_call()
print(batman.state) # 'saving the world'