source: vendor/python/2.5/Doc/ref/ref7.tex

Last change on this file was 3225, checked in by bird, 18 years ago

Python 2.5

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