Passing on named variable arguments in python
-
09-06-2019 - |
Question
Say I have the following methods:
def methodA(arg, **kwargs):
pass
def methodB(arg, *args, **kwargs):
pass
In methodA I wish to call methodB, passing on the kwargs. However, it seems that if I define methodA
as follows, the second argument will be passed on as positional rather than named variable arguments.
def methodA(arg, **kwargs):
methodB("argvalue", kwargs)
How do I make sure that the **kwargs in methodA gets passed as **kwargs to methodB?
Solution
Put the asterisks before the kwargs variable. This makes Python pass the variable (which is assumed to be a dictionary) as keyword arguments.
methodB("argvalue", **kwargs)
OTHER TIPS
As an aside: When using functions instead of methods, you could also use functools.partial:
import functools
def foo(arg, **kwargs):
...
bar = functools.partial(foo, "argvalue")
The last line will define a function "bar" that, when called, will call foo with the first argument set to "argvalue" and all other functions just passed on:
bar(5, myarg="value")
will call
foo("argvalue", 5, myarg="value")
Unfortunately that will not work with methods.
Some experimentation and I figured this one out:
def methodA(arg, **kwargs): methodB("argvalue", **kwargs)
Seems obvious now...