Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 411
RubenLaguna Avatar asked Dec 10 '25 09:12

RubenLaguna


2 Answers

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
like image 108
Padraic Cunningham Avatar answered Dec 12 '25 22:12

Padraic Cunningham


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
like image 29
loopbackbee Avatar answered Dec 12 '25 22:12

loopbackbee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!