Make kwargs directly accessible
arguments, keyword-argument, python
Solution
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
Problem
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?