Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make kwargs directly accessible

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?

like image 402
blueFast Avatar asked Nov 21 '13 08:11

blueFast


People also ask

How do I unpack Kwargs?

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.

How do you pass a Kwargs in Python?

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 ** .

Can you have Kwargs without args?

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.

How do you specify Kwargs?

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.


1 Answers

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
like image 172
Inbar Rose Avatar answered Sep 30 '22 23:09

Inbar Rose