The args and kwargs parameters
We frequently use functions and methods with asterisk or star characters (*
) in their definitions, as shown in the following code snippet:
def spam(*args, **kwargs):
...
Programmers unfamiliar with Python are often puzzled when they encounter this for the first time. What does the single and double asterisk/star character do?
We'll start with *args
. The single *
character tells Python that the function takes a variable number (zero or more) of positional parameters.
>>> def countargs(*args): ... print 'Passed in', len(args), 'args.' >>> countargs('a', 'b', 'c') Passed in 3 args. >>> countargs() Passed in 0 args.
You can combine normal positional parameters and *args
to require some arguments. The os.path.join
method, for example, requires at least one positional argument. Its signature is os.path.join(a, *p)
.
>>> import os >>> os.path.join('a',...