RubenLaguna
RubenLaguna

Reputation: 24846

is there a way to access kwargs dict without explicitly using it with def(**kwargs)?

Let's say that we have a function declaration like

def myfunc(a=None,b=None):
    as_dict = {"a": a,
               "b": b,
              }
    print a * b
    some_other_function_that_takes_a_dict(as_dict)

Is there a way to capture the keyword arguments as a dict without changing the def myfunc(...), I mean I can do

 def myfunc(**kwargs):
    print kwargs['a'] * kwargs['b']
    some_other_function_that_takes_a_dict(kwargs)

But if I want to keep the function signature for clarity and documentation, do I have any other way to get the keyword arguments as a dict. I tried to search for magic variables, etc but I can see any that does that.

Just to be clear I'm search for something like

def myfunc(a=None,b=None):
    print a * b
    some_other_function_that_takes_a_dict(__kwargs__)

is there a magical __kwargs__ of some sort in python?

Upvotes: 2

Views: 166

Answers (3)

loopbackbee
loopbackbee

Reputation: 23342

Extending Padraic Cunningham's answer to work with functions that have non-keyword arguments:

from inspect import getargspec

def get_function_kwargs( f, f_locals ):
    argspec= getargspec(f)
    kwargs_keys = argspec[0][-len(argspec[3]):] #get only arguments with defaults
    return  {k:f_locals[k] for k in kwargs_keys}

def my_func(a, b=1, c=2):
    kwargs= get_function_kwargs( my_func, locals() )
    print kwargs

Upvotes: 1

chepner
chepner

Reputation: 532448

Be explicit. Build the dictionary from just those variables that other needs.

def myfunc(a=None, b=None):
    other({'a': a, 'b': b})

Upvotes: 0

Padraic Cunningham
Padraic Cunningham

Reputation: 180540

If you only have kwargs in your function just use locals

def my_func(a=None,b=None):
    kwargs = locals()
    print (kwargs["a"] * kwargs["b"])

In [5]: my_func(10,2)
20

Upvotes: 3

Related Questions