How to create a function that applies a function to the inputs of another function in Python?

I’m looking for a nice functional way to do the following:

def add(x, y):
    return x + y

def neg(x):
    return -x

def c(x, y):
    # Apply neg to inputs for add
    _x = neg(x)
    _y = neg(y)

    return add(_x, _y)

neg_sum = c(2, 2)   # -4

It seems related to currying, but all of the examples I can find use functions that only have one input variable. I would like something that looks like this:

def add(x, y):
    return x + y

def neg(x):
    return -x

c = apply(neg, add)
neg_sum = c(2, 2)   # -4

Answer

This is a fairly direct way to do it:

def add(x, y):
    return x + y

def neg(x):
    return -x

def apply(g, f):
    # h is a function that returns
    # f(g(arg1), g(arg2), ...)
    def h(*args):
        return f(*map(g, args))
    return h

# or this:
# def apply(g, f):
#    return lambda *args: f(*map(g, args))

c = apply(neg, add)
neg_sum = c(2, 2)   # -4

Note that when you use *myvar as an argument in a function definition, myvar becomes a list of all non-keyword arguments that are received. And if you call a function with *expression as an argument, then all the items in expression are unpacked and sent as separate arguments to the function. I use these two behaviors to make h accept an unknown list of arguments, then apply function g to each one (with map), then pass all of them as arguments to f.