tags:

views:

2150

answers:

3

Say I have the following 2 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 if I simply do:

def methodA(arg, **kwargs):
    methodB("argvalue", kwargs)

The second argument will be passed on as positional rather than named variable arguments. How do I make sure that the **kwargs in methodA gets passed as **kwargs to methodB?

+1  A: 

Some experimentation and I figured this one out:

def methodA(arg, **kwargs): methodB("argvalue", **kwargs)

Seems obvious now...

Staale
+18  A: 

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

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.

Sebastian Rittau
What does that actually do? What has it got to do with the question?
rjmunro