python high order function: generic functions calls with parameter list

129 views Asked by At

I am looking for a high order function in python that takes in a function as parameter and a list of corresponding parameters, and call the function on the parameter list. Something like:

def exec(func,paramlist):
    return CALL(func,paramlist)  

The paramlist length is undetermined, since it goes with each func passed in. The CALL should be able to extract the elements in the list and put each parameter in the right slot and make the function call.

For reference, in Q language there is this "apply" function that handles generic function calls:

f1: {x}
f2: {x+y}
execFunction: {[fun;param] .[fun;param] }
execFunction[f1;enlist 1] // result is 1
execFunction[f2;(1 2)] // result is 3
2

There are 2 answers

0
Óscar López On BEST ANSWER

If func expects multiple parameters and paramlist is a list of parameters, is as simple as this:

func(*paramlist)
0
kindall On

Python used to have an apply function but it was removed in Python 3 because it is so easy to unpack a list into individual arguments using the * operator. In fact an apply function can be written like so:

def apply(func, paramlist)
    return func(*paramlist)

This is so trivial, of course, that you wouldn't bother to write a function for it; you'd just write func(*paramlist) wherever you needed it.