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