Next / Previous / Contents / TCC Help System / NM Tech homepage

16. Defining and calling functions

To define a function named n:

def n(p0[=e0][,p1[=e1]]...[,*pv][,**pd]):
    B

Function n is defined as block B. A function can have any number of parameters p1, p2, ....

If there is an expression ei for parameter pi, that expression specifies the default value for that parameter used if the caller does not supply a value. Such parameters are called keyword parameters, and all keyword parameters must follow all positional (non-keyword) parameters.

If there is a *pv parameter, that parameter gets a (possibly empty) list of all extra positional arguments passed to the function.

If there is a **pd parameter, that parameter gets a dictionary of all extra keyword arguments passed to the function.

To sum up, a function's parameters must start with zero or more positional parameters, followed by zero or more keyword parameters, followed optionally by a parameter to receive extra positional arguments, followed optionally by a parameter to receive extra keyword arguments.

16.1. Calling a function

The arguments you supply to a function must satisfy these rules:

  • You must supply all positional arguments.

  • If you supply additional arguments beyond the positional arguments and the function has keyword arguments, the additional arguments are matched to those keyword parameters by position. Any unmatched keywoard parameters assume their default values.

  • You can supply arguments for keyword parameters in any order by using the form k=v, where k is the keyword used in the declaration of that parameter and v is your desired argument.

  • If the function is declared with a **pd parameter, you can supply keyword arguments that don't match the keywords of the parameters. Those extras will be packaged as a dictionary with the keywords as the keys and their values as the values.

For example, suppose a function is defined with this parameter list:

def foo(a, b, c=9, d="blue", *e, **f): ...

This function has two positional parameters a and b and two keyword parameters c and d. Callers must supply at least two positional arguments. If a third or fourth positional argument is supplied, they are bound to parameters c and d respectively; additional positional arguments are bound in a list to e.

If the caller supplies keyword arguments of the form c=value or d=value, those values are bound to parameters c and d respectively. Any other keyword arguments are packaged as a dictionary and bound to parameter f.