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