glyph / automat

Self-service finite-state machines for the programmer on the go.
MIT License
591 stars 65 forks source link

Query valid inputs? #115

Open jackgeek opened 5 years ago

jackgeek commented 5 years ago

Hi there. I'm new to automa and interested in your library. Thank you for the effort you have put in and for making it open source.

Can you recommend an approach for knowing which inputs are valid at any given time? It seems to me that the FSM has this information and so I should be able to query it. Is there a way I can know what inputs are presently valid/subscribe to changes?

My use case right now is a simple calculator app. I want to bind the input buttons to inputs and auto disable them if the input is not valid in the current state.

How would you approach this?

Thank you for your time and consideration.

jackgeek commented 5 years ago

Here is the hacky work around that I have come up with... But there must be a better way?

from automat._core import Transitioner

def get_transitioner(fsm):
    attributes = fsm.__dict__
    for attribute in attributes.values():
        if isinstance(attribute, Transitioner):
            return attribute

def print_valid_inputs(fsm):
    transitioner = get_transitioner(fsm)
    automaton = transitioner.__dict__["_automaton"]
    current_state = transitioner.__dict__["_state"]
    transitions = automaton.__dict__["_transitions"]

    def for_current_state(t):
        return t[0] == current_state

    for t in filter(for_current_state, transitions):
        f = t[1].method.__name__
        print(f)
jackgeek commented 5 years ago

Interestingly, the above hack only works after the first input has been executed. Beforehand the _automaton attribute is not in the transitioner dict

glyph commented 5 years ago

It would be great to have a patch to support this.

glyph commented 5 years ago

I don’t have much time to look into this myself, but have you used the visualizer? It’s the closest thing to an inspection API we have yet.