blob: d1e89e5684d8fb1f2e79205cefc2f144ff628e3e [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2.. _simple:
3
4*****************
5Simple statements
6*****************
7
8.. index:: pair: simple; statement
9
10Simple statements are comprised within a single logical line. Several simple
11statements may occur on a single line separated by semicolons. The syntax for
12simple statements is:
13
14.. productionlist::
15 simple_stmt: `expression_stmt`
16 : | `assert_stmt`
17 : | `assignment_stmt`
18 : | `augmented_assignment_stmt`
19 : | `pass_stmt`
20 : | `del_stmt`
21 : | `return_stmt`
22 : | `yield_stmt`
23 : | `raise_stmt`
24 : | `break_stmt`
25 : | `continue_stmt`
26 : | `import_stmt`
27 : | `global_stmt`
Georg Brandl02c30562007-09-07 17:52:53 +000028 : | `nonlocal_stmt`
Georg Brandl116aa622007-08-15 14:28:22 +000029
30
31.. _exprstmts:
32
33Expression statements
34=====================
35
Christian Heimesfaf2f632008-01-06 16:59:19 +000036.. index::
37 pair: expression; statement
38 pair: expression; list
Georg Brandl02c30562007-09-07 17:52:53 +000039.. index:: pair: expression; list
Georg Brandl116aa622007-08-15 14:28:22 +000040
41Expression statements are used (mostly interactively) to compute and write a
42value, or (usually) to call a procedure (a function that returns no meaningful
43result; in Python, procedures return the value ``None``). Other uses of
44expression statements are allowed and occasionally useful. The syntax for an
45expression statement is:
46
47.. productionlist::
48 expression_stmt: `expression_list`
49
Georg Brandl116aa622007-08-15 14:28:22 +000050An expression statement evaluates the expression list (which may be a single
51expression).
52
53.. index::
54 builtin: repr
55 object: None
56 pair: string; conversion
57 single: output
58 pair: standard; output
59 pair: writing; values
60 pair: procedure; call
61
62In interactive mode, if the value is not ``None``, it is converted to a string
63using the built-in :func:`repr` function and the resulting string is written to
Georg Brandl02c30562007-09-07 17:52:53 +000064standard output on a line by itself (except if the result is ``None``, so that
65procedure calls do not cause any output.)
Georg Brandl116aa622007-08-15 14:28:22 +000066
Georg Brandl116aa622007-08-15 14:28:22 +000067.. _assignment:
68
69Assignment statements
70=====================
71
72.. index::
73 pair: assignment; statement
74 pair: binding; name
75 pair: rebinding; name
76 object: mutable
77 pair: attribute; assignment
78
79Assignment statements are used to (re)bind names to values and to modify
80attributes or items of mutable objects:
81
82.. productionlist::
83 assignment_stmt: (`target_list` "=")+ (`expression_list` | `yield_expression`)
84 target_list: `target` ("," `target`)* [","]
85 target: `identifier`
86 : | "(" `target_list` ")"
87 : | "[" `target_list` "]"
88 : | `attributeref`
89 : | `subscription`
90 : | `slicing`
Georg Brandl02c30562007-09-07 17:52:53 +000091 : | "*" `target`
Georg Brandl116aa622007-08-15 14:28:22 +000092
93(See section :ref:`primaries` for the syntax definitions for the last three
94symbols.)
95
Georg Brandl116aa622007-08-15 14:28:22 +000096An assignment statement evaluates the expression list (remember that this can be
97a single expression or a comma-separated list, the latter yielding a tuple) and
98assigns the single resulting object to each of the target lists, from left to
99right.
100
101.. index::
102 single: target
103 pair: target; list
104
105Assignment is defined recursively depending on the form of the target (list).
106When a target is part of a mutable object (an attribute reference, subscription
107or slicing), the mutable object must ultimately perform the assignment and
108decide about its validity, and may raise an exception if the assignment is
109unacceptable. The rules observed by various types and the exceptions raised are
110given with the definition of the object types (see section :ref:`types`).
111
112.. index:: triple: target; list; assignment
113
Georg Brandl02c30562007-09-07 17:52:53 +0000114Assignment of an object to a target list, optionally enclosed in parentheses or
115square brackets, is recursively defined as follows.
Georg Brandl116aa622007-08-15 14:28:22 +0000116
117* If the target list is a single target: The object is assigned to that target.
118
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000119* If the target list is a comma-separated list of targets: The object must be an
120 iterable with the same number of items as there are targets in the target list,
121 and the items are assigned, from left to right, to the corresponding targets.
122 (This rule is relaxed as of Python 1.5; in earlier versions, the object had to
123 be a tuple. Since strings are sequences, an assignment like ``a, b = "xy"`` is
124 now legal as long as the string has the right length.)
Georg Brandl02c30562007-09-07 17:52:53 +0000125
126 * If the target list contains one target prefixed with an asterisk, called a
127 "starred" target: The object must be a sequence with at least as many items
128 as there are targets in the target list, minus one. The first items of the
129 sequence are assigned, from left to right, to the targets before the starred
130 target. The final items of the sequence are assigned to the targets after
131 the starred target. A list of the remaining items in the sequence is then
132 assigned to the starred target (the list can be empty).
133
134 * Else: The object must be a sequence with the same number of items as there
135 are targets in the target list, and the items are assigned, from left to
136 right, to the corresponding targets.
Georg Brandl116aa622007-08-15 14:28:22 +0000137
138Assignment of an object to a single target is recursively defined as follows.
139
140* If the target is an identifier (name):
141
Georg Brandl02c30562007-09-07 17:52:53 +0000142 * If the name does not occur in a :keyword:`global` or :keyword:`nonlocal`
143 statement in the current code block: the name is bound to the object in the
144 current local namespace.
Georg Brandl116aa622007-08-15 14:28:22 +0000145
Georg Brandl02c30562007-09-07 17:52:53 +0000146 * Otherwise: the name is bound to the object in the global namespace or the
147 outer namespace determined by :keyword:`nonlocal`, respectively.
Georg Brandl116aa622007-08-15 14:28:22 +0000148
Georg Brandl02c30562007-09-07 17:52:53 +0000149 The name is rebound if it was already bound. This may cause the reference
150 count for the object previously bound to the name to reach zero, causing the
151 object to be deallocated and its destructor (if it has one) to be called.
Georg Brandl116aa622007-08-15 14:28:22 +0000152
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000153 .. index:: single: destructor
154
155 The name is rebound if it was already bound. This may cause the reference count
156 for the object previously bound to the name to reach zero, causing the object to
157 be deallocated and its destructor (if it has one) to be called.
158
159* If the target is a target list enclosed in parentheses or in square brackets:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000160 The object must be an iterable with the same number of items as there are
161 targets in the target list, and its items are assigned, from left to right,
162 to the corresponding targets.
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000163
164 .. index:: pair: attribute; assignment
165
Georg Brandl116aa622007-08-15 14:28:22 +0000166* If the target is an attribute reference: The primary expression in the
167 reference is evaluated. It should yield an object with assignable attributes;
Georg Brandl02c30562007-09-07 17:52:53 +0000168 if this is not the case, :exc:`TypeError` is raised. That object is then
169 asked to assign the assigned object to the given attribute; if it cannot
170 perform the assignment, it raises an exception (usually but not necessarily
Georg Brandl116aa622007-08-15 14:28:22 +0000171 :exc:`AttributeError`).
172
173 .. index::
174 pair: subscription; assignment
175 object: mutable
176
177* If the target is a subscription: The primary expression in the reference is
Georg Brandl02c30562007-09-07 17:52:53 +0000178 evaluated. It should yield either a mutable sequence object (such as a list)
179 or a mapping object (such as a dictionary). Next, the subscript expression is
Georg Brandl116aa622007-08-15 14:28:22 +0000180 evaluated.
181
182 .. index::
183 object: sequence
184 object: list
185
Georg Brandl02c30562007-09-07 17:52:53 +0000186 If the primary is a mutable sequence object (such as a list), the subscript
187 must yield an integer. If it is negative, the sequence's length is added to
188 it. The resulting value must be a nonnegative integer less than the
189 sequence's length, and the sequence is asked to assign the assigned object to
190 its item with that index. If the index is out of range, :exc:`IndexError` is
191 raised (assignment to a subscripted sequence cannot add new items to a list).
Georg Brandl116aa622007-08-15 14:28:22 +0000192
193 .. index::
194 object: mapping
195 object: dictionary
196
197 If the primary is a mapping object (such as a dictionary), the subscript must
198 have a type compatible with the mapping's key type, and the mapping is then
199 asked to create a key/datum pair which maps the subscript to the assigned
200 object. This can either replace an existing key/value pair with the same key
201 value, or insert a new key/value pair (if no key with the same value existed).
202
Georg Brandl02c30562007-09-07 17:52:53 +0000203 For user-defined objects, the :meth:`__setitem__` method is called with
204 appropriate arguments.
205
Georg Brandl116aa622007-08-15 14:28:22 +0000206 .. index:: pair: slicing; assignment
207
208* If the target is a slicing: The primary expression in the reference is
209 evaluated. It should yield a mutable sequence object (such as a list). The
210 assigned object should be a sequence object of the same type. Next, the lower
211 and upper bound expressions are evaluated, insofar they are present; defaults
Georg Brandl02c30562007-09-07 17:52:53 +0000212 are zero and the sequence's length. The bounds should evaluate to integers.
213 If either bound is negative, the sequence's length is added to it. The
214 resulting bounds are clipped to lie between zero and the sequence's length,
215 inclusive. Finally, the sequence object is asked to replace the slice with
216 the items of the assigned sequence. The length of the slice may be different
217 from the length of the assigned sequence, thus changing the length of the
218 target sequence, if the object allows it.
Georg Brandl116aa622007-08-15 14:28:22 +0000219
220(In the current implementation, the syntax for targets is taken to be the same
221as for expressions, and invalid syntax is rejected during the code generation
222phase, causing less detailed error messages.)
223
224WARNING: Although the definition of assignment implies that overlaps between the
225left-hand side and the right-hand side are 'safe' (for example ``a, b = b, a``
226swaps two variables), overlaps *within* the collection of assigned-to variables
227are not safe! For instance, the following program prints ``[0, 2]``::
228
229 x = [0, 1]
230 i = 0
231 i, x[i] = 1, 2
Georg Brandl6911e3c2007-09-04 07:15:32 +0000232 print(x)
Georg Brandl116aa622007-08-15 14:28:22 +0000233
234
Georg Brandl02c30562007-09-07 17:52:53 +0000235.. seealso::
236
237 :pep:`3132` - Extended Iterable Unpacking
238 The specification for the ``*target`` feature.
239
240
Georg Brandl116aa622007-08-15 14:28:22 +0000241.. _augassign:
242
243Augmented assignment statements
244-------------------------------
245
246.. index::
247 pair: augmented; assignment
248 single: statement; assignment, augmented
249
250Augmented assignment is the combination, in a single statement, of a binary
251operation and an assignment statement:
252
253.. productionlist::
Benjamin Petersonb58dda72009-01-18 22:27:04 +0000254 augmented_assignment_stmt: `augtarget` `augop` (`expression_list` | `yield_expression`)
255 augtarget: `identifier` | `attributeref` | `subscription` | `slicing`
Benjamin Peterson9bc93512008-09-22 22:10:59 +0000256 augop: "+=" | "-=" | "*=" | "/=" | "//=" | "%=" | "**="
Georg Brandl116aa622007-08-15 14:28:22 +0000257 : | ">>=" | "<<=" | "&=" | "^=" | "|="
258
259(See section :ref:`primaries` for the syntax definitions for the last three
260symbols.)
261
262An augmented assignment evaluates the target (which, unlike normal assignment
263statements, cannot be an unpacking) and the expression list, performs the binary
264operation specific to the type of assignment on the two operands, and assigns
265the result to the original target. The target is only evaluated once.
266
267An augmented assignment expression like ``x += 1`` can be rewritten as ``x = x +
2681`` to achieve a similar, but not exactly equal effect. In the augmented
269version, ``x`` is only evaluated once. Also, when possible, the actual operation
270is performed *in-place*, meaning that rather than creating a new object and
271assigning that to the target, the old object is modified instead.
272
273With the exception of assigning to tuples and multiple targets in a single
274statement, the assignment done by augmented assignment statements is handled the
275same way as normal assignments. Similarly, with the exception of the possible
276*in-place* behavior, the binary operation performed by augmented assignment is
277the same as the normal binary operations.
278
279For targets which are attribute references, the initial value is retrieved with
280a :meth:`getattr` and the result is assigned with a :meth:`setattr`. Notice
281that the two methods do not necessarily refer to the same variable. When
282:meth:`getattr` refers to a class variable, :meth:`setattr` still writes to an
283instance variable. For example::
284
285 class A:
286 x = 3 # class variable
287 a = A()
288 a.x += 1 # writes a.x as 4 leaving A.x as 3
289
290
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000291.. _assert:
292
293The :keyword:`assert` statement
294===============================
295
296.. index::
297 statement: assert
298 pair: debugging; assertions
299
300Assert statements are a convenient way to insert debugging assertions into a
301program:
302
303.. productionlist::
304 assert_stmt: "assert" `expression` ["," `expression`]
305
306The simple form, ``assert expression``, is equivalent to ::
307
308 if __debug__:
309 if not expression: raise AssertionError
310
311The extended form, ``assert expression1, expression2``, is equivalent to ::
312
313 if __debug__:
Georg Brandl18a499d2007-12-29 10:57:11 +0000314 if not expression1: raise AssertionError(expression2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000315
316.. index::
317 single: __debug__
318 exception: AssertionError
319
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000320These equivalences assume that :const:`__debug__` and :exc:`AssertionError` refer to
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000321the built-in variables with those names. In the current implementation, the
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000322built-in variable :const:`__debug__` is ``True`` under normal circumstances,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000323``False`` when optimization is requested (command line option -O). The current
324code generator emits no code for an assert statement when optimization is
325requested at compile time. Note that it is unnecessary to include the source
326code for the expression that failed in the error message; it will be displayed
327as part of the stack trace.
328
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000329Assignments to :const:`__debug__` are illegal. The value for the built-in variable
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000330is determined when the interpreter starts.
331
332
Georg Brandl116aa622007-08-15 14:28:22 +0000333.. _pass:
334
335The :keyword:`pass` statement
336=============================
337
Christian Heimesfaf2f632008-01-06 16:59:19 +0000338.. index::
339 statement: pass
340 pair: null; operation
Georg Brandl02c30562007-09-07 17:52:53 +0000341 pair: null; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000342
343.. productionlist::
344 pass_stmt: "pass"
345
Georg Brandl116aa622007-08-15 14:28:22 +0000346:keyword:`pass` is a null operation --- when it is executed, nothing happens.
347It is useful as a placeholder when a statement is required syntactically, but no
348code needs to be executed, for example::
349
350 def f(arg): pass # a function that does nothing (yet)
351
352 class C: pass # a class with no methods (yet)
353
354
355.. _del:
356
357The :keyword:`del` statement
358============================
359
Christian Heimesfaf2f632008-01-06 16:59:19 +0000360.. index::
361 statement: del
362 pair: deletion; target
363 triple: deletion; target; list
Georg Brandl116aa622007-08-15 14:28:22 +0000364
365.. productionlist::
366 del_stmt: "del" `target_list`
367
Georg Brandl116aa622007-08-15 14:28:22 +0000368Deletion is recursively defined very similar to the way assignment is defined.
369Rather that spelling it out in full details, here are some hints.
370
371Deletion of a target list recursively deletes each target, from left to right.
372
373.. index::
374 statement: global
375 pair: unbinding; name
376
Georg Brandl02c30562007-09-07 17:52:53 +0000377Deletion of a name removes the binding of that name from the local or global
Georg Brandl116aa622007-08-15 14:28:22 +0000378namespace, depending on whether the name occurs in a :keyword:`global` statement
379in the same code block. If the name is unbound, a :exc:`NameError` exception
380will be raised.
381
382.. index:: pair: free; variable
383
384It is illegal to delete a name from the local namespace if it occurs as a free
385variable in a nested block.
386
387.. index:: pair: attribute; deletion
388
389Deletion of attribute references, subscriptions and slicings is passed to the
390primary object involved; deletion of a slicing is in general equivalent to
391assignment of an empty slice of the right type (but even this is determined by
392the sliced object).
393
394
395.. _return:
396
397The :keyword:`return` statement
398===============================
399
Christian Heimesfaf2f632008-01-06 16:59:19 +0000400.. index::
401 statement: return
402 pair: function; definition
403 pair: class; definition
Georg Brandl116aa622007-08-15 14:28:22 +0000404
405.. productionlist::
406 return_stmt: "return" [`expression_list`]
407
Georg Brandl116aa622007-08-15 14:28:22 +0000408:keyword:`return` may only occur syntactically nested in a function definition,
409not within a nested class definition.
410
411If an expression list is present, it is evaluated, else ``None`` is substituted.
412
413:keyword:`return` leaves the current function call with the expression list (or
414``None``) as return value.
415
416.. index:: keyword: finally
417
418When :keyword:`return` passes control out of a :keyword:`try` statement with a
419:keyword:`finally` clause, that :keyword:`finally` clause is executed before
420really leaving the function.
421
422In a generator function, the :keyword:`return` statement is not allowed to
423include an :token:`expression_list`. In that context, a bare :keyword:`return`
424indicates that the generator is done and will cause :exc:`StopIteration` to be
425raised.
426
427
428.. _yield:
429
430The :keyword:`yield` statement
431==============================
432
Christian Heimesfaf2f632008-01-06 16:59:19 +0000433.. index::
434 statement: yield
435 single: generator; function
436 single: generator; iterator
437 single: function; generator
438 exception: StopIteration
439
Georg Brandl116aa622007-08-15 14:28:22 +0000440.. productionlist::
441 yield_stmt: `yield_expression`
442
Christian Heimesfaf2f632008-01-06 16:59:19 +0000443The :keyword:`yield` statement is only used when defining a generator function,
444and is only used in the body of the generator function. Using a :keyword:`yield`
445statement in a function definition is sufficient to cause that definition to
446create a generator function instead of a normal function.
Christian Heimes33fe8092008-04-13 13:53:33 +0000447When a generator function is called, it returns an iterator known as a generator
448iterator, or more commonly, a generator. The body of the generator function is
Georg Brandl6520d822009-02-05 11:01:54 +0000449executed by calling the :func:`next` function on the generator repeatedly until
450it raises an exception.
Christian Heimes33fe8092008-04-13 13:53:33 +0000451
452When a :keyword:`yield` statement is executed, the state of the generator is
453frozen and the value of :token:`expression_list` is returned to :meth:`next`'s
454caller. By "frozen" we mean that all local state is retained, including the
455current bindings of local variables, the instruction pointer, and the internal
Georg Brandl6520d822009-02-05 11:01:54 +0000456evaluation stack: enough information is saved so that the next time :func:`next`
Christian Heimes33fe8092008-04-13 13:53:33 +0000457is invoked, the function can proceed exactly as if the :keyword:`yield`
458statement were just another external call.
459
Georg Brandle6bcc912008-05-12 18:05:20 +0000460The :keyword:`yield` statement is allowed in the :keyword:`try` clause of a
461:keyword:`try` ... :keyword:`finally` construct. If the generator is not
462resumed before it is finalized (by reaching a zero reference count or by being
463garbage collected), the generator-iterator's :meth:`close` method will be
464called, allowing any pending :keyword:`finally` clauses to execute.
Christian Heimes33fe8092008-04-13 13:53:33 +0000465
466.. seealso::
467
468 :pep:`0255` - Simple Generators
469 The proposal for adding generators and the :keyword:`yield` statement to Python.
470
471 :pep:`0342` - Coroutines via Enhanced Generators
472 The proposal that, among other generator enhancements, proposed allowing
473 :keyword:`yield` to appear inside a :keyword:`try` ... :keyword:`finally` block.
474
Georg Brandl116aa622007-08-15 14:28:22 +0000475
476.. _raise:
477
478The :keyword:`raise` statement
479==============================
480
Christian Heimesfaf2f632008-01-06 16:59:19 +0000481.. index::
482 statement: raise
483 single: exception
484 pair: raising; exception
Georg Brandl1aea30a2008-07-19 15:51:07 +0000485 single: __traceback__ (exception attribute)
Georg Brandl116aa622007-08-15 14:28:22 +0000486
487.. productionlist::
Georg Brandle06de8b2008-05-05 21:42:51 +0000488 raise_stmt: "raise" [`expression` ["from" `expression`]]
Georg Brandl116aa622007-08-15 14:28:22 +0000489
490If no expressions are present, :keyword:`raise` re-raises the last exception
491that was active in the current scope. If no exception is active in the current
492scope, a :exc:`TypeError` exception is raised indicating that this is an error
Alexandre Vassalottif260e442008-05-11 19:59:59 +0000493(if running under IDLE, a :exc:`queue.Empty` exception is raised instead).
Georg Brandl116aa622007-08-15 14:28:22 +0000494
Georg Brandl02c30562007-09-07 17:52:53 +0000495Otherwise, :keyword:`raise` evaluates the first expression as the exception
496object. It must be either a subclass or an instance of :class:`BaseException`.
497If it is a class, the exception instance will be obtained when needed by
498instantiating the class with no arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000499
Georg Brandl02c30562007-09-07 17:52:53 +0000500The :dfn:`type` of the exception is the exception instance's class, the
501:dfn:`value` is the instance itself.
Georg Brandl116aa622007-08-15 14:28:22 +0000502
503.. index:: object: traceback
504
Georg Brandl02c30562007-09-07 17:52:53 +0000505A traceback object is normally created automatically when an exception is raised
Georg Brandle06de8b2008-05-05 21:42:51 +0000506and attached to it as the :attr:`__traceback__` attribute, which is writable.
507You can create an exception and set your own traceback in one step using the
508:meth:`with_traceback` exception method (which returns the same exception
509instance, with its traceback set to its argument), like so::
Georg Brandl02c30562007-09-07 17:52:53 +0000510
Benjamin Petersonb7851692009-02-16 16:15:34 +0000511 raise Exception("foo occurred").with_traceback(tracebackobj)
Georg Brandl02c30562007-09-07 17:52:53 +0000512
Georg Brandl1aea30a2008-07-19 15:51:07 +0000513.. index:: pair: exception; chaining
514 __cause__ (exception attribute)
515 __context__ (exception attribute)
Georg Brandl48310cd2009-01-03 21:18:54 +0000516
Georg Brandl1aea30a2008-07-19 15:51:07 +0000517The ``from`` clause is used for exception chaining: if given, the second
518*expression* must be another exception class or instance, which will then be
519attached to the raised exception as the :attr:`__cause__` attribute (which is
520writable). If the raised exception is not handled, both exceptions will be
521printed::
Georg Brandl02c30562007-09-07 17:52:53 +0000522
Georg Brandl1aea30a2008-07-19 15:51:07 +0000523 >>> try:
524 ... print(1 / 0)
525 ... except Exception as exc:
526 ... raise RuntimeError("Something bad happened") from exc
527 ...
528 Traceback (most recent call last):
529 File "<stdin>", line 2, in <module>
530 ZeroDivisionError: int division or modulo by zero
531
532 The above exception was the direct cause of the following exception:
533
534 Traceback (most recent call last):
535 File "<stdin>", line 4, in <module>
536 RuntimeError: Something bad happened
537
538A similar mechanism works implicitly if an exception is raised inside an
539exception handler: the previous exception is then attached as the new
540exception's :attr:`__context__` attribute::
541
542 >>> try:
543 ... print(1 / 0)
544 ... except:
545 ... raise RuntimeError("Something bad happened")
546 ...
547 Traceback (most recent call last):
548 File "<stdin>", line 2, in <module>
549 ZeroDivisionError: int division or modulo by zero
550
551 During handling of the above exception, another exception occurred:
552
553 Traceback (most recent call last):
554 File "<stdin>", line 4, in <module>
555 RuntimeError: Something bad happened
Georg Brandl116aa622007-08-15 14:28:22 +0000556
557Additional information on exceptions can be found in section :ref:`exceptions`,
558and information about handling exceptions is in section :ref:`try`.
559
560
561.. _break:
562
563The :keyword:`break` statement
564==============================
565
Christian Heimesfaf2f632008-01-06 16:59:19 +0000566.. index::
567 statement: break
568 statement: for
569 statement: while
570 pair: loop; statement
Georg Brandl116aa622007-08-15 14:28:22 +0000571
572.. productionlist::
573 break_stmt: "break"
574
Georg Brandl116aa622007-08-15 14:28:22 +0000575:keyword:`break` may only occur syntactically nested in a :keyword:`for` or
576:keyword:`while` loop, but not nested in a function or class definition within
577that loop.
578
579.. index:: keyword: else
Georg Brandl02c30562007-09-07 17:52:53 +0000580 pair: loop control; target
Georg Brandl116aa622007-08-15 14:28:22 +0000581
582It terminates the nearest enclosing loop, skipping the optional :keyword:`else`
583clause if the loop has one.
584
Georg Brandl116aa622007-08-15 14:28:22 +0000585If a :keyword:`for` loop is terminated by :keyword:`break`, the loop control
586target keeps its current value.
587
588.. index:: keyword: finally
589
590When :keyword:`break` passes control out of a :keyword:`try` statement with a
591:keyword:`finally` clause, that :keyword:`finally` clause is executed before
592really leaving the loop.
593
594
595.. _continue:
596
597The :keyword:`continue` statement
598=================================
599
Christian Heimesfaf2f632008-01-06 16:59:19 +0000600.. index::
601 statement: continue
602 statement: for
603 statement: while
604 pair: loop; statement
605 keyword: finally
Georg Brandl116aa622007-08-15 14:28:22 +0000606
607.. productionlist::
608 continue_stmt: "continue"
609
Georg Brandl116aa622007-08-15 14:28:22 +0000610:keyword:`continue` may only occur syntactically nested in a :keyword:`for` or
611:keyword:`while` loop, but not nested in a function or class definition or
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000612:keyword:`finally` clause within that loop. It continues with the next
Georg Brandl116aa622007-08-15 14:28:22 +0000613cycle of the nearest enclosing loop.
614
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000615When :keyword:`continue` passes control out of a :keyword:`try` statement with a
616:keyword:`finally` clause, that :keyword:`finally` clause is executed before
617really starting the next loop cycle.
618
Georg Brandl116aa622007-08-15 14:28:22 +0000619
620.. _import:
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000621.. _from:
Georg Brandl116aa622007-08-15 14:28:22 +0000622
623The :keyword:`import` statement
624===============================
625
626.. index::
627 statement: import
628 single: module; importing
629 pair: name; binding
630 keyword: from
631
632.. productionlist::
633 import_stmt: "import" `module` ["as" `name`] ( "," `module` ["as" `name`] )*
634 : | "from" `relative_module` "import" `identifier` ["as" `name`]
635 : ( "," `identifier` ["as" `name`] )*
636 : | "from" `relative_module` "import" "(" `identifier` ["as" `name`]
637 : ( "," `identifier` ["as" `name`] )* [","] ")"
638 : | "from" `module` "import" "*"
639 module: (`identifier` ".")* `identifier`
640 relative_module: "."* `module` | "."+
641 name: `identifier`
642
643Import statements are executed in two steps: (1) find a module, and initialize
644it if necessary; (2) define a name or names in the local namespace (of the scope
Georg Brandl02c30562007-09-07 17:52:53 +0000645where the :keyword:`import` statement occurs). The first form (without
Georg Brandl116aa622007-08-15 14:28:22 +0000646:keyword:`from`) repeats these steps for each identifier in the list. The form
647with :keyword:`from` performs step (1) once, and then performs step (2)
648repeatedly.
649
650In this context, to "initialize" a built-in or extension module means to call an
651initialization function that the module must provide for the purpose (in the
652reference implementation, the function's name is obtained by prepending string
653"init" to the module's name); to "initialize" a Python-coded module means to
654execute the module's body.
655
656.. index::
657 single: modules (in module sys)
658 single: sys.modules
659 pair: module; name
660 pair: built-in; module
661 pair: user-defined; module
Georg Brandl116aa622007-08-15 14:28:22 +0000662 pair: filename; extension
663 triple: module; search; path
Georg Brandl02c30562007-09-07 17:52:53 +0000664 module: sys
Georg Brandl116aa622007-08-15 14:28:22 +0000665
666The system maintains a table of modules that have been or are being initialized,
667indexed by module name. This table is accessible as ``sys.modules``. When a
668module name is found in this table, step (1) is finished. If not, a search for
669a module definition is started. When a module is found, it is loaded. Details
670of the module searching and loading process are implementation and platform
671specific. It generally involves searching for a "built-in" module with the
672given name and then searching a list of locations given as ``sys.path``.
673
674.. index::
675 pair: module; initialization
676 exception: ImportError
677 single: code block
678 exception: SyntaxError
679
680If a built-in module is found, its built-in initialization code is executed and
681step (1) is finished. If no matching file is found, :exc:`ImportError` is
682raised. If a file is found, it is parsed, yielding an executable code block. If
683a syntax error occurs, :exc:`SyntaxError` is raised. Otherwise, an empty module
684of the given name is created and inserted in the module table, and then the code
685block is executed in the context of this module. Exceptions during this
686execution terminate step (1).
687
688When step (1) finishes without raising an exception, step (2) can begin.
689
690The first form of :keyword:`import` statement binds the module name in the local
691namespace to the module object, and then goes on to import the next identifier,
692if any. If the module name is followed by :keyword:`as`, the name following
693:keyword:`as` is used as the local name for the module.
694
695.. index::
696 pair: name; binding
697 exception: ImportError
698
699The :keyword:`from` form does not bind the module name: it goes through the list
700of identifiers, looks each one of them up in the module found in step (1), and
701binds the name in the local namespace to the object thus found. As with the
702first form of :keyword:`import`, an alternate local name can be supplied by
703specifying ":keyword:`as` localname". If a name is not found,
704:exc:`ImportError` is raised. If the list of identifiers is replaced by a star
705(``'*'``), all public names defined in the module are bound in the local
706namespace of the :keyword:`import` statement..
707
708.. index:: single: __all__ (optional module attribute)
709
710The *public names* defined by a module are determined by checking the module's
711namespace for a variable named ``__all__``; if defined, it must be a sequence of
712strings which are names defined or imported by that module. The names given in
713``__all__`` are all considered public and are required to exist. If ``__all__``
714is not defined, the set of public names includes all names found in the module's
715namespace which do not begin with an underscore character (``'_'``).
716``__all__`` should contain the entire public API. It is intended to avoid
717accidentally exporting items that are not part of the API (such as library
718modules which were imported and used within the module).
719
720The :keyword:`from` form with ``*`` may only occur in a module scope. If the
721wild card form of import --- ``import *`` --- is used in a function and the
722function contains or is a nested block with free variables, the compiler will
723raise a :exc:`SyntaxError`.
724
725.. index::
726 keyword: from
Christian Heimesfaf2f632008-01-06 16:59:19 +0000727 statement: from
Georg Brandl116aa622007-08-15 14:28:22 +0000728 triple: hierarchical; module; names
729 single: packages
730 single: __init__.py
731
732**Hierarchical module names:** when the module names contains one or more dots,
733the module search path is carried out differently. The sequence of identifiers
734up to the last dot is used to find a "package"; the final identifier is then
735searched inside the package. A package is generally a subdirectory of a
Georg Brandl5b318c02008-08-03 09:47:27 +0000736directory on ``sys.path`` that has a file :file:`__init__.py`.
737
Georg Brandl48310cd2009-01-03 21:18:54 +0000738..
Georg Brandl5b318c02008-08-03 09:47:27 +0000739 [XXX Can't be
740 bothered to spell this out right now; see the URL
741 http://www.python.org/doc/essays/packages.html for more details, also about how
742 the module search works from inside a package.]
Georg Brandl116aa622007-08-15 14:28:22 +0000743
Georg Brandl116aa622007-08-15 14:28:22 +0000744.. index:: builtin: __import__
745
746The built-in function :func:`__import__` is provided to support applications
747that determine which modules need to be loaded dynamically; refer to
748:ref:`built-in-funcs` for additional information.
749
750
751.. _future:
752
753Future statements
754-----------------
755
756.. index:: pair: future; statement
757
758A :dfn:`future statement` is a directive to the compiler that a particular
759module should be compiled using syntax or semantics that will be available in a
760specified future release of Python. The future statement is intended to ease
761migration to future versions of Python that introduce incompatible changes to
762the language. It allows use of the new features on a per-module basis before
763the release in which the feature becomes standard.
764
765.. productionlist:: *
766 future_statement: "from" "__future__" "import" feature ["as" name]
767 : ("," feature ["as" name])*
768 : | "from" "__future__" "import" "(" feature ["as" name]
769 : ("," feature ["as" name])* [","] ")"
770 feature: identifier
771 name: identifier
772
773A future statement must appear near the top of the module. The only lines that
774can appear before a future statement are:
775
776* the module docstring (if any),
777* comments,
778* blank lines, and
779* other future statements.
780
Georg Brandl02c30562007-09-07 17:52:53 +0000781.. XXX change this if future is cleaned out
782
783The features recognized by Python 3.0 are ``absolute_import``, ``division``,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000784``generators``, ``unicode_literals``, ``print_function``, ``nested_scopes`` and
785``with_statement``. They are all redundant because they are always enabled, and
786only kept for backwards compatibility.
Georg Brandl116aa622007-08-15 14:28:22 +0000787
788A future statement is recognized and treated specially at compile time: Changes
789to the semantics of core constructs are often implemented by generating
790different code. It may even be the case that a new feature introduces new
791incompatible syntax (such as a new reserved word), in which case the compiler
792may need to parse the module differently. Such decisions cannot be pushed off
793until runtime.
794
795For any given release, the compiler knows which feature names have been defined,
796and raises a compile-time error if a future statement contains a feature not
797known to it.
798
799The direct runtime semantics are the same as for any import statement: there is
800a standard module :mod:`__future__`, described later, and it will be imported in
801the usual way at the time the future statement is executed.
802
803The interesting runtime semantics depend on the specific feature enabled by the
804future statement.
805
806Note that there is nothing special about the statement::
807
808 import __future__ [as name]
809
810That is not a future statement; it's an ordinary import statement with no
811special semantics or syntax restrictions.
812
813Code compiled by calls to the builtin functions :func:`exec` and :func:`compile`
Georg Brandl02c30562007-09-07 17:52:53 +0000814that occur in a module :mod:`M` containing a future statement will, by default,
815use the new syntax or semantics associated with the future statement. This can
816be controlled by optional arguments to :func:`compile` --- see the documentation
817of that function for details.
Georg Brandl116aa622007-08-15 14:28:22 +0000818
819A future statement typed at an interactive interpreter prompt will take effect
820for the rest of the interpreter session. If an interpreter is started with the
821:option:`-i` option, is passed a script name to execute, and the script includes
822a future statement, it will be in effect in the interactive session started
823after the script is executed.
824
825
826.. _global:
827
828The :keyword:`global` statement
829===============================
830
Christian Heimesfaf2f632008-01-06 16:59:19 +0000831.. index::
832 statement: global
833 triple: global; name; binding
Georg Brandl116aa622007-08-15 14:28:22 +0000834
835.. productionlist::
836 global_stmt: "global" `identifier` ("," `identifier`)*
837
Georg Brandl116aa622007-08-15 14:28:22 +0000838The :keyword:`global` statement is a declaration which holds for the entire
839current code block. It means that the listed identifiers are to be interpreted
840as globals. It would be impossible to assign to a global variable without
841:keyword:`global`, although free variables may refer to globals without being
842declared global.
843
844Names listed in a :keyword:`global` statement must not be used in the same code
845block textually preceding that :keyword:`global` statement.
846
847Names listed in a :keyword:`global` statement must not be defined as formal
848parameters or in a :keyword:`for` loop control target, :keyword:`class`
849definition, function definition, or :keyword:`import` statement.
850
851(The current implementation does not enforce the latter two restrictions, but
852programs should not abuse this freedom, as future implementations may enforce
853them or silently change the meaning of the program.)
854
855.. index::
856 builtin: exec
857 builtin: eval
858 builtin: compile
859
860**Programmer's note:** the :keyword:`global` is a directive to the parser. It
861applies only to code parsed at the same time as the :keyword:`global` statement.
862In particular, a :keyword:`global` statement contained in a string or code
863object supplied to the builtin :func:`exec` function does not affect the code
864block *containing* the function call, and code contained in such a string is
865unaffected by :keyword:`global` statements in the code containing the function
866call. The same applies to the :func:`eval` and :func:`compile` functions.
867
Georg Brandl02c30562007-09-07 17:52:53 +0000868
869.. _nonlocal:
870
871The :keyword:`nonlocal` statement
872=================================
873
874.. index:: statement: nonlocal
875
876.. productionlist::
877 nonlocal_stmt: "nonlocal" `identifier` ("," `identifier`)*
878
Georg Brandlc5d98b42007-12-04 18:11:03 +0000879.. XXX add when implemented
Georg Brandl06788c92009-01-03 21:31:47 +0000880 : ["=" (`target_list` "=")+ expression_list]
881 : | "nonlocal" identifier augop expression_list
Georg Brandlc5d98b42007-12-04 18:11:03 +0000882
Georg Brandl48310cd2009-01-03 21:18:54 +0000883The :keyword:`nonlocal` statement causes the listed identifiers to refer to
884previously bound variables in the nearest enclosing scope. This is important
885because the default behavior for binding is to search the local namespace
Georg Brandlc5d98b42007-12-04 18:11:03 +0000886first. The statement allows encapsulated code to rebind variables outside of
887the local scope besides the global (module) scope.
888
Georg Brandlc5d98b42007-12-04 18:11:03 +0000889.. XXX not implemented
890 The :keyword:`nonlocal` statement may prepend an assignment or augmented
891 assignment, but not an expression.
892
893Names listed in a :keyword:`nonlocal` statement, unlike to those listed in a
894:keyword:`global` statement, must refer to pre-existing bindings in an
895enclosing scope (the scope in which a new binding should be created cannot
896be determined unambiguously).
897
Georg Brandl48310cd2009-01-03 21:18:54 +0000898Names listed in a :keyword:`nonlocal` statement must not collide with
Georg Brandlc5d98b42007-12-04 18:11:03 +0000899pre-existing bindings in the local scope.
900
901.. seealso::
902
903 :pep:`3104` - Access to Names in Outer Scopes
904 The specification for the :keyword:`nonlocal` statement.
Georg Brandl02c30562007-09-07 17:52:53 +0000905
906
Georg Brandl116aa622007-08-15 14:28:22 +0000907.. rubric:: Footnotes
908
909.. [#] It may occur within an :keyword:`except` or :keyword:`else` clause. The
Georg Brandlc5d98b42007-12-04 18:11:03 +0000910 restriction on occurring in the :keyword:`try` clause is implementor's
911 laziness and will eventually be lifted.