What is the purpose and use of **kwargs?

Federer picture Federer · Nov 20, 2009 · Viewed 596.9k times · Source

What are the uses for **kwargs in Python?

I know you can do an objects.filter on a table and pass in a **kwargs argument.  

Can I also do this for specifying time deltas i.e. timedelta(hours = time1)?

How exactly does it work? Is it classes as 'unpacking'? Like a,b=1,2?

Answer

Pär Wieslander picture Pär Wieslander · Nov 20, 2009

You can use **kwargs to let your functions take an arbitrary number of keyword arguments ("kwargs" means "keyword arguments"):

>>> def print_keyword_args(**kwargs):
...     # kwargs is a dict of the keyword args passed to the function
...     for key, value in kwargs.iteritems():
...         print "%s = %s" % (key, value)
... 
>>> print_keyword_args(first_name="John", last_name="Doe")
first_name = John
last_name = Doe

You can also use the **kwargs syntax when calling functions by constructing a dictionary of keyword arguments and passing it to your function:

>>> kwargs = {'first_name': 'Bobby', 'last_name': 'Smith'}
>>> print_keyword_args(**kwargs)
first_name = Bobby
last_name = Smith

The Python Tutorial contains a good explanation of how it works, along with some nice examples.

<--Update-->

For people using Python 3, instead of iteritems(), use items()