13

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?

3 Answers 3

34

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)
Sign up to request clarification or add additional context in comments.

1 Comment

I don't know how many times I've had to look up this thing - it's so simple and yet. Thanks for putting it up even though it's obvious :)
2

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.

1 Comment

What does that actually do? What has it got to do with the question?
1

Some experimentation and I figured this one out:

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

Seems obvious now...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.