Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python partial with keyword arguments

Tags:

python

partial

I have a function that takes 3 keyword parameters. It has default values for x and y and I would like to call the function for different values of z using map. When I run the code below I get the following error:

foo() got multiple values for keyword argument 'x'

def foo(x =1, y = 2, z = 3):
    print 'x:%d, y:%d, z:%d'%(x, y, z)


if __name__ == '__main__':
    f1 = functools.partial(foo, x= 0, y = -6)
    zz = range(10)
    res = map(f1, zz)

Is there a Pythonic way to solve this problem?

like image 276
motam79 Avatar asked Aug 16 '16 13:08

motam79


People also ask

What is partial keyword in python?

What is a Partial Function? Using partial functions is a component of metaprogramming in Python, a concept that refers to a programmer writing code that manipulates code. You can think of a partial function as an extension of another specified function.

What does Functools partial do?

You can create partial functions in python by using the partial function from the functools library. Partial functions allow one to derive a function with x parameters to a function with fewer parameters and fixed values set for the more limited function.

What are the 3 types of arguments in python?

Hence, we conclude that Python Function Arguments and its three types of arguments to functions. These are- default, keyword, and arbitrary arguments.

What does Functools do in python?

Functools module is for higher-order functions that work on other functions. It provides functions for working with other functions and callable objects to use or extend them without completely rewriting them.


1 Answers

map(f1, zz) tries to call the function f1 on every element in zz, but it doesn't know with which arguments to do it. partial redefined foo with x=0 but map will try to reassign x because it uses positional arguments.

To counter this you can either use a simple list comprehension as in @mic4ael's answer, or define a lambda inside the map:

res = map(lambda z: f1(z=z), zz)

Another solution would be to change the order of the arguments in the function's signature:

def foo(z=3, x=1, y=2):
like image 103
DeepSpace Avatar answered Oct 20 '22 04:10

DeepSpace