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} |
Fred Drake | 5381588 | 2002-03-15 23:21:37 +0000 | [diff] [blame] | 45 | {\token{if_stmt}} |
| 46 | \productioncont{| \token{while_stmt}} |
| 47 | \productioncont{| \token{for_stmt}} |
| 48 | \productioncont{| \token{try_stmt}} |
Phillip J. Eby | 075ef1a | 2006-03-27 21:06:13 +0000 | [diff] [blame^] | 49 | \productioncont{| \token{with_stmt}} |
Fred Drake | 5381588 | 2002-03-15 23:21:37 +0000 | [diff] [blame] | 50 | \productioncont{| \token{funcdef}} |
| 51 | \productioncont{| \token{classdef}} |
Fred Drake | cb4638a | 2001-07-06 22:49:53 +0000 | [diff] [blame] | 52 | \production{suite} |
| 53 | {\token{stmt_list} NEWLINE |
| 54 | | NEWLINE INDENT \token{statement}+ DEDENT} |
| 55 | \production{statement} |
| 56 | {\token{stmt_list} NEWLINE | \token{compound_stmt}} |
| 57 | \production{stmt_list} |
| 58 | {\token{simple_stmt} (";" \token{simple_stmt})* [";"]} |
| 59 | \end{productionlist} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 60 | |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 61 | Note that statements always end in a |
| 62 | \code{NEWLINE}\index{NEWLINE token} possibly followed by a |
| 63 | \code{DEDENT}.\index{DEDENT token} Also note that optional |
| 64 | continuation clauses always begin with a keyword that cannot start a |
| 65 | statement, thus there are no ambiguities (the `dangling |
| 66 | \keyword{else}' problem is solved in Python by requiring nested |
| 67 | \keyword{if} statements to be indented). |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 68 | \indexii{dangling}{else} |
| 69 | |
| 70 | The formatting of the grammar rules in the following sections places |
| 71 | each clause on a separate line for clarity. |
| 72 | |
Fred Drake | 2829f1c | 2001-06-23 05:27:20 +0000 | [diff] [blame] | 73 | |
Fred Drake | 61c7728 | 1998-07-28 19:34:22 +0000 | [diff] [blame] | 74 | \section{The \keyword{if} statement\label{if}} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 75 | \stindex{if} |
| 76 | |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 77 | The \keyword{if} statement is used for conditional execution: |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 78 | |
Fred Drake | cb4638a | 2001-07-06 22:49:53 +0000 | [diff] [blame] | 79 | \begin{productionlist} |
| 80 | \production{if_stmt} |
Fred Drake | 5381588 | 2002-03-15 23:21:37 +0000 | [diff] [blame] | 81 | {"if" \token{expression} ":" \token{suite}} |
| 82 | \productioncont{( "elif" \token{expression} ":" \token{suite} )*} |
| 83 | \productioncont{["else" ":" \token{suite}]} |
Fred Drake | cb4638a | 2001-07-06 22:49:53 +0000 | [diff] [blame] | 84 | \end{productionlist} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 85 | |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 86 | It selects exactly one of the suites by evaluating the expressions one |
Fred Drake | 78eb200 | 2002-10-18 15:20:32 +0000 | [diff] [blame] | 87 | by one until one is found to be true (see section~\ref{Booleans} for |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 88 | 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] | 89 | 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] | 90 | all expressions are false, the suite of the \keyword{else} clause, if |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 91 | present, is executed. |
| 92 | \kwindex{elif} |
| 93 | \kwindex{else} |
| 94 | |
Fred Drake | 2829f1c | 2001-06-23 05:27:20 +0000 | [diff] [blame] | 95 | |
Fred Drake | 61c7728 | 1998-07-28 19:34:22 +0000 | [diff] [blame] | 96 | \section{The \keyword{while} statement\label{while}} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 97 | \stindex{while} |
| 98 | \indexii{loop}{statement} |
| 99 | |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 100 | The \keyword{while} statement is used for repeated execution as long |
| 101 | as an expression is true: |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 102 | |
Fred Drake | cb4638a | 2001-07-06 22:49:53 +0000 | [diff] [blame] | 103 | \begin{productionlist} |
| 104 | \production{while_stmt} |
Fred Drake | 5381588 | 2002-03-15 23:21:37 +0000 | [diff] [blame] | 105 | {"while" \token{expression} ":" \token{suite}} |
| 106 | \productioncont{["else" ":" \token{suite}]} |
Fred Drake | cb4638a | 2001-07-06 22:49:53 +0000 | [diff] [blame] | 107 | \end{productionlist} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 108 | |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 109 | This repeatedly tests the expression and, if it is true, executes the |
| 110 | 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] | 111 | is tested) the suite of the \keyword{else} clause, if present, is |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 112 | executed and the loop terminates. |
| 113 | \kwindex{else} |
| 114 | |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 115 | A \keyword{break} statement executed in the first suite terminates the |
| 116 | loop without executing the \keyword{else} clause's suite. A |
| 117 | \keyword{continue} statement executed in the first suite skips the rest |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 118 | of the suite and goes back to testing the expression. |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 119 | \stindex{break} |
| 120 | \stindex{continue} |
| 121 | |
Fred Drake | 2829f1c | 2001-06-23 05:27:20 +0000 | [diff] [blame] | 122 | |
Fred Drake | 61c7728 | 1998-07-28 19:34:22 +0000 | [diff] [blame] | 123 | \section{The \keyword{for} statement\label{for}} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 124 | \stindex{for} |
| 125 | \indexii{loop}{statement} |
| 126 | |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 127 | 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] | 128 | sequence (such as a string, tuple or list) or other iterable object: |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 129 | \obindex{sequence} |
| 130 | |
Fred Drake | cb4638a | 2001-07-06 22:49:53 +0000 | [diff] [blame] | 131 | \begin{productionlist} |
| 132 | \production{for_stmt} |
| 133 | {"for" \token{target_list} "in" \token{expression_list} |
Fred Drake | 5381588 | 2002-03-15 23:21:37 +0000 | [diff] [blame] | 134 | ":" \token{suite}} |
| 135 | \productioncont{["else" ":" \token{suite}]} |
Fred Drake | cb4638a | 2001-07-06 22:49:53 +0000 | [diff] [blame] | 136 | \end{productionlist} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 137 | |
Fred Drake | 7fabaf8 | 2004-11-02 19:18:20 +0000 | [diff] [blame] | 138 | The expression list is evaluated once; it should yield an iterable |
| 139 | object. An iterator is created for the result of the |
| 140 | {}\code{expression_list}. The suite is then executed once for each |
| 141 | item provided by the iterator, in the |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 142 | order of ascending indices. Each item in turn is assigned to the |
| 143 | target list using the standard rules for assignments, and then the |
| 144 | suite is executed. When the items are exhausted (which is immediately |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 145 | 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] | 146 | present, is executed, and the loop terminates. |
| 147 | \kwindex{in} |
| 148 | \kwindex{else} |
| 149 | \indexii{target}{list} |
| 150 | |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 151 | A \keyword{break} statement executed in the first suite terminates the |
| 152 | loop without executing the \keyword{else} clause's suite. A |
| 153 | \keyword{continue} statement executed in the first suite skips the rest |
| 154 | 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] | 155 | clause if there was no next item. |
| 156 | \stindex{break} |
| 157 | \stindex{continue} |
| 158 | |
| 159 | The suite may assign to the variable(s) in the target list; this does |
| 160 | not affect the next item assigned to it. |
| 161 | |
| 162 | The target list is not deleted when the loop is finished, but if the |
| 163 | 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] | 164 | loop. Hint: the built-in function \function{range()} returns a |
| 165 | sequence of integers suitable to emulate the effect of Pascal's |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 166 | \code{for i := a to b do}; |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 167 | e.g., \code{range(3)} returns the list \code{[0, 1, 2]}. |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 168 | \bifuncindex{range} |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 169 | \indexii{Pascal}{language} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 170 | |
Fred Drake | 0aa811c | 2001-10-20 04:24:09 +0000 | [diff] [blame] | 171 | \warning{There is a subtlety when the sequence is being modified |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 172 | by the loop (this can only occur for mutable sequences, i.e. lists). |
| 173 | An internal counter is used to keep track of which item is used next, |
| 174 | and this is incremented on each iteration. When this counter has |
| 175 | reached the length of the sequence the loop terminates. This means that |
| 176 | if the suite deletes the current (or a previous) item from the |
| 177 | sequence, the next item will be skipped (since it gets the index of |
| 178 | the current item which has already been treated). Likewise, if the |
| 179 | suite inserts an item in the sequence before the current item, the |
| 180 | current item will be treated again the next time through the loop. |
| 181 | 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] | 182 | copy using a slice of the whole sequence, e.g., |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 183 | \index{loop!over mutable sequence} |
Fred Drake | 0aa811c | 2001-10-20 04:24:09 +0000 | [diff] [blame] | 184 | \index{mutable sequence!loop over}} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 185 | |
| 186 | \begin{verbatim} |
| 187 | for x in a[:]: |
| 188 | if x < 0: a.remove(x) |
| 189 | \end{verbatim} |
| 190 | |
Fred Drake | 2829f1c | 2001-06-23 05:27:20 +0000 | [diff] [blame] | 191 | |
Fred Drake | 61c7728 | 1998-07-28 19:34:22 +0000 | [diff] [blame] | 192 | \section{The \keyword{try} statement\label{try}} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 193 | \stindex{try} |
| 194 | |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 195 | The \keyword{try} statement specifies exception handlers and/or cleanup |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 196 | code for a group of statements: |
| 197 | |
Fred Drake | cb4638a | 2001-07-06 22:49:53 +0000 | [diff] [blame] | 198 | \begin{productionlist} |
Neal Norwitz | 11ca77e | 2005-12-17 22:24:12 +0000 | [diff] [blame] | 199 | \production{try_stmt} {try1_stmt | try2_stmt} |
| 200 | \production{try1_stmt} |
Fred Drake | 5381588 | 2002-03-15 23:21:37 +0000 | [diff] [blame] | 201 | {"try" ":" \token{suite}} |
| 202 | \productioncont{("except" [\token{expression} |
| 203 | ["," \token{target}]] ":" \token{suite})+} |
| 204 | \productioncont{["else" ":" \token{suite}]} |
Neal Norwitz | 11ca77e | 2005-12-17 22:24:12 +0000 | [diff] [blame] | 205 | \productioncont{["finally" ":" \token{suite}]} |
| 206 | \production{try2_stmt} |
| 207 | {"try" ":" \token{suite}} |
| 208 | \productioncont{"finally" ":" \token{suite}} |
Fred Drake | cb4638a | 2001-07-06 22:49:53 +0000 | [diff] [blame] | 209 | \end{productionlist} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 210 | |
Neal Norwitz | 11ca77e | 2005-12-17 22:24:12 +0000 | [diff] [blame] | 211 | \versionchanged[In previous versions of Python, |
| 212 | \keyword{try}...\keyword{except}...\keyword{finally} did not work. |
| 213 | \keyword{try}...\keyword{except} had to be nested in |
| 214 | \keyword{try}...\keyword{finally}]{2.5} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 215 | |
Neal Norwitz | 11ca77e | 2005-12-17 22:24:12 +0000 | [diff] [blame] | 216 | The \keyword{except} clause(s) specify one or more exception handlers. |
| 217 | When no exception occurs in the |
Fred Drake | 5c07d9b | 1998-05-14 19:37:06 +0000 | [diff] [blame] | 218 | \keyword{try} clause, no exception handler is executed. When an |
| 219 | 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] | 220 | handler is started. This search inspects the except clauses in turn until |
| 221 | one is found that matches the exception. An expression-less except |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 222 | 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] | 223 | except clause with an expression, that expression is evaluated, and the |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 224 | clause matches the exception if the resulting object is ``compatible'' |
| 225 | with the exception. An object is compatible with an exception if it |
Michael W. Hudson | a2a9888 | 2005-03-04 14:33:32 +0000 | [diff] [blame] | 226 | is the class or a base class of the exception object, a tuple |
| 227 | containing an item compatible with the exception, or, in the |
| 228 | (deprecated) case of string exceptions, is the raised string itself |
| 229 | (note that the object identities must match, i.e. it must be the same |
| 230 | string object, not just a string with the same value). |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 231 | \kwindex{except} |
| 232 | |
| 233 | If no except clause matches the exception, the search for an exception |
| 234 | handler continues in the surrounding code and on the invocation stack. |
Neal Norwitz | 11ca77e | 2005-12-17 22:24:12 +0000 | [diff] [blame] | 235 | \footnote{The exception is propogated to the invocation stack only if |
| 236 | there is no \keyword{finally} clause that negates the exception.} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 237 | |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 238 | 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] | 239 | raises an exception, the original search for a handler is canceled |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 240 | 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] | 241 | 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] | 242 | raised the exception). |
| 243 | |
Michael W. Hudson | a2a9888 | 2005-03-04 14:33:32 +0000 | [diff] [blame] | 244 | When a matching except clause is found, the exception is assigned to |
| 245 | the target specified in that except clause, if present, and the except |
| 246 | clause's suite is executed. All except clauses must have an |
| 247 | executable block. When the end of this block is reached, execution |
| 248 | continues normally after the entire try statement. (This means that |
| 249 | if two nested handlers exist for the same exception, and the exception |
| 250 | occurs in the try clause of the inner handler, the outer handler will |
| 251 | not handle the exception.) |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 252 | |
| 253 | Before an except clause's suite is executed, details about the |
Fred Drake | 99cd573 | 1999-02-12 20:40:09 +0000 | [diff] [blame] | 254 | exception are assigned to three variables in the |
| 255 | \module{sys}\refbimodindex{sys} module: \code{sys.exc_type} receives |
| 256 | the object identifying the exception; \code{sys.exc_value} receives |
| 257 | the exception's parameter; \code{sys.exc_traceback} receives a |
Fred Drake | 78eb200 | 2002-10-18 15:20:32 +0000 | [diff] [blame] | 258 | traceback object\obindex{traceback} (see section~\ref{traceback}) |
Fred Drake | 99cd573 | 1999-02-12 20:40:09 +0000 | [diff] [blame] | 259 | identifying the point in the program where the exception occurred. |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 260 | These details are also available through the \function{sys.exc_info()} |
Fred Drake | 99cd573 | 1999-02-12 20:40:09 +0000 | [diff] [blame] | 261 | function, which returns a tuple \code{(\var{exc_type}, \var{exc_value}, |
| 262 | \var{exc_traceback})}. Use of the corresponding variables is |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 263 | deprecated in favor of this function, since their use is unsafe in a |
| 264 | threaded program. As of Python 1.5, the variables are restored to |
| 265 | their previous values (before the call) when returning from a function |
| 266 | that handled an exception. |
Fred Drake | 99cd573 | 1999-02-12 20:40:09 +0000 | [diff] [blame] | 267 | \withsubitem{(in module sys)}{\ttindex{exc_type} |
| 268 | \ttindex{exc_value}\ttindex{exc_traceback}} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 269 | |
Fred Drake | 2cba0f6 | 2001-01-02 19:22:48 +0000 | [diff] [blame] | 270 | The optional \keyword{else} clause is executed if and when control |
| 271 | flows off the end of the \keyword{try} clause.\footnote{ |
| 272 | Currently, control ``flows off the end'' except in the case of an |
| 273 | exception or the execution of a \keyword{return}, |
| 274 | \keyword{continue}, or \keyword{break} statement. |
| 275 | } Exceptions in the \keyword{else} clause are not handled by the |
| 276 | preceding \keyword{except} clauses. |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 277 | \kwindex{else} |
Fred Drake | 2cba0f6 | 2001-01-02 19:22:48 +0000 | [diff] [blame] | 278 | \stindex{return} |
| 279 | \stindex{break} |
| 280 | \stindex{continue} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 281 | |
Neal Norwitz | 11ca77e | 2005-12-17 22:24:12 +0000 | [diff] [blame] | 282 | If \keyword{finally} is present, it specifies a `cleanup' handler. The |
| 283 | \keyword{try} clause is executed, including any \keyword{except} and |
| 284 | \keyword{else} clauses. If an exception occurs in any of the clauses |
| 285 | and is not handled, the exception is temporarily saved. The |
| 286 | \keyword{finally} clause is executed. If there is a saved exception, |
| 287 | it is re-raised at the end of the \keyword{finally} clause. |
| 288 | If the \keyword{finally} clause raises another exception or |
Jeremy Hylton | 3faa52e | 2001-02-01 22:48:12 +0000 | [diff] [blame] | 289 | executes a \keyword{return} or \keyword{break} statement, the saved |
| 290 | exception is lost. A \keyword{continue} statement is illegal in the |
| 291 | \keyword{finally} clause. (The reason is a problem with the current |
Fred Drake | 216cbca | 2002-02-22 15:40:23 +0000 | [diff] [blame] | 292 | implementation -- this restriction may be lifted in the future). The |
Jeremy Hylton | 3faa52e | 2001-02-01 22:48:12 +0000 | [diff] [blame] | 293 | exception information is not available to the program during execution of |
| 294 | the \keyword{finally} clause. |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 295 | \kwindex{finally} |
| 296 | |
Jeremy Hylton | 3faa52e | 2001-02-01 22:48:12 +0000 | [diff] [blame] | 297 | When a \keyword{return}, \keyword{break} or \keyword{continue} statement is |
| 298 | executed in the \keyword{try} suite of a \keyword{try}...\keyword{finally} |
| 299 | statement, the \keyword{finally} clause is also executed `on the way out.' A |
| 300 | \keyword{continue} statement is illegal in the \keyword{finally} clause. |
| 301 | (The reason is a problem with the current implementation --- this |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 302 | restriction may be lifted in the future). |
| 303 | \stindex{return} |
| 304 | \stindex{break} |
| 305 | \stindex{continue} |
| 306 | |
Fred Drake | 78eb200 | 2002-10-18 15:20:32 +0000 | [diff] [blame] | 307 | Additional information on exceptions can be found in |
| 308 | section~\ref{exceptions}, and information on using the \keyword{raise} |
| 309 | statement to generate exceptions may be found in section~\ref{raise}. |
| 310 | |
Fred Drake | 2829f1c | 2001-06-23 05:27:20 +0000 | [diff] [blame] | 311 | |
Guido van Rossum | c2e2074 | 2006-02-27 22:32:47 +0000 | [diff] [blame] | 312 | \section{The \keyword{with} statement\label{with}} |
| 313 | \stindex{with} |
| 314 | |
Phillip J. Eby | 075ef1a | 2006-03-27 21:06:13 +0000 | [diff] [blame^] | 315 | The \keyword{with} statement is used to wrap the execution of a block |
| 316 | with methods defined by a context manager (see |
| 317 | section~\ref{context-managers}). This allows common |
| 318 | \keyword{try}...\keyword{except}...\keyword{finally} usage patterns to |
| 319 | be encapsulated as context managers for convenient reuse. |
Guido van Rossum | c2e2074 | 2006-02-27 22:32:47 +0000 | [diff] [blame] | 320 | |
Phillip J. Eby | 075ef1a | 2006-03-27 21:06:13 +0000 | [diff] [blame^] | 321 | \begin{productionlist} |
| 322 | \production{with_stmt} |
| 323 | {"with" \token{expression} ["as" target_list] ":" \token{suite}} |
| 324 | \end{productionlist} |
| 325 | |
| 326 | The execution of the \keyword{with} statement proceeds as follows: |
| 327 | |
| 328 | \begin{enumerate} |
| 329 | |
| 330 | \item The expression is evaluated, to obtain a context manager |
| 331 | object. |
| 332 | |
| 333 | \item The context manager's \method{__context__()} method is invoked to |
| 334 | obtain a context object. |
| 335 | |
| 336 | \item The context object's \method{__enter__()} method is invoked. |
| 337 | |
| 338 | \item If a target list was included in the \keyword{with} |
| 339 | statement, the return value from \method{__enter__()} is assigned to it. |
| 340 | |
| 341 | \note{The \keyword{with} statement guarantees that if the |
| 342 | \method{__enter__()} method returns without an error, then |
| 343 | \method{__exit__()} will always be called. Thus, if an error occurs |
| 344 | during the assignment to the target list, it will be treated the same as |
| 345 | an error occurring within the suite would be. See step 6 below.} |
| 346 | |
| 347 | \item The suite is executed. |
| 348 | |
| 349 | \item The context object's \method{__exit__()} method is invoked. If an |
| 350 | exception caused the suite to be exited, its type, value, and |
| 351 | traceback are passed as arguments to \method{__exit__()}. Otherwise, |
| 352 | three \constant{None} arguments are supplied. |
| 353 | |
| 354 | If the suite was exited due to an exception, and the return |
| 355 | value from the \method{__exit__()} method was false, the exception is |
| 356 | reraised. If the return value was true, the exception is suppressed, and |
| 357 | execution continues with the statement following the \keyword{with} |
| 358 | statement. |
| 359 | |
| 360 | If the suite was exited for any reason other than an exception, the |
| 361 | return value from \method{__exit__()} is ignored, and execution proceeds |
| 362 | at the normal location for the kind of exit that was taken. |
| 363 | |
| 364 | \end{enumerate} |
| 365 | |
| 366 | \begin{seealso} |
| 367 | \seepep{0343}{The "with" statement} |
| 368 | {The specification, background, and examples for the |
| 369 | Python \keyword{with} statement.} |
| 370 | \end{seealso} |
Guido van Rossum | c2e2074 | 2006-02-27 22:32:47 +0000 | [diff] [blame] | 371 | |
Fred Drake | 61c7728 | 1998-07-28 19:34:22 +0000 | [diff] [blame] | 372 | \section{Function definitions\label{function}} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 373 | \indexii{function}{definition} |
Fred Drake | 687bde9 | 2001-12-27 18:38:10 +0000 | [diff] [blame] | 374 | \stindex{def} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 375 | |
| 376 | A function definition defines a user-defined function object (see |
Fred Drake | 78eb200 | 2002-10-18 15:20:32 +0000 | [diff] [blame] | 377 | section~\ref{types}): |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 378 | \obindex{user-defined function} |
| 379 | \obindex{function} |
| 380 | |
Fred Drake | cb4638a | 2001-07-06 22:49:53 +0000 | [diff] [blame] | 381 | \begin{productionlist} |
| 382 | \production{funcdef} |
Anthony Baxter | c2a5a63 | 2004-08-02 06:10:11 +0000 | [diff] [blame] | 383 | {[\token{decorators}] "def" \token{funcname} "(" [\token{parameter_list}] ")" |
Fred Drake | cb4638a | 2001-07-06 22:49:53 +0000 | [diff] [blame] | 384 | ":" \token{suite}} |
Anthony Baxter | c2a5a63 | 2004-08-02 06:10:11 +0000 | [diff] [blame] | 385 | \production{decorators} |
Michael W. Hudson | 0ccff07 | 2004-08-17 17:29:16 +0000 | [diff] [blame] | 386 | {\token{decorator}+} |
Anthony Baxter | c2a5a63 | 2004-08-02 06:10:11 +0000 | [diff] [blame] | 387 | \production{decorator} |
Michael W. Hudson | 0ccff07 | 2004-08-17 17:29:16 +0000 | [diff] [blame] | 388 | {"@" \token{dotted_name} ["(" [\token{argument_list} [","]] ")"] NEWLINE} |
Michael W. Hudson | 2f475a7 | 2005-05-26 07:58:22 +0000 | [diff] [blame] | 389 | \production{dotted_name} |
| 390 | {\token{identifier} ("." \token{identifier})*} |
Fred Drake | cb4638a | 2001-07-06 22:49:53 +0000 | [diff] [blame] | 391 | \production{parameter_list} |
Fred Drake | 9a40851 | 2004-11-02 18:57:33 +0000 | [diff] [blame] | 392 | {(\token{defparameter} ",")*} |
| 393 | \productioncont{(~~"*" \token{identifier} [, "**" \token{identifier}]} |
| 394 | \productioncont{ | "**" \token{identifier}} |
| 395 | \productioncont{ | \token{defparameter} [","] )} |
Fred Drake | cb4638a | 2001-07-06 22:49:53 +0000 | [diff] [blame] | 396 | \production{defparameter} |
| 397 | {\token{parameter} ["=" \token{expression}]} |
| 398 | \production{sublist} |
| 399 | {\token{parameter} ("," \token{parameter})* [","]} |
| 400 | \production{parameter} |
| 401 | {\token{identifier} | "(" \token{sublist} ")"} |
| 402 | \production{funcname} |
| 403 | {\token{identifier}} |
| 404 | \end{productionlist} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 405 | |
| 406 | A function definition is an executable statement. Its execution binds |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 407 | the function name in the current local namespace to a function object |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 408 | (a wrapper around the executable code for the function). This |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 409 | function object contains a reference to the current global namespace |
| 410 | as the global namespace to be used when the function is called. |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 411 | \indexii{function}{name} |
| 412 | \indexii{name}{binding} |
| 413 | |
| 414 | The function definition does not execute the function body; this gets |
| 415 | executed only when the function is called. |
| 416 | |
Anthony Baxter | c2a5a63 | 2004-08-02 06:10:11 +0000 | [diff] [blame] | 417 | A function definition may be wrapped by one or more decorator expressions. |
| 418 | Decorator expressions are evaluated when the function is defined, in the scope |
| 419 | that contains the function definition. The result must be a callable, |
| 420 | which is invoked with the function object as the only argument. |
| 421 | The returned value is bound to the function name instead of the function |
Michael W. Hudson | 0ccff07 | 2004-08-17 17:29:16 +0000 | [diff] [blame] | 422 | object. Multiple decorators are applied in nested fashion. |
| 423 | For example, the following code: |
Anthony Baxter | c2a5a63 | 2004-08-02 06:10:11 +0000 | [diff] [blame] | 424 | |
| 425 | \begin{verbatim} |
Michael W. Hudson | 0ccff07 | 2004-08-17 17:29:16 +0000 | [diff] [blame] | 426 | @f1(arg) |
Anthony Baxter | c2a5a63 | 2004-08-02 06:10:11 +0000 | [diff] [blame] | 427 | @f2 |
| 428 | def func(): pass |
| 429 | \end{verbatim} |
| 430 | |
| 431 | is equivalent to: |
| 432 | |
| 433 | \begin{verbatim} |
| 434 | def func(): pass |
Michael W. Hudson | 0ccff07 | 2004-08-17 17:29:16 +0000 | [diff] [blame] | 435 | func = f1(arg)(f2(func)) |
Anthony Baxter | c2a5a63 | 2004-08-02 06:10:11 +0000 | [diff] [blame] | 436 | \end{verbatim} |
| 437 | |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 438 | When one or more top-level parameters have the form \var{parameter} |
| 439 | \code{=} \var{expression}, the function is said to have ``default |
Guido van Rossum | e039439 | 1998-12-04 19:37:10 +0000 | [diff] [blame] | 440 | parameter values.'' For a parameter with a |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 441 | default value, the corresponding argument may be omitted from a call, |
| 442 | in which case the parameter's default value is substituted. If a |
| 443 | parameter has a default value, all following parameters must also have |
| 444 | a default value --- this is a syntactic restriction that is not |
Fred Drake | e15956b | 2000-04-03 04:51:13 +0000 | [diff] [blame] | 445 | expressed by the grammar. |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 446 | \indexiii{default}{parameter}{value} |
| 447 | |
Guido van Rossum | e039439 | 1998-12-04 19:37:10 +0000 | [diff] [blame] | 448 | \strong{Default parameter values are evaluated when the function |
| 449 | definition is executed.} This means that the expression is evaluated |
| 450 | once, when the function is defined, and that that same |
| 451 | ``pre-computed'' value is used for each call. This is especially |
| 452 | important to understand when a default parameter is a mutable object, |
| 453 | such as a list or a dictionary: if the function modifies the object |
| 454 | (e.g. by appending an item to a list), the default value is in effect |
| 455 | modified. This is generally not what was intended. A way around this |
| 456 | is to use \code{None} as the default, and explicitly test for it in |
| 457 | the body of the function, e.g.: |
| 458 | |
| 459 | \begin{verbatim} |
| 460 | def whats_on_the_telly(penguin=None): |
| 461 | if penguin is None: |
| 462 | penguin = [] |
| 463 | penguin.append("property of the zoo") |
| 464 | return penguin |
| 465 | \end{verbatim} |
| 466 | |
Fred Drake | 78eb200 | 2002-10-18 15:20:32 +0000 | [diff] [blame] | 467 | Function call semantics are described in more detail in |
| 468 | section~\ref{calls}. |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 469 | A function call always assigns values to all parameters mentioned in |
| 470 | the parameter list, either from position arguments, from keyword |
| 471 | arguments, or from default values. If the form ``\code{*identifier}'' |
| 472 | is present, it is initialized to a tuple receiving any excess |
| 473 | positional parameters, defaulting to the empty tuple. If the form |
| 474 | ``\code{**identifier}'' is present, it is initialized to a new |
| 475 | dictionary receiving any excess keyword arguments, defaulting to a |
| 476 | new empty dictionary. |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 477 | |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 478 | It is also possible to create anonymous functions (functions not bound |
| 479 | to a name), for immediate use in expressions. This uses lambda forms, |
Fred Drake | 78eb200 | 2002-10-18 15:20:32 +0000 | [diff] [blame] | 480 | described in section~\ref{lambda}. Note that the lambda form is |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 481 | merely a shorthand for a simplified function definition; a function |
| 482 | defined in a ``\keyword{def}'' statement can be passed around or |
| 483 | assigned to another name just like a function defined by a lambda |
| 484 | form. The ``\keyword{def}'' form is actually more powerful since it |
| 485 | allows the execution of multiple statements. |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 486 | \indexii{lambda}{form} |
| 487 | |
Jeremy Hylton | 1824b59 | 2002-04-01 21:30:15 +0000 | [diff] [blame] | 488 | \strong{Programmer's note:} Functions are first-class objects. A |
| 489 | ``\code{def}'' form executed inside a function definition defines a |
| 490 | local function that can be returned or passed around. Free variables |
| 491 | used in the nested function can access the local variables of the |
Fred Drake | 78eb200 | 2002-10-18 15:20:32 +0000 | [diff] [blame] | 492 | function containing the def. See section~\ref{naming} for details. |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 493 | |
Fred Drake | 2829f1c | 2001-06-23 05:27:20 +0000 | [diff] [blame] | 494 | |
Fred Drake | 61c7728 | 1998-07-28 19:34:22 +0000 | [diff] [blame] | 495 | \section{Class definitions\label{class}} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 496 | \indexii{class}{definition} |
Fred Drake | 687bde9 | 2001-12-27 18:38:10 +0000 | [diff] [blame] | 497 | \stindex{class} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 498 | |
Fred Drake | 78eb200 | 2002-10-18 15:20:32 +0000 | [diff] [blame] | 499 | A class definition defines a class object (see section~\ref{types}): |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 500 | \obindex{class} |
| 501 | |
Fred Drake | cb4638a | 2001-07-06 22:49:53 +0000 | [diff] [blame] | 502 | \begin{productionlist} |
| 503 | \production{classdef} |
| 504 | {"class" \token{classname} [\token{inheritance}] ":" |
| 505 | \token{suite}} |
| 506 | \production{inheritance} |
Brett Cannon | 629496b | 2005-04-09 03:03:00 +0000 | [diff] [blame] | 507 | {"(" [\token{expression_list}] ")"} |
Fred Drake | cb4638a | 2001-07-06 22:49:53 +0000 | [diff] [blame] | 508 | \production{classname} |
| 509 | {\token{identifier}} |
| 510 | \end{productionlist} |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 511 | |
| 512 | A class definition is an executable statement. It first evaluates the |
| 513 | inheritance list, if present. Each item in the inheritance list |
Fred Drake | 2348afd | 2003-09-24 04:11:47 +0000 | [diff] [blame] | 514 | should evaluate to a class object or class type which allows |
| 515 | subclassing. The class's suite is then executed |
Fred Drake | 78eb200 | 2002-10-18 15:20:32 +0000 | [diff] [blame] | 516 | in a new execution frame (see section~\ref{naming}), using a newly |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 517 | created local namespace and the original global namespace. |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 518 | (Usually, the suite contains only function definitions.) When the |
| 519 | class's suite finishes execution, its execution frame is discarded but |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 520 | its local namespace is saved. A class object is then created using |
| 521 | the inheritance list for the base classes and the saved local |
| 522 | namespace for the attribute dictionary. The class name is bound to this |
| 523 | class object in the original local namespace. |
Fred Drake | f666917 | 1998-05-06 19:52:49 +0000 | [diff] [blame] | 524 | \index{inheritance} |
| 525 | \indexii{class}{name} |
| 526 | \indexii{name}{binding} |
| 527 | \indexii{execution}{frame} |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 528 | |
Fred Drake | 2348afd | 2003-09-24 04:11:47 +0000 | [diff] [blame] | 529 | \strong{Programmer's note:} Variables defined in the class definition |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 530 | are class variables; they are shared by all instances. To define |
Raymond Hettinger | c7a2656 | 2003-08-12 00:01:17 +0000 | [diff] [blame] | 531 | instance variables, they must be given a value in the |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 532 | \method{__init__()} method or in another method. Both class and |
| 533 | instance variables are accessible through the notation |
Fred Drake | 7c116d7 | 2001-05-10 15:09:36 +0000 | [diff] [blame] | 534 | ``\code{self.name}'', and an instance variable hides a class variable |
Guido van Rossum | 5399d68 | 1998-07-24 18:51:11 +0000 | [diff] [blame] | 535 | with the same name when accessed in this way. Class variables with |
| 536 | immutable values can be used as defaults for instance variables. |
Fred Drake | 2348afd | 2003-09-24 04:11:47 +0000 | [diff] [blame] | 537 | For new-style classes, descriptors can be used to create instance |
| 538 | variables with different implementation details. |