Reputation:
What is a move efficient way to run a function dependant on a parameter. I will always know what x will be so I could store all these possibilities in a list but then how would this help me call the appropriate function?
Just for context, I have just over 12 possibility's for x and I get the feeling writing 12 if statements is just wrong.
def run(x):
if x == "dog":
dogfunction()
if x == "cat":
catfunction()
Upvotes: 1
Views: 68
Reputation: 122456
You could do:
def run(x):
functions = {
"dog": dogfunction,
"cat": catfunction,
}
functions[x]()
This explicitly maps a string to a function. It also raises a KeyError
in case the string isn't in the dictionary of functions.
Upvotes: 5