pytransitions / transitions

A lightweight, object-oriented finite state machine implementation in Python with many extensions
MIT License
5.49k stars 525 forks source link

Dynamically adding HSM to an existing state, results in child transitions to be absent. #610

Closed e0lithic closed 1 month ago

e0lithic commented 1 year ago

The following can be considered a derivative of Resuse of previously created hsms, where the child states need to be dynamically added to an existing state.

from transitions.extensions.nesting import HierarchicalMachine

count_states = ['1', '2', '3', 'done']
count_trans = [
    ['increase', '1', '2'],
    ['increase', '2', '3'],
    ['decrease', '3', '2'],
    ['decrease', '2', '1'],
    ['done', '3', 'done'],
    ['reset', '*', '1']
]

counter = HierarchicalMachine(states=count_states, transitions=count_trans, initial='1')

counter.increase() # love my counter

states = ['waiting', "collecting", "counting"] # counting's children will be added later.
transitions = [
    ['collect', '*', 'collecting'],
    ['wait', '*', 'waiting'],
    ['count', 'collecting', 'counting']
]

collector = HierarchicalMachine(states=states, transitions=transitions, initial="waiting")
collector.add_state({'name': 'counting', 'children': counter}) # I found this to be the only way to add children to an existing state dynamically

collector.collect()  # collecting
collector.count()  # let's see what we got; counting_1
collector.increase()  # AttributeError: 'increase' does not exist on <Machine@140688982695024>

Expected behavior Ideally, I would have expected "increase" transition to also be copied to the parent machine(Unless I am doing something wrong)