merlin2011
merlin2011

Reputation: 75585

Is there a simpler notation to forward a particular keyword argument to a function?

Sometimes I will write a function which calls another function with the same long keyword argument, as well as a bunch of unrelated arguments.

Is there a short notation for forwarding the keyword argument without repeating it twice, assuming that it must be called by keyword (because there are other keyword args for bar which are not used)?

Consider the following function.

def foo(a1, a2, a3, arg_with_very_long_name):
    # do other work
    bar(b1, b2, b3, b4, arg_with_very_long_name=arg_with_very_long_name)

Is there a shorter form for arg_with_very_long_name=arg_with_very_long_name in the call to bar above?

Upvotes: 0

Views: 162

Answers (2)

mgilson
mgilson

Reputation: 310079

There's not a perfect way to do this better than what you have already. One other option is to use **kwarg unpacking instead:

def foo(a, b, c, **kwargs):
    # do stuff
    bar(aa, bb, cc, **kwargs)

The downside (and upside) here is that you don't immediately know what keywords are getting forwarded on to bar. It makes it so that foo accepts any default arguments that bar does -- But you can't introspect what those are just by looking at foo.

Upvotes: 2

Nikola Dimitroff
Nikola Dimitroff

Reputation: 6237

If the keyword argument follows directly the positional arguments, you need not use the kwarg=kwarg syntax:

def f(a, b, c, some_ver_long_kwarg_name=None):
    print(some_very_long_kwarg_name)

f(1, 2, 3, 4) # Prints 4

Upvotes: 0

Related Questions