Search code examples
pythonstate-machine

Simple State Machine in Python


im a rookie in Python and trying to build a state machine. My idea was a dictionary. So when i enter a key i get a value. And with that i would like to switch a function.

def one():
    return "January"

def two():
    return "February"

def three():
    return "March"

def four():
    return "April"

def numbers_to_months(argument):
    switcher = {
        1: one,
        2: two,
        3: three,
        4: four,
    }

but i dont know how i could go on. My goal would be to use the values to use the function with same name. Could anyone of you help me with a idea?


Solution

  • It's not really a state machine, but what you probably mean is:

    def numbers_to_months(argument):
        switcher = {
            1: one,
            2: two,
            3: three,
            4: four,
        }
        func_to_call = switcher[argument]
        func_to_call()
    

    or perhaps

    def numbers_to_months(argument):
        switcher = {
            1: one,
            2: two,
            3: three,
            4: four,
        }
        func_to_call = switcher[argument]
        return func_to_call