ser co
ser co

Reputation: 87

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?

Upvotes: 2

Views: 778

Answers (2)

oppressionslayer
oppressionslayer

Reputation: 7204

You can call any object in swicther with eval as well:

eval('switcher[1]()')                                                                                                                                                                             
# 'January'

Upvotes: 0

gelonida
gelonida

Reputation: 5630

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

Upvotes: 1

Related Questions