1 \chapter{Compound statements
\label{compound
}}
2 \indexii{compound
}{statement
}
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.
9 The
\keyword{if
},
\keyword{while
} and
\keyword{for
} statements implement
10 traditional control flow constructs.
\keyword{try
} specifies exception
11 handlers and/or cleanup code for a group of statements. Function and
12 class definitions are also syntactically compound statements.
14 Compound statements consist of one or more `clauses.' A clause
15 consists of a header and a `suite.' The clause headers of a
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
24 clear to which
\keyword{if
} clause a following
\keyword{else
} clause would
30 if test1: if test2: print x
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
35 \keyword{print
} statements are executed:
38 if x < y < z: print x; print y; print z
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)*
[";"
]
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).
58 \indexii{dangling
}{else
}
60 The formatting of the grammar rules in the following sections places
61 each clause on a separate line for clarity.
63 \section{The
\keyword{if
} statement
\label{if
}}
66 The
\keyword{if
} statement is used for conditional execution:
69 if_stmt: "if" expression ":" suite
70 ("elif" expression ":" suite)*
74 It selects exactly one of the suites by evaluating the expressions one
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
77 other part of the
\keyword{if
} statement is executed or evaluated). If
78 all expressions are false, the suite of the
\keyword{else
} clause, if
83 \section{The
\keyword{while
} statement
\label{while
}}
85 \indexii{loop
}{statement
}
87 The
\keyword{while
} statement is used for repeated execution as long
88 as an expression is true:
91 while_stmt: "while" expression ":" suite
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
97 is tested) the suite of the
\keyword{else
} clause, if present, is
98 executed and the loop terminates.
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
104 of the suite and goes back to testing the expression.
108 \section{The
\keyword{for
} statement
\label{for
}}
110 \indexii{loop
}{statement
}
112 The
\keyword{for
} statement is used to iterate over the elements of a
113 sequence (string, tuple or list):
117 for_stmt: "for" target_list "in" expression_list ":" suite
121 The expression list is evaluated once; it should yield a sequence. The
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
126 when the sequence is empty), the suite in the
\keyword{else
} clause, if
127 present, is executed, and the loop terminates.
130 \indexii{target
}{list
}
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
}
136 clause if there was no next item.
140 The suite may assign to the variable(s) in the target list; this does
141 not affect the next item assigned to it.
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
145 loop. Hint: the built-in function
\function{range()
} returns a
146 sequence of integers suitable to emulate the effect of Pascal's
147 \code{for i := a to b do
};
148 e.g.,
\code{range(
3)
} returns the list
\code{[0,
1,
2]}.
150 \indexii{Pascal
}{language
}
152 \strong{Warning:
} There is a subtlety when the sequence is being modified
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
163 copy using a slice of the whole sequence, e.g.,
164 \index{loop!over mutable sequence
}
165 \index{mutable sequence!loop over
}
169 if x <
0: a.remove(x)
172 \section{The
\keyword{try
} statement
\label{try
}}
175 The
\keyword{try
} statement specifies exception handlers and/or cleanup
176 code for a group of statements:
179 try_stmt: try_exc_stmt | try_fin_stmt
180 try_exc_stmt: "try" ":" suite
181 ("except"
[expression
["," target
]] ":" suite)+
183 try_fin_stmt: "try" ":" suite
187 There are two forms of
\keyword{try
} statement:
188 \keyword{try
}...
\keyword{except
} and
189 \keyword{try
}...
\keyword{finally
}. These forms cannot be mixed (but
190 they can be nested in each other).
192 The
\keyword{try
}...
\keyword{except
} form specifies one or more
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
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
199 clause, if present, must be last; it matches any exception. For an
200 except clause with an expression, that expression is evaluated, and the
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.
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.
213 If the evaluation of an expression in the header of an except clause
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
216 on the call stack (it is treated as if the entire
\keyword{try
} statement
217 raised the exception).
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,
221 and the except clause's suite is executed. All except clauses must
222 have an executable block. When the end of this block
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.)
228 Before an except clause's suite is executed, details about the
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.
235 These details are also available through the
\function{sys.exc_info()
}
236 function, which returns a tuple
\code{(
\var{exc_type
},
\var{exc_value
},
237 \var{exc_traceback
})
}. Use of the corresponding variables is
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.
242 \withsubitem{(in module sys)
}{\ttindex{exc_type
}
243 \ttindex{exc_value
}\ttindex{exc_traceback
}}
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.
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,
257 the saved exception is lost. The exception information is not
258 available to the program during execution of the
\keyword{finally
}
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
264 \keyword{finally
} clause is also executed `on the way out.' A
265 \keyword{continue
} statement is illegal in the
\keyword{try
} clause. (The
266 reason is a problem with the current implementation --- this
267 restriction may be lifted in the future).
272 \section{Function definitions
\label{function
}}
273 \indexii{function
}{definition
}
275 A function definition defines a user-defined function object (see
276 section
\ref{types
}):
277 \obindex{user-defined function
}
281 funcdef: "def" funcname "("
[parameter_list
] ")" ":" suite
282 parameter_list: (defparameter ",")* ("*" identifier
[, "**" identifier
]
284 | defparameter
[","
])
285 defparameter: parameter
["=" expression
]
286 sublist: parameter ("," parameter)*
[","
]
287 parameter: identifier | "(" sublist ")"
291 A function definition is an executable statement. Its execution binds
292 the function name in the current local namespace to a function object
293 (a wrapper around the executable code for the function). This
294 function object contains a reference to the current global namespace
295 as the global namespace to be used when the function is called.
296 \indexii{function
}{name
}
297 \indexii{name
}{binding
}
299 The function definition does not execute the function body; this gets
300 executed only when the function is called.
302 When one or more top-level parameters have the form
\var{parameter
}
303 \code{=
} \var{expression
}, the function is said to have ``default
304 parameter values.'' For a parameter with a
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
309 expressed by the grammar.
\footnote{
310 Currently this is not checked; instead,
\code{def f(a=
1, b)
} is
311 interpreted as
\code{def f(a=
1, b=None)
}.
}
312 \indexiii{default
}{parameter
}{value
}
314 \strong{Default parameter values are evaluated when the function
315 definition is executed.
} This means that the expression is evaluated
316 once, when the function is defined, and that that same
317 ``pre-computed'' value is used for each call. This is especially
318 important to understand when a default parameter is a mutable object,
319 such as a list or a dictionary: if the function modifies the object
320 (e.g. by appending an item to a list), the default value is in effect
321 modified. This is generally not what was intended. A way around this
322 is to use
\code{None
} as the default, and explicitly test for it in
323 the body of the function, e.g.:
326 def whats_on_the_telly(penguin=None):
329 penguin.append("property of the zoo")
333 Function call semantics are described in more detail in section
335 A function call always assigns values to all parameters mentioned in
336 the parameter list, either from position arguments, from keyword
337 arguments, or from default values. If the form ``
\code{*identifier
}''
338 is present, it is initialized to a tuple receiving any excess
339 positional parameters, defaulting to the empty tuple. If the form
340 ``
\code{**identifier
}'' is present, it is initialized to a new
341 dictionary receiving any excess keyword arguments, defaulting to a
342 new empty dictionary.
348 It is also possible to create anonymous functions (functions not bound
349 to a name), for immediate use in expressions. This uses lambda forms,
350 described in section
\ref{lambda
}. Note that the lambda form is
351 merely a shorthand for a simplified function definition; a function
352 defined in a ``
\keyword{def
}'' statement can be passed around or
353 assigned to another name just like a function defined by a lambda
354 form. The ``
\keyword{def
}'' form is actually more powerful since it
355 allows the execution of multiple statements.
356 \indexii{lambda
}{form
}
358 \strong{Programmer's note:
} a ``
\code{def
}'' form executed inside a
359 function definition defines a local function that can be returned or
360 passed around. Because of Python's two-scope philosophy, a local
361 function defined in this way does not have access to the local
362 variables of the function that contains its definition; the same rule
363 applies to functions defined by a lambda form. A standard trick to
364 pass selected local variables into a locally defined function is to
365 use default argument values, like this:
368 # Return a function that returns its argument incremented by 'n'
369 def make_incrementer(n):
370 def increment(x, n=n):
374 add1 = make_incrementer(
1)
375 print add1(
3) # This prints '
4'
378 \section{Class definitions
\label{class
}}
379 \indexii{class
}{definition
}
381 A class definition defines a class object (see section
\ref{types
}):
385 classdef: "class" classname
[inheritance
] ":" suite
386 inheritance: "("
[expression_list
] ")"
387 classname: identifier
390 A class definition is an executable statement. It first evaluates the
391 inheritance list, if present. Each item in the inheritance list
392 should evaluate to a class object. The class's suite is then executed
393 in a new execution frame (see section
\ref{execframes
}), using a newly
394 created local namespace and the original global namespace.
395 (Usually, the suite contains only function definitions.) When the
396 class's suite finishes execution, its execution frame is discarded but
397 its local namespace is saved. A class object is then created using
398 the inheritance list for the base classes and the saved local
399 namespace for the attribute dictionary. The class name is bound to this
400 class object in the original local namespace.
402 \indexii{class
}{name
}
403 \indexii{name
}{binding
}
404 \indexii{execution
}{frame
}
406 \strong{Programmer's note:
} variables defined in the class definition
407 are class variables; they are shared by all instances. To define
408 instance variables, they must be given a value in the the
409 \method{__init__()
} method or in another method. Both class and
410 instance variables are accessible through the notation
411 ```code
{self.name
}'', and an instance variable hides a class variable
412 with the same name when accessed in this way. Class variables with
413 immutable values can be used as defaults for instance variables.