Search code examples
pythonfunctional-programmingpartial

Can a function be one of kwargs in Python partial?


I would like to use functools.partial to reduce the number of arguments in one of my functions. Here's the catch: one or more kwargs may be functions themselves. Here's what I mean:

from functools import partial

def B(alpha, x, y):
    return alpha(x)*y

def alpha(x):
    return x+1

g = partial(B, alpha=alpha, y=2)
print(g(5))

This throws an error:

TypeError: B() got multiple values for argument 'alpha'

Can partial handle functions as provided arguments? If not is there a workaround or something more generic than partial?


Solution

  • partial itself doesn't know that a given positional argument should be assigned to x just because you specified a keyword argument for alpha. If you want alpha to be particular function, pass that function as a positional argument to partial.

    >>> g = partial(B, alpha, y=2)
    >>> g(5)
    12
    

    g is equivalent to

    def g(x):
        return alpha(x) * 2  #  == (x + 1) * 2
    

    Alternately, you can use your original definition of g, but be sure to pass 5 as a keyword argument as well, avoiding any additional positional arguments.

    >>> g = partial(B, alpha=alpha, y=2)
    >>> g(x=5)
    12
    

    This works because between g and partial, you have provided keyword arguments for all required parameters, eliminating the need for any positional arguments.