1

I have written a state machine for a pool controller, but I am struggling with something that is noted in the documentation about forcing the on_enter method to fire off when I initialize the model. The documentation says:

"Note that on_enter_«state name» callback will not fire when a Machine is first initialized. For example if you have an on_enter_A() callback defined, and initialize the Machine with initial='A', on_enter_A() will not be fired until the next time you enter state A. (If you need to make sure on_enter_A() fires at initialization, you can simply create a dummy initial state and then explicitly call to_A() inside the __init__ method.)"

But I am not sure where I need to call this out....I create a Class called Pool_Controller, then create an instance of Pool_Controller like this

MyController=Pool_Controller

And then I create the state machine like this

machine = Machine(MyController, states=states, transitions, initial='dummy_state')

Where do I need to put the to_initial_state() to get the dummy_state immediately jump to my initial_state so that on_enter_initial_state will execute when the model intializes?

Adrian W
  • 4,563
  • 11
  • 38
  • 52

1 Answers1

2

You need to explicitly call to_initial_state after the controller (the model) has been decorated (added to the machine). I'd suggest an approach where the machine is instantiated first and passed to the model's constructor:

from transitions import Machine

class PoolController:

    def __init__(self, machine):
        machine.add_model(self)
        self.to_initial_state()

# we will add the model later (in the model constructor)
machine = Machine(model=None, states=['dummy_state', 'initial_state'], initial='dummy_state')
controller = PoolController(machine)
assert controller.is_initial_state()
aleneum
  • 2,083
  • 12
  • 29