Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use **kwargs in python? What are some real world advantages over using named arguments?

People also ask

Why do we use Kwargs in Python?

The special syntax **kwargs in function definitions in python is used to pass a keyworded, variable-length argument list. We use the name kwargs with the double star. The reason is that the double star allows us to pass through keyword arguments (and any number of them).

What is an advantage of using * args?

It allows you to pass on the arguments, without knowing how much you need. A typical example: def f(some, args, here): # <- this function might accept a varying nb of args ... def run_f(args, *f_args): do_something(args) # run f with whatever arguments were given: f(*f_args)

What is Kwargs and why do we need them?

Kwargs allow you to pass keyword arguments to a function. They are used when you are not sure of the number of keyword arguments that will be passed in the function. Kwargs can be used for unpacking dictionary key, value pairs.

What is asterisk in Python function argument?

In Python, the single-asterisk form of *args can be used as a parameter to send a non-keyworded variable-length argument list to functions. It is worth noting that the asterisk ( * ) is the important element here, as the word args is the established conventional idiom, though it is not enforced by the language.


You may want to accept nearly-arbitrary named arguments for a series of reasons -- and that's what the **kw form lets you do.

The most common reason is to pass the arguments right on to some other function you're wrapping (decorators are one case of this, but FAR from the only one!) -- in this case, **kw loosens the coupling between wrapper and wrappee, as the wrapper doesn't have to know or care about all of the wrappee's arguments. Here's another, completely different reason:

d = dict(a=1, b=2, c=3, d=4)

if all the names had to be known in advance, then obviously this approach just couldn't exist, right? And btw, when applicable, I much prefer this way of making a dict whose keys are literal strings to:

d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

simply because the latter is quite punctuation-heavy and hence less readable.

When none of the excellent reasons for accepting **kwargs applies, then don't accept it: it's as simple as that. IOW, if there's no good reason to allow the caller to pass extra named args with arbitrary names, don't allow that to happen -- just avoid putting a **kw form at the end of the function's signature in the def statement.

As for using **kw in a call, that lets you put together the exact set of named arguments that you must pass, each with corresponding values, in a dict, independently of a single call point, then use that dict at the single calling point. Compare:

if x: kw['x'] = x
if y: kw['y'] = y
f(**kw)

to:

if x:
  if y:
    f(x=x, y=y)
  else:
    f(x=x)
else:
  if y:
    f(y=y)
  else:
    f()

Even with just two possibilities (and of the very simplest kind!), the lack of **kw is aleady making the second option absolutely untenable and intolerable -- just imagine how it plays out when there half a dozen possibilities, possibly in slightly richer interaction... without **kw, life would be absolute hell under such circumstances!


Another reason you might want to use **kwargs (and *args) is if you're extending an existing method in a subclass. You want to pass all the existing arguments onto the superclass's method, but want to ensure that your class keeps working even if the signature changes in a future version:

class MySubclass(Superclass):
    def __init__(self, *args, **kwargs):
        self.myvalue = kwargs.pop('myvalue', None)
        super(MySubclass, self).__init__(*args, **kwargs)

Real-world examples:

Decorators - they're usually generic, so you can't specify the arguments upfront:

def decorator(old):
    def new(*args, **kwargs):
        # ...
        return old(*args, **kwargs)
    return new

Places where you want to do magic with an unknown number of keyword arguments. Django's ORM does that, e.g.:

Model.objects.filter(foo__lt = 4, bar__iexact = 'bar')

There are two common cases:

First: You are wrapping another function which takes a number of keyword argument, but you are just going to pass them along:

def my_wrapper(a, b, **kwargs):
    do_something_first(a, b)
    the_real_function(**kwargs)

Second: You are willing to accept any keyword argument, for example, to set attributes on an object:

class OpenEndedObject:
    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)

foo = OpenEndedObject(a=1, foo='bar')
assert foo.a == 1
assert foo.foo == 'bar'

**kwargs are good if you don't know in advance the name of the parameters. For example the dict constructor uses them to initialize the keys of the new dictionary.

dict(**kwargs) -> new dictionary initialized with the name=value pairs
    in the keyword argument list.  For example:  dict(one=1, two=2)
In [3]: dict(one=1, two=2)
Out[3]: {'one': 1, 'two': 2}