stackoverflower
stackoverflower

Reputation: 301

How to use the functools.partial on a function which has an argument which is a callable?

I'm trying to use the function partial from module functools on a callable which has an argument which is a function. I've come up with a minimalist sample code.

from functools import partial

def g(f, x):
  return f(x)

def cube(x):  
  return x*x*x


p1 = partial(g, x=3)
abc = p1(cube) # works


p2 = partial( g, f=cube) 
abc = p2(3)    # fails TypeError: g() got multiple values for keyword argument 'f'

Can the function work with that case?

Thanks

Upvotes: 0

Views: 5371

Answers (2)

stackoverflower
stackoverflower

Reputation: 301

It is not link to the type of the argument, the (partial) function call follows the rules https://docs.python.org/2/reference/expressions.html#calls The positional arguments are placed in the first parameter slots, then if *expression is present, expression is unzipped and placed in the next slots, finally if **expression is present, expression is mapped to function parameters and throws an error if parameter is already bound to an argument.

So

p2 = partial( g, f=cube) 
p2(3)    # fails

is the same as calling

g(3, f=cube)

Upvotes: 1

Govind
Govind

Reputation: 444

You can refer to the partial method from the python doc

In partial we cannot pass two functions, so this may be the issue. Try to pass one function object and the second arg is the functional argument.

You can use this,

p2 = partial(g, f=cube, x=1)
abc = p2(x=3)
print(abc)

Hope this will help you.

Upvotes: 0

Related Questions