Next: Class definitions Up: Compound statements Previous: The try statement

Function definitions

A function definition defines a user-defined function object (see section ):


funcdef:        "def" funcname "(" [parameter_list] ")" ":" suite
parameter_list: (defparameter ",")* ("*" identifier | defparameter [","])
defparameter:   parameter ["=" condition]
sublist:        parameter ("," parameter)* [","]
parameter:      identifier | "(" sublist ")"
funcname:       identifier

A function definition is an executable statement. Its execution binds the function name in the current local name space to a function object (a wrapper around the executable code for the function). This function object contains a reference to the current global name space as the global name space to be used when the function is called.

The function definition does not execute the function body; this gets executed only when the function is called.

When one or more top-level parameters have the form parameter = condition, the function is said to have ``default parameter values''. Default parameter values are evaluated when the function definition is executed. For a parameter with a default value, the correponding argument may be omitted from a call, in which case the parameter's default value is substituted. If a parameter has a default value, all following parameters must also have a default value - this is a syntactic restriction that is not expressed by the grammar.

Function call semantics are described in section . When a user-defined function is called, first missing arguments for which a default value exists are supplied; then the arguments (a.k.a. actual parameters) are bound to the (formal) parameters, as follows:

Note that the `variable length parameter list' feature only works at the top level of the parameter list; individual parameters use a model corresponding more closely to that of ordinary assignment. While the latter model is generally preferable, because of the greater type safety it offers (wrong-sized tuples aren't silently mistreated), variable length parameter lists are a sufficiently accepted practice in most programming languages that a compromise has been worked out. (And anyway, assignment has no equivalent for empty argument lists.)

It is also possible to create anonymous functions (functions not bound to a name), for immediate use in expressions. This uses lambda forms, described in section .



Next: Class definitions Up: Compound statements Previous: The try statement


guido@cwi.nl