python partial with keyword arguments

醉酒当歌 提交于 2020-08-27 09:31:49

问题


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?


回答1:


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):



回答2:


When trying to call res = map(f1, zz) internally it actually looks like [f1(i) for i in range(10). As you can see you call f1 function with only one positional argument (in this case f1(x=i)). A possible solution would be to do something like this

res = [f1(z=i) for i in range(10)]



回答3:


You may obtain the equivalent result you expect without using partial:

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


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

Please see this link to have a better understanding: functools.partial wants to use a positional argument as a keyword argument



来源:https://stackoverflow.com/questions/38975975/python-partial-with-keyword-arguments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!