Arguments that are just expressions are known as positional arguments. Each positional argument supplies the value for the parameter that corresponds to it by position (order) in the function definition.
In a function call, zero or more positional arguments may be followed by zero or more named arguments, each with the following syntax:
identifier=expression
The identifier must be one of the parameter names used in the def statement for the function. The expression supplies the value for the parameter of that name. Most built-in functions do not accept named arguments, you must call such functions with positional arguments only. However, all normal functions coded in Python accept named as well as positional arguments, so you may call them in different ways.
A function call must supply, via a positional or a named argument, exactly one value for each mandatory parameter, and zero or one value for each optional parameter. For example:
As you can see, the two calls to divide are equivalent. You can pass named arguments for readability purposes whenever you think that identifying the role of each argument and controlling the order of arguments enhances your code's clarity.
A common use of named arguments is to bind some optional parameters to specific values, while letting other optional parameters take default values:
Thanks to named argument end='', the caller can specify a value, the empty string '', for f's third parameter, end, and still let f's second parameter, begin, use its default value, the string 'init'.
At the end of the arguments in a function call, you may optionally use either or both of the special forms *seq and **dct. If both forms are present, the form with two asterisks must be last. *seq passes the items of seq to the function as positional arguments (after the normal positional arguments, if any, that the call gives with the usual syntax). seq may be any iterable. **dct passes the items of dct to the function as named arguments, where dct must be a dictionary whose keys are all strings. Each item's key is a parameter name, and the item's value is the argument's value.
Sometimes you want to pass an argument of the form *seq or **dct when the parameters use similar forms, as described earlier in "Parameters" on page 71. For example, using the function sum_args defined in that section (and shown again here), you may want to print the sum of all the values in dictionary d . This is easy with *seq :
(Of course, in this case, print sum(d.values()) would be simpler and more direct!)
However, you may also pass arguments of the form *seq or **dct when calling a function that does not use the corresponding forms in its parameters. In that case, of course, you must ensure that iterable seq has the right number of items, or, respectively, that dictionary dct uses the right names as its keys; otherwise, the call operation raises an exception.
Please check back next week for the conclusion to this article.