blob: ce7ce92cd87fa3beacde286e391aeee7a2853673 [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.
Georg Brandl02c30562007-09-07 17:52:53 +0000122
123 * If the target list contains one target prefixed with an asterisk, called a
124 "starred" target: The object must be a sequence with at least as many items
125 as there are targets in the target list, minus one. The first items of the
126 sequence are assigned, from left to right, to the targets before the starred
127 target. The final items of the sequence are assigned to the targets after
128 the starred target. A list of the remaining items in the sequence is then
129 assigned to the starred target (the list can be empty).
130
131 * Else: The object must be a sequence with the same number of items as there
132 are targets in the target list, and the items are assigned, from left to
133 right, to the corresponding targets.
Georg Brandl116aa622007-08-15 14:28:22 +0000134
135Assignment of an object to a single target is recursively defined as follows.
136
137* If the target is an identifier (name):
138
Georg Brandl02c30562007-09-07 17:52:53 +0000139 * If the name does not occur in a :keyword:`global` or :keyword:`nonlocal`
140 statement in the current code block: the name is bound to the object in the
141 current local namespace.
Georg Brandl116aa622007-08-15 14:28:22 +0000142
Georg Brandl02c30562007-09-07 17:52:53 +0000143 * Otherwise: the name is bound to the object in the global namespace or the
144 outer namespace determined by :keyword:`nonlocal`, respectively.
Georg Brandl116aa622007-08-15 14:28:22 +0000145
Georg Brandl482b1512010-03-21 09:02:59 +0000146 .. index:: single: destructor
147
Georg Brandl02c30562007-09-07 17:52:53 +0000148 The name is rebound if it was already bound. This may cause the reference
149 count for the object previously bound to the name to reach zero, causing the
150 object to be deallocated and its destructor (if it has one) to be called.
Georg Brandl116aa622007-08-15 14:28:22 +0000151
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000152* If the target is a target list enclosed in parentheses or in square brackets:
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000153 The object must be an iterable with the same number of items as there are
154 targets in the target list, and its items are assigned, from left to right,
155 to the corresponding targets.
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000156
157 .. index:: pair: attribute; assignment
158
Georg Brandl116aa622007-08-15 14:28:22 +0000159* If the target is an attribute reference: The primary expression in the
160 reference is evaluated. It should yield an object with assignable attributes;
Georg Brandl02c30562007-09-07 17:52:53 +0000161 if this is not the case, :exc:`TypeError` is raised. That object is then
162 asked to assign the assigned object to the given attribute; if it cannot
163 perform the assignment, it raises an exception (usually but not necessarily
Georg Brandl116aa622007-08-15 14:28:22 +0000164 :exc:`AttributeError`).
165
Georg Brandlee8783d2009-09-16 16:00:31 +0000166 .. _attr-target-note:
167
168 Note: If the object is a class instance and the attribute reference occurs on
169 both sides of the assignment operator, the RHS expression, ``a.x`` can access
170 either an instance attribute or (if no instance attribute exists) a class
171 attribute. The LHS target ``a.x`` is always set as an instance attribute,
172 creating it if necessary. Thus, the two occurrences of ``a.x`` do not
173 necessarily refer to the same attribute: if the RHS expression refers to a
174 class attribute, the LHS creates a new instance attribute as the target of the
175 assignment::
176
177 class Cls:
178 x = 3 # class variable
179 inst = Cls()
180 inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x as 3
181
182 This description does not necessarily apply to descriptor attributes, such as
183 properties created with :func:`property`.
184
Georg Brandl116aa622007-08-15 14:28:22 +0000185 .. index::
186 pair: subscription; assignment
187 object: mutable
188
189* If the target is a subscription: The primary expression in the reference is
Georg Brandl02c30562007-09-07 17:52:53 +0000190 evaluated. It should yield either a mutable sequence object (such as a list)
191 or a mapping object (such as a dictionary). Next, the subscript expression is
Georg Brandl116aa622007-08-15 14:28:22 +0000192 evaluated.
193
194 .. index::
195 object: sequence
196 object: list
197
Georg Brandl02c30562007-09-07 17:52:53 +0000198 If the primary is a mutable sequence object (such as a list), the subscript
199 must yield an integer. If it is negative, the sequence's length is added to
200 it. The resulting value must be a nonnegative integer less than the
201 sequence's length, and the sequence is asked to assign the assigned object to
202 its item with that index. If the index is out of range, :exc:`IndexError` is
203 raised (assignment to a subscripted sequence cannot add new items to a list).
Georg Brandl116aa622007-08-15 14:28:22 +0000204
205 .. index::
206 object: mapping
207 object: dictionary
208
209 If the primary is a mapping object (such as a dictionary), the subscript must
210 have a type compatible with the mapping's key type, and the mapping is then
211 asked to create a key/datum pair which maps the subscript to the assigned
212 object. This can either replace an existing key/value pair with the same key
213 value, or insert a new key/value pair (if no key with the same value existed).
214
Georg Brandl02c30562007-09-07 17:52:53 +0000215 For user-defined objects, the :meth:`__setitem__` method is called with
216 appropriate arguments.
217
Georg Brandl116aa622007-08-15 14:28:22 +0000218 .. index:: pair: slicing; assignment
219
220* If the target is a slicing: The primary expression in the reference is
221 evaluated. It should yield a mutable sequence object (such as a list). The
222 assigned object should be a sequence object of the same type. Next, the lower
223 and upper bound expressions are evaluated, insofar they are present; defaults
Georg Brandl02c30562007-09-07 17:52:53 +0000224 are zero and the sequence's length. The bounds should evaluate to integers.
225 If either bound is negative, the sequence's length is added to it. The
226 resulting bounds are clipped to lie between zero and the sequence's length,
227 inclusive. Finally, the sequence object is asked to replace the slice with
228 the items of the assigned sequence. The length of the slice may be different
229 from the length of the assigned sequence, thus changing the length of the
230 target sequence, if the object allows it.
Georg Brandl116aa622007-08-15 14:28:22 +0000231
Georg Brandl495f7b52009-10-27 15:28:25 +0000232.. impl-detail::
233
234 In the current implementation, the syntax for targets is taken to be the same
235 as for expressions, and invalid syntax is rejected during the code generation
236 phase, causing less detailed error messages.
Georg Brandl116aa622007-08-15 14:28:22 +0000237
238WARNING: Although the definition of assignment implies that overlaps between the
239left-hand side and the right-hand side are 'safe' (for example ``a, b = b, a``
240swaps two variables), overlaps *within* the collection of assigned-to variables
241are not safe! For instance, the following program prints ``[0, 2]``::
242
243 x = [0, 1]
244 i = 0
245 i, x[i] = 1, 2
Georg Brandl6911e3c2007-09-04 07:15:32 +0000246 print(x)
Georg Brandl116aa622007-08-15 14:28:22 +0000247
248
Georg Brandl02c30562007-09-07 17:52:53 +0000249.. seealso::
250
251 :pep:`3132` - Extended Iterable Unpacking
252 The specification for the ``*target`` feature.
253
254
Georg Brandl116aa622007-08-15 14:28:22 +0000255.. _augassign:
256
257Augmented assignment statements
258-------------------------------
259
260.. index::
261 pair: augmented; assignment
262 single: statement; assignment, augmented
263
264Augmented assignment is the combination, in a single statement, of a binary
265operation and an assignment statement:
266
267.. productionlist::
Benjamin Petersonb58dda72009-01-18 22:27:04 +0000268 augmented_assignment_stmt: `augtarget` `augop` (`expression_list` | `yield_expression`)
269 augtarget: `identifier` | `attributeref` | `subscription` | `slicing`
Benjamin Peterson9bc93512008-09-22 22:10:59 +0000270 augop: "+=" | "-=" | "*=" | "/=" | "//=" | "%=" | "**="
Georg Brandl116aa622007-08-15 14:28:22 +0000271 : | ">>=" | "<<=" | "&=" | "^=" | "|="
272
273(See section :ref:`primaries` for the syntax definitions for the last three
274symbols.)
275
276An augmented assignment evaluates the target (which, unlike normal assignment
277statements, cannot be an unpacking) and the expression list, performs the binary
278operation specific to the type of assignment on the two operands, and assigns
279the result to the original target. The target is only evaluated once.
280
281An augmented assignment expression like ``x += 1`` can be rewritten as ``x = x +
2821`` to achieve a similar, but not exactly equal effect. In the augmented
283version, ``x`` is only evaluated once. Also, when possible, the actual operation
284is performed *in-place*, meaning that rather than creating a new object and
285assigning that to the target, the old object is modified instead.
286
287With the exception of assigning to tuples and multiple targets in a single
288statement, the assignment done by augmented assignment statements is handled the
289same way as normal assignments. Similarly, with the exception of the possible
290*in-place* behavior, the binary operation performed by augmented assignment is
291the same as the normal binary operations.
292
Georg Brandlee8783d2009-09-16 16:00:31 +0000293For targets which are attribute references, the same :ref:`caveat about class
294and instance attributes <attr-target-note>` applies as for regular assignments.
Georg Brandl116aa622007-08-15 14:28:22 +0000295
296
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000297.. _assert:
298
299The :keyword:`assert` statement
300===============================
301
302.. index::
303 statement: assert
304 pair: debugging; assertions
305
306Assert statements are a convenient way to insert debugging assertions into a
307program:
308
309.. productionlist::
310 assert_stmt: "assert" `expression` ["," `expression`]
311
312The simple form, ``assert expression``, is equivalent to ::
313
314 if __debug__:
315 if not expression: raise AssertionError
316
317The extended form, ``assert expression1, expression2``, is equivalent to ::
318
319 if __debug__:
Georg Brandl18a499d2007-12-29 10:57:11 +0000320 if not expression1: raise AssertionError(expression2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000321
322.. index::
323 single: __debug__
324 exception: AssertionError
325
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000326These equivalences assume that :const:`__debug__` and :exc:`AssertionError` refer to
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000327the built-in variables with those names. In the current implementation, the
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000328built-in variable :const:`__debug__` is ``True`` under normal circumstances,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000329``False`` when optimization is requested (command line option -O). The current
330code generator emits no code for an assert statement when optimization is
331requested at compile time. Note that it is unnecessary to include the source
332code for the expression that failed in the error message; it will be displayed
333as part of the stack trace.
334
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000335Assignments to :const:`__debug__` are illegal. The value for the built-in variable
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000336is determined when the interpreter starts.
337
338
Georg Brandl116aa622007-08-15 14:28:22 +0000339.. _pass:
340
341The :keyword:`pass` statement
342=============================
343
Christian Heimesfaf2f632008-01-06 16:59:19 +0000344.. index::
345 statement: pass
346 pair: null; operation
Georg Brandl02c30562007-09-07 17:52:53 +0000347 pair: null; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000348
349.. productionlist::
350 pass_stmt: "pass"
351
Georg Brandl116aa622007-08-15 14:28:22 +0000352:keyword:`pass` is a null operation --- when it is executed, nothing happens.
353It is useful as a placeholder when a statement is required syntactically, but no
354code needs to be executed, for example::
355
356 def f(arg): pass # a function that does nothing (yet)
357
358 class C: pass # a class with no methods (yet)
359
360
361.. _del:
362
363The :keyword:`del` statement
364============================
365
Christian Heimesfaf2f632008-01-06 16:59:19 +0000366.. index::
367 statement: del
368 pair: deletion; target
369 triple: deletion; target; list
Georg Brandl116aa622007-08-15 14:28:22 +0000370
371.. productionlist::
372 del_stmt: "del" `target_list`
373
Georg Brandl116aa622007-08-15 14:28:22 +0000374Deletion is recursively defined very similar to the way assignment is defined.
Sandro Tosi75c71cc2011-12-24 19:56:04 +0100375Rather than spelling it out in full details, here are some hints.
Georg Brandl116aa622007-08-15 14:28:22 +0000376
377Deletion of a target list recursively deletes each target, from left to right.
378
379.. index::
380 statement: global
381 pair: unbinding; name
382
Georg Brandl02c30562007-09-07 17:52:53 +0000383Deletion of a name removes the binding of that name from the local or global
Georg Brandl116aa622007-08-15 14:28:22 +0000384namespace, depending on whether the name occurs in a :keyword:`global` statement
385in the same code block. If the name is unbound, a :exc:`NameError` exception
386will be raised.
387
Georg Brandl116aa622007-08-15 14:28:22 +0000388.. index:: pair: attribute; deletion
389
390Deletion of attribute references, subscriptions and slicings is passed to the
391primary object involved; deletion of a slicing is in general equivalent to
392assignment of an empty slice of the right type (but even this is determined by
393the sliced object).
394
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000395.. versionchanged:: 3.2
396 Previously it was illegal to delete a name from the local namespace if it
397 occurs as a free variable in a nested block.
398
Georg Brandl116aa622007-08-15 14:28:22 +0000399
400.. _return:
401
402The :keyword:`return` statement
403===============================
404
Christian Heimesfaf2f632008-01-06 16:59:19 +0000405.. index::
406 statement: return
407 pair: function; definition
408 pair: class; definition
Georg Brandl116aa622007-08-15 14:28:22 +0000409
410.. productionlist::
411 return_stmt: "return" [`expression_list`]
412
Georg Brandl116aa622007-08-15 14:28:22 +0000413:keyword:`return` may only occur syntactically nested in a function definition,
414not within a nested class definition.
415
416If an expression list is present, it is evaluated, else ``None`` is substituted.
417
418:keyword:`return` leaves the current function call with the expression list (or
419``None``) as return value.
420
421.. index:: keyword: finally
422
423When :keyword:`return` passes control out of a :keyword:`try` statement with a
424:keyword:`finally` clause, that :keyword:`finally` clause is executed before
425really leaving the function.
426
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000427In a generator function, the :keyword:`return` statement indicates that the
428generator is done and will cause :exc:`StopIteration` to be raised. The returned
429value (if any) is used as an argument to construct :exc:`StopIteration` and
430becomes the :attr:`StopIteration.value` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000431
432
433.. _yield:
434
435The :keyword:`yield` statement
436==============================
437
Christian Heimesfaf2f632008-01-06 16:59:19 +0000438.. index::
439 statement: yield
440 single: generator; function
441 single: generator; iterator
442 single: function; generator
443 exception: StopIteration
444
Georg Brandl116aa622007-08-15 14:28:22 +0000445.. productionlist::
446 yield_stmt: `yield_expression`
447
Christian Heimesfaf2f632008-01-06 16:59:19 +0000448The :keyword:`yield` statement is only used when defining a generator function,
449and is only used in the body of the generator function. Using a :keyword:`yield`
450statement in a function definition is sufficient to cause that definition to
451create a generator function instead of a normal function.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000452
Christian Heimes33fe8092008-04-13 13:53:33 +0000453When a generator function is called, it returns an iterator known as a generator
454iterator, or more commonly, a generator. The body of the generator function is
Georg Brandl6520d822009-02-05 11:01:54 +0000455executed by calling the :func:`next` function on the generator repeatedly until
456it raises an exception.
Christian Heimes33fe8092008-04-13 13:53:33 +0000457
458When a :keyword:`yield` statement is executed, the state of the generator is
459frozen and the value of :token:`expression_list` is returned to :meth:`next`'s
460caller. By "frozen" we mean that all local state is retained, including the
461current bindings of local variables, the instruction pointer, and the internal
Georg Brandl6520d822009-02-05 11:01:54 +0000462evaluation stack: enough information is saved so that the next time :func:`next`
Christian Heimes33fe8092008-04-13 13:53:33 +0000463is invoked, the function can proceed exactly as if the :keyword:`yield`
464statement were just another external call.
465
Georg Brandle6bcc912008-05-12 18:05:20 +0000466The :keyword:`yield` statement is allowed in the :keyword:`try` clause of a
467:keyword:`try` ... :keyword:`finally` construct. If the generator is not
468resumed before it is finalized (by reaching a zero reference count or by being
469garbage collected), the generator-iterator's :meth:`close` method will be
470called, allowing any pending :keyword:`finally` clauses to execute.
Christian Heimes33fe8092008-04-13 13:53:33 +0000471
Nick Coghlan0ed80192012-01-14 14:43:24 +1000472When ``yield from <expr>`` is used, it treats the supplied expression as
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000473a subiterator, producing values from it until the underlying iterator is
474exhausted.
475
Nick Coghlan0ed80192012-01-14 14:43:24 +1000476 .. versionchanged:: 3.3
477 Added ``yield from <expr>`` to delegate control flow to a subiterator
478
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000479For full details of :keyword:`yield` semantics, refer to the :ref:`yieldexpr`
480section.
481
Christian Heimes33fe8092008-04-13 13:53:33 +0000482.. seealso::
483
484 :pep:`0255` - Simple Generators
485 The proposal for adding generators and the :keyword:`yield` statement to Python.
486
487 :pep:`0342` - Coroutines via Enhanced Generators
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000488 The proposal to enhance the API and syntax of generators, making them
489 usable as simple coroutines.
490
491 :pep:`0380` - Syntax for Delegating to a Subgenerator
492 The proposal to introduce the :token:`yield_from` syntax, making delegation
493 to sub-generators easy.
Christian Heimes33fe8092008-04-13 13:53:33 +0000494
Georg Brandl116aa622007-08-15 14:28:22 +0000495
496.. _raise:
497
498The :keyword:`raise` statement
499==============================
500
Christian Heimesfaf2f632008-01-06 16:59:19 +0000501.. index::
502 statement: raise
503 single: exception
504 pair: raising; exception
Georg Brandl1aea30a2008-07-19 15:51:07 +0000505 single: __traceback__ (exception attribute)
Georg Brandl116aa622007-08-15 14:28:22 +0000506
507.. productionlist::
Georg Brandle06de8b2008-05-05 21:42:51 +0000508 raise_stmt: "raise" [`expression` ["from" `expression`]]
Georg Brandl116aa622007-08-15 14:28:22 +0000509
510If no expressions are present, :keyword:`raise` re-raises the last exception
511that was active in the current scope. If no exception is active in the current
Sandro Tosib2794c82012-01-01 12:17:15 +0100512scope, a :exc:`RuntimeError` exception is raised indicating that this is an
513error.
Georg Brandl116aa622007-08-15 14:28:22 +0000514
Georg Brandl02c30562007-09-07 17:52:53 +0000515Otherwise, :keyword:`raise` evaluates the first expression as the exception
516object. It must be either a subclass or an instance of :class:`BaseException`.
517If it is a class, the exception instance will be obtained when needed by
518instantiating the class with no arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000519
Georg Brandl02c30562007-09-07 17:52:53 +0000520The :dfn:`type` of the exception is the exception instance's class, the
521:dfn:`value` is the instance itself.
Georg Brandl116aa622007-08-15 14:28:22 +0000522
523.. index:: object: traceback
524
Georg Brandl02c30562007-09-07 17:52:53 +0000525A traceback object is normally created automatically when an exception is raised
Georg Brandle06de8b2008-05-05 21:42:51 +0000526and attached to it as the :attr:`__traceback__` attribute, which is writable.
527You can create an exception and set your own traceback in one step using the
528:meth:`with_traceback` exception method (which returns the same exception
529instance, with its traceback set to its argument), like so::
Georg Brandl02c30562007-09-07 17:52:53 +0000530
Benjamin Petersonb7851692009-02-16 16:15:34 +0000531 raise Exception("foo occurred").with_traceback(tracebackobj)
Georg Brandl02c30562007-09-07 17:52:53 +0000532
Georg Brandl1aea30a2008-07-19 15:51:07 +0000533.. index:: pair: exception; chaining
534 __cause__ (exception attribute)
535 __context__ (exception attribute)
Georg Brandl48310cd2009-01-03 21:18:54 +0000536
Georg Brandl1aea30a2008-07-19 15:51:07 +0000537The ``from`` clause is used for exception chaining: if given, the second
538*expression* must be another exception class or instance, which will then be
539attached to the raised exception as the :attr:`__cause__` attribute (which is
540writable). If the raised exception is not handled, both exceptions will be
541printed::
Georg Brandl02c30562007-09-07 17:52:53 +0000542
Georg Brandl1aea30a2008-07-19 15:51:07 +0000543 >>> try:
544 ... print(1 / 0)
545 ... except Exception as exc:
546 ... raise RuntimeError("Something bad happened") from exc
547 ...
548 Traceback (most recent call last):
549 File "<stdin>", line 2, in <module>
550 ZeroDivisionError: int division or modulo by zero
551
552 The above exception was the direct cause of the following exception:
553
554 Traceback (most recent call last):
555 File "<stdin>", line 4, in <module>
556 RuntimeError: Something bad happened
557
558A similar mechanism works implicitly if an exception is raised inside an
559exception handler: the previous exception is then attached as the new
560exception's :attr:`__context__` attribute::
561
562 >>> try:
563 ... print(1 / 0)
564 ... except:
565 ... raise RuntimeError("Something bad happened")
566 ...
567 Traceback (most recent call last):
568 File "<stdin>", line 2, in <module>
569 ZeroDivisionError: int division or modulo by zero
570
571 During handling of the above exception, another exception occurred:
572
573 Traceback (most recent call last):
574 File "<stdin>", line 4, in <module>
575 RuntimeError: Something bad happened
Georg Brandl116aa622007-08-15 14:28:22 +0000576
577Additional information on exceptions can be found in section :ref:`exceptions`,
578and information about handling exceptions is in section :ref:`try`.
579
580
581.. _break:
582
583The :keyword:`break` statement
584==============================
585
Christian Heimesfaf2f632008-01-06 16:59:19 +0000586.. index::
587 statement: break
588 statement: for
589 statement: while
590 pair: loop; statement
Georg Brandl116aa622007-08-15 14:28:22 +0000591
592.. productionlist::
593 break_stmt: "break"
594
Georg Brandl116aa622007-08-15 14:28:22 +0000595:keyword:`break` may only occur syntactically nested in a :keyword:`for` or
596:keyword:`while` loop, but not nested in a function or class definition within
597that loop.
598
599.. index:: keyword: else
Georg Brandl02c30562007-09-07 17:52:53 +0000600 pair: loop control; target
Georg Brandl116aa622007-08-15 14:28:22 +0000601
602It terminates the nearest enclosing loop, skipping the optional :keyword:`else`
603clause if the loop has one.
604
Georg Brandl116aa622007-08-15 14:28:22 +0000605If a :keyword:`for` loop is terminated by :keyword:`break`, the loop control
606target keeps its current value.
607
608.. index:: keyword: finally
609
610When :keyword:`break` passes control out of a :keyword:`try` statement with a
611:keyword:`finally` clause, that :keyword:`finally` clause is executed before
612really leaving the loop.
613
614
615.. _continue:
616
617The :keyword:`continue` statement
618=================================
619
Christian Heimesfaf2f632008-01-06 16:59:19 +0000620.. index::
621 statement: continue
622 statement: for
623 statement: while
624 pair: loop; statement
625 keyword: finally
Georg Brandl116aa622007-08-15 14:28:22 +0000626
627.. productionlist::
628 continue_stmt: "continue"
629
Georg Brandl116aa622007-08-15 14:28:22 +0000630:keyword:`continue` may only occur syntactically nested in a :keyword:`for` or
631:keyword:`while` loop, but not nested in a function or class definition or
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000632:keyword:`finally` clause within that loop. It continues with the next
Georg Brandl116aa622007-08-15 14:28:22 +0000633cycle of the nearest enclosing loop.
634
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000635When :keyword:`continue` passes control out of a :keyword:`try` statement with a
636:keyword:`finally` clause, that :keyword:`finally` clause is executed before
637really starting the next loop cycle.
638
Georg Brandl116aa622007-08-15 14:28:22 +0000639
640.. _import:
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000641.. _from:
Georg Brandl116aa622007-08-15 14:28:22 +0000642
643The :keyword:`import` statement
644===============================
645
646.. index::
647 statement: import
648 single: module; importing
649 pair: name; binding
650 keyword: from
651
652.. productionlist::
653 import_stmt: "import" `module` ["as" `name`] ( "," `module` ["as" `name`] )*
654 : | "from" `relative_module` "import" `identifier` ["as" `name`]
655 : ( "," `identifier` ["as" `name`] )*
656 : | "from" `relative_module` "import" "(" `identifier` ["as" `name`]
657 : ( "," `identifier` ["as" `name`] )* [","] ")"
658 : | "from" `module` "import" "*"
659 module: (`identifier` ".")* `identifier`
660 relative_module: "."* `module` | "."+
661 name: `identifier`
662
663Import statements are executed in two steps: (1) find a module, and initialize
664it if necessary; (2) define a name or names in the local namespace (of the scope
Brett Cannone43b0602009-03-21 03:11:16 +0000665where the :keyword:`import` statement occurs). The statement comes in two
666forms differing on whether it uses the :keyword:`from` keyword. The first form
667(without :keyword:`from`) repeats these steps for each identifier in the list.
668The form with :keyword:`from` performs step (1) once, and then performs step
669(2) repeatedly. For a reference implementation of step (1), see the
670:mod:`importlib` module.
Georg Brandl116aa622007-08-15 14:28:22 +0000671
672.. index::
Brett Cannone43b0602009-03-21 03:11:16 +0000673 single: package
Georg Brandl116aa622007-08-15 14:28:22 +0000674
Brett Cannone43b0602009-03-21 03:11:16 +0000675To understand how step (1) occurs, one must first understand how Python handles
676hierarchical naming of modules. To help organize modules and provide a
677hierarchy in naming, Python has a concept of packages. A package can contain
678other packages and modules while modules cannot contain other modules or
679packages. From a file system perspective, packages are directories and modules
680are files. The original `specification for packages
681<http://www.python.org/doc/essays/packages.html>`_ is still available to read,
682although minor details have changed since the writing of that document.
Georg Brandl116aa622007-08-15 14:28:22 +0000683
684.. index::
Brett Cannone43b0602009-03-21 03:11:16 +0000685 single: sys.modules
Georg Brandl116aa622007-08-15 14:28:22 +0000686
Brett Cannone43b0602009-03-21 03:11:16 +0000687Once the name of the module is known (unless otherwise specified, the term
688"module" will refer to both packages and modules), searching
689for the module or package can begin. The first place checked is
690:data:`sys.modules`, the cache of all modules that have been imported
Brett Cannon757df6e2009-08-30 04:00:12 +0000691previously. If the module is found there then it is used in step (2) of import
Georg Brandl375aec22011-01-15 17:03:02 +0000692unless ``None`` is found in :data:`sys.modules`, in which case
Brett Cannon757df6e2009-08-30 04:00:12 +0000693:exc:`ImportError` is raised.
Brett Cannone43b0602009-03-21 03:11:16 +0000694
695.. index::
696 single: sys.meta_path
697 single: finder
698 pair: finder; find_module
699 single: __path__
700
701If the module is not found in the cache, then :data:`sys.meta_path` is searched
702(the specification for :data:`sys.meta_path` can be found in :pep:`302`).
703The object is a list of :term:`finder` objects which are queried in order as to
704whether they know how to load the module by calling their :meth:`find_module`
705method with the name of the module. If the module happens to be contained
706within a package (as denoted by the existence of a dot in the name), then a
707second argument to :meth:`find_module` is given as the value of the
708:attr:`__path__` attribute from the parent package (everything up to the last
709dot in the name of the module being imported). If a finder can find the module
Georg Brandl375aec22011-01-15 17:03:02 +0000710it returns a :term:`loader` (discussed later) or returns ``None``.
Brett Cannone43b0602009-03-21 03:11:16 +0000711
712.. index::
713 single: sys.path_hooks
714 single: sys.path_importer_cache
715 single: sys.path
716
717If none of the finders on :data:`sys.meta_path` are able to find the module
718then some implicitly defined finders are queried. Implementations of Python
719vary in what implicit meta path finders are defined. The one they all do
720define, though, is one that handles :data:`sys.path_hooks`,
721:data:`sys.path_importer_cache`, and :data:`sys.path`.
722
723The implicit finder searches for the requested module in the "paths" specified
724in one of two places ("paths" do not have to be file system paths). If the
725module being imported is supposed to be contained within a package then the
726second argument passed to :meth:`find_module`, :attr:`__path__` on the parent
727package, is used as the source of paths. If the module is not contained in a
728package then :data:`sys.path` is used as the source of paths.
729
730Once the source of paths is chosen it is iterated over to find a finder that
731can handle that path. The dict at :data:`sys.path_importer_cache` caches
732finders for paths and is checked for a finder. If the path does not have a
733finder cached then :data:`sys.path_hooks` is searched by calling each object in
734the list with a single argument of the path, returning a finder or raises
735:exc:`ImportError`. If a finder is returned then it is cached in
736:data:`sys.path_importer_cache` and then used for that path entry. If no finder
Georg Brandl375aec22011-01-15 17:03:02 +0000737can be found but the path exists then a value of ``None`` is
Brett Cannone43b0602009-03-21 03:11:16 +0000738stored in :data:`sys.path_importer_cache` to signify that an implicit,
739file-based finder that handles modules stored as individual files should be
740used for that path. If the path does not exist then a finder which always
Georg Brandl375aec22011-01-15 17:03:02 +0000741returns ``None`` is placed in the cache for the path.
Brett Cannone43b0602009-03-21 03:11:16 +0000742
743.. index::
744 single: loader
745 pair: loader; load_module
746 exception: ImportError
747
748If no finder can find the module then :exc:`ImportError` is raised. Otherwise
749some finder returned a loader whose :meth:`load_module` method is called with
750the name of the module to load (see :pep:`302` for the original definition of
751loaders). A loader has several responsibilities to perform on a module it
752loads. First, if the module already exists in :data:`sys.modules` (a
753possibility if the loader is called outside of the import machinery) then it
754is to use that module for initialization and not a new module. But if the
755module does not exist in :data:`sys.modules` then it is to be added to that
756dict before initialization begins. If an error occurs during loading of the
757module and it was added to :data:`sys.modules` it is to be removed from the
758dict. If an error occurs but the module was already in :data:`sys.modules` it
759is left in the dict.
760
761.. index::
762 single: __name__
763 single: __file__
764 single: __path__
765 single: __package__
766 single: __loader__
767
768The loader must set several attributes on the module. :data:`__name__` is to be
769set to the name of the module. :data:`__file__` is to be the "path" to the file
770unless the module is built-in (and thus listed in
771:data:`sys.builtin_module_names`) in which case the attribute is not set.
772If what is being imported is a package then :data:`__path__` is to be set to a
773list of paths to be searched when looking for modules and packages contained
774within the package being imported. :data:`__package__` is optional but should
775be set to the name of package that contains the module or package (the empty
776string is used for module not contained in a package). :data:`__loader__` is
777also optional but should be set to the loader object that is loading the
Brett Cannon1b5123a2012-04-20 15:57:46 -0400778module. While loaders are required to return the module they loaded, import
779itself always retrieves any modules it returns from :data:`sys.modules`.
Brett Cannone43b0602009-03-21 03:11:16 +0000780
781.. index::
782 exception: ImportError
783
784If an error occurs during loading then the loader raises :exc:`ImportError` if
785some other exception is not already being propagated. Otherwise the loader
786returns the module that was loaded and initialized.
Georg Brandl116aa622007-08-15 14:28:22 +0000787
788When step (1) finishes without raising an exception, step (2) can begin.
789
790The first form of :keyword:`import` statement binds the module name in the local
791namespace to the module object, and then goes on to import the next identifier,
792if any. If the module name is followed by :keyword:`as`, the name following
793:keyword:`as` is used as the local name for the module.
794
795.. index::
796 pair: name; binding
797 exception: ImportError
798
799The :keyword:`from` form does not bind the module name: it goes through the list
800of identifiers, looks each one of them up in the module found in step (1), and
801binds the name in the local namespace to the object thus found. As with the
802first form of :keyword:`import`, an alternate local name can be supplied by
803specifying ":keyword:`as` localname". If a name is not found,
804:exc:`ImportError` is raised. If the list of identifiers is replaced by a star
805(``'*'``), all public names defined in the module are bound in the local
Michael Foordbcc48102010-11-18 11:02:50 +0000806namespace of the :keyword:`import` statement.
Georg Brandl116aa622007-08-15 14:28:22 +0000807
808.. index:: single: __all__ (optional module attribute)
809
810The *public names* defined by a module are determined by checking the module's
811namespace for a variable named ``__all__``; if defined, it must be a sequence of
812strings which are names defined or imported by that module. The names given in
813``__all__`` are all considered public and are required to exist. If ``__all__``
814is not defined, the set of public names includes all names found in the module's
815namespace which do not begin with an underscore character (``'_'``).
816``__all__`` should contain the entire public API. It is intended to avoid
817accidentally exporting items that are not part of the API (such as library
818modules which were imported and used within the module).
819
Benjamin Peterson9611b5e2009-03-25 21:50:43 +0000820The :keyword:`from` form with ``*`` may only occur in a module scope. The wild
821card form of import --- ``import *`` --- is only allowed at the module level.
Ezio Melotti4bbfa2a2009-09-16 01:18:27 +0000822Attempting to use it in class or function definitions will raise a
Benjamin Peterson9611b5e2009-03-25 21:50:43 +0000823:exc:`SyntaxError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000824
825.. index::
Brett Cannone43b0602009-03-21 03:11:16 +0000826 single: relative; import
Georg Brandl116aa622007-08-15 14:28:22 +0000827
Brett Cannone43b0602009-03-21 03:11:16 +0000828When specifying what module to import you do not have to specify the absolute
829name of the module. When a module or package is contained within another
830package it is possible to make a relative import within the same top package
831without having to mention the package name. By using leading dots in the
832specified module or package after :keyword:`from` you can specify how high to
833traverse up the current package hierarchy without specifying exact names. One
834leading dot means the current package where the module making the import
835exists. Two dots means up one package level. Three dots is up two levels, etc.
836So if you execute ``from . import mod`` from a module in the ``pkg`` package
837then you will end up importing ``pkg.mod``. If you execute ``from ..subpkg2
Florent Xicluna0c8414e2010-09-03 20:23:40 +0000838import mod`` from within ``pkg.subpkg1`` you will import ``pkg.subpkg2.mod``.
Brett Cannone43b0602009-03-21 03:11:16 +0000839The specification for relative imports is contained within :pep:`328`.
Georg Brandl5b318c02008-08-03 09:47:27 +0000840
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000841:func:`importlib.import_module` is provided to support applications that
842determine which modules need to be loaded dynamically.
Georg Brandl116aa622007-08-15 14:28:22 +0000843
844
845.. _future:
846
847Future statements
848-----------------
849
850.. index:: pair: future; statement
851
852A :dfn:`future statement` is a directive to the compiler that a particular
853module should be compiled using syntax or semantics that will be available in a
854specified future release of Python. The future statement is intended to ease
855migration to future versions of Python that introduce incompatible changes to
856the language. It allows use of the new features on a per-module basis before
857the release in which the feature becomes standard.
858
859.. productionlist:: *
860 future_statement: "from" "__future__" "import" feature ["as" name]
861 : ("," feature ["as" name])*
862 : | "from" "__future__" "import" "(" feature ["as" name]
863 : ("," feature ["as" name])* [","] ")"
864 feature: identifier
865 name: identifier
866
867A future statement must appear near the top of the module. The only lines that
868can appear before a future statement are:
869
870* the module docstring (if any),
871* comments,
872* blank lines, and
873* other future statements.
874
Georg Brandl02c30562007-09-07 17:52:53 +0000875.. XXX change this if future is cleaned out
876
877The features recognized by Python 3.0 are ``absolute_import``, ``division``,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000878``generators``, ``unicode_literals``, ``print_function``, ``nested_scopes`` and
879``with_statement``. They are all redundant because they are always enabled, and
880only kept for backwards compatibility.
Georg Brandl116aa622007-08-15 14:28:22 +0000881
882A future statement is recognized and treated specially at compile time: Changes
883to the semantics of core constructs are often implemented by generating
884different code. It may even be the case that a new feature introduces new
885incompatible syntax (such as a new reserved word), in which case the compiler
886may need to parse the module differently. Such decisions cannot be pushed off
887until runtime.
888
889For any given release, the compiler knows which feature names have been defined,
890and raises a compile-time error if a future statement contains a feature not
891known to it.
892
893The direct runtime semantics are the same as for any import statement: there is
894a standard module :mod:`__future__`, described later, and it will be imported in
895the usual way at the time the future statement is executed.
896
897The interesting runtime semantics depend on the specific feature enabled by the
898future statement.
899
900Note that there is nothing special about the statement::
901
902 import __future__ [as name]
903
904That is not a future statement; it's an ordinary import statement with no
905special semantics or syntax restrictions.
906
Georg Brandl22b34312009-07-26 14:54:51 +0000907Code compiled by calls to the built-in functions :func:`exec` and :func:`compile`
Georg Brandl02c30562007-09-07 17:52:53 +0000908that occur in a module :mod:`M` containing a future statement will, by default,
909use the new syntax or semantics associated with the future statement. This can
910be controlled by optional arguments to :func:`compile` --- see the documentation
911of that function for details.
Georg Brandl116aa622007-08-15 14:28:22 +0000912
913A future statement typed at an interactive interpreter prompt will take effect
914for the rest of the interpreter session. If an interpreter is started with the
915:option:`-i` option, is passed a script name to execute, and the script includes
916a future statement, it will be in effect in the interactive session started
917after the script is executed.
918
Georg Brandlff2ad0e2009-04-27 16:51:45 +0000919.. seealso::
920
921 :pep:`236` - Back to the __future__
922 The original proposal for the __future__ mechanism.
923
Georg Brandl116aa622007-08-15 14:28:22 +0000924
925.. _global:
926
927The :keyword:`global` statement
928===============================
929
Christian Heimesfaf2f632008-01-06 16:59:19 +0000930.. index::
931 statement: global
932 triple: global; name; binding
Georg Brandl116aa622007-08-15 14:28:22 +0000933
934.. productionlist::
935 global_stmt: "global" `identifier` ("," `identifier`)*
936
Georg Brandl116aa622007-08-15 14:28:22 +0000937The :keyword:`global` statement is a declaration which holds for the entire
938current code block. It means that the listed identifiers are to be interpreted
939as globals. It would be impossible to assign to a global variable without
940:keyword:`global`, although free variables may refer to globals without being
941declared global.
942
943Names listed in a :keyword:`global` statement must not be used in the same code
944block textually preceding that :keyword:`global` statement.
945
946Names listed in a :keyword:`global` statement must not be defined as formal
947parameters or in a :keyword:`for` loop control target, :keyword:`class`
948definition, function definition, or :keyword:`import` statement.
949
Georg Brandl495f7b52009-10-27 15:28:25 +0000950.. impl-detail::
951
952 The current implementation does not enforce the latter two restrictions, but
953 programs should not abuse this freedom, as future implementations may enforce
954 them or silently change the meaning of the program.
Georg Brandl116aa622007-08-15 14:28:22 +0000955
956.. index::
957 builtin: exec
958 builtin: eval
959 builtin: compile
960
961**Programmer's note:** the :keyword:`global` is a directive to the parser. It
962applies only to code parsed at the same time as the :keyword:`global` statement.
963In particular, a :keyword:`global` statement contained in a string or code
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000964object supplied to the built-in :func:`exec` function does not affect the code
Georg Brandl116aa622007-08-15 14:28:22 +0000965block *containing* the function call, and code contained in such a string is
966unaffected by :keyword:`global` statements in the code containing the function
967call. The same applies to the :func:`eval` and :func:`compile` functions.
968
Georg Brandl02c30562007-09-07 17:52:53 +0000969
970.. _nonlocal:
971
972The :keyword:`nonlocal` statement
973=================================
974
975.. index:: statement: nonlocal
976
977.. productionlist::
978 nonlocal_stmt: "nonlocal" `identifier` ("," `identifier`)*
979
Georg Brandlc5d98b42007-12-04 18:11:03 +0000980.. XXX add when implemented
Georg Brandl06788c92009-01-03 21:31:47 +0000981 : ["=" (`target_list` "=")+ expression_list]
982 : | "nonlocal" identifier augop expression_list
Georg Brandlc5d98b42007-12-04 18:11:03 +0000983
Georg Brandl48310cd2009-01-03 21:18:54 +0000984The :keyword:`nonlocal` statement causes the listed identifiers to refer to
985previously bound variables in the nearest enclosing scope. This is important
986because the default behavior for binding is to search the local namespace
Georg Brandlc5d98b42007-12-04 18:11:03 +0000987first. The statement allows encapsulated code to rebind variables outside of
988the local scope besides the global (module) scope.
989
Georg Brandlc5d98b42007-12-04 18:11:03 +0000990.. XXX not implemented
991 The :keyword:`nonlocal` statement may prepend an assignment or augmented
992 assignment, but not an expression.
993
994Names listed in a :keyword:`nonlocal` statement, unlike to those listed in a
995:keyword:`global` statement, must refer to pre-existing bindings in an
996enclosing scope (the scope in which a new binding should be created cannot
997be determined unambiguously).
998
Georg Brandl48310cd2009-01-03 21:18:54 +0000999Names listed in a :keyword:`nonlocal` statement must not collide with
Georg Brandlc5d98b42007-12-04 18:11:03 +00001000pre-existing bindings in the local scope.
1001
1002.. seealso::
1003
1004 :pep:`3104` - Access to Names in Outer Scopes
1005 The specification for the :keyword:`nonlocal` statement.