0

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

stackoverflower
  • 301
  • 4
  • 14
  • 1
    In this statement `abc = p2(3)` you are reassigning 3 to **f** which is already assigned in the previous statement `partial( g, f=cube)`. – Akshay Kandul Jun 30 '17 at 11:13

2 Answers2

1

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)
stackoverflower
  • 301
  • 4
  • 14
0

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.

Govind
  • 434
  • 4
  • 8