0

I am trying to call certain functions based on a certain variable. If I have lots of functions based on this variable it quickly gets very ugly with all if statements. My questions is if there is a more elegant and "pythonic" solution than doing something like the code below?

if variable == 0:
    function_0()
elif variable == 1:
    function_1()
elif variable == 2:
    function_2()
wjandrea
  • 28,235
  • 9
  • 60
  • 81
eligolf
  • 1,682
  • 1
  • 6
  • 22

2 Answers2

4

Create an array of the functions, index with the variable and call the function.

[function_0, function_1, function_2][variable]()

Or do it via a dictionary

dd = {0 : function_0, 1 : function_1, 2 : function_2}
dd[variable]()
rioV8
  • 24,506
  • 3
  • 32
  • 49
0

You could use a dictionary

fmap = {0: f1, 1: f2, 2: f3}
fmap[variable]() 
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245