Search code examples
pythonargumentswrapperpartialfunctools

Creating a partial function that sets a keyword argument in the original function


Not sure if this is possible but I'm trying to create a partial function from a function with positional and keyword arguments. The problem is, I want the argument in the resulting partial function to set one of the keyword arguments in the original function - not one of its positional arguments.

Here is the original function's definition:

def cost_function(self, X, y, weights=None, lambda_param=0.0):

I want a partial function that I can pass to scipy.minimise so I can find the optimum weights values (weights is an ndarray).

So what I need is a partial function with just one argument (x say):

E.g.

cost_func(x)

But I want the partial function to set the weights argument when it calls the original function:

my_network.cost_function(X, y, weights=x, lambda_param=0.0)

(I know I could change the original function so that the weights argument is positional not a keyword argument but I don't want to do that because I also want to use the function without a weights argument set).


Solution

  • I think that functools.partial meet your needs

    See example:

    import functools
    def cost_function(self, X, y, weights=None, lambda_param=0.0):
        print (weights)
    
    cost_func = functools.partial(cost_function, None, 20, 30, lambda_param=2.0)
    
    
    print (cost_func("Yay it worked!!!"))