blob: 1e3cb8559bbfca8e0e5a90bf5937fdd8433f64aa [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
Georg Brandl02c30562007-09-07 17:52:53 +0000119* If the target list is a comma-separated list of targets:
120
121 * If the target list contains one target prefixed with an asterisk, called a
122 "starred" target: The object must be a sequence with at least as many items
123 as there are targets in the target list, minus one. The first items of the
124 sequence are assigned, from left to right, to the targets before the starred
125 target. The final items of the sequence are assigned to the targets after
126 the starred target. A list of the remaining items in the sequence is then
127 assigned to the starred target (the list can be empty).
128
129 * Else: The object must be a sequence with the same number of items as there
130 are targets in the target list, and the items are assigned, from left to
131 right, to the corresponding targets.
Georg Brandl116aa622007-08-15 14:28:22 +0000132
133Assignment of an object to a single target is recursively defined as follows.
134
135* If the target is an identifier (name):
136
Georg Brandl02c30562007-09-07 17:52:53 +0000137 * If the name does not occur in a :keyword:`global` or :keyword:`nonlocal`
138 statement in the current code block: the name is bound to the object in the
139 current local namespace.
Georg Brandl116aa622007-08-15 14:28:22 +0000140
Georg Brandl02c30562007-09-07 17:52:53 +0000141 * Otherwise: the name is bound to the object in the global namespace or the
142 outer namespace determined by :keyword:`nonlocal`, respectively.
Georg Brandl116aa622007-08-15 14:28:22 +0000143
Georg Brandl02c30562007-09-07 17:52:53 +0000144 The name is rebound if it was already bound. This may cause the reference
145 count for the object previously bound to the name to reach zero, causing the
146 object to be deallocated and its destructor (if it has one) to be called.
Georg Brandl116aa622007-08-15 14:28:22 +0000147
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000148 .. index:: single: destructor
149
150 The name is rebound if it was already bound. This may cause the reference count
151 for the object previously bound to the name to reach zero, causing the object to
152 be deallocated and its destructor (if it has one) to be called.
153
154* If the target is a target list enclosed in parentheses or in square brackets:
155 The object must be a sequence with the same number of items as there are targets
156 in the target list, and its items are assigned, from left to right, to the
157 corresponding targets.
158
159 .. index:: pair: attribute; assignment
160
Georg Brandl116aa622007-08-15 14:28:22 +0000161* If the target is an attribute reference: The primary expression in the
162 reference is evaluated. It should yield an object with assignable attributes;
Georg Brandl02c30562007-09-07 17:52:53 +0000163 if this is not the case, :exc:`TypeError` is raised. That object is then
164 asked to assign the assigned object to the given attribute; if it cannot
165 perform the assignment, it raises an exception (usually but not necessarily
Georg Brandl116aa622007-08-15 14:28:22 +0000166 :exc:`AttributeError`).
167
168 .. index::
169 pair: subscription; assignment
170 object: mutable
171
172* If the target is a subscription: The primary expression in the reference is
Georg Brandl02c30562007-09-07 17:52:53 +0000173 evaluated. It should yield either a mutable sequence object (such as a list)
174 or a mapping object (such as a dictionary). Next, the subscript expression is
Georg Brandl116aa622007-08-15 14:28:22 +0000175 evaluated.
176
177 .. index::
178 object: sequence
179 object: list
180
Georg Brandl02c30562007-09-07 17:52:53 +0000181 If the primary is a mutable sequence object (such as a list), the subscript
182 must yield an integer. If it is negative, the sequence's length is added to
183 it. The resulting value must be a nonnegative integer less than the
184 sequence's length, and the sequence is asked to assign the assigned object to
185 its item with that index. If the index is out of range, :exc:`IndexError` is
186 raised (assignment to a subscripted sequence cannot add new items to a list).
Georg Brandl116aa622007-08-15 14:28:22 +0000187
188 .. index::
189 object: mapping
190 object: dictionary
191
192 If the primary is a mapping object (such as a dictionary), the subscript must
193 have a type compatible with the mapping's key type, and the mapping is then
194 asked to create a key/datum pair which maps the subscript to the assigned
195 object. This can either replace an existing key/value pair with the same key
196 value, or insert a new key/value pair (if no key with the same value existed).
197
Georg Brandl02c30562007-09-07 17:52:53 +0000198 For user-defined objects, the :meth:`__setitem__` method is called with
199 appropriate arguments.
200
Georg Brandl116aa622007-08-15 14:28:22 +0000201 .. index:: pair: slicing; assignment
202
203* If the target is a slicing: The primary expression in the reference is
204 evaluated. It should yield a mutable sequence object (such as a list). The
205 assigned object should be a sequence object of the same type. Next, the lower
206 and upper bound expressions are evaluated, insofar they are present; defaults
Georg Brandl02c30562007-09-07 17:52:53 +0000207 are zero and the sequence's length. The bounds should evaluate to integers.
208 If either bound is negative, the sequence's length is added to it. The
209 resulting bounds are clipped to lie between zero and the sequence's length,
210 inclusive. Finally, the sequence object is asked to replace the slice with
211 the items of the assigned sequence. The length of the slice may be different
212 from the length of the assigned sequence, thus changing the length of the
213 target sequence, if the object allows it.
Georg Brandl116aa622007-08-15 14:28:22 +0000214
215(In the current implementation, the syntax for targets is taken to be the same
216as for expressions, and invalid syntax is rejected during the code generation
217phase, causing less detailed error messages.)
218
219WARNING: Although the definition of assignment implies that overlaps between the
220left-hand side and the right-hand side are 'safe' (for example ``a, b = b, a``
221swaps two variables), overlaps *within* the collection of assigned-to variables
222are not safe! For instance, the following program prints ``[0, 2]``::
223
224 x = [0, 1]
225 i = 0
226 i, x[i] = 1, 2
Georg Brandl6911e3c2007-09-04 07:15:32 +0000227 print(x)
Georg Brandl116aa622007-08-15 14:28:22 +0000228
229
Georg Brandl02c30562007-09-07 17:52:53 +0000230.. seealso::
231
232 :pep:`3132` - Extended Iterable Unpacking
233 The specification for the ``*target`` feature.
234
235
Georg Brandl116aa622007-08-15 14:28:22 +0000236.. _augassign:
237
238Augmented assignment statements
239-------------------------------
240
241.. index::
242 pair: augmented; assignment
243 single: statement; assignment, augmented
244
245Augmented assignment is the combination, in a single statement, of a binary
246operation and an assignment statement:
247
248.. productionlist::
Benjamin Petersonb58dda72009-01-18 22:27:04 +0000249 augmented_assignment_stmt: `augtarget` `augop` (`expression_list` | `yield_expression`)
250 augtarget: `identifier` | `attributeref` | `subscription` | `slicing`
Benjamin Peterson9bc93512008-09-22 22:10:59 +0000251 augop: "+=" | "-=" | "*=" | "/=" | "//=" | "%=" | "**="
Georg Brandl116aa622007-08-15 14:28:22 +0000252 : | ">>=" | "<<=" | "&=" | "^=" | "|="
253
254(See section :ref:`primaries` for the syntax definitions for the last three
255symbols.)
256
257An augmented assignment evaluates the target (which, unlike normal assignment
258statements, cannot be an unpacking) and the expression list, performs the binary
259operation specific to the type of assignment on the two operands, and assigns
260the result to the original target. The target is only evaluated once.
261
262An augmented assignment expression like ``x += 1`` can be rewritten as ``x = x +
2631`` to achieve a similar, but not exactly equal effect. In the augmented
264version, ``x`` is only evaluated once. Also, when possible, the actual operation
265is performed *in-place*, meaning that rather than creating a new object and
266assigning that to the target, the old object is modified instead.
267
268With the exception of assigning to tuples and multiple targets in a single
269statement, the assignment done by augmented assignment statements is handled the
270same way as normal assignments. Similarly, with the exception of the possible
271*in-place* behavior, the binary operation performed by augmented assignment is
272the same as the normal binary operations.
273
274For targets which are attribute references, the initial value is retrieved with
275a :meth:`getattr` and the result is assigned with a :meth:`setattr`. Notice
276that the two methods do not necessarily refer to the same variable. When
277:meth:`getattr` refers to a class variable, :meth:`setattr` still writes to an
278instance variable. For example::
279
280 class A:
281 x = 3 # class variable
282 a = A()
283 a.x += 1 # writes a.x as 4 leaving A.x as 3
284
285
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000286.. _assert:
287
288The :keyword:`assert` statement
289===============================
290
291.. index::
292 statement: assert
293 pair: debugging; assertions
294
295Assert statements are a convenient way to insert debugging assertions into a
296program:
297
298.. productionlist::
299 assert_stmt: "assert" `expression` ["," `expression`]
300
301The simple form, ``assert expression``, is equivalent to ::
302
303 if __debug__:
304 if not expression: raise AssertionError
305
306The extended form, ``assert expression1, expression2``, is equivalent to ::
307
308 if __debug__:
Georg Brandl18a499d2007-12-29 10:57:11 +0000309 if not expression1: raise AssertionError(expression2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000310
311.. index::
312 single: __debug__
313 exception: AssertionError
314
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000315These equivalences assume that :const:`__debug__` and :exc:`AssertionError` refer to
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000316the built-in variables with those names. In the current implementation, the
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000317built-in variable :const:`__debug__` is ``True`` under normal circumstances,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000318``False`` when optimization is requested (command line option -O). The current
319code generator emits no code for an assert statement when optimization is
320requested at compile time. Note that it is unnecessary to include the source
321code for the expression that failed in the error message; it will be displayed
322as part of the stack trace.
323
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000324Assignments to :const:`__debug__` are illegal. The value for the built-in variable
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000325is determined when the interpreter starts.
326
327
Georg Brandl116aa622007-08-15 14:28:22 +0000328.. _pass:
329
330The :keyword:`pass` statement
331=============================
332
Christian Heimesfaf2f632008-01-06 16:59:19 +0000333.. index::
334 statement: pass
335 pair: null; operation
Georg Brandl02c30562007-09-07 17:52:53 +0000336 pair: null; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000337
338.. productionlist::
339 pass_stmt: "pass"
340
Georg Brandl116aa622007-08-15 14:28:22 +0000341:keyword:`pass` is a null operation --- when it is executed, nothing happens.
342It is useful as a placeholder when a statement is required syntactically, but no
343code needs to be executed, for example::
344
345 def f(arg): pass # a function that does nothing (yet)
346
347 class C: pass # a class with no methods (yet)
348
349
350.. _del:
351
352The :keyword:`del` statement
353============================
354
Christian Heimesfaf2f632008-01-06 16:59:19 +0000355.. index::
356 statement: del
357 pair: deletion; target
358 triple: deletion; target; list
Georg Brandl116aa622007-08-15 14:28:22 +0000359
360.. productionlist::
361 del_stmt: "del" `target_list`
362
Georg Brandl116aa622007-08-15 14:28:22 +0000363Deletion is recursively defined very similar to the way assignment is defined.
364Rather that spelling it out in full details, here are some hints.
365
366Deletion of a target list recursively deletes each target, from left to right.
367
368.. index::
369 statement: global
370 pair: unbinding; name
371
Georg Brandl02c30562007-09-07 17:52:53 +0000372Deletion of a name removes the binding of that name from the local or global
Georg Brandl116aa622007-08-15 14:28:22 +0000373namespace, depending on whether the name occurs in a :keyword:`global` statement
374in the same code block. If the name is unbound, a :exc:`NameError` exception
375will be raised.
376
377.. index:: pair: free; variable
378
379It is illegal to delete a name from the local namespace if it occurs as a free
380variable in a nested block.
381
382.. index:: pair: attribute; deletion
383
384Deletion of attribute references, subscriptions and slicings is passed to the
385primary object involved; deletion of a slicing is in general equivalent to
386assignment of an empty slice of the right type (but even this is determined by
387the sliced object).
388
389
390.. _return:
391
392The :keyword:`return` statement
393===============================
394
Christian Heimesfaf2f632008-01-06 16:59:19 +0000395.. index::
396 statement: return
397 pair: function; definition
398 pair: class; definition
Georg Brandl116aa622007-08-15 14:28:22 +0000399
400.. productionlist::
401 return_stmt: "return" [`expression_list`]
402
Georg Brandl116aa622007-08-15 14:28:22 +0000403:keyword:`return` may only occur syntactically nested in a function definition,
404not within a nested class definition.
405
406If an expression list is present, it is evaluated, else ``None`` is substituted.
407
408:keyword:`return` leaves the current function call with the expression list (or
409``None``) as return value.
410
411.. index:: keyword: finally
412
413When :keyword:`return` passes control out of a :keyword:`try` statement with a
414:keyword:`finally` clause, that :keyword:`finally` clause is executed before
415really leaving the function.
416
417In a generator function, the :keyword:`return` statement is not allowed to
418include an :token:`expression_list`. In that context, a bare :keyword:`return`
419indicates that the generator is done and will cause :exc:`StopIteration` to be
420raised.
421
422
423.. _yield:
424
425The :keyword:`yield` statement
426==============================
427
Christian Heimesfaf2f632008-01-06 16:59:19 +0000428.. index::
429 statement: yield
430 single: generator; function
431 single: generator; iterator
432 single: function; generator
433 exception: StopIteration
434
Georg Brandl116aa622007-08-15 14:28:22 +0000435.. productionlist::
436 yield_stmt: `yield_expression`
437
Christian Heimesfaf2f632008-01-06 16:59:19 +0000438The :keyword:`yield` statement is only used when defining a generator function,
439and is only used in the body of the generator function. Using a :keyword:`yield`
440statement in a function definition is sufficient to cause that definition to
441create a generator function instead of a normal function.
Christian Heimes33fe8092008-04-13 13:53:33 +0000442When a generator function is called, it returns an iterator known as a generator
443iterator, or more commonly, a generator. The body of the generator function is
Georg Brandl6520d822009-02-05 11:01:54 +0000444executed by calling the :func:`next` function on the generator repeatedly until
445it raises an exception.
Christian Heimes33fe8092008-04-13 13:53:33 +0000446
447When a :keyword:`yield` statement is executed, the state of the generator is
448frozen and the value of :token:`expression_list` is returned to :meth:`next`'s
449caller. By "frozen" we mean that all local state is retained, including the
450current bindings of local variables, the instruction pointer, and the internal
Georg Brandl6520d822009-02-05 11:01:54 +0000451evaluation stack: enough information is saved so that the next time :func:`next`
Christian Heimes33fe8092008-04-13 13:53:33 +0000452is invoked, the function can proceed exactly as if the :keyword:`yield`
453statement were just another external call.
454
Georg Brandle6bcc912008-05-12 18:05:20 +0000455The :keyword:`yield` statement is allowed in the :keyword:`try` clause of a
456:keyword:`try` ... :keyword:`finally` construct. If the generator is not
457resumed before it is finalized (by reaching a zero reference count or by being
458garbage collected), the generator-iterator's :meth:`close` method will be
459called, allowing any pending :keyword:`finally` clauses to execute.
Christian Heimes33fe8092008-04-13 13:53:33 +0000460
461.. seealso::
462
463 :pep:`0255` - Simple Generators
464 The proposal for adding generators and the :keyword:`yield` statement to Python.
465
466 :pep:`0342` - Coroutines via Enhanced Generators
467 The proposal that, among other generator enhancements, proposed allowing
468 :keyword:`yield` to appear inside a :keyword:`try` ... :keyword:`finally` block.
469
Georg Brandl116aa622007-08-15 14:28:22 +0000470
471.. _raise:
472
473The :keyword:`raise` statement
474==============================
475
Christian Heimesfaf2f632008-01-06 16:59:19 +0000476.. index::
477 statement: raise
478 single: exception
479 pair: raising; exception
Georg Brandl1aea30a2008-07-19 15:51:07 +0000480 single: __traceback__ (exception attribute)
Georg Brandl116aa622007-08-15 14:28:22 +0000481
482.. productionlist::
Georg Brandle06de8b2008-05-05 21:42:51 +0000483 raise_stmt: "raise" [`expression` ["from" `expression`]]
Georg Brandl116aa622007-08-15 14:28:22 +0000484
485If no expressions are present, :keyword:`raise` re-raises the last exception
486that was active in the current scope. If no exception is active in the current
487scope, a :exc:`TypeError` exception is raised indicating that this is an error
Alexandre Vassalottif260e442008-05-11 19:59:59 +0000488(if running under IDLE, a :exc:`queue.Empty` exception is raised instead).
Georg Brandl116aa622007-08-15 14:28:22 +0000489
Georg Brandl02c30562007-09-07 17:52:53 +0000490Otherwise, :keyword:`raise` evaluates the first expression as the exception
491object. It must be either a subclass or an instance of :class:`BaseException`.
492If it is a class, the exception instance will be obtained when needed by
493instantiating the class with no arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000494
Georg Brandl02c30562007-09-07 17:52:53 +0000495The :dfn:`type` of the exception is the exception instance's class, the
496:dfn:`value` is the instance itself.
Georg Brandl116aa622007-08-15 14:28:22 +0000497
498.. index:: object: traceback
499
Georg Brandl02c30562007-09-07 17:52:53 +0000500A traceback object is normally created automatically when an exception is raised
Georg Brandle06de8b2008-05-05 21:42:51 +0000501and attached to it as the :attr:`__traceback__` attribute, which is writable.
502You can create an exception and set your own traceback in one step using the
503:meth:`with_traceback` exception method (which returns the same exception
504instance, with its traceback set to its argument), like so::
Georg Brandl02c30562007-09-07 17:52:53 +0000505
Benjamin Petersonb7851692009-02-16 16:15:34 +0000506 raise Exception("foo occurred").with_traceback(tracebackobj)
Georg Brandl02c30562007-09-07 17:52:53 +0000507
Georg Brandl1aea30a2008-07-19 15:51:07 +0000508.. index:: pair: exception; chaining
509 __cause__ (exception attribute)
510 __context__ (exception attribute)
Georg Brandl48310cd2009-01-03 21:18:54 +0000511
Georg Brandl1aea30a2008-07-19 15:51:07 +0000512The ``from`` clause is used for exception chaining: if given, the second
513*expression* must be another exception class or instance, which will then be
514attached to the raised exception as the :attr:`__cause__` attribute (which is
515writable). If the raised exception is not handled, both exceptions will be
516printed::
Georg Brandl02c30562007-09-07 17:52:53 +0000517
Georg Brandl1aea30a2008-07-19 15:51:07 +0000518 >>> try:
519 ... print(1 / 0)
520 ... except Exception as exc:
521 ... raise RuntimeError("Something bad happened") from exc
522 ...
523 Traceback (most recent call last):
524 File "<stdin>", line 2, in <module>
525 ZeroDivisionError: int division or modulo by zero
526
527 The above exception was the direct cause of the following exception:
528
529 Traceback (most recent call last):
530 File "<stdin>", line 4, in <module>
531 RuntimeError: Something bad happened
532
533A similar mechanism works implicitly if an exception is raised inside an
534exception handler: the previous exception is then attached as the new
535exception's :attr:`__context__` attribute::
536
537 >>> try:
538 ... print(1 / 0)
539 ... except:
540 ... raise RuntimeError("Something bad happened")
541 ...
542 Traceback (most recent call last):
543 File "<stdin>", line 2, in <module>
544 ZeroDivisionError: int division or modulo by zero
545
546 During handling of the above exception, another exception occurred:
547
548 Traceback (most recent call last):
549 File "<stdin>", line 4, in <module>
550 RuntimeError: Something bad happened
Georg Brandl116aa622007-08-15 14:28:22 +0000551
552Additional information on exceptions can be found in section :ref:`exceptions`,
553and information about handling exceptions is in section :ref:`try`.
554
555
556.. _break:
557
558The :keyword:`break` statement
559==============================
560
Christian Heimesfaf2f632008-01-06 16:59:19 +0000561.. index::
562 statement: break
563 statement: for
564 statement: while
565 pair: loop; statement
Georg Brandl116aa622007-08-15 14:28:22 +0000566
567.. productionlist::
568 break_stmt: "break"
569
Georg Brandl116aa622007-08-15 14:28:22 +0000570:keyword:`break` may only occur syntactically nested in a :keyword:`for` or
571:keyword:`while` loop, but not nested in a function or class definition within
572that loop.
573
574.. index:: keyword: else
Georg Brandl02c30562007-09-07 17:52:53 +0000575 pair: loop control; target
Georg Brandl116aa622007-08-15 14:28:22 +0000576
577It terminates the nearest enclosing loop, skipping the optional :keyword:`else`
578clause if the loop has one.
579
Georg Brandl116aa622007-08-15 14:28:22 +0000580If a :keyword:`for` loop is terminated by :keyword:`break`, the loop control
581target keeps its current value.
582
583.. index:: keyword: finally
584
585When :keyword:`break` passes control out of a :keyword:`try` statement with a
586:keyword:`finally` clause, that :keyword:`finally` clause is executed before
587really leaving the loop.
588
589
590.. _continue:
591
592The :keyword:`continue` statement
593=================================
594
Christian Heimesfaf2f632008-01-06 16:59:19 +0000595.. index::
596 statement: continue
597 statement: for
598 statement: while
599 pair: loop; statement
600 keyword: finally
Georg Brandl116aa622007-08-15 14:28:22 +0000601
602.. productionlist::
603 continue_stmt: "continue"
604
Georg Brandl116aa622007-08-15 14:28:22 +0000605:keyword:`continue` may only occur syntactically nested in a :keyword:`for` or
606:keyword:`while` loop, but not nested in a function or class definition or
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000607:keyword:`finally` clause within that loop. It continues with the next
Georg Brandl116aa622007-08-15 14:28:22 +0000608cycle of the nearest enclosing loop.
609
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000610When :keyword:`continue` passes control out of a :keyword:`try` statement with a
611:keyword:`finally` clause, that :keyword:`finally` clause is executed before
612really starting the next loop cycle.
613
Georg Brandl116aa622007-08-15 14:28:22 +0000614
615.. _import:
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000616.. _from:
Georg Brandl116aa622007-08-15 14:28:22 +0000617
618The :keyword:`import` statement
619===============================
620
621.. index::
622 statement: import
623 single: module; importing
624 pair: name; binding
625 keyword: from
626
627.. productionlist::
628 import_stmt: "import" `module` ["as" `name`] ( "," `module` ["as" `name`] )*
629 : | "from" `relative_module` "import" `identifier` ["as" `name`]
630 : ( "," `identifier` ["as" `name`] )*
631 : | "from" `relative_module` "import" "(" `identifier` ["as" `name`]
632 : ( "," `identifier` ["as" `name`] )* [","] ")"
633 : | "from" `module` "import" "*"
634 module: (`identifier` ".")* `identifier`
635 relative_module: "."* `module` | "."+
636 name: `identifier`
637
638Import statements are executed in two steps: (1) find a module, and initialize
639it if necessary; (2) define a name or names in the local namespace (of the scope
Georg Brandl02c30562007-09-07 17:52:53 +0000640where the :keyword:`import` statement occurs). The first form (without
Georg Brandl116aa622007-08-15 14:28:22 +0000641:keyword:`from`) repeats these steps for each identifier in the list. The form
642with :keyword:`from` performs step (1) once, and then performs step (2)
643repeatedly.
644
645In this context, to "initialize" a built-in or extension module means to call an
646initialization function that the module must provide for the purpose (in the
647reference implementation, the function's name is obtained by prepending string
648"init" to the module's name); to "initialize" a Python-coded module means to
649execute the module's body.
650
651.. index::
652 single: modules (in module sys)
653 single: sys.modules
654 pair: module; name
655 pair: built-in; module
656 pair: user-defined; module
Georg Brandl116aa622007-08-15 14:28:22 +0000657 pair: filename; extension
658 triple: module; search; path
Georg Brandl02c30562007-09-07 17:52:53 +0000659 module: sys
Georg Brandl116aa622007-08-15 14:28:22 +0000660
661The system maintains a table of modules that have been or are being initialized,
662indexed by module name. This table is accessible as ``sys.modules``. When a
663module name is found in this table, step (1) is finished. If not, a search for
664a module definition is started. When a module is found, it is loaded. Details
665of the module searching and loading process are implementation and platform
666specific. It generally involves searching for a "built-in" module with the
667given name and then searching a list of locations given as ``sys.path``.
668
669.. index::
670 pair: module; initialization
671 exception: ImportError
672 single: code block
673 exception: SyntaxError
674
675If a built-in module is found, its built-in initialization code is executed and
676step (1) is finished. If no matching file is found, :exc:`ImportError` is
677raised. If a file is found, it is parsed, yielding an executable code block. If
678a syntax error occurs, :exc:`SyntaxError` is raised. Otherwise, an empty module
679of the given name is created and inserted in the module table, and then the code
680block is executed in the context of this module. Exceptions during this
681execution terminate step (1).
682
683When step (1) finishes without raising an exception, step (2) can begin.
684
685The first form of :keyword:`import` statement binds the module name in the local
686namespace to the module object, and then goes on to import the next identifier,
687if any. If the module name is followed by :keyword:`as`, the name following
688:keyword:`as` is used as the local name for the module.
689
690.. index::
691 pair: name; binding
692 exception: ImportError
693
694The :keyword:`from` form does not bind the module name: it goes through the list
695of identifiers, looks each one of them up in the module found in step (1), and
696binds the name in the local namespace to the object thus found. As with the
697first form of :keyword:`import`, an alternate local name can be supplied by
698specifying ":keyword:`as` localname". If a name is not found,
699:exc:`ImportError` is raised. If the list of identifiers is replaced by a star
700(``'*'``), all public names defined in the module are bound in the local
701namespace of the :keyword:`import` statement..
702
703.. index:: single: __all__ (optional module attribute)
704
705The *public names* defined by a module are determined by checking the module's
706namespace for a variable named ``__all__``; if defined, it must be a sequence of
707strings which are names defined or imported by that module. The names given in
708``__all__`` are all considered public and are required to exist. If ``__all__``
709is not defined, the set of public names includes all names found in the module's
710namespace which do not begin with an underscore character (``'_'``).
711``__all__`` should contain the entire public API. It is intended to avoid
712accidentally exporting items that are not part of the API (such as library
713modules which were imported and used within the module).
714
715The :keyword:`from` form with ``*`` may only occur in a module scope. If the
716wild card form of import --- ``import *`` --- is used in a function and the
717function contains or is a nested block with free variables, the compiler will
718raise a :exc:`SyntaxError`.
719
720.. index::
721 keyword: from
Christian Heimesfaf2f632008-01-06 16:59:19 +0000722 statement: from
Georg Brandl116aa622007-08-15 14:28:22 +0000723 triple: hierarchical; module; names
724 single: packages
725 single: __init__.py
726
727**Hierarchical module names:** when the module names contains one or more dots,
728the module search path is carried out differently. The sequence of identifiers
729up to the last dot is used to find a "package"; the final identifier is then
730searched inside the package. A package is generally a subdirectory of a
Georg Brandl5b318c02008-08-03 09:47:27 +0000731directory on ``sys.path`` that has a file :file:`__init__.py`.
732
Georg Brandl48310cd2009-01-03 21:18:54 +0000733..
Georg Brandl5b318c02008-08-03 09:47:27 +0000734 [XXX Can't be
735 bothered to spell this out right now; see the URL
736 http://www.python.org/doc/essays/packages.html for more details, also about how
737 the module search works from inside a package.]
Georg Brandl116aa622007-08-15 14:28:22 +0000738
Georg Brandl116aa622007-08-15 14:28:22 +0000739.. index:: builtin: __import__
740
741The built-in function :func:`__import__` is provided to support applications
742that determine which modules need to be loaded dynamically; refer to
743:ref:`built-in-funcs` for additional information.
744
745
746.. _future:
747
748Future statements
749-----------------
750
751.. index:: pair: future; statement
752
753A :dfn:`future statement` is a directive to the compiler that a particular
754module should be compiled using syntax or semantics that will be available in a
755specified future release of Python. The future statement is intended to ease
756migration to future versions of Python that introduce incompatible changes to
757the language. It allows use of the new features on a per-module basis before
758the release in which the feature becomes standard.
759
760.. productionlist:: *
761 future_statement: "from" "__future__" "import" feature ["as" name]
762 : ("," feature ["as" name])*
763 : | "from" "__future__" "import" "(" feature ["as" name]
764 : ("," feature ["as" name])* [","] ")"
765 feature: identifier
766 name: identifier
767
768A future statement must appear near the top of the module. The only lines that
769can appear before a future statement are:
770
771* the module docstring (if any),
772* comments,
773* blank lines, and
774* other future statements.
775
Georg Brandl02c30562007-09-07 17:52:53 +0000776.. XXX change this if future is cleaned out
777
778The features recognized by Python 3.0 are ``absolute_import``, ``division``,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000779``generators``, ``unicode_literals``, ``print_function``, ``nested_scopes`` and
780``with_statement``. They are all redundant because they are always enabled, and
781only kept for backwards compatibility.
Georg Brandl116aa622007-08-15 14:28:22 +0000782
783A future statement is recognized and treated specially at compile time: Changes
784to the semantics of core constructs are often implemented by generating
785different code. It may even be the case that a new feature introduces new
786incompatible syntax (such as a new reserved word), in which case the compiler
787may need to parse the module differently. Such decisions cannot be pushed off
788until runtime.
789
790For any given release, the compiler knows which feature names have been defined,
791and raises a compile-time error if a future statement contains a feature not
792known to it.
793
794The direct runtime semantics are the same as for any import statement: there is
795a standard module :mod:`__future__`, described later, and it will be imported in
796the usual way at the time the future statement is executed.
797
798The interesting runtime semantics depend on the specific feature enabled by the
799future statement.
800
801Note that there is nothing special about the statement::
802
803 import __future__ [as name]
804
805That is not a future statement; it's an ordinary import statement with no
806special semantics or syntax restrictions.
807
808Code compiled by calls to the builtin functions :func:`exec` and :func:`compile`
Georg Brandl02c30562007-09-07 17:52:53 +0000809that occur in a module :mod:`M` containing a future statement will, by default,
810use the new syntax or semantics associated with the future statement. This can
811be controlled by optional arguments to :func:`compile` --- see the documentation
812of that function for details.
Georg Brandl116aa622007-08-15 14:28:22 +0000813
814A future statement typed at an interactive interpreter prompt will take effect
815for the rest of the interpreter session. If an interpreter is started with the
816:option:`-i` option, is passed a script name to execute, and the script includes
817a future statement, it will be in effect in the interactive session started
818after the script is executed.
819
820
821.. _global:
822
823The :keyword:`global` statement
824===============================
825
Christian Heimesfaf2f632008-01-06 16:59:19 +0000826.. index::
827 statement: global
828 triple: global; name; binding
Georg Brandl116aa622007-08-15 14:28:22 +0000829
830.. productionlist::
831 global_stmt: "global" `identifier` ("," `identifier`)*
832
Georg Brandl116aa622007-08-15 14:28:22 +0000833The :keyword:`global` statement is a declaration which holds for the entire
834current code block. It means that the listed identifiers are to be interpreted
835as globals. It would be impossible to assign to a global variable without
836:keyword:`global`, although free variables may refer to globals without being
837declared global.
838
839Names listed in a :keyword:`global` statement must not be used in the same code
840block textually preceding that :keyword:`global` statement.
841
842Names listed in a :keyword:`global` statement must not be defined as formal
843parameters or in a :keyword:`for` loop control target, :keyword:`class`
844definition, function definition, or :keyword:`import` statement.
845
846(The current implementation does not enforce the latter two restrictions, but
847programs should not abuse this freedom, as future implementations may enforce
848them or silently change the meaning of the program.)
849
850.. index::
851 builtin: exec
852 builtin: eval
853 builtin: compile
854
855**Programmer's note:** the :keyword:`global` is a directive to the parser. It
856applies only to code parsed at the same time as the :keyword:`global` statement.
857In particular, a :keyword:`global` statement contained in a string or code
858object supplied to the builtin :func:`exec` function does not affect the code
859block *containing* the function call, and code contained in such a string is
860unaffected by :keyword:`global` statements in the code containing the function
861call. The same applies to the :func:`eval` and :func:`compile` functions.
862
Georg Brandl02c30562007-09-07 17:52:53 +0000863
864.. _nonlocal:
865
866The :keyword:`nonlocal` statement
867=================================
868
869.. index:: statement: nonlocal
870
871.. productionlist::
872 nonlocal_stmt: "nonlocal" `identifier` ("," `identifier`)*
873
Georg Brandlc5d98b42007-12-04 18:11:03 +0000874.. XXX add when implemented
Georg Brandl06788c92009-01-03 21:31:47 +0000875 : ["=" (`target_list` "=")+ expression_list]
876 : | "nonlocal" identifier augop expression_list
Georg Brandlc5d98b42007-12-04 18:11:03 +0000877
Georg Brandl48310cd2009-01-03 21:18:54 +0000878The :keyword:`nonlocal` statement causes the listed identifiers to refer to
879previously bound variables in the nearest enclosing scope. This is important
880because the default behavior for binding is to search the local namespace
Georg Brandlc5d98b42007-12-04 18:11:03 +0000881first. The statement allows encapsulated code to rebind variables outside of
882the local scope besides the global (module) scope.
883
Georg Brandlc5d98b42007-12-04 18:11:03 +0000884.. XXX not implemented
885 The :keyword:`nonlocal` statement may prepend an assignment or augmented
886 assignment, but not an expression.
887
888Names listed in a :keyword:`nonlocal` statement, unlike to those listed in a
889:keyword:`global` statement, must refer to pre-existing bindings in an
890enclosing scope (the scope in which a new binding should be created cannot
891be determined unambiguously).
892
Georg Brandl48310cd2009-01-03 21:18:54 +0000893Names listed in a :keyword:`nonlocal` statement must not collide with
Georg Brandlc5d98b42007-12-04 18:11:03 +0000894pre-existing bindings in the local scope.
895
896.. seealso::
897
898 :pep:`3104` - Access to Names in Outer Scopes
899 The specification for the :keyword:`nonlocal` statement.
Georg Brandl02c30562007-09-07 17:52:53 +0000900
901
Georg Brandl116aa622007-08-15 14:28:22 +0000902.. rubric:: Footnotes
903
904.. [#] It may occur within an :keyword:`except` or :keyword:`else` clause. The
Georg Brandlc5d98b42007-12-04 18:11:03 +0000905 restriction on occurring in the :keyword:`try` clause is implementor's
906 laziness and will eventually be lifted.