functools.partial wants to use a positional argument as a keyword argument

后端 未结 3 1586
情话喂你
情话喂你 2020-11-30 07:28

So I am trying to understand partial:

import functools

def f(x,y) :
    print x+y

g0 = functools.partial( f, 3 )
g0(1)

4 # Works as expected
         


        
3条回答
  •  一个人的身影
    2020-11-30 08:03

    This has nothing to do with functools.partial, really. You are essentially calling your function like this:

    f(1, x=3)
    

    Python first fulfils the positional arguments, and your first argument is x. Then the keyword arguments are applied, and you again supplied x.

    functools.partial() has no means to detect that you already supplied the first positional argument as a keyword argument instead. It will not augment your call by replacing the positional argument with a y= keyword argument.

    When mixing positional and keyword arguments, you must take care not to use the same argument twice.

提交回复
热议问题