Home > Software design >  How do I reduce a function consisting of many conditional statements?
How do I reduce a function consisting of many conditional statements?

Time:09-26

I'm working with a function that has multiple conditional statements in it similar to the function illustrated below:

def apply_function(column, function):
  if function == 'function_1':
    return function_1(column)
  
  elif function == 'function_2':
    return function_2(column)
  
  elif function == 'function_3':
    return function_3(column)
  
  elif function == 'function_4':
    return function_4(column)
  
  elif function == 'function_5':
    return function_5(column)
...

Is there a way I can reduce the number of conditional statements and implement the function in more pythonic way with enhanced performance?

Please Advise.

CodePudding user response:

Create a dictionary and get the function from the key of the string function name:

def apply_function(column, function):
    dct = {'function_1': function_1, 'function_2': function_2, 'function_3': function_3
           'function_4': function_4, 'function_5': function_5}
    return dct[function](column)

Or use globals:

def apply_function(column, function):
    return globals()[function](column)
  • Related