Fred Drake | 61c7728 | 1998-07-28 19:34:22 +0000 | [diff] [blame] | 1 | \chapter{Compound statements\label{compound}} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 2 | \indexii{compound}{statement} |
| 3 | |
| 4 | Compound statements contain (groups of) other statements; they affect |
| 5 | or control the execution of those other statements in some way. In |
| 6 | general, compound statements span multiple lines, although in simple |
| 7 | incarnations a whole compound statement may be contained in one line. |
| 8 | |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 9 | The \keyword{if}, \keyword{while} and \keyword{for} statements implement |
| 10 | traditional control flow constructs. \keyword{try} specifies exception |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 11 | handlers and/or cleanup code for a group of statements. Function and |
| 12 | class definitions are also syntactically compound statements. |
| 13 | |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 14 | Compound statements consist of one or more `clauses.' A clause |
| 15 | consists of a header and a `suite.' The clause headers of a |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 16 | particular compound statement are all at the same indentation level. |
| 17 | Each clause header begins with a uniquely identifying keyword and ends |
| 18 | with a colon. A suite is a group of statements controlled by a |
| 19 | clause. A suite can be one or more semicolon-separated simple |
| 20 | statements on the same line as the header, following the header's |
| 21 | colon, or it can be one or more indented statements on subsequent |
| 22 | lines. Only the latter form of suite can contain nested compound |
| 23 | statements; the following is illegal, mostly because it wouldn't be |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 24 | clear to which \keyword{if} clause a following \keyword{else} clause would |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 25 | belong: |
| 26 | \index{clause} |
| 27 | \index{suite} |
| 28 | |
| 29 | \begin{verbatim} |
| 30 | if test1: if test2: print x |
| 31 | \end{verbatim} |
| 32 | |
| 33 | Also note that the semicolon binds tighter than the colon in this |
| 34 | context, so that in the following example, either all or none of the |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 35 | \keyword{print} statements are executed: |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 36 | |
| 37 | \begin{verbatim} |
| 38 | if x < y < z: print x; print y; print z |
| 39 | \end{verbatim} |
| 40 | |
| 41 | Summarizing: |
| 42 | |
| 43 | \begin{verbatim} |
| 44 | compound_stmt: if_stmt | while_stmt | for_stmt |
| 45 | | try_stmt | funcdef | classdef |
| 46 | suite: stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT |
| 47 | statement: stmt_list NEWLINE | compound_stmt |
| 48 | stmt_list: simple_stmt (";" simple_stmt)* [";"] |
| 49 | \end{verbatim} |
| 50 | |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 51 | Note that statements always end in a |
| 52 | \code{NEWLINE}\index{NEWLINE token} possibly followed by a |
| 53 | \code{DEDENT}.\index{DEDENT token} Also note that optional |
| 54 | continuation clauses always begin with a keyword that cannot start a |
| 55 | statement, thus there are no ambiguities (the `dangling |
| 56 | \keyword{else}' problem is solved in Python by requiring nested |
| 57 | \keyword{if} statements to be indented). |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 58 | \indexii{dangling}{else} |
| 59 | |
| 60 | The formatting of the grammar rules in the following sections places |
| 61 | each clause on a separate line for clarity. |
| 62 | |
Fred Drake | 61c7728 | 1998-07-28 19:34:22 +0000 | [diff] [blame] | 63 | \section{The \keyword{if} statement\label{if}} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 64 | \stindex{if} |
| 65 | |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 66 | The \keyword{if} statement is used for conditional execution: |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 67 | |
| 68 | \begin{verbatim} |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 69 | if_stmt: "if" expression ":" suite |
| 70 | ("elif" expression ":" suite)* |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 71 | ["else" ":" suite] |
| 72 | \end{verbatim} |
| 73 | |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 74 | It selects exactly one of the suites by evaluating the expressions one |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 75 | by one until one is found to be true (see section \ref{Booleans} for |
| 76 | the definition of true and false); then that suite is executed (and no |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 77 | other part of the \keyword{if} statement is executed or evaluated). If |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 78 | all expressions are false, the suite of the \keyword{else} clause, if |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 79 | present, is executed. |
| 80 | \kwindex{elif} |
| 81 | \kwindex{else} |
| 82 | |
Fred Drake | 61c7728 | 1998-07-28 19:34:22 +0000 | [diff] [blame] | 83 | \section{The \keyword{while} statement\label{while}} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 84 | \stindex{while} |
| 85 | \indexii{loop}{statement} |
| 86 | |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 87 | The \keyword{while} statement is used for repeated execution as long |
| 88 | as an expression is true: |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 89 | |
| 90 | \begin{verbatim} |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 91 | while_stmt: "while" expression ":" suite |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 92 | ["else" ":" suite] |
| 93 | \end{verbatim} |
| 94 | |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 95 | This repeatedly tests the expression and, if it is true, executes the |
| 96 | first suite; if the expression is false (which may be the first time it |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 97 | is tested) the suite of the \keyword{else} clause, if present, is |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 98 | executed and the loop terminates. |
| 99 | \kwindex{else} |
| 100 | |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 101 | A \keyword{break} statement executed in the first suite terminates the |
| 102 | loop without executing the \keyword{else} clause's suite. A |
| 103 | \keyword{continue} statement executed in the first suite skips the rest |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 104 | of the suite and goes back to testing the expression. |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 105 | \stindex{break} |
| 106 | \stindex{continue} |
| 107 | |
Fred Drake | 61c7728 | 1998-07-28 19:34:22 +0000 | [diff] [blame] | 108 | \section{The \keyword{for} statement\label{for}} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 109 | \stindex{for} |
| 110 | \indexii{loop}{statement} |
| 111 | |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 112 | The \keyword{for} statement is used to iterate over the elements of a |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 113 | sequence (string, tuple or list): |
| 114 | \obindex{sequence} |
| 115 | |
| 116 | \begin{verbatim} |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 117 | for_stmt: "for" target_list "in" expression_list ":" suite |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 118 | ["else" ":" suite] |
| 119 | \end{verbatim} |
| 120 | |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 121 | The expression list is evaluated once; it should yield a sequence. The |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 122 | suite is then executed once for each item in the sequence, in the |
| 123 | order of ascending indices. Each item in turn is assigned to the |
| 124 | target list using the standard rules for assignments, and then the |
| 125 | suite is executed. When the items are exhausted (which is immediately |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 126 | when the sequence is empty), the suite in the \keyword{else} clause, if |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 127 | present, is executed, and the loop terminates. |
| 128 | \kwindex{in} |
| 129 | \kwindex{else} |
| 130 | \indexii{target}{list} |
| 131 | |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 132 | A \keyword{break} statement executed in the first suite terminates the |
| 133 | loop without executing the \keyword{else} clause's suite. A |
| 134 | \keyword{continue} statement executed in the first suite skips the rest |
| 135 | of the suite and continues with the next item, or with the \keyword{else} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 136 | clause if there was no next item. |
| 137 | \stindex{break} |
| 138 | \stindex{continue} |
| 139 | |
| 140 | The suite may assign to the variable(s) in the target list; this does |
| 141 | not affect the next item assigned to it. |
| 142 | |
| 143 | The target list is not deleted when the loop is finished, but if the |
| 144 | sequence is empty, it will not have been assigned to at all by the |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 145 | loop. Hint: the built-in function \function{range()} returns a |
| 146 | sequence of integers suitable to emulate the effect of Pascal's |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 147 | \code{for i := a to b do}; |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 148 | e.g., \code{range(3)} returns the list \code{[0, 1, 2]}. |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 149 | \bifuncindex{range} |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 150 | \indexii{Pascal}{language} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 151 | |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 152 | \strong{Warning:} There is a subtlety when the sequence is being modified |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 153 | by the loop (this can only occur for mutable sequences, i.e. lists). |
| 154 | An internal counter is used to keep track of which item is used next, |
| 155 | and this is incremented on each iteration. When this counter has |
| 156 | reached the length of the sequence the loop terminates. This means that |
| 157 | if the suite deletes the current (or a previous) item from the |
| 158 | sequence, the next item will be skipped (since it gets the index of |
| 159 | the current item which has already been treated). Likewise, if the |
| 160 | suite inserts an item in the sequence before the current item, the |
| 161 | current item will be treated again the next time through the loop. |
| 162 | This can lead to nasty bugs that can be avoided by making a temporary |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 163 | copy using a slice of the whole sequence, e.g., |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 164 | \index{loop!over mutable sequence} |
| 165 | \index{mutable sequence!loop over} |
| 166 | |
| 167 | \begin{verbatim} |
| 168 | for x in a[:]: |
| 169 | if x < 0: a.remove(x) |
| 170 | \end{verbatim} |
| 171 | |
Fred Drake | 61c7728 | 1998-07-28 19:34:22 +0000 | [diff] [blame] | 172 | \section{The \keyword{try} statement\label{try}} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 173 | \stindex{try} |
| 174 | |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 175 | The \keyword{try} statement specifies exception handlers and/or cleanup |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 176 | code for a group of statements: |
| 177 | |
| 178 | \begin{verbatim} |
| 179 | try_stmt: try_exc_stmt | try_fin_stmt |
| 180 | try_exc_stmt: "try" ":" suite |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 181 | ("except" [expression ["," target]] ":" suite)+ |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 182 | ["else" ":" suite] |
| 183 | try_fin_stmt: "try" ":" suite |
| 184 | "finally" ":" suite |
| 185 | \end{verbatim} |
| 186 | |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 187 | There are two forms of \keyword{try} statement: |
| 188 | \keyword{try}...\keyword{except} and |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 189 | \keyword{try}...\keyword{finally}. These forms cannot be mixed (but |
| 190 | they can be nested in each other). |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 191 | |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 192 | The \keyword{try}...\keyword{except} form specifies one or more |
| 193 | exception handlers |
| 194 | (the \keyword{except} clauses). When no exception occurs in the |
| 195 | \keyword{try} clause, no exception handler is executed. When an |
| 196 | exception occurs in the \keyword{try} suite, a search for an exception |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 197 | handler is started. This search inspects the except clauses in turn until |
| 198 | one is found that matches the exception. An expression-less except |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 199 | clause, if present, must be last; it matches any exception. For an |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 200 | except clause with an expression, that expression is evaluated, and the |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 201 | clause matches the exception if the resulting object is ``compatible'' |
| 202 | with the exception. An object is compatible with an exception if it |
| 203 | is either the object that identifies the exception, or (for exceptions |
| 204 | that are classes) it is a base class of the exception, or it is a |
| 205 | tuple containing an item that is compatible with the exception. Note |
| 206 | that the object identities must match, i.e. it must be the same |
| 207 | object, not just an object with the same value. |
| 208 | \kwindex{except} |
| 209 | |
| 210 | If no except clause matches the exception, the search for an exception |
| 211 | handler continues in the surrounding code and on the invocation stack. |
| 212 | |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 213 | If the evaluation of an expression in the header of an except clause |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 214 | raises an exception, the original search for a handler is cancelled |
| 215 | and a search starts for the new exception in the surrounding code and |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 216 | on the call stack (it is treated as if the entire \keyword{try} statement |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 217 | raised the exception). |
| 218 | |
| 219 | When a matching except clause is found, the exception's parameter is |
| 220 | assigned to the target specified in that except clause, if present, |
Fred Drake | 4c2533f | 1999-08-24 22:14:01 +0000 | [diff] [blame] | 221 | and the except clause's suite is executed. All except clauses must |
| 222 | have an executable block. When the end of this block |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 223 | is reached, execution continues normally after the entire try |
| 224 | statement. (This means that if two nested handlers exist for the same |
| 225 | exception, and the exception occurs in the try clause of the inner |
| 226 | handler, the outer handler will not handle the exception.) |
| 227 | |
| 228 | Before an except clause's suite is executed, details about the |
Fred Drake | 99cd573 | 1999-02-12 20:40:09 +0000 | [diff] [blame] | 229 | exception are assigned to three variables in the |
| 230 | \module{sys}\refbimodindex{sys} module: \code{sys.exc_type} receives |
| 231 | the object identifying the exception; \code{sys.exc_value} receives |
| 232 | the exception's parameter; \code{sys.exc_traceback} receives a |
| 233 | traceback object\obindex{traceback} (see section \ref{traceback}) |
| 234 | identifying the point in the program where the exception occurred. |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 235 | These details are also available through the \function{sys.exc_info()} |
Fred Drake | 99cd573 | 1999-02-12 20:40:09 +0000 | [diff] [blame] | 236 | function, which returns a tuple \code{(\var{exc_type}, \var{exc_value}, |
| 237 | \var{exc_traceback})}. Use of the corresponding variables is |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 238 | deprecated in favor of this function, since their use is unsafe in a |
| 239 | threaded program. As of Python 1.5, the variables are restored to |
| 240 | their previous values (before the call) when returning from a function |
| 241 | that handled an exception. |
Fred Drake | 99cd573 | 1999-02-12 20:40:09 +0000 | [diff] [blame] | 242 | \withsubitem{(in module sys)}{\ttindex{exc_type} |
| 243 | \ttindex{exc_value}\ttindex{exc_traceback}} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 244 | |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 245 | The optional \keyword{else} clause is executed when no exception occurs |
| 246 | in the \keyword{try} clause. Exceptions in the \keyword{else} clause are |
| 247 | not handled by the preceding \keyword{except} clauses. |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 248 | \kwindex{else} |
| 249 | |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 250 | The \keyword{try}...\keyword{finally} form specifies a `cleanup' handler. The |
| 251 | \keyword{try} clause is executed. When no exception occurs, the |
| 252 | \keyword{finally} clause is executed. When an exception occurs in the |
| 253 | \keyword{try} clause, the exception is temporarily saved, the |
| 254 | \keyword{finally} clause is executed, and then the saved exception is |
| 255 | re-raised. If the \keyword{finally} clause raises another exception or |
| 256 | executes a \keyword{return}, \keyword{break} or \keyword{continue} statement, |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 257 | the saved exception is lost. The exception information is not |
| 258 | available to the program during execution of the \keyword{finally} |
| 259 | clause. |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 260 | \kwindex{finally} |
| 261 | |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 262 | When a \keyword{return} or \keyword{break} statement is executed in the |
| 263 | \keyword{try} suite of a \keyword{try}...\keyword{finally} statement, the |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 264 | \keyword{finally} clause is also executed `on the way out.' A |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 265 | \keyword{continue} statement is illegal in the \keyword{try} clause. (The |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 266 | reason is a problem with the current implementation --- this |
| 267 | restriction may be lifted in the future). |
| 268 | \stindex{return} |
| 269 | \stindex{break} |
| 270 | \stindex{continue} |
| 271 | |
Fred Drake | 61c7728 | 1998-07-28 19:34:22 +0000 | [diff] [blame] | 272 | \section{Function definitions\label{function}} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 273 | \indexii{function}{definition} |
| 274 | |
| 275 | A function definition defines a user-defined function object (see |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 276 | section \ref{types}): |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 277 | \obindex{user-defined function} |
| 278 | \obindex{function} |
| 279 | |
| 280 | \begin{verbatim} |
| 281 | funcdef: "def" funcname "(" [parameter_list] ")" ":" suite |
| 282 | parameter_list: (defparameter ",")* ("*" identifier [, "**" identifier] |
| 283 | | "**" identifier |
| 284 | | defparameter [","]) |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 285 | defparameter: parameter ["=" expression] |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 286 | sublist: parameter ("," parameter)* [","] |
| 287 | parameter: identifier | "(" sublist ")" |
| 288 | funcname: identifier |
| 289 | \end{verbatim} |
| 290 | |
| 291 | A function definition is an executable statement. Its execution binds |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 292 | the function name in the current local namespace to a function object |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 293 | (a wrapper around the executable code for the function). This |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 294 | function object contains a reference to the current global namespace |
| 295 | as the global namespace to be used when the function is called. |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 296 | \indexii{function}{name} |
| 297 | \indexii{name}{binding} |
| 298 | |
| 299 | The function definition does not execute the function body; this gets |
| 300 | executed only when the function is called. |
| 301 | |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 302 | When one or more top-level parameters have the form \var{parameter} |
| 303 | \code{=} \var{expression}, the function is said to have ``default |
Guido van Rossum | e039439 | 1998-12-04 19:37:10 +0000 | [diff] [blame] | 304 | parameter values.'' For a parameter with a |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 305 | default value, the corresponding argument may be omitted from a call, |
| 306 | in which case the parameter's default value is substituted. If a |
| 307 | parameter has a default value, all following parameters must also have |
| 308 | a default value --- this is a syntactic restriction that is not |
Fred Drake | e15956b | 2000-04-03 04:51:13 +0000 | [diff] [blame] | 309 | expressed by the grammar. |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 310 | \indexiii{default}{parameter}{value} |
| 311 | |
Guido van Rossum | e039439 | 1998-12-04 19:37:10 +0000 | [diff] [blame] | 312 | \strong{Default parameter values are evaluated when the function |
| 313 | definition is executed.} This means that the expression is evaluated |
| 314 | once, when the function is defined, and that that same |
| 315 | ``pre-computed'' value is used for each call. This is especially |
| 316 | important to understand when a default parameter is a mutable object, |
| 317 | such as a list or a dictionary: if the function modifies the object |
| 318 | (e.g. by appending an item to a list), the default value is in effect |
| 319 | modified. This is generally not what was intended. A way around this |
| 320 | is to use \code{None} as the default, and explicitly test for it in |
| 321 | the body of the function, e.g.: |
| 322 | |
| 323 | \begin{verbatim} |
| 324 | def whats_on_the_telly(penguin=None): |
| 325 | if penguin is None: |
| 326 | penguin = [] |
| 327 | penguin.append("property of the zoo") |
| 328 | return penguin |
| 329 | \end{verbatim} |
| 330 | |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 331 | Function call semantics are described in more detail in section |
| 332 | \ref{calls}. |
| 333 | A function call always assigns values to all parameters mentioned in |
| 334 | the parameter list, either from position arguments, from keyword |
| 335 | arguments, or from default values. If the form ``\code{*identifier}'' |
| 336 | is present, it is initialized to a tuple receiving any excess |
| 337 | positional parameters, defaulting to the empty tuple. If the form |
| 338 | ``\code{**identifier}'' is present, it is initialized to a new |
| 339 | dictionary receiving any excess keyword arguments, defaulting to a |
| 340 | new empty dictionary. |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 341 | |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 342 | |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 343 | |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 344 | |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 345 | |
| 346 | It is also possible to create anonymous functions (functions not bound |
| 347 | to a name), for immediate use in expressions. This uses lambda forms, |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 348 | described in section \ref{lambda}. Note that the lambda form is |
| 349 | merely a shorthand for a simplified function definition; a function |
| 350 | defined in a ``\keyword{def}'' statement can be passed around or |
| 351 | assigned to another name just like a function defined by a lambda |
| 352 | form. The ``\keyword{def}'' form is actually more powerful since it |
| 353 | allows the execution of multiple statements. |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 354 | \indexii{lambda}{form} |
| 355 | |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 356 | \strong{Programmer's note:} a ``\code{def}'' form executed inside a |
| 357 | function definition defines a local function that can be returned or |
| 358 | passed around. Because of Python's two-scope philosophy, a local |
| 359 | function defined in this way does not have access to the local |
| 360 | variables of the function that contains its definition; the same rule |
| 361 | applies to functions defined by a lambda form. A standard trick to |
| 362 | pass selected local variables into a locally defined function is to |
| 363 | use default argument values, like this: |
| 364 | |
| 365 | \begin{verbatim} |
| 366 | # Return a function that returns its argument incremented by 'n' |
| 367 | def make_incrementer(n): |
| 368 | def increment(x, n=n): |
| 369 | return x+n |
| 370 | return increment |
| 371 | |
| 372 | add1 = make_incrementer(1) |
| 373 | print add1(3) # This prints '4' |
| 374 | \end{verbatim} |
| 375 | |
Fred Drake | 61c7728 | 1998-07-28 19:34:22 +0000 | [diff] [blame] | 376 | \section{Class definitions\label{class}} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 377 | \indexii{class}{definition} |
| 378 | |
| 379 | A class definition defines a class object (see section \ref{types}): |
| 380 | \obindex{class} |
| 381 | |
| 382 | \begin{verbatim} |
| 383 | classdef: "class" classname [inheritance] ":" suite |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 384 | inheritance: "(" [expression_list] ")" |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 385 | classname: identifier |
| 386 | \end{verbatim} |
| 387 | |
| 388 | A class definition is an executable statement. It first evaluates the |
| 389 | inheritance list, if present. Each item in the inheritance list |
| 390 | should evaluate to a class object. The class's suite is then executed |
| 391 | in a new execution frame (see section \ref{execframes}), using a newly |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 392 | created local namespace and the original global namespace. |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 393 | (Usually, the suite contains only function definitions.) When the |
| 394 | class's suite finishes execution, its execution frame is discarded but |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 395 | its local namespace is saved. A class object is then created using |
| 396 | the inheritance list for the base classes and the saved local |
| 397 | namespace for the attribute dictionary. The class name is bound to this |
| 398 | class object in the original local namespace. |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 399 | \index{inheritance} |
| 400 | \indexii{class}{name} |
| 401 | \indexii{name}{binding} |
| 402 | \indexii{execution}{frame} |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 403 | |
| 404 | \strong{Programmer's note:} variables defined in the class definition |
| 405 | are class variables; they are shared by all instances. To define |
| 406 | instance variables, they must be given a value in the the |
| 407 | \method{__init__()} method or in another method. Both class and |
| 408 | instance variables are accessible through the notation |
| 409 | ```code{self.name}'', and an instance variable hides a class variable |
| 410 | with the same name when accessed in this way. Class variables with |
| 411 | immutable values can be used as defaults for instance variables. |