Specifying a function with an arbitrary number of arguments

To pass an arbitrary number of arguments to a function, use the parameter *args in the def statement for the function. Here are tips and rules for using *args:

• The parameter *args stands for a set of positional arguments that aren't explicitly named in the function definition.

• When you call the function and pass it arguments, *args automatically creates a tuple out of the arguments.

• The parameter *args must come last in the function definition (or next-to-last if there is also a **kwargs parameter).

To pass an arbitrary number of keyword=value pairs to a function, use the parameter **kwargs in the function's def statement. Here's how it works:

• When you call the function and pass the keyword=value pairs, **kwargs automatically creates a dictionary from them.

• The parameter **kwargs must come last in the function definition.

TECHNICAL The names don't have to be *args or **kwargs; Python cares only STUFF that the * or ** operator comes first in the name. But Pythonistas always use *args and **kwargs. This consistency makes programs easier to read by humans.

This example program shows how *args and **kwargs work in a function that also has two positional parameters:

def a function(a, b, *args, **kwargs): print "a is", a print "b is", b print "*args is this tuple:", args print "**kwargs is this dictionary:", kwargs

It produces the following result:

>>> a function(1, '2', 'three', 'blind', 'mice', see="how", they="run") a is 1 b is 2

**kwargs is this dictionary: {'see': 'how', 'they': 'run'}

Was this article helpful?

0 0

Post a comment