Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 919
user32882 Avatar asked Dec 18 '25 07:12

user32882


1 Answers

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.

like image 146
chepner Avatar answered Dec 20 '25 21:12

chepner