Home > Enterprise >  How to convert nested if/else function calls to a dictionary in python?
How to convert nested if/else function calls to a dictionary in python?

Time:10-25

I have a function which calls different functions based on the conditional statement satisfied. The function currently looks something like this.

def func1(var_a, var_b=1):
    return 'Some values'

def func2(var_c, var_d=2):
    return  'Some values'

def func3(var_e, var_f):
    return 'Some values'


def choose_function(a, b, c):
    if a == 'first_option':
        val = func1(b, c)
    elif a == 'second_option':
        val = func2(b, c)
    elif a == 'third_option':
        val = func3(b, c)

    return val

The function choose_function can have more than 8-10 if else conditions in the future. Is there a more pythonic way to handle these kind of conditional statements.

Can I convert this into a dictionary which calls the functions based on the variable a provided as key in the dictionary. More specifically I want the function to be something like the following

def choose_function(a, b, c):
    func_options ={
        'first_option': func1(b, c),
        'second_option': func2(b, c),
        'third_option': func3(b, c)
    }

    return func_options[a]

Even if the above function works correctly, how can I handle the condition whenever someone provides a value which is not present in the dictionary key?

CodePudding user response:

Store the function references - don't call the functions when defining the dict

def choose_function(a, b, c):
    func_options ={
        'first_option': func1,
        'second_option': func2,
        'third_option': func3
    }

    return func_options[a](b,c)

Handle invalid options using the .get() method on the dictionary

    return func_options.get(a, lambda *args, **kwargs: ...)(b,c)

Substitute ... with print/default value etc.

  • Related