class Matter(object):
def __init__(self, states, transitions):
self.states = states
self.transitions = transitions
self.machine = Machine(model=self, states=self.states, transitions=transitions, initial='liquid')
def get_triggered_events(self, source, dest):
self.machine.set_state(source)
eval("self.to_{}()".format(dest))
return
states=['solid', 'liquid', 'gas', 'plasma']
transitions = [
{ 'trigger': 'melt', 'source': 'solid', 'dest': 'liquid' },
{ 'trigger': 'evaporate', 'source': 'liquid', 'dest': 'gas' },
{ 'trigger': 'sublimate', 'source': 'solid', 'dest': 'gas' },
{ 'trigger': 'ionize', 'source': 'gas', 'dest': 'plasma' }
]
matter=Matter(states,transitions)
matter.get_triggered_events("solid","plasma")
I want to get the history of triggered events from source to destination in get_triggered_events method. E.g. runing matter.get_triggered_events("solid","plasma") will get [["melt","evaporate","ionize"],["sublimate","ionize"]]. Is there a simple way to achieve it?
I guess what you intend to do is to get all possible paths from one state to another. You are interested in the names of the events that must be emitted/triggered to reach your target.
A solution is to traverse through all events that can be triggered in a state. Since one event can result in multiple transitions we need to loop over a list of transitions as well. With
Machine.get_triggers(<state_name>)we'll get a list of all events that can be triggered from<state_name>. WithMachine.get_transitions(<event_name>, source=<state_name>)we will get a list of all transitions that are associated with<event_name>and can be triggered from<state_name>.We basically feed the result from
Machine.get_triggerstoMachine.get_transitionsand loop over the list of transitions while keeping track of the events that have been processed so far. Furthermore, to prevent cyclic traversal, we also keep track of the transition entities we have already visited:You might want to have a look at the discussion in
transitionsissue tracker about automatic traversal as it contains some insights about conditional traversal.