views:

465

answers:

10

So I have difficulty with the concept of *args and **kwargs.

So far I have learned that:

  • *args = list of arguments -as positional arguments
  • **kwargs = dictionary - whose keys become separate keyword arguments and the values become values of these arguments.

??

To be honest I don't understand and don't get for what programming task this would helpful. (I am sure there is, but I can't get an understanding of it.)

Maybe:

I think to enter lists and dictionaries as arguments of a function AND at the same time as a wildcard, so I can pass ANY argument?

Is there a simple example on which to explain how *args and **kwargs are used?

Also the tutorial I run through used just the "*" and a variable name.

Is *args and **kwargs just a placeholder or do you use exactly "args" and "*kwargs" in the code?

A: 

The names *args and **kwargs or **kw are purely by convention. It makes it easier for us to read each other's code

One place it is handy is when using the struct module

struct.unpack() returns a tuple whereas struct.pack() uses a variable number of arguments. When manipulating data it is convenient to be able to pass a tuple to struck.pack() eg.

tuple_of_data = struct.unpack(format_str, data)
... manipulate the data
new_data = struct.pack(format_str, *tuple_of_data)

without this ability you would be forced to write

new_data = struct.pack(format_str, tuple_of_data[0], tuple_of_data[1], tuple_of_data[2],...)

which also means the if the format_str changes and the size of the tuple changes, I'll have to go back and edit that really long line

gnibbler
+20  A: 

The syntax is the * and **. The names *args and **kwargs are only by convention but there's no need not to use them.

You would use *args when you're not sure how many arguments might be passed to your function, i.e. it allows you pass an arbitrary number of arguments to your function. For example:

>>> def print_everything(*args):
...     count = 1
...     for thing in args:
...         print "%d. %s" % (count,thing)
...         count += 1
...
>>> print_everything('apple', 'banana', 'cabbage')
1. apple
2. banana
3. cabbage

Similarly, **kwargs allows you to handle named arguments that you have not defined in advance:

>>> def table_things(**kwargs):
...     for name,value in kwargs.items():
...         print name, "=", value
...
>>> table_things(apple = 'fruit', cabbage = 'vegetable')
cabbage = vegetable
apple = fruit

You can use these along with named arguments too. The explicit arguments get values first and then everything else is passed to *args and *kwargs. The named arguments come first in the list. For example:

def table_things(titlestring, **kwargs)

You can also use both in the same function definition but *args must occur before **kwargs.

You can also use the * and ** syntax when calling a function. For example:

>>> def print_three_things(a, b, c):
...     print "a =", a, "& b =", b, "& c =", c
...
>>> mylist = ['aardvark', 'baboon', 'cat']
>>> print_three_things(*mylist)
a = aardvark & b = baboon & c = cat

As you can see in this case it takes the list (or tuple) of items and matches them to the arguments in the function. Of course, you could have a * both in the function definition and in the function call.

Dave Webb
You should probably also mention that `*` and `**` can be used when calling a function as well :)
Blixt
@Blixt - good point, have added that now.
Dave Webb
Wow! Thanks to everybody who responded so quickly. I think I have a lot of examples to go through now !. Fantastic, really..
MacPython
Ugh, no spaces after commas make the code hardtoread.
Marius Gedminas
@Marius Gedminas - fixed.
Dave Webb
+9  A: 

One place where the use of *args and **kwargs is quite useful is for subclassing.

class Foo(object):
    def __init__(self, value1, value2):
        # do something with the values
        print value1, value2

class MyFoo(Foo):
    def __init__(self, *args, **kwargs):
        # do something else, don't care about the args
        print 'myfoo'
        super(MyFoo, self).__init__(*args, **kwargs)

This way you can extend the behaviour of the Foo class, without having to know too much about Foo. This can be quite convenient if you are programming to an API which might change. MyFoo just passes all arguments to the Foo.

Mark van Lent
+1  A: 

*args and **kwargs are special-magic features of Python. Think of a function that could have an unknown number of arguments. For example, for whatever reasons, you want to have function that sums an unknown number of numbers (and you don't want to use the built-in sum function). So you write this function:

def sumFunction(*args):
  result = 0
  for x in args:
    result += x
  return result

and use it like: sumFunction(3,4,6,3,6,8,9).

**kwargs has a diffrent function. With **kwargs you can give arbitrary keyword arguments to a function and you can access them as a dictonary.

def someFunction(**kwargs):
  if 'text' in kwargs:
    print kwargs['text']

Calling someFunction(text="foo") will print foo.

Steven Mohr
`for(x in args):` would be a horrible case of unnecessary parentheses if it were valid syntax -- but it's not valid.
John Machin
You're right ... Too much Java at work ;-)
Steven Mohr
A: 

Just imagine you have a function but you don't want to restrict the number of parameter it takes. Example:

>>> import operator
>>> def multiply(*args):
...  return reduce(operator.mul, args)

Then you use this function like:

>>> multiply(1,2,3)
6

or

>>> numbers = [1,2,3]
>>> multiply(*numbers)
6
Felix Kling
+3  A: 

One case where *args and **kwargs are useful is when writing wrapper functions (such as decorators) that need to be able accept arbitrary arguments to pass through to the function being wrapped. For example, a simple decorator that prints the arguments and return value of the function being wrapped:

def mydecorator( f ):
   @functools.wraps( f )
   def wrapper( *args, **kwargs ):
      print "Calling f", args, kwargs
      v = f( *args, **kwargs )
      print "f returned", v
      return v
   return wrapper
jchl
A: 

You can have a look at python docs (docs.python.org in the FAQ), but more specifically for a good explanation the mysterious miss args and mister kwargs.

In a nutshell, both are used when optional parameters to a function or method are used. As Dave says, *args is used when you don't know how many arguments may be passed, and **kwargs when you want to handle parameters specified by name and value as in:

myfunction(myarg=1)
Yoni H
+1  A: 

These parameters are typically used for proxy functions, so the proxy can pass any input parameter to the target function.

def foo(bar=2, baz=5):
    print bar, baz

def proxy(x, *args, **kwargs): # reqire parameter x and accept any number of additional arguments
    print x
    foo(*args, **kwargs) # applies the "non-x" parameter to foo

proxy(23, 5, baz='foo') # calls foo with bar=5 and baz=foo
proxy(6)# calls foo with its default arguments
proxy(7, bar='asdas') # calls foo with bar='asdas' and leave baz default argument

But since these parameters hide the actual parameter names, it is better to avoid them.

Rudi
+2  A: 

Try this, save this as example.py

def any_function(required_arg, *args, **kwargs):
    print required_arg

    # args will be a list of positional arguments
    # because it has * before it
    if args: # If there is anything in args
        print args

    # kwargs will be a dictionary of keyword arguments,
    # because it has ** before it
    if kwargs: # If there is anything in kwargs
        print kwargs

any_function("Required Argument.")
any_function("Required Argument", 1, 2, "pos3")
any_function("Required Argument", 1, 2, "pos3", keyword1=5, keyword2="spam")
Kit
+2  A: 

Here's one of my favorite places to use the ** syntax as in Dave Webb's final example:

mynum = 1000
mystr = 'Hello World!'
print "{mystr} New-style formatting is {mynum}x more fun!".format(**locals())

I'm not sure if it's terribly fast when compared to just using the names themselves, but it's a lot easier to type!

Wayne Werner