I am refactoring a piece of code, and I have run into the following problem. I have a huge parameter list, which now I want to pass as kwargs
. The code is like this:
def f(a, b, c, ...):
print a
...
f(a, b, c, ...)
I am refactoring it to:
data = dict(a='aaa', b='bbb', c='ccc', ...)
f(**data)
Which means I have to do:
def f(**kwargs):
print kwargs['a']
...
But this is a pita. I would like to keep:
def f(**kwargs):
# Do some magic here to make the kwargs directly accessible
print a
...
Is there any straightforward way of making the arguments in the kwargs
dict
directly accessible, maybe by using some helper class / library?
Unpacking kwargs and dictionaries You cannot directly send a dictionary as a parameter to a function accepting kwargs. The dictionary must be unpacked so that the function may make use of its elements. This is done by unpacking the dictionary, by placing ** before the dictionary name as you pass it into the function.
Python **kwargs In the function, we use the double asterisk ** before the parameter name to denote this type of argument. The arguments are passed as a dictionary and these arguments make a dictionary inside function with name same as the parameter excluding double asterisk ** .
First of all, let me tell you that it is not necessary to write *args or **kwargs. Only the * (asterisk) is necessary. You could have also written *var and **vars. Writing *args and **kwargs is just a convention.
Understanding **kwargsThe double asterisk form of **kwargs is used to pass a keyworded, variable-length argument dictionary to a function. Again, the two asterisks ( ** ) are the important element here, as the word kwargs is conventionally used, though not enforced by the language.
There are some ways - but you can also wrap your function like this:
def f(**kwargs):
arg_order = ['a', 'b', 'c', ...]
args = [kwargs.get(arg, None) for arg in arg_order]
def _f(a, b, c, ...):
# The main code of your function
return _f(*args)
Sample:
def f(**kwargs):
arg_order = ['a', 'b', 'c']
args = [kwargs.get(arg, None) for arg in arg_order]
def _f(a, b, c):
print a, b, c
return _f(*args)
data = dict(a='aaa', b='bbb', c='ccc')
f(**data)
Output:
>>>
aaa bbb ccc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With