Question

I have different functions, but each takes different number of arguments and different arguments. I want to be able to execute only one of them and to do this based on the name of the function as string. I tried this:

def execute_function(function_name, arg1, arg2, arg3):
    return {
        'func1': func1(arg1),
        'func2': func2(arg1, arg3),
        'func3': func3(arg2),
    }[function_name]

but it executes all functions :( no matter what is the string function_name.

Do you have any ideas why this happens and how to achieve what I want. (I'm new to Python). Thank you very much in advance! :)

Was it helpful?

Solution

You need to add just the functions to the dictionary; you added their result.

To support variable arguments, use either lambdas or functools.partial() to wrap your functions instead:

def execute_function(function_name, arg1, arg2, arg3):
    return {
        'func1': lambda: func1(arg1),
        'func2': lambda: func2(arg1, arg3),
        'func3': lambda: func3(arg2),
    }[function_name]()

or

from functools import partial

def execute_function(function_name, arg1, arg2, arg3):
    return {
        'func1': partial(func1, arg1),
        'func2': partial(func2, arg1, arg3),
        'func3': partial(func3, arg2),
    }[function_name]()

In both cases you call the resulting object (partial or lambda function) after retrieving it from the dictionary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top