2

When can I pass * and ** in the argument of a Python function? i.e.:

def fun_name(arg1, *arg2 , ** arg3):
1

3 Answers 3

11

As you've stated your question, you aren't using them in the arguments (which occur when you are calling a function), you are using them in the parameters which occur when you are creating a function. The * and ** operators serve different purposes in each of those situations.

When you are defining a function, they specify that positional arguments will be placed in a tuple and that keyword arguments will be placed in a dict. Yes I did just say arguments, but they are applied to paramaters in this case.

def example(*args, **kwargs):
    print "args: {0}".format(args)
    print "kwargs: {0}".format(kwargs)

example(1, 2, 'a', foo='bar', bar='foo')

when run, this outputs:

args: (1, 2, 'a')
kwargs: {'foo': 'bar', 'bar': 'foo'}

Do you see what I mean when I say that we applied it to the paramaters in the function definition? the arguments are 1, 2, 'a', foo='bar', bar='foo'. the paramaters are *args, **kwargs.

Now here's an example applying them to arguments.

def example2(a, b, foo=None, bar=None):
    print "a: {0}, b:{1}, foo:{2}, bar: {3}".format(a, b, foo, bar)

args = (1, 2)
kwargs = {'foo': 'bar', 'bar': 'foo'}
example2(*args, **kwargs)

This outputs:

a: 1, b:2, foo:bar, bar: foo

You can see that when we apply them to arguments (that is when we are calling the function), * has the effect of expanding a list or tuple to fill the positional arguments of a function and ** has the effect of expanding a dictionary to fill the keyword arguments of a function. You just need to make sure that there are enough and not too much arguments in total after the expansions have taken place.

in the last example, the arguments are *args, **kwargs and the parameters are a, b, foo=None, bar=None

3

When can I pass * and ** in the argument of a Python function? i.e.:

Short answer: when you require variable number of argument to be passed to your function.

That said, I honestly think that this a very broad question. You will be much better off reading more about these concepts, trying them off and then asking an specific questions here.

@Wooble's answer will help you; but what will help you even more is to understand what *args and **kwargs do. Then you can use them as befits the situations you encounter.

You can learn more about the variable and keyword arguments concepts for example at:

  1. http://www.network-theory.co.uk/docs/pytut/KeywordArguments.html
  2. http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
1

Any time you want your function to accept non-named positional arguments (*), or additional named arguments (**).

It's certainly possible to include *args, **kwargs in every function definition, although this might not be a great idea if passing more arguments won't actually have any effect.

Not the answer you're looking for? Browse other questions tagged or ask your own question.