python-statemachine icon indicating copy to clipboard operation
python-statemachine copied to clipboard

feature request: return to previous state

Open bernarde01 opened this issue 1 year ago • 2 comments

Thanks for an awesome tool!

I have a state machine that can go to an "ask if exit" state from every state. It would be great if I could define this ask_if_exit as a single state, and then enable this state to transition back to the previous state if the user does not want to exit.

This means that this transition will need to be dynamically defined. I have tried to do this using the library, but no luck. I forked the repo to see if I can implement this, but I don't see how this would be possible.

bernarde01 avatar May 29 '24 08:05 bernarde01

Hi @bernarde01, how are you? Thanks for your suggestion! I really liked it and believe it would be a great addition to the library.

I’m still exploring how to implement this. A related concept in the literature is history pseudo-states, which are defined in the SCXML standard: https://www.w3.org/TR/scxml/#history.

If we can incorporate both history and compound states, this could become a viable solution.

I have an ongoing effort to add support for compound states in this PR: https://github.com/fgmacedo/python-statemachine/pull/329. I’m working on refining this into a non-breaking API, but it’s a significant and complex task.

fgmacedo avatar Sep 09 '24 14:09 fgmacedo

@fgmacedo could somehow source be used here? Something like:

def on_ask_if_exit(self, source: State) -> None:
      user_input = input("Answer: ")

      if user_input == "exit":
          self.send("exit")
      else:
          # Return to the previous state
          self.current_state = source

Unfortunately setting current_state does not trigger any Actions which is required for my use-case.

Love the library btw!

collindutter avatar Sep 17 '24 22:09 collindutter