tags:

views:

1082

answers:

4

What are the uses for **kwargs in Python?

I know you can do an objects.filter on a table and pass in a **kargs 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?

+4  A: 

kwargs is just a dictionary that is added to the parameters.

A dictionary can contain key, value pairs. And that are the kwargs. Ok, this is how.

The whatfor is not so simple.

For example (very hypothetical) you have an interface that just calls other routines to do the job:

def myDo(what, where, why):
   if what == 'swim':
      doSwim(where, why)
   elif what == 'walk':
      doWalk(where, why)
   ...

Now you get a new method "drive":

elif what == 'drive':
   doDrive(where, why, vehicle)

But wait a minute, there is a new parameter "vehicle" -- you did not know it before. Now you must add it to the signature of the myDo-function.

Here you can throw kwargs into play:

def myDo(what, where, why, **kwargs):
   if what == 'drive':
      doDrive(where, why, **kwargs)
   elif what == 'swim':
      doSwim(where, why, **kwargs)

This way you don't need to change the signature of your interface function every time some of your called routines might change.

This is just one nice example you could find kwargs helpful.

Juergen
+1 for useful example
Javier Badia
+6  A: 

You can use **kwargs to let your functions take an arbitrary number of 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:

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

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

Pär Wieslander
+5  A: 

Unpacking dictionaries

** do unpack dictionaries.

This

func(a=1, b=2, c=3)

is the same as

args = {a: 1, b: 2, c:3}
func(**args)

It's useful if you have to construct parameters:

args = {name: person.name}
if hasattr(person, "address"):
    args["address"] = person.address
func(**args)  # either expanded to func(name=person.name) or
              #                    func(name=person.name, address=person.address)

Packing parameters of a function

def setstyle(**styles):
    for key, value in styles.iteritems():      # styles is a regular dictionary
        setattr(someobject, key, value)

This let's you use the function like this:

setstyle(color="red", bold=False)
Georg
A: 

kwargs are a syntactic sugar to pass name arguments as dictionaries(for func), or dictionaries as named arguments(to func)