Search code examples
pythonfunctionkeyword-argument

Pass a list of functions with their corresponding parameters to another function


I am struggling to pass a list of functions with a list of corresponding parameters. I also checked here, but it wasn't very helpful. for example (a naive approach which doesn't work):

def foo(data, functions_list, **kwarg):
    for func_i in functions_list:
        print func_i(data, **kwarg)

def func_1(data, par_1):
    return some_function_1(data, par_1)

def func_2(data, par_2_0, par_2_1):
    return some_function_2(data, par_2_0, par_2_1)

foo(data, [func_1, func_2], par_1='some_par', par_2_0=5, par_2_1=11)

Importantly, par_1 cannot be used in func_2, so each function consumes a unique set of parameters.


Solution

  • You could use the function's name as the keyword arguments. When indexing kwargs, you'd use func_i.__name__ as the key.

    def foo(data, function_list, **kwargs):
        for func_i in function_list:
            print(func_i(data, kwargs[func_i.__name__]))
    

    And now,

    foo(data, [func_1, func_2], func_1='some_par', func_2=[5, 11])