Search code examples
pythonargumentspartialkeyword-argumentfunctools

functools partial with bound first argument and *args and **kwargs interprets calls as multiple values


Using python 3.10:

I have a function with a first argument and then *args and **kwargs. I want to bind the first argument and leave the *args and **kwargs free. If I do this and the bound function gets called using a list of arguments, python interprets it as multiple values for the bound argument. An example:

from functools import partial
def foo1(a : int, *args, **kwargs):
    print(a)
    print(args)
    print(kwargs)
pfoo1 = partial(foo1, a=10)
pfoo1() # works
pfoo1(something="testme") # works
# pfoo1("testme")       # !! interpreted as multiple values for argument a?
# pfoo1(*("testme"))    # !! interpreted as multiple values for argument a?
# pfoo1(*["testme"])    # !! interpreted as multiple values for argument a?

I know I can easily solve this by replacing the foo1 function with:

def foo1(*args, **kwargs):
    print(args)
    print(kwargs)

And then running the same code, but I do not have the luxury of control over the incoming functions so I am stuck with a given signature. A solution could be to create one's own partial class through lambdas and bound members, but that seems excessive. Is there a way of doing this in the partial framework or at least a simple way?


Solution

  • a is the first parameter to function foo1. If you want a partial, do not use keyword:

     pfoo1 = partial(foo1, 10)