blob: 531d69a90be3ff18b6e299b98df9d0678834423e [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
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000149 .. index:: single: destructor
150
151 The name is rebound if it was already bound. This may cause the reference count
152 for the object previously bound to the name to reach zero, causing the object to
153 be deallocated and its destructor (if it has one) to be called.
154
155* If the target is a target list enclosed in parentheses or in square brackets:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000156 The object must be an iterable with the same number of items as there are
157 targets in the target list, and its items are assigned, from left to right,
158 to the corresponding targets.
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000159
160 .. index:: pair: attribute; assignment
161
Georg Brandl116aa622007-08-15 14:28:22 +0000162* If the target is an attribute reference: The primary expression in the
163 reference is evaluated. It should yield an object with assignable attributes;
Georg Brandl02c30562007-09-07 17:52:53 +0000164 if this is not the case, :exc:`TypeError` is raised. That object is then
165 asked to assign the assigned object to the given attribute; if it cannot
166 perform the assignment, it raises an exception (usually but not necessarily
Georg Brandl116aa622007-08-15 14:28:22 +0000167 :exc:`AttributeError`).
168
Georg Brandlb044b2a2009-09-16 16:05:59 +0000169 .. _attr-target-note:
170
171 Note: If the object is a class instance and the attribute reference occurs on
172 both sides of the assignment operator, the RHS expression, ``a.x`` can access
173 either an instance attribute or (if no instance attribute exists) a class
174 attribute. The LHS target ``a.x`` is always set as an instance attribute,
175 creating it if necessary. Thus, the two occurrences of ``a.x`` do not
176 necessarily refer to the same attribute: if the RHS expression refers to a
177 class attribute, the LHS creates a new instance attribute as the target of the
178 assignment::
179
180 class Cls:
181 x = 3 # class variable
182 inst = Cls()
183 inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x as 3
184
185 This description does not necessarily apply to descriptor attributes, such as
186 properties created with :func:`property`.
187
Georg Brandl116aa622007-08-15 14:28:22 +0000188 .. index::
189 pair: subscription; assignment
190 object: mutable
191
192* If the target is a subscription: The primary expression in the reference is
Georg Brandl02c30562007-09-07 17:52:53 +0000193 evaluated. It should yield either a mutable sequence object (such as a list)
194 or a mapping object (such as a dictionary). Next, the subscript expression is
Georg Brandl116aa622007-08-15 14:28:22 +0000195 evaluated.
196
197 .. index::
198 object: sequence
199 object: list
200
Georg Brandl02c30562007-09-07 17:52:53 +0000201 If the primary is a mutable sequence object (such as a list), the subscript
202 must yield an integer. If it is negative, the sequence's length is added to
203 it. The resulting value must be a nonnegative integer less than the
204 sequence's length, and the sequence is asked to assign the assigned object to
205 its item with that index. If the index is out of range, :exc:`IndexError` is
206 raised (assignment to a subscripted sequence cannot add new items to a list).
Georg Brandl116aa622007-08-15 14:28:22 +0000207
208 .. index::
209 object: mapping
210 object: dictionary
211
212 If the primary is a mapping object (such as a dictionary), the subscript must
213 have a type compatible with the mapping's key type, and the mapping is then
214 asked to create a key/datum pair which maps the subscript to the assigned
215 object. This can either replace an existing key/value pair with the same key
216 value, or insert a new key/value pair (if no key with the same value existed).
217
Georg Brandl02c30562007-09-07 17:52:53 +0000218 For user-defined objects, the :meth:`__setitem__` method is called with
219 appropriate arguments.
220
Georg Brandl116aa622007-08-15 14:28:22 +0000221 .. index:: pair: slicing; assignment
222
223* If the target is a slicing: The primary expression in the reference is
224 evaluated. It should yield a mutable sequence object (such as a list). The
225 assigned object should be a sequence object of the same type. Next, the lower
226 and upper bound expressions are evaluated, insofar they are present; defaults
Georg Brandl02c30562007-09-07 17:52:53 +0000227 are zero and the sequence's length. The bounds should evaluate to integers.
228 If either bound is negative, the sequence's length is added to it. The
229 resulting bounds are clipped to lie between zero and the sequence's length,
230 inclusive. Finally, the sequence object is asked to replace the slice with
231 the items of the assigned sequence. The length of the slice may be different
232 from the length of the assigned sequence, thus changing the length of the
233 target sequence, if the object allows it.
Georg Brandl116aa622007-08-15 14:28:22 +0000234
Georg Brandl628e6f92009-10-27 20:24:45 +0000235.. impl-detail::
236
237 In the current implementation, the syntax for targets is taken to be the same
238 as for expressions, and invalid syntax is rejected during the code generation
239 phase, causing less detailed error messages.
Georg Brandl116aa622007-08-15 14:28:22 +0000240
241WARNING: Although the definition of assignment implies that overlaps between the
242left-hand side and the right-hand side are 'safe' (for example ``a, b = b, a``
243swaps two variables), overlaps *within* the collection of assigned-to variables
244are not safe! For instance, the following program prints ``[0, 2]``::
245
246 x = [0, 1]
247 i = 0
248 i, x[i] = 1, 2
Georg Brandl6911e3c2007-09-04 07:15:32 +0000249 print(x)
Georg Brandl116aa622007-08-15 14:28:22 +0000250
251
Georg Brandl02c30562007-09-07 17:52:53 +0000252.. seealso::
253
254 :pep:`3132` - Extended Iterable Unpacking
255 The specification for the ``*target`` feature.
256
257
Georg Brandl116aa622007-08-15 14:28:22 +0000258.. _augassign:
259
260Augmented assignment statements
261-------------------------------
262
263.. index::
264 pair: augmented; assignment
265 single: statement; assignment, augmented
266
267Augmented assignment is the combination, in a single statement, of a binary
268operation and an assignment statement:
269
270.. productionlist::
Benjamin Petersonb58dda72009-01-18 22:27:04 +0000271 augmented_assignment_stmt: `augtarget` `augop` (`expression_list` | `yield_expression`)
272 augtarget: `identifier` | `attributeref` | `subscription` | `slicing`
Benjamin Peterson9bc93512008-09-22 22:10:59 +0000273 augop: "+=" | "-=" | "*=" | "/=" | "//=" | "%=" | "**="
Georg Brandl116aa622007-08-15 14:28:22 +0000274 : | ">>=" | "<<=" | "&=" | "^=" | "|="
275
276(See section :ref:`primaries` for the syntax definitions for the last three
277symbols.)
278
279An augmented assignment evaluates the target (which, unlike normal assignment
280statements, cannot be an unpacking) and the expression list, performs the binary
281operation specific to the type of assignment on the two operands, and assigns
282the result to the original target. The target is only evaluated once.
283
284An augmented assignment expression like ``x += 1`` can be rewritten as ``x = x +
2851`` to achieve a similar, but not exactly equal effect. In the augmented
286version, ``x`` is only evaluated once. Also, when possible, the actual operation
287is performed *in-place*, meaning that rather than creating a new object and
288assigning that to the target, the old object is modified instead.
289
290With the exception of assigning to tuples and multiple targets in a single
291statement, the assignment done by augmented assignment statements is handled the
292same way as normal assignments. Similarly, with the exception of the possible
293*in-place* behavior, the binary operation performed by augmented assignment is
294the same as the normal binary operations.
295
Georg Brandlb044b2a2009-09-16 16:05:59 +0000296For targets which are attribute references, the same :ref:`caveat about class
297and instance attributes <attr-target-note>` applies as for regular assignments.
Georg Brandl116aa622007-08-15 14:28:22 +0000298
299
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000300.. _assert:
301
302The :keyword:`assert` statement
303===============================
304
305.. index::
306 statement: assert
307 pair: debugging; assertions
308
309Assert statements are a convenient way to insert debugging assertions into a
310program:
311
312.. productionlist::
313 assert_stmt: "assert" `expression` ["," `expression`]
314
315The simple form, ``assert expression``, is equivalent to ::
316
317 if __debug__:
318 if not expression: raise AssertionError
319
320The extended form, ``assert expression1, expression2``, is equivalent to ::
321
322 if __debug__:
Georg Brandl18a499d2007-12-29 10:57:11 +0000323 if not expression1: raise AssertionError(expression2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000324
325.. index::
326 single: __debug__
327 exception: AssertionError
328
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000329These equivalences assume that :const:`__debug__` and :exc:`AssertionError` refer to
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000330the built-in variables with those names. In the current implementation, the
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000331built-in variable :const:`__debug__` is ``True`` under normal circumstances,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000332``False`` when optimization is requested (command line option -O). The current
333code generator emits no code for an assert statement when optimization is
334requested at compile time. Note that it is unnecessary to include the source
335code for the expression that failed in the error message; it will be displayed
336as part of the stack trace.
337
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000338Assignments to :const:`__debug__` are illegal. The value for the built-in variable
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000339is determined when the interpreter starts.
340
341
Georg Brandl116aa622007-08-15 14:28:22 +0000342.. _pass:
343
344The :keyword:`pass` statement
345=============================
346
Christian Heimesfaf2f632008-01-06 16:59:19 +0000347.. index::
348 statement: pass
349 pair: null; operation
Georg Brandl02c30562007-09-07 17:52:53 +0000350 pair: null; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000351
352.. productionlist::
353 pass_stmt: "pass"
354
Georg Brandl116aa622007-08-15 14:28:22 +0000355:keyword:`pass` is a null operation --- when it is executed, nothing happens.
356It is useful as a placeholder when a statement is required syntactically, but no
357code needs to be executed, for example::
358
359 def f(arg): pass # a function that does nothing (yet)
360
361 class C: pass # a class with no methods (yet)
362
363
364.. _del:
365
366The :keyword:`del` statement
367============================
368
Christian Heimesfaf2f632008-01-06 16:59:19 +0000369.. index::
370 statement: del
371 pair: deletion; target
372 triple: deletion; target; list
Georg Brandl116aa622007-08-15 14:28:22 +0000373
374.. productionlist::
375 del_stmt: "del" `target_list`
376
Georg Brandl116aa622007-08-15 14:28:22 +0000377Deletion is recursively defined very similar to the way assignment is defined.
378Rather that spelling it out in full details, here are some hints.
379
380Deletion of a target list recursively deletes each target, from left to right.
381
382.. index::
383 statement: global
384 pair: unbinding; name
385
Georg Brandl02c30562007-09-07 17:52:53 +0000386Deletion of a name removes the binding of that name from the local or global
Georg Brandl116aa622007-08-15 14:28:22 +0000387namespace, depending on whether the name occurs in a :keyword:`global` statement
388in the same code block. If the name is unbound, a :exc:`NameError` exception
389will be raised.
390
391.. index:: pair: free; variable
392
393It is illegal to delete a name from the local namespace if it occurs as a free
394variable in a nested block.
395
396.. index:: pair: attribute; deletion
397
398Deletion of attribute references, subscriptions and slicings is passed to the
399primary object involved; deletion of a slicing is in general equivalent to
400assignment of an empty slice of the right type (but even this is determined by
401the sliced object).
402
403
404.. _return:
405
406The :keyword:`return` statement
407===============================
408
Christian Heimesfaf2f632008-01-06 16:59:19 +0000409.. index::
410 statement: return
411 pair: function; definition
412 pair: class; definition
Georg Brandl116aa622007-08-15 14:28:22 +0000413
414.. productionlist::
415 return_stmt: "return" [`expression_list`]
416
Georg Brandl116aa622007-08-15 14:28:22 +0000417:keyword:`return` may only occur syntactically nested in a function definition,
418not within a nested class definition.
419
420If an expression list is present, it is evaluated, else ``None`` is substituted.
421
422:keyword:`return` leaves the current function call with the expression list (or
423``None``) as return value.
424
425.. index:: keyword: finally
426
427When :keyword:`return` passes control out of a :keyword:`try` statement with a
428:keyword:`finally` clause, that :keyword:`finally` clause is executed before
429really leaving the function.
430
431In a generator function, the :keyword:`return` statement is not allowed to
432include an :token:`expression_list`. In that context, a bare :keyword:`return`
433indicates that the generator is done and will cause :exc:`StopIteration` to be
434raised.
435
436
437.. _yield:
438
439The :keyword:`yield` statement
440==============================
441
Christian Heimesfaf2f632008-01-06 16:59:19 +0000442.. index::
443 statement: yield
444 single: generator; function
445 single: generator; iterator
446 single: function; generator
447 exception: StopIteration
448
Georg Brandl116aa622007-08-15 14:28:22 +0000449.. productionlist::
450 yield_stmt: `yield_expression`
451
Christian Heimesfaf2f632008-01-06 16:59:19 +0000452The :keyword:`yield` statement is only used when defining a generator function,
453and is only used in the body of the generator function. Using a :keyword:`yield`
454statement in a function definition is sufficient to cause that definition to
455create a generator function instead of a normal function.
Christian Heimes33fe8092008-04-13 13:53:33 +0000456When a generator function is called, it returns an iterator known as a generator
457iterator, or more commonly, a generator. The body of the generator function is
Georg Brandl6520d822009-02-05 11:01:54 +0000458executed by calling the :func:`next` function on the generator repeatedly until
459it raises an exception.
Christian Heimes33fe8092008-04-13 13:53:33 +0000460
461When a :keyword:`yield` statement is executed, the state of the generator is
462frozen and the value of :token:`expression_list` is returned to :meth:`next`'s
463caller. By "frozen" we mean that all local state is retained, including the
464current bindings of local variables, the instruction pointer, and the internal
Georg Brandl6520d822009-02-05 11:01:54 +0000465evaluation stack: enough information is saved so that the next time :func:`next`
Christian Heimes33fe8092008-04-13 13:53:33 +0000466is invoked, the function can proceed exactly as if the :keyword:`yield`
467statement were just another external call.
468
Georg Brandle6bcc912008-05-12 18:05:20 +0000469The :keyword:`yield` statement is allowed in the :keyword:`try` clause of a
470:keyword:`try` ... :keyword:`finally` construct. If the generator is not
471resumed before it is finalized (by reaching a zero reference count or by being
472garbage collected), the generator-iterator's :meth:`close` method will be
473called, allowing any pending :keyword:`finally` clauses to execute.
Christian Heimes33fe8092008-04-13 13:53:33 +0000474
475.. seealso::
476
477 :pep:`0255` - Simple Generators
478 The proposal for adding generators and the :keyword:`yield` statement to Python.
479
480 :pep:`0342` - Coroutines via Enhanced Generators
481 The proposal that, among other generator enhancements, proposed allowing
482 :keyword:`yield` to appear inside a :keyword:`try` ... :keyword:`finally` block.
483
Georg Brandl116aa622007-08-15 14:28:22 +0000484
485.. _raise:
486
487The :keyword:`raise` statement
488==============================
489
Christian Heimesfaf2f632008-01-06 16:59:19 +0000490.. index::
491 statement: raise
492 single: exception
493 pair: raising; exception
Georg Brandl1aea30a2008-07-19 15:51:07 +0000494 single: __traceback__ (exception attribute)
Georg Brandl116aa622007-08-15 14:28:22 +0000495
496.. productionlist::
Georg Brandle06de8b2008-05-05 21:42:51 +0000497 raise_stmt: "raise" [`expression` ["from" `expression`]]
Georg Brandl116aa622007-08-15 14:28:22 +0000498
499If no expressions are present, :keyword:`raise` re-raises the last exception
500that was active in the current scope. If no exception is active in the current
501scope, a :exc:`TypeError` exception is raised indicating that this is an error
Alexandre Vassalottif260e442008-05-11 19:59:59 +0000502(if running under IDLE, a :exc:`queue.Empty` exception is raised instead).
Georg Brandl116aa622007-08-15 14:28:22 +0000503
Georg Brandl02c30562007-09-07 17:52:53 +0000504Otherwise, :keyword:`raise` evaluates the first expression as the exception
505object. It must be either a subclass or an instance of :class:`BaseException`.
506If it is a class, the exception instance will be obtained when needed by
507instantiating the class with no arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000508
Georg Brandl02c30562007-09-07 17:52:53 +0000509The :dfn:`type` of the exception is the exception instance's class, the
510:dfn:`value` is the instance itself.
Georg Brandl116aa622007-08-15 14:28:22 +0000511
512.. index:: object: traceback
513
Georg Brandl02c30562007-09-07 17:52:53 +0000514A traceback object is normally created automatically when an exception is raised
Georg Brandle06de8b2008-05-05 21:42:51 +0000515and attached to it as the :attr:`__traceback__` attribute, which is writable.
516You can create an exception and set your own traceback in one step using the
517:meth:`with_traceback` exception method (which returns the same exception
518instance, with its traceback set to its argument), like so::
Georg Brandl02c30562007-09-07 17:52:53 +0000519
Benjamin Petersonb7851692009-02-16 16:15:34 +0000520 raise Exception("foo occurred").with_traceback(tracebackobj)
Georg Brandl02c30562007-09-07 17:52:53 +0000521
Georg Brandl1aea30a2008-07-19 15:51:07 +0000522.. index:: pair: exception; chaining
523 __cause__ (exception attribute)
524 __context__ (exception attribute)
Georg Brandl48310cd2009-01-03 21:18:54 +0000525
Georg Brandl1aea30a2008-07-19 15:51:07 +0000526The ``from`` clause is used for exception chaining: if given, the second
527*expression* must be another exception class or instance, which will then be
528attached to the raised exception as the :attr:`__cause__` attribute (which is
529writable). If the raised exception is not handled, both exceptions will be
530printed::
Georg Brandl02c30562007-09-07 17:52:53 +0000531
Georg Brandl1aea30a2008-07-19 15:51:07 +0000532 >>> try:
533 ... print(1 / 0)
534 ... except Exception as exc:
535 ... raise RuntimeError("Something bad happened") from exc
536 ...
537 Traceback (most recent call last):
538 File "<stdin>", line 2, in <module>
539 ZeroDivisionError: int division or modulo by zero
540
541 The above exception was the direct cause of the following exception:
542
543 Traceback (most recent call last):
544 File "<stdin>", line 4, in <module>
545 RuntimeError: Something bad happened
546
547A similar mechanism works implicitly if an exception is raised inside an
548exception handler: the previous exception is then attached as the new
549exception's :attr:`__context__` attribute::
550
551 >>> try:
552 ... print(1 / 0)
553 ... except:
554 ... raise RuntimeError("Something bad happened")
555 ...
556 Traceback (most recent call last):
557 File "<stdin>", line 2, in <module>
558 ZeroDivisionError: int division or modulo by zero
559
560 During handling of the above exception, another exception occurred:
561
562 Traceback (most recent call last):
563 File "<stdin>", line 4, in <module>
564 RuntimeError: Something bad happened
Georg Brandl116aa622007-08-15 14:28:22 +0000565
566Additional information on exceptions can be found in section :ref:`exceptions`,
567and information about handling exceptions is in section :ref:`try`.
568
569
570.. _break:
571
572The :keyword:`break` statement
573==============================
574
Christian Heimesfaf2f632008-01-06 16:59:19 +0000575.. index::
576 statement: break
577 statement: for
578 statement: while
579 pair: loop; statement
Georg Brandl116aa622007-08-15 14:28:22 +0000580
581.. productionlist::
582 break_stmt: "break"
583
Georg Brandl116aa622007-08-15 14:28:22 +0000584:keyword:`break` may only occur syntactically nested in a :keyword:`for` or
585:keyword:`while` loop, but not nested in a function or class definition within
586that loop.
587
588.. index:: keyword: else
Georg Brandl02c30562007-09-07 17:52:53 +0000589 pair: loop control; target
Georg Brandl116aa622007-08-15 14:28:22 +0000590
591It terminates the nearest enclosing loop, skipping the optional :keyword:`else`
592clause if the loop has one.
593
Georg Brandl116aa622007-08-15 14:28:22 +0000594If a :keyword:`for` loop is terminated by :keyword:`break`, the loop control
595target keeps its current value.
596
597.. index:: keyword: finally
598
599When :keyword:`break` passes control out of a :keyword:`try` statement with a
600:keyword:`finally` clause, that :keyword:`finally` clause is executed before
601really leaving the loop.
602
603
604.. _continue:
605
606The :keyword:`continue` statement
607=================================
608
Christian Heimesfaf2f632008-01-06 16:59:19 +0000609.. index::
610 statement: continue
611 statement: for
612 statement: while
613 pair: loop; statement
614 keyword: finally
Georg Brandl116aa622007-08-15 14:28:22 +0000615
616.. productionlist::
617 continue_stmt: "continue"
618
Georg Brandl116aa622007-08-15 14:28:22 +0000619:keyword:`continue` may only occur syntactically nested in a :keyword:`for` or
620:keyword:`while` loop, but not nested in a function or class definition or
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000621:keyword:`finally` clause within that loop. It continues with the next
Georg Brandl116aa622007-08-15 14:28:22 +0000622cycle of the nearest enclosing loop.
623
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000624When :keyword:`continue` passes control out of a :keyword:`try` statement with a
625:keyword:`finally` clause, that :keyword:`finally` clause is executed before
626really starting the next loop cycle.
627
Georg Brandl116aa622007-08-15 14:28:22 +0000628
629.. _import:
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000630.. _from:
Georg Brandl116aa622007-08-15 14:28:22 +0000631
632The :keyword:`import` statement
633===============================
634
635.. index::
636 statement: import
637 single: module; importing
638 pair: name; binding
639 keyword: from
640
641.. productionlist::
642 import_stmt: "import" `module` ["as" `name`] ( "," `module` ["as" `name`] )*
643 : | "from" `relative_module` "import" `identifier` ["as" `name`]
644 : ( "," `identifier` ["as" `name`] )*
645 : | "from" `relative_module` "import" "(" `identifier` ["as" `name`]
646 : ( "," `identifier` ["as" `name`] )* [","] ")"
647 : | "from" `module` "import" "*"
648 module: (`identifier` ".")* `identifier`
649 relative_module: "."* `module` | "."+
650 name: `identifier`
651
652Import statements are executed in two steps: (1) find a module, and initialize
653it if necessary; (2) define a name or names in the local namespace (of the scope
Brett Cannone43b0602009-03-21 03:11:16 +0000654where the :keyword:`import` statement occurs). The statement comes in two
655forms differing on whether it uses the :keyword:`from` keyword. The first form
656(without :keyword:`from`) repeats these steps for each identifier in the list.
657The form with :keyword:`from` performs step (1) once, and then performs step
658(2) repeatedly. For a reference implementation of step (1), see the
659:mod:`importlib` module.
Georg Brandl116aa622007-08-15 14:28:22 +0000660
661.. index::
Brett Cannone43b0602009-03-21 03:11:16 +0000662 single: package
Georg Brandl116aa622007-08-15 14:28:22 +0000663
Brett Cannone43b0602009-03-21 03:11:16 +0000664To understand how step (1) occurs, one must first understand how Python handles
665hierarchical naming of modules. To help organize modules and provide a
666hierarchy in naming, Python has a concept of packages. A package can contain
667other packages and modules while modules cannot contain other modules or
668packages. From a file system perspective, packages are directories and modules
669are files. The original `specification for packages
670<http://www.python.org/doc/essays/packages.html>`_ is still available to read,
671although minor details have changed since the writing of that document.
Georg Brandl116aa622007-08-15 14:28:22 +0000672
673.. index::
Brett Cannone43b0602009-03-21 03:11:16 +0000674 single: sys.modules
Georg Brandl116aa622007-08-15 14:28:22 +0000675
Brett Cannone43b0602009-03-21 03:11:16 +0000676Once the name of the module is known (unless otherwise specified, the term
677"module" will refer to both packages and modules), searching
678for the module or package can begin. The first place checked is
679:data:`sys.modules`, the cache of all modules that have been imported
680previously. If the module is found there then it is used in step (2) of import.
681
682.. index::
683 single: sys.meta_path
684 single: finder
685 pair: finder; find_module
686 single: __path__
687
688If the module is not found in the cache, then :data:`sys.meta_path` is searched
689(the specification for :data:`sys.meta_path` can be found in :pep:`302`).
690The object is a list of :term:`finder` objects which are queried in order as to
691whether they know how to load the module by calling their :meth:`find_module`
692method with the name of the module. If the module happens to be contained
693within a package (as denoted by the existence of a dot in the name), then a
694second argument to :meth:`find_module` is given as the value of the
695:attr:`__path__` attribute from the parent package (everything up to the last
696dot in the name of the module being imported). If a finder can find the module
697it returns a :term:`loader` (discussed later) or returns :keyword:`None`.
698
699.. index::
700 single: sys.path_hooks
701 single: sys.path_importer_cache
702 single: sys.path
703
704If none of the finders on :data:`sys.meta_path` are able to find the module
705then some implicitly defined finders are queried. Implementations of Python
706vary in what implicit meta path finders are defined. The one they all do
707define, though, is one that handles :data:`sys.path_hooks`,
708:data:`sys.path_importer_cache`, and :data:`sys.path`.
709
710The implicit finder searches for the requested module in the "paths" specified
711in one of two places ("paths" do not have to be file system paths). If the
712module being imported is supposed to be contained within a package then the
713second argument passed to :meth:`find_module`, :attr:`__path__` on the parent
714package, is used as the source of paths. If the module is not contained in a
715package then :data:`sys.path` is used as the source of paths.
716
717Once the source of paths is chosen it is iterated over to find a finder that
718can handle that path. The dict at :data:`sys.path_importer_cache` caches
719finders for paths and is checked for a finder. If the path does not have a
720finder cached then :data:`sys.path_hooks` is searched by calling each object in
721the list with a single argument of the path, returning a finder or raises
722:exc:`ImportError`. If a finder is returned then it is cached in
723:data:`sys.path_importer_cache` and then used for that path entry. If no finder
724can be found but the path exists then a value of :keyword:`None` is
725stored in :data:`sys.path_importer_cache` to signify that an implicit,
726file-based finder that handles modules stored as individual files should be
727used for that path. If the path does not exist then a finder which always
728returns :keyword:`None` is placed in the cache for the path.
729
730.. index::
731 single: loader
732 pair: loader; load_module
733 exception: ImportError
734
735If no finder can find the module then :exc:`ImportError` is raised. Otherwise
736some finder returned a loader whose :meth:`load_module` method is called with
737the name of the module to load (see :pep:`302` for the original definition of
738loaders). A loader has several responsibilities to perform on a module it
739loads. First, if the module already exists in :data:`sys.modules` (a
740possibility if the loader is called outside of the import machinery) then it
741is to use that module for initialization and not a new module. But if the
742module does not exist in :data:`sys.modules` then it is to be added to that
743dict before initialization begins. If an error occurs during loading of the
744module and it was added to :data:`sys.modules` it is to be removed from the
745dict. If an error occurs but the module was already in :data:`sys.modules` it
746is left in the dict.
747
748.. index::
749 single: __name__
750 single: __file__
751 single: __path__
752 single: __package__
753 single: __loader__
754
755The loader must set several attributes on the module. :data:`__name__` is to be
756set to the name of the module. :data:`__file__` is to be the "path" to the file
757unless the module is built-in (and thus listed in
758:data:`sys.builtin_module_names`) in which case the attribute is not set.
759If what is being imported is a package then :data:`__path__` is to be set to a
760list of paths to be searched when looking for modules and packages contained
761within the package being imported. :data:`__package__` is optional but should
762be set to the name of package that contains the module or package (the empty
763string is used for module not contained in a package). :data:`__loader__` is
764also optional but should be set to the loader object that is loading the
765module.
766
767.. index::
768 exception: ImportError
769
770If an error occurs during loading then the loader raises :exc:`ImportError` if
771some other exception is not already being propagated. Otherwise the loader
772returns the module that was loaded and initialized.
Georg Brandl116aa622007-08-15 14:28:22 +0000773
774When step (1) finishes without raising an exception, step (2) can begin.
775
776The first form of :keyword:`import` statement binds the module name in the local
777namespace to the module object, and then goes on to import the next identifier,
778if any. If the module name is followed by :keyword:`as`, the name following
779:keyword:`as` is used as the local name for the module.
780
781.. index::
782 pair: name; binding
783 exception: ImportError
784
785The :keyword:`from` form does not bind the module name: it goes through the list
786of identifiers, looks each one of them up in the module found in step (1), and
787binds the name in the local namespace to the object thus found. As with the
788first form of :keyword:`import`, an alternate local name can be supplied by
789specifying ":keyword:`as` localname". If a name is not found,
790:exc:`ImportError` is raised. If the list of identifiers is replaced by a star
791(``'*'``), all public names defined in the module are bound in the local
792namespace of the :keyword:`import` statement..
793
794.. index:: single: __all__ (optional module attribute)
795
796The *public names* defined by a module are determined by checking the module's
797namespace for a variable named ``__all__``; if defined, it must be a sequence of
798strings which are names defined or imported by that module. The names given in
799``__all__`` are all considered public and are required to exist. If ``__all__``
800is not defined, the set of public names includes all names found in the module's
801namespace which do not begin with an underscore character (``'_'``).
802``__all__`` should contain the entire public API. It is intended to avoid
803accidentally exporting items that are not part of the API (such as library
804modules which were imported and used within the module).
805
Benjamin Peterson9611b5e2009-03-25 21:50:43 +0000806The :keyword:`from` form with ``*`` may only occur in a module scope. The wild
807card form of import --- ``import *`` --- is only allowed at the module level.
Ezio Melottif4b46232009-09-16 01:33:31 +0000808Attempting to use it in class or function definitions will raise a
Benjamin Peterson9611b5e2009-03-25 21:50:43 +0000809:exc:`SyntaxError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000810
811.. index::
Brett Cannone43b0602009-03-21 03:11:16 +0000812 single: relative; import
Georg Brandl116aa622007-08-15 14:28:22 +0000813
Brett Cannone43b0602009-03-21 03:11:16 +0000814When specifying what module to import you do not have to specify the absolute
815name of the module. When a module or package is contained within another
816package it is possible to make a relative import within the same top package
817without having to mention the package name. By using leading dots in the
818specified module or package after :keyword:`from` you can specify how high to
819traverse up the current package hierarchy without specifying exact names. One
820leading dot means the current package where the module making the import
821exists. Two dots means up one package level. Three dots is up two levels, etc.
822So if you execute ``from . import mod`` from a module in the ``pkg`` package
823then you will end up importing ``pkg.mod``. If you execute ``from ..subpkg2
824imprt mod`` from within ``pkg.subpkg1`` you will import ``pkg.subpkg2.mod``.
825The specification for relative imports is contained within :pep:`328`.
Georg Brandl5b318c02008-08-03 09:47:27 +0000826
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000827:func:`importlib.import_module` is provided to support applications that
828determine which modules need to be loaded dynamically.
Georg Brandl116aa622007-08-15 14:28:22 +0000829
830
831.. _future:
832
833Future statements
834-----------------
835
836.. index:: pair: future; statement
837
838A :dfn:`future statement` is a directive to the compiler that a particular
839module should be compiled using syntax or semantics that will be available in a
840specified future release of Python. The future statement is intended to ease
841migration to future versions of Python that introduce incompatible changes to
842the language. It allows use of the new features on a per-module basis before
843the release in which the feature becomes standard.
844
845.. productionlist:: *
846 future_statement: "from" "__future__" "import" feature ["as" name]
847 : ("," feature ["as" name])*
848 : | "from" "__future__" "import" "(" feature ["as" name]
849 : ("," feature ["as" name])* [","] ")"
850 feature: identifier
851 name: identifier
852
853A future statement must appear near the top of the module. The only lines that
854can appear before a future statement are:
855
856* the module docstring (if any),
857* comments,
858* blank lines, and
859* other future statements.
860
Georg Brandl02c30562007-09-07 17:52:53 +0000861.. XXX change this if future is cleaned out
862
863The features recognized by Python 3.0 are ``absolute_import``, ``division``,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000864``generators``, ``unicode_literals``, ``print_function``, ``nested_scopes`` and
865``with_statement``. They are all redundant because they are always enabled, and
866only kept for backwards compatibility.
Georg Brandl116aa622007-08-15 14:28:22 +0000867
868A future statement is recognized and treated specially at compile time: Changes
869to the semantics of core constructs are often implemented by generating
870different code. It may even be the case that a new feature introduces new
871incompatible syntax (such as a new reserved word), in which case the compiler
872may need to parse the module differently. Such decisions cannot be pushed off
873until runtime.
874
875For any given release, the compiler knows which feature names have been defined,
876and raises a compile-time error if a future statement contains a feature not
877known to it.
878
879The direct runtime semantics are the same as for any import statement: there is
880a standard module :mod:`__future__`, described later, and it will be imported in
881the usual way at the time the future statement is executed.
882
883The interesting runtime semantics depend on the specific feature enabled by the
884future statement.
885
886Note that there is nothing special about the statement::
887
888 import __future__ [as name]
889
890That is not a future statement; it's an ordinary import statement with no
891special semantics or syntax restrictions.
892
Georg Brandlc5605df2009-08-13 08:26:44 +0000893Code compiled by calls to the built-in functions :func:`exec` and :func:`compile`
Georg Brandl02c30562007-09-07 17:52:53 +0000894that occur in a module :mod:`M` containing a future statement will, by default,
895use the new syntax or semantics associated with the future statement. This can
896be controlled by optional arguments to :func:`compile` --- see the documentation
897of that function for details.
Georg Brandl116aa622007-08-15 14:28:22 +0000898
899A future statement typed at an interactive interpreter prompt will take effect
900for the rest of the interpreter session. If an interpreter is started with the
901:option:`-i` option, is passed a script name to execute, and the script includes
902a future statement, it will be in effect in the interactive session started
903after the script is executed.
904
Georg Brandlff2ad0e2009-04-27 16:51:45 +0000905.. seealso::
906
907 :pep:`236` - Back to the __future__
908 The original proposal for the __future__ mechanism.
909
Georg Brandl116aa622007-08-15 14:28:22 +0000910
911.. _global:
912
913The :keyword:`global` statement
914===============================
915
Christian Heimesfaf2f632008-01-06 16:59:19 +0000916.. index::
917 statement: global
918 triple: global; name; binding
Georg Brandl116aa622007-08-15 14:28:22 +0000919
920.. productionlist::
921 global_stmt: "global" `identifier` ("," `identifier`)*
922
Georg Brandl116aa622007-08-15 14:28:22 +0000923The :keyword:`global` statement is a declaration which holds for the entire
924current code block. It means that the listed identifiers are to be interpreted
925as globals. It would be impossible to assign to a global variable without
926:keyword:`global`, although free variables may refer to globals without being
927declared global.
928
929Names listed in a :keyword:`global` statement must not be used in the same code
930block textually preceding that :keyword:`global` statement.
931
932Names listed in a :keyword:`global` statement must not be defined as formal
933parameters or in a :keyword:`for` loop control target, :keyword:`class`
934definition, function definition, or :keyword:`import` statement.
935
Georg Brandl628e6f92009-10-27 20:24:45 +0000936.. impl-detail::
937
938 The current implementation does not enforce the latter two restrictions, but
939 programs should not abuse this freedom, as future implementations may enforce
940 them or silently change the meaning of the program.
Georg Brandl116aa622007-08-15 14:28:22 +0000941
942.. index::
943 builtin: exec
944 builtin: eval
945 builtin: compile
946
947**Programmer's note:** the :keyword:`global` is a directive to the parser. It
948applies only to code parsed at the same time as the :keyword:`global` statement.
949In particular, a :keyword:`global` statement contained in a string or code
950object supplied to the builtin :func:`exec` function does not affect the code
951block *containing* the function call, and code contained in such a string is
952unaffected by :keyword:`global` statements in the code containing the function
953call. The same applies to the :func:`eval` and :func:`compile` functions.
954
Georg Brandl02c30562007-09-07 17:52:53 +0000955
956.. _nonlocal:
957
958The :keyword:`nonlocal` statement
959=================================
960
961.. index:: statement: nonlocal
962
963.. productionlist::
964 nonlocal_stmt: "nonlocal" `identifier` ("," `identifier`)*
965
Georg Brandlc5d98b42007-12-04 18:11:03 +0000966.. XXX add when implemented
Georg Brandl06788c92009-01-03 21:31:47 +0000967 : ["=" (`target_list` "=")+ expression_list]
968 : | "nonlocal" identifier augop expression_list
Georg Brandlc5d98b42007-12-04 18:11:03 +0000969
Georg Brandl48310cd2009-01-03 21:18:54 +0000970The :keyword:`nonlocal` statement causes the listed identifiers to refer to
971previously bound variables in the nearest enclosing scope. This is important
972because the default behavior for binding is to search the local namespace
Georg Brandlc5d98b42007-12-04 18:11:03 +0000973first. The statement allows encapsulated code to rebind variables outside of
974the local scope besides the global (module) scope.
975
Georg Brandlc5d98b42007-12-04 18:11:03 +0000976.. XXX not implemented
977 The :keyword:`nonlocal` statement may prepend an assignment or augmented
978 assignment, but not an expression.
979
980Names listed in a :keyword:`nonlocal` statement, unlike to those listed in a
981:keyword:`global` statement, must refer to pre-existing bindings in an
982enclosing scope (the scope in which a new binding should be created cannot
983be determined unambiguously).
984
Georg Brandl48310cd2009-01-03 21:18:54 +0000985Names listed in a :keyword:`nonlocal` statement must not collide with
Georg Brandlc5d98b42007-12-04 18:11:03 +0000986pre-existing bindings in the local scope.
987
988.. seealso::
989
990 :pep:`3104` - Access to Names in Outer Scopes
991 The specification for the :keyword:`nonlocal` statement.
Georg Brandl02c30562007-09-07 17:52:53 +0000992
993
Georg Brandl116aa622007-08-15 14:28:22 +0000994.. rubric:: Footnotes
995
996.. [#] It may occur within an :keyword:`except` or :keyword:`else` clause. The
Georg Brandlc5d98b42007-12-04 18:11:03 +0000997 restriction on occurring in the :keyword:`try` clause is implementor's
998 laziness and will eventually be lifted.