blob: 7d71752936568bd87e294e2bb8f93b3ec517806b [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
Raymond Hettingeraa7886d2014-05-26 22:20:37 -070010A simple statement is comprised within a single logical line. Several simple
Georg Brandl116aa622007-08-15 14:28:22 +000011statements 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::
Terry Jan Reedy9cc90262014-04-29 01:19:17 -040073 single: =; assignment statement
Georg Brandl116aa622007-08-15 14:28:22 +000074 pair: assignment; statement
75 pair: binding; name
76 pair: rebinding; name
77 object: mutable
78 pair: attribute; assignment
79
80Assignment statements are used to (re)bind names to values and to modify
81attributes or items of mutable objects:
82
83.. productionlist::
84 assignment_stmt: (`target_list` "=")+ (`expression_list` | `yield_expression`)
85 target_list: `target` ("," `target`)* [","]
86 target: `identifier`
87 : | "(" `target_list` ")"
Martin Panter7d7a11b2016-06-08 12:44:30 +000088 : | "[" [`target_list`] "]"
Georg Brandl116aa622007-08-15 14:28:22 +000089 : | `attributeref`
90 : | `subscription`
91 : | `slicing`
Georg Brandl02c30562007-09-07 17:52:53 +000092 : | "*" `target`
Georg Brandl116aa622007-08-15 14:28:22 +000093
Raymond Hettingeraa7886d2014-05-26 22:20:37 -070094(See section :ref:`primaries` for the syntax definitions for *attributeref*,
95*subscription*, and *slicing*.)
Georg Brandl116aa622007-08-15 14:28:22 +000096
Georg Brandl116aa622007-08-15 14:28:22 +000097An assignment statement evaluates the expression list (remember that this can be
98a single expression or a comma-separated list, the latter yielding a tuple) and
99assigns the single resulting object to each of the target lists, from left to
100right.
101
102.. index::
103 single: target
104 pair: target; list
105
106Assignment is defined recursively depending on the form of the target (list).
107When a target is part of a mutable object (an attribute reference, subscription
108or slicing), the mutable object must ultimately perform the assignment and
109decide about its validity, and may raise an exception if the assignment is
110unacceptable. The rules observed by various types and the exceptions raised are
111given with the definition of the object types (see section :ref:`types`).
112
113.. index:: triple: target; list; assignment
114
Georg Brandl02c30562007-09-07 17:52:53 +0000115Assignment of an object to a target list, optionally enclosed in parentheses or
116square brackets, is recursively defined as follows.
Georg Brandl116aa622007-08-15 14:28:22 +0000117
Martin Panter7d7a11b2016-06-08 12:44:30 +0000118* If the target list is empty: The object must also be an empty iterable.
Georg Brandl116aa622007-08-15 14:28:22 +0000119
Martin Panter7d7a11b2016-06-08 12:44:30 +0000120* If the target list is a single target in parentheses: The object is assigned
121 to that target.
122
123* If the target list is a comma-separated list of targets, or a single target
124 in square brackets: The object must be an iterable with the same number of
125 items as there are targets in the target list, and the items are assigned,
126 from left to right, to the corresponding targets.
Georg Brandl02c30562007-09-07 17:52:53 +0000127
128 * If the target list contains one target prefixed with an asterisk, called a
Martin Panter7d7a11b2016-06-08 12:44:30 +0000129 "starred" target: The object must be an iterable with at least as many items
Georg Brandl02c30562007-09-07 17:52:53 +0000130 as there are targets in the target list, minus one. The first items of the
Martin Panter7d7a11b2016-06-08 12:44:30 +0000131 iterable are assigned, from left to right, to the targets before the starred
132 target. The final items of the iterable are assigned to the targets after
133 the starred target. A list of the remaining items in the iterable is then
Georg Brandl02c30562007-09-07 17:52:53 +0000134 assigned to the starred target (the list can be empty).
135
Martin Panter7d7a11b2016-06-08 12:44:30 +0000136 * Else: The object must be an iterable with the same number of items as there
Georg Brandl02c30562007-09-07 17:52:53 +0000137 are targets in the target list, and the items are assigned, from left to
138 right, to the corresponding targets.
Georg Brandl116aa622007-08-15 14:28:22 +0000139
140Assignment of an object to a single target is recursively defined as follows.
141
142* If the target is an identifier (name):
143
Georg Brandl02c30562007-09-07 17:52:53 +0000144 * If the name does not occur in a :keyword:`global` or :keyword:`nonlocal`
145 statement in the current code block: the name is bound to the object in the
146 current local namespace.
Georg Brandl116aa622007-08-15 14:28:22 +0000147
Georg Brandl02c30562007-09-07 17:52:53 +0000148 * Otherwise: the name is bound to the object in the global namespace or the
149 outer namespace determined by :keyword:`nonlocal`, respectively.
Georg Brandl116aa622007-08-15 14:28:22 +0000150
Georg Brandl482b1512010-03-21 09:02:59 +0000151 .. index:: single: destructor
152
Georg Brandl02c30562007-09-07 17:52:53 +0000153 The name is rebound if it was already bound. This may cause the reference
154 count for the object previously bound to the name to reach zero, causing the
155 object to be deallocated and its destructor (if it has one) to be called.
Georg Brandl116aa622007-08-15 14:28:22 +0000156
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000157 .. 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
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700230 target sequence, if the target sequence 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
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700238Although the definition of assignment implies that overlaps between the
Martin Panterf05641642016-05-08 13:48:10 +0000239left-hand side and the right-hand side are 'simultaneous' (for example ``a, b =
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700240b, a`` swaps two variables), overlaps *within* the collection of assigned-to
241variables occur left-to-right, sometimes resulting in confusion. For instance,
242the following program prints ``[0, 2]``::
Georg Brandl116aa622007-08-15 14:28:22 +0000243
244 x = [0, 1]
245 i = 0
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700246 i, x[i] = 1, 2 # i is updated, then x[i] is updated
Georg Brandl6911e3c2007-09-04 07:15:32 +0000247 print(x)
Georg Brandl116aa622007-08-15 14:28:22 +0000248
249
Georg Brandl02c30562007-09-07 17:52:53 +0000250.. seealso::
251
252 :pep:`3132` - Extended Iterable Unpacking
253 The specification for the ``*target`` feature.
254
255
Georg Brandl116aa622007-08-15 14:28:22 +0000256.. _augassign:
257
258Augmented assignment statements
259-------------------------------
260
261.. index::
262 pair: augmented; assignment
263 single: statement; assignment, augmented
Terry Jan Reedy9cc90262014-04-29 01:19:17 -0400264 single: +=; augmented assignment
265 single: -=; augmented assignment
266 single: *=; augmented assignment
267 single: /=; augmented assignment
268 single: %=; augmented assignment
269 single: &=; augmented assignment
270 single: ^=; augmented assignment
271 single: |=; augmented assignment
272 single: **=; augmented assignment
273 single: //=; augmented assignment
274 single: >>=; augmented assignment
275 single: <<=; augmented assignment
Georg Brandl116aa622007-08-15 14:28:22 +0000276
277Augmented assignment is the combination, in a single statement, of a binary
278operation and an assignment statement:
279
280.. productionlist::
Benjamin Petersonb58dda72009-01-18 22:27:04 +0000281 augmented_assignment_stmt: `augtarget` `augop` (`expression_list` | `yield_expression`)
282 augtarget: `identifier` | `attributeref` | `subscription` | `slicing`
Benjamin Petersond51374e2014-04-09 23:55:56 -0400283 augop: "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**="
Georg Brandl116aa622007-08-15 14:28:22 +0000284 : | ">>=" | "<<=" | "&=" | "^=" | "|="
285
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700286(See section :ref:`primaries` for the syntax definitions of the last three
Georg Brandl116aa622007-08-15 14:28:22 +0000287symbols.)
288
289An augmented assignment evaluates the target (which, unlike normal assignment
290statements, cannot be an unpacking) and the expression list, performs the binary
291operation specific to the type of assignment on the two operands, and assigns
292the result to the original target. The target is only evaluated once.
293
294An augmented assignment expression like ``x += 1`` can be rewritten as ``x = x +
2951`` to achieve a similar, but not exactly equal effect. In the augmented
296version, ``x`` is only evaluated once. Also, when possible, the actual operation
297is performed *in-place*, meaning that rather than creating a new object and
298assigning that to the target, the old object is modified instead.
299
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700300Unlike normal assignments, augmented assignments evaluate the left-hand side
301*before* evaluating the right-hand side. For example, ``a[i] += f(x)`` first
302looks-up ``a[i]``, then it evaluates ``f(x)`` and performs the addition, and
303lastly, it writes the result back to ``a[i]``.
304
Georg Brandl116aa622007-08-15 14:28:22 +0000305With the exception of assigning to tuples and multiple targets in a single
306statement, the assignment done by augmented assignment statements is handled the
307same way as normal assignments. Similarly, with the exception of the possible
308*in-place* behavior, the binary operation performed by augmented assignment is
309the same as the normal binary operations.
310
Georg Brandlee8783d2009-09-16 16:00:31 +0000311For targets which are attribute references, the same :ref:`caveat about class
312and instance attributes <attr-target-note>` applies as for regular assignments.
Georg Brandl116aa622007-08-15 14:28:22 +0000313
314
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000315.. _assert:
316
317The :keyword:`assert` statement
318===============================
319
320.. index::
321 statement: assert
322 pair: debugging; assertions
323
324Assert statements are a convenient way to insert debugging assertions into a
325program:
326
327.. productionlist::
328 assert_stmt: "assert" `expression` ["," `expression`]
329
330The simple form, ``assert expression``, is equivalent to ::
331
332 if __debug__:
Serhiy Storchakadba90392016-05-10 12:01:23 +0300333 if not expression: raise AssertionError
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000334
335The extended form, ``assert expression1, expression2``, is equivalent to ::
336
337 if __debug__:
Serhiy Storchakadba90392016-05-10 12:01:23 +0300338 if not expression1: raise AssertionError(expression2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000339
340.. index::
341 single: __debug__
342 exception: AssertionError
343
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000344These equivalences assume that :const:`__debug__` and :exc:`AssertionError` refer to
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000345the built-in variables with those names. In the current implementation, the
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000346built-in variable :const:`__debug__` is ``True`` under normal circumstances,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000347``False`` when optimization is requested (command line option -O). The current
348code generator emits no code for an assert statement when optimization is
349requested at compile time. Note that it is unnecessary to include the source
350code for the expression that failed in the error message; it will be displayed
351as part of the stack trace.
352
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000353Assignments to :const:`__debug__` are illegal. The value for the built-in variable
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000354is determined when the interpreter starts.
355
356
Georg Brandl116aa622007-08-15 14:28:22 +0000357.. _pass:
358
359The :keyword:`pass` statement
360=============================
361
Christian Heimesfaf2f632008-01-06 16:59:19 +0000362.. index::
363 statement: pass
364 pair: null; operation
Georg Brandl02c30562007-09-07 17:52:53 +0000365 pair: null; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000366
367.. productionlist::
368 pass_stmt: "pass"
369
Georg Brandl116aa622007-08-15 14:28:22 +0000370:keyword:`pass` is a null operation --- when it is executed, nothing happens.
371It is useful as a placeholder when a statement is required syntactically, but no
372code needs to be executed, for example::
373
374 def f(arg): pass # a function that does nothing (yet)
375
376 class C: pass # a class with no methods (yet)
377
378
379.. _del:
380
381The :keyword:`del` statement
382============================
383
Christian Heimesfaf2f632008-01-06 16:59:19 +0000384.. index::
385 statement: del
386 pair: deletion; target
387 triple: deletion; target; list
Georg Brandl116aa622007-08-15 14:28:22 +0000388
389.. productionlist::
390 del_stmt: "del" `target_list`
391
Georg Brandl116aa622007-08-15 14:28:22 +0000392Deletion is recursively defined very similar to the way assignment is defined.
Sandro Tosi75c71cc2011-12-24 19:56:04 +0100393Rather than spelling it out in full details, here are some hints.
Georg Brandl116aa622007-08-15 14:28:22 +0000394
395Deletion of a target list recursively deletes each target, from left to right.
396
397.. index::
398 statement: global
399 pair: unbinding; name
400
Georg Brandl02c30562007-09-07 17:52:53 +0000401Deletion of a name removes the binding of that name from the local or global
Georg Brandl116aa622007-08-15 14:28:22 +0000402namespace, depending on whether the name occurs in a :keyword:`global` statement
403in the same code block. If the name is unbound, a :exc:`NameError` exception
404will be raised.
405
Georg Brandl116aa622007-08-15 14:28:22 +0000406.. index:: pair: attribute; deletion
407
408Deletion of attribute references, subscriptions and slicings is passed to the
409primary object involved; deletion of a slicing is in general equivalent to
410assignment of an empty slice of the right type (but even this is determined by
411the sliced object).
412
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000413.. versionchanged:: 3.2
414 Previously it was illegal to delete a name from the local namespace if it
415 occurs as a free variable in a nested block.
416
Georg Brandl116aa622007-08-15 14:28:22 +0000417
418.. _return:
419
420The :keyword:`return` statement
421===============================
422
Christian Heimesfaf2f632008-01-06 16:59:19 +0000423.. index::
424 statement: return
425 pair: function; definition
426 pair: class; definition
Georg Brandl116aa622007-08-15 14:28:22 +0000427
428.. productionlist::
429 return_stmt: "return" [`expression_list`]
430
Georg Brandl116aa622007-08-15 14:28:22 +0000431:keyword:`return` may only occur syntactically nested in a function definition,
432not within a nested class definition.
433
434If an expression list is present, it is evaluated, else ``None`` is substituted.
435
436:keyword:`return` leaves the current function call with the expression list (or
437``None``) as return value.
438
439.. index:: keyword: finally
440
441When :keyword:`return` passes control out of a :keyword:`try` statement with a
442:keyword:`finally` clause, that :keyword:`finally` clause is executed before
443really leaving the function.
444
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000445In a generator function, the :keyword:`return` statement indicates that the
446generator is done and will cause :exc:`StopIteration` to be raised. The returned
447value (if any) is used as an argument to construct :exc:`StopIteration` and
448becomes the :attr:`StopIteration.value` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000449
450
451.. _yield:
452
453The :keyword:`yield` statement
454==============================
455
Christian Heimesfaf2f632008-01-06 16:59:19 +0000456.. index::
457 statement: yield
458 single: generator; function
459 single: generator; iterator
460 single: function; generator
461 exception: StopIteration
462
Georg Brandl116aa622007-08-15 14:28:22 +0000463.. productionlist::
464 yield_stmt: `yield_expression`
465
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500466A :keyword:`yield` statement is semantically equivalent to a :ref:`yield
467expression <yieldexpr>`. The yield statement can be used to omit the parentheses
468that would otherwise be required in the equivalent yield expression
469statement. For example, the yield statements ::
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000470
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500471 yield <expr>
472 yield from <expr>
Christian Heimes33fe8092008-04-13 13:53:33 +0000473
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500474are equivalent to the yield expression statements ::
Christian Heimes33fe8092008-04-13 13:53:33 +0000475
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500476 (yield <expr>)
477 (yield from <expr>)
Christian Heimes33fe8092008-04-13 13:53:33 +0000478
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500479Yield expressions and statements are only used when defining a :term:`generator`
480function, and are only used in the body of the generator function. Using yield
481in a function definition is sufficient to cause that definition to create a
482generator function instead of a normal function.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000483
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500484For full details of :keyword:`yield` semantics, refer to the
485:ref:`yieldexpr` section.
Georg Brandl116aa622007-08-15 14:28:22 +0000486
487.. _raise:
488
489The :keyword:`raise` statement
490==============================
491
Christian Heimesfaf2f632008-01-06 16:59:19 +0000492.. index::
493 statement: raise
494 single: exception
495 pair: raising; exception
Georg Brandl1aea30a2008-07-19 15:51:07 +0000496 single: __traceback__ (exception attribute)
Georg Brandl116aa622007-08-15 14:28:22 +0000497
498.. productionlist::
Georg Brandle06de8b2008-05-05 21:42:51 +0000499 raise_stmt: "raise" [`expression` ["from" `expression`]]
Georg Brandl116aa622007-08-15 14:28:22 +0000500
501If no expressions are present, :keyword:`raise` re-raises the last exception
502that was active in the current scope. If no exception is active in the current
Sandro Tosib2794c82012-01-01 12:17:15 +0100503scope, a :exc:`RuntimeError` exception is raised indicating that this is an
504error.
Georg Brandl116aa622007-08-15 14:28:22 +0000505
Georg Brandl02c30562007-09-07 17:52:53 +0000506Otherwise, :keyword:`raise` evaluates the first expression as the exception
507object. It must be either a subclass or an instance of :class:`BaseException`.
508If it is a class, the exception instance will be obtained when needed by
509instantiating the class with no arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000510
Georg Brandl02c30562007-09-07 17:52:53 +0000511The :dfn:`type` of the exception is the exception instance's class, the
512:dfn:`value` is the instance itself.
Georg Brandl116aa622007-08-15 14:28:22 +0000513
514.. index:: object: traceback
515
Georg Brandl02c30562007-09-07 17:52:53 +0000516A traceback object is normally created automatically when an exception is raised
Georg Brandle06de8b2008-05-05 21:42:51 +0000517and attached to it as the :attr:`__traceback__` attribute, which is writable.
518You can create an exception and set your own traceback in one step using the
519:meth:`with_traceback` exception method (which returns the same exception
520instance, with its traceback set to its argument), like so::
Georg Brandl02c30562007-09-07 17:52:53 +0000521
Benjamin Petersonb7851692009-02-16 16:15:34 +0000522 raise Exception("foo occurred").with_traceback(tracebackobj)
Georg Brandl02c30562007-09-07 17:52:53 +0000523
Georg Brandl1aea30a2008-07-19 15:51:07 +0000524.. index:: pair: exception; chaining
525 __cause__ (exception attribute)
526 __context__ (exception attribute)
Georg Brandl48310cd2009-01-03 21:18:54 +0000527
Georg Brandl1aea30a2008-07-19 15:51:07 +0000528The ``from`` clause is used for exception chaining: if given, the second
529*expression* must be another exception class or instance, which will then be
530attached to the raised exception as the :attr:`__cause__` attribute (which is
531writable). If the raised exception is not handled, both exceptions will be
532printed::
Georg Brandl02c30562007-09-07 17:52:53 +0000533
Georg Brandl1aea30a2008-07-19 15:51:07 +0000534 >>> try:
535 ... print(1 / 0)
536 ... except Exception as exc:
537 ... raise RuntimeError("Something bad happened") from exc
538 ...
539 Traceback (most recent call last):
540 File "<stdin>", line 2, in <module>
541 ZeroDivisionError: int division or modulo by zero
542
543 The above exception was the direct cause of the following exception:
544
545 Traceback (most recent call last):
546 File "<stdin>", line 4, in <module>
547 RuntimeError: Something bad happened
548
549A similar mechanism works implicitly if an exception is raised inside an
Georg Brandla4c8c472014-10-31 10:38:49 +0100550exception handler or a :keyword:`finally` clause: the previous exception is then
551attached as the new exception's :attr:`__context__` attribute::
Georg Brandl1aea30a2008-07-19 15:51:07 +0000552
553 >>> try:
554 ... print(1 / 0)
555 ... except:
556 ... raise RuntimeError("Something bad happened")
557 ...
558 Traceback (most recent call last):
559 File "<stdin>", line 2, in <module>
560 ZeroDivisionError: int division or modulo by zero
561
562 During handling of the above exception, another exception occurred:
563
564 Traceback (most recent call last):
565 File "<stdin>", line 4, in <module>
566 RuntimeError: Something bad happened
Georg Brandl116aa622007-08-15 14:28:22 +0000567
568Additional information on exceptions can be found in section :ref:`exceptions`,
569and information about handling exceptions is in section :ref:`try`.
570
571
572.. _break:
573
574The :keyword:`break` statement
575==============================
576
Christian Heimesfaf2f632008-01-06 16:59:19 +0000577.. index::
578 statement: break
579 statement: for
580 statement: while
581 pair: loop; statement
Georg Brandl116aa622007-08-15 14:28:22 +0000582
583.. productionlist::
584 break_stmt: "break"
585
Georg Brandl116aa622007-08-15 14:28:22 +0000586:keyword:`break` may only occur syntactically nested in a :keyword:`for` or
587:keyword:`while` loop, but not nested in a function or class definition within
588that loop.
589
590.. index:: keyword: else
Georg Brandl02c30562007-09-07 17:52:53 +0000591 pair: loop control; target
Georg Brandl116aa622007-08-15 14:28:22 +0000592
593It terminates the nearest enclosing loop, skipping the optional :keyword:`else`
594clause if the loop has one.
595
Georg Brandl116aa622007-08-15 14:28:22 +0000596If a :keyword:`for` loop is terminated by :keyword:`break`, the loop control
597target keeps its current value.
598
599.. index:: keyword: finally
600
601When :keyword:`break` passes control out of a :keyword:`try` statement with a
602:keyword:`finally` clause, that :keyword:`finally` clause is executed before
603really leaving the loop.
604
605
606.. _continue:
607
608The :keyword:`continue` statement
609=================================
610
Christian Heimesfaf2f632008-01-06 16:59:19 +0000611.. index::
612 statement: continue
613 statement: for
614 statement: while
615 pair: loop; statement
616 keyword: finally
Georg Brandl116aa622007-08-15 14:28:22 +0000617
618.. productionlist::
619 continue_stmt: "continue"
620
Georg Brandl116aa622007-08-15 14:28:22 +0000621:keyword:`continue` may only occur syntactically nested in a :keyword:`for` or
622:keyword:`while` loop, but not nested in a function or class definition or
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000623:keyword:`finally` clause within that loop. It continues with the next
Georg Brandl116aa622007-08-15 14:28:22 +0000624cycle of the nearest enclosing loop.
625
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000626When :keyword:`continue` passes control out of a :keyword:`try` statement with a
627:keyword:`finally` clause, that :keyword:`finally` clause is executed before
628really starting the next loop cycle.
629
Georg Brandl116aa622007-08-15 14:28:22 +0000630
631.. _import:
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000632.. _from:
Georg Brandl116aa622007-08-15 14:28:22 +0000633
634The :keyword:`import` statement
635===============================
636
637.. index::
638 statement: import
639 single: module; importing
640 pair: name; binding
641 keyword: from
642
643.. productionlist::
644 import_stmt: "import" `module` ["as" `name`] ( "," `module` ["as" `name`] )*
645 : | "from" `relative_module` "import" `identifier` ["as" `name`]
646 : ( "," `identifier` ["as" `name`] )*
647 : | "from" `relative_module` "import" "(" `identifier` ["as" `name`]
648 : ( "," `identifier` ["as" `name`] )* [","] ")"
649 : | "from" `module` "import" "*"
650 module: (`identifier` ".")* `identifier`
651 relative_module: "."* `module` | "."+
652 name: `identifier`
653
Nick Coghlane3376ef2012-08-02 22:02:35 +1000654The basic import statement (no :keyword:`from` clause) is executed in two
655steps:
Barry Warsawdadebab2012-07-31 16:03:09 -0400656
Nick Coghlane3376ef2012-08-02 22:02:35 +1000657#. find a module, loading and initializing it if necessary
658#. define a name or names in the local namespace for the scope where
659 the :keyword:`import` statement occurs.
Georg Brandl116aa622007-08-15 14:28:22 +0000660
Nick Coghlane3376ef2012-08-02 22:02:35 +1000661When the statement contains multiple clauses (separated by
662commas) the two steps are carried out separately for each clause, just
Ned Deilycec95812016-05-17 21:44:46 -0400663as though the clauses had been separated out into individual import
Nick Coghlane3376ef2012-08-02 22:02:35 +1000664statements.
Georg Brandl116aa622007-08-15 14:28:22 +0000665
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700666The details of the first step, finding and loading modules are described in
Nick Coghlane3376ef2012-08-02 22:02:35 +1000667greater detail in the section on the :ref:`import system <importsystem>`,
668which also describes the various types of packages and modules that can
669be imported, as well as all the hooks that can be used to customize
670the import system. Note that failures in this step may indicate either
671that the module could not be located, *or* that an error occurred while
672initializing the module, which includes execution of the module's code.
Georg Brandl116aa622007-08-15 14:28:22 +0000673
Nick Coghlane3376ef2012-08-02 22:02:35 +1000674If the requested module is retrieved successfully, it will be made
675available in the local namespace in one of three ways:
676
Terry Jan Reedy7c895ed2014-04-29 00:58:56 -0400677.. index:: single: as; import statement
678
Nick Coghlane3376ef2012-08-02 22:02:35 +1000679* If the module name is followed by :keyword:`as`, then the name
680 following :keyword:`as` is bound directly to the imported module.
681* If no other name is specified, and the module being imported is a top
682 level module, the module's name is bound in the local namespace as a
683 reference to the imported module
684* If the module being imported is *not* a top level module, then the name
685 of the top level package that contains the module is bound in the local
686 namespace as a reference to the top level package. The imported module
687 must be accessed using its full qualified name rather than directly
688
Georg Brandl116aa622007-08-15 14:28:22 +0000689
690.. index::
691 pair: name; binding
Nick Coghlane3376ef2012-08-02 22:02:35 +1000692 keyword: from
Georg Brandl116aa622007-08-15 14:28:22 +0000693 exception: ImportError
694
Nick Coghlane3376ef2012-08-02 22:02:35 +1000695The :keyword:`from` form uses a slightly more complex process:
696
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700697#. find the module specified in the :keyword:`from` clause, loading and
Nick Coghlane3376ef2012-08-02 22:02:35 +1000698 initializing it if necessary;
699#. for each of the identifiers specified in the :keyword:`import` clauses:
700
701 #. check if the imported module has an attribute by that name
702 #. if not, attempt to import a submodule with that name and then
703 check the imported module again for that attribute
704 #. if the attribute is not found, :exc:`ImportError` is raised.
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700705 #. otherwise, a reference to that value is stored in the local namespace,
Nick Coghlane3376ef2012-08-02 22:02:35 +1000706 using the name in the :keyword:`as` clause if it is present,
707 otherwise using the attribute name
708
709Examples::
710
711 import foo # foo imported and bound locally
712 import foo.bar.baz # foo.bar.baz imported, foo bound locally
713 import foo.bar.baz as fbb # foo.bar.baz imported and bound as fbb
714 from foo.bar import baz # foo.bar.baz imported and bound as baz
715 from foo import attr # foo imported and foo.attr bound as attr
716
717If the list of identifiers is replaced by a star (``'*'``), all public
718names defined in the module are bound in the local namespace for the scope
719where the :keyword:`import` statement occurs.
720
721.. index:: single: __all__ (optional module attribute)
722
723The *public names* defined by a module are determined by checking the module's
724namespace for a variable named ``__all__``; if defined, it must be a sequence
725of strings which are names defined or imported by that module. The names
726given in ``__all__`` are all considered public and are required to exist. If
727``__all__`` is not defined, the set of public names includes all names found
728in the module's namespace which do not begin with an underscore character
729(``'_'``). ``__all__`` should contain the entire public API. It is intended
730to avoid accidentally exporting items that are not part of the API (such as
731library modules which were imported and used within the module).
732
Georg Brandla4c8c472014-10-31 10:38:49 +0100733The wild card form of import --- ``from module import *`` --- is only allowed at
734the module level. Attempting to use it in class or function definitions will
735raise a :exc:`SyntaxError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000736
737.. index::
Brett Cannone43b0602009-03-21 03:11:16 +0000738 single: relative; import
Georg Brandl116aa622007-08-15 14:28:22 +0000739
Brett Cannone43b0602009-03-21 03:11:16 +0000740When specifying what module to import you do not have to specify the absolute
741name of the module. When a module or package is contained within another
742package it is possible to make a relative import within the same top package
743without having to mention the package name. By using leading dots in the
744specified module or package after :keyword:`from` you can specify how high to
745traverse up the current package hierarchy without specifying exact names. One
746leading dot means the current package where the module making the import
747exists. Two dots means up one package level. Three dots is up two levels, etc.
748So if you execute ``from . import mod`` from a module in the ``pkg`` package
749then you will end up importing ``pkg.mod``. If you execute ``from ..subpkg2
Florent Xicluna0c8414e2010-09-03 20:23:40 +0000750import mod`` from within ``pkg.subpkg1`` you will import ``pkg.subpkg2.mod``.
Brett Cannone43b0602009-03-21 03:11:16 +0000751The specification for relative imports is contained within :pep:`328`.
Georg Brandl5b318c02008-08-03 09:47:27 +0000752
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000753:func:`importlib.import_module` is provided to support applications that
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700754determine dynamically the modules to be loaded.
Georg Brandl116aa622007-08-15 14:28:22 +0000755
756
757.. _future:
758
759Future statements
760-----------------
761
762.. index:: pair: future; statement
763
764A :dfn:`future statement` is a directive to the compiler that a particular
765module should be compiled using syntax or semantics that will be available in a
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700766specified future release of Python where the feature becomes standard.
767
768The future statement is intended to ease migration to future versions of Python
769that introduce incompatible changes to the language. It allows use of the new
770features on a per-module basis before the release in which the feature becomes
771standard.
Georg Brandl116aa622007-08-15 14:28:22 +0000772
773.. productionlist:: *
774 future_statement: "from" "__future__" "import" feature ["as" name]
775 : ("," feature ["as" name])*
776 : | "from" "__future__" "import" "(" feature ["as" name]
777 : ("," feature ["as" name])* [","] ")"
778 feature: identifier
779 name: identifier
780
781A future statement must appear near the top of the module. The only lines that
782can appear before a future statement are:
783
784* the module docstring (if any),
785* comments,
786* blank lines, and
787* other future statements.
788
Georg Brandl02c30562007-09-07 17:52:53 +0000789.. XXX change this if future is cleaned out
790
791The features recognized by Python 3.0 are ``absolute_import``, ``division``,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000792``generators``, ``unicode_literals``, ``print_function``, ``nested_scopes`` and
793``with_statement``. They are all redundant because they are always enabled, and
794only kept for backwards compatibility.
Georg Brandl116aa622007-08-15 14:28:22 +0000795
796A future statement is recognized and treated specially at compile time: Changes
797to the semantics of core constructs are often implemented by generating
798different code. It may even be the case that a new feature introduces new
799incompatible syntax (such as a new reserved word), in which case the compiler
800may need to parse the module differently. Such decisions cannot be pushed off
801until runtime.
802
803For any given release, the compiler knows which feature names have been defined,
804and raises a compile-time error if a future statement contains a feature not
805known to it.
806
807The direct runtime semantics are the same as for any import statement: there is
808a standard module :mod:`__future__`, described later, and it will be imported in
809the usual way at the time the future statement is executed.
810
811The interesting runtime semantics depend on the specific feature enabled by the
812future statement.
813
814Note that there is nothing special about the statement::
815
816 import __future__ [as name]
817
818That is not a future statement; it's an ordinary import statement with no
819special semantics or syntax restrictions.
820
Georg Brandl22b34312009-07-26 14:54:51 +0000821Code compiled by calls to the built-in functions :func:`exec` and :func:`compile`
Georg Brandl02c30562007-09-07 17:52:53 +0000822that occur in a module :mod:`M` containing a future statement will, by default,
823use the new syntax or semantics associated with the future statement. This can
824be controlled by optional arguments to :func:`compile` --- see the documentation
825of that function for details.
Georg Brandl116aa622007-08-15 14:28:22 +0000826
827A future statement typed at an interactive interpreter prompt will take effect
828for the rest of the interpreter session. If an interpreter is started with the
829:option:`-i` option, is passed a script name to execute, and the script includes
830a future statement, it will be in effect in the interactive session started
831after the script is executed.
832
Georg Brandlff2ad0e2009-04-27 16:51:45 +0000833.. seealso::
834
835 :pep:`236` - Back to the __future__
836 The original proposal for the __future__ mechanism.
837
Georg Brandl116aa622007-08-15 14:28:22 +0000838
839.. _global:
840
841The :keyword:`global` statement
842===============================
843
Christian Heimesfaf2f632008-01-06 16:59:19 +0000844.. index::
845 statement: global
846 triple: global; name; binding
Georg Brandl116aa622007-08-15 14:28:22 +0000847
848.. productionlist::
849 global_stmt: "global" `identifier` ("," `identifier`)*
850
Georg Brandl116aa622007-08-15 14:28:22 +0000851The :keyword:`global` statement is a declaration which holds for the entire
852current code block. It means that the listed identifiers are to be interpreted
853as globals. It would be impossible to assign to a global variable without
854:keyword:`global`, although free variables may refer to globals without being
855declared global.
856
857Names listed in a :keyword:`global` statement must not be used in the same code
858block textually preceding that :keyword:`global` statement.
859
860Names listed in a :keyword:`global` statement must not be defined as formal
861parameters or in a :keyword:`for` loop control target, :keyword:`class`
862definition, function definition, or :keyword:`import` statement.
863
Georg Brandl495f7b52009-10-27 15:28:25 +0000864.. impl-detail::
865
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700866 The current implementation does not enforce the two restrictions, but
Georg Brandl495f7b52009-10-27 15:28:25 +0000867 programs should not abuse this freedom, as future implementations may enforce
868 them or silently change the meaning of the program.
Georg Brandl116aa622007-08-15 14:28:22 +0000869
870.. index::
871 builtin: exec
872 builtin: eval
873 builtin: compile
874
875**Programmer's note:** the :keyword:`global` is a directive to the parser. It
876applies only to code parsed at the same time as the :keyword:`global` statement.
877In particular, a :keyword:`global` statement contained in a string or code
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000878object supplied to the built-in :func:`exec` function does not affect the code
Georg Brandl116aa622007-08-15 14:28:22 +0000879block *containing* the function call, and code contained in such a string is
880unaffected by :keyword:`global` statements in the code containing the function
881call. The same applies to the :func:`eval` and :func:`compile` functions.
882
Georg Brandl02c30562007-09-07 17:52:53 +0000883
884.. _nonlocal:
885
886The :keyword:`nonlocal` statement
887=================================
888
889.. index:: statement: nonlocal
890
891.. productionlist::
892 nonlocal_stmt: "nonlocal" `identifier` ("," `identifier`)*
893
Georg Brandlc5d98b42007-12-04 18:11:03 +0000894.. XXX add when implemented
Georg Brandl06788c92009-01-03 21:31:47 +0000895 : ["=" (`target_list` "=")+ expression_list]
896 : | "nonlocal" identifier augop expression_list
Georg Brandlc5d98b42007-12-04 18:11:03 +0000897
Georg Brandl48310cd2009-01-03 21:18:54 +0000898The :keyword:`nonlocal` statement causes the listed identifiers to refer to
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700899previously bound variables in the nearest enclosing scope excluding globals.
900This is important because the default behavior for binding is to search the
901local namespace first. The statement allows encapsulated code to rebind
902variables outside of the local scope besides the global (module) scope.
Georg Brandlc5d98b42007-12-04 18:11:03 +0000903
Georg Brandlc5d98b42007-12-04 18:11:03 +0000904.. XXX not implemented
905 The :keyword:`nonlocal` statement may prepend an assignment or augmented
906 assignment, but not an expression.
907
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700908Names listed in a :keyword:`nonlocal` statement, unlike those listed in a
Georg Brandlc5d98b42007-12-04 18:11:03 +0000909:keyword:`global` statement, must refer to pre-existing bindings in an
910enclosing scope (the scope in which a new binding should be created cannot
911be determined unambiguously).
912
Georg Brandl48310cd2009-01-03 21:18:54 +0000913Names listed in a :keyword:`nonlocal` statement must not collide with
Georg Brandlc5d98b42007-12-04 18:11:03 +0000914pre-existing bindings in the local scope.
915
916.. seealso::
917
918 :pep:`3104` - Access to Names in Outer Scopes
919 The specification for the :keyword:`nonlocal` statement.