blob: d509700f7507086526062d34a1044fe4cb934a21 [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`
Yury Selivanovf8cb8a12016-09-08 20:50:03 -070019 : | `annotated_assignment_stmt`
Georg Brandl116aa622007-08-15 14:28:22 +000020 : | `pass_stmt`
21 : | `del_stmt`
22 : | `return_stmt`
23 : | `yield_stmt`
24 : | `raise_stmt`
25 : | `break_stmt`
26 : | `continue_stmt`
27 : | `import_stmt`
Andrés Delfinocdb96f42018-11-07 14:32:18 -030028 : | `future_stmt`
Georg Brandl116aa622007-08-15 14:28:22 +000029 : | `global_stmt`
Georg Brandl02c30562007-09-07 17:52:53 +000030 : | `nonlocal_stmt`
Georg Brandl116aa622007-08-15 14:28:22 +000031
32
33.. _exprstmts:
34
35Expression statements
36=====================
37
Christian Heimesfaf2f632008-01-06 16:59:19 +000038.. index::
39 pair: expression; statement
40 pair: expression; list
Georg Brandl02c30562007-09-07 17:52:53 +000041.. index:: pair: expression; list
Georg Brandl116aa622007-08-15 14:28:22 +000042
43Expression statements are used (mostly interactively) to compute and write a
44value, or (usually) to call a procedure (a function that returns no meaningful
45result; in Python, procedures return the value ``None``). Other uses of
46expression statements are allowed and occasionally useful. The syntax for an
47expression statement is:
48
49.. productionlist::
Martin Panter0c0da482016-06-12 01:46:50 +000050 expression_stmt: `starred_expression`
Georg Brandl116aa622007-08-15 14:28:22 +000051
Georg Brandl116aa622007-08-15 14:28:22 +000052An expression statement evaluates the expression list (which may be a single
53expression).
54
55.. index::
56 builtin: repr
57 object: None
58 pair: string; conversion
59 single: output
60 pair: standard; output
61 pair: writing; values
62 pair: procedure; call
63
64In interactive mode, if the value is not ``None``, it is converted to a string
65using the built-in :func:`repr` function and the resulting string is written to
Georg Brandl02c30562007-09-07 17:52:53 +000066standard output on a line by itself (except if the result is ``None``, so that
67procedure calls do not cause any output.)
Georg Brandl116aa622007-08-15 14:28:22 +000068
Georg Brandl116aa622007-08-15 14:28:22 +000069.. _assignment:
70
71Assignment statements
72=====================
73
74.. index::
Serhiy Storchaka913876d2018-10-28 13:41:26 +020075 single: = (equals); assignment statement
Georg Brandl116aa622007-08-15 14:28:22 +000076 pair: assignment; statement
77 pair: binding; name
78 pair: rebinding; name
79 object: mutable
80 pair: attribute; assignment
81
82Assignment statements are used to (re)bind names to values and to modify
83attributes or items of mutable objects:
84
85.. productionlist::
Martin Panter0c0da482016-06-12 01:46:50 +000086 assignment_stmt: (`target_list` "=")+ (`starred_expression` | `yield_expression`)
Georg Brandl116aa622007-08-15 14:28:22 +000087 target_list: `target` ("," `target`)* [","]
88 target: `identifier`
Berker Peksag094c9c92016-05-18 08:44:29 +030089 : | "(" [`target_list`] ")"
90 : | "[" [`target_list`] "]"
Georg Brandl116aa622007-08-15 14:28:22 +000091 : | `attributeref`
92 : | `subscription`
93 : | `slicing`
Georg Brandl02c30562007-09-07 17:52:53 +000094 : | "*" `target`
Georg Brandl116aa622007-08-15 14:28:22 +000095
Raymond Hettingeraa7886d2014-05-26 22:20:37 -070096(See section :ref:`primaries` for the syntax definitions for *attributeref*,
97*subscription*, and *slicing*.)
Georg Brandl116aa622007-08-15 14:28:22 +000098
Georg Brandl116aa622007-08-15 14:28:22 +000099An assignment statement evaluates the expression list (remember that this can be
100a single expression or a comma-separated list, the latter yielding a tuple) and
101assigns the single resulting object to each of the target lists, from left to
102right.
103
104.. index::
105 single: target
106 pair: target; list
107
108Assignment is defined recursively depending on the form of the target (list).
109When a target is part of a mutable object (an attribute reference, subscription
110or slicing), the mutable object must ultimately perform the assignment and
111decide about its validity, and may raise an exception if the assignment is
112unacceptable. The rules observed by various types and the exceptions raised are
113given with the definition of the object types (see section :ref:`types`).
114
115.. index:: triple: target; list; assignment
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200116 single: , (comma); in target list
117 single: * (asterisk); in assignment target list
118 single: [] (square brackets); in assignment target list
119 single: () (parentheses); in assignment target list
Georg Brandl116aa622007-08-15 14:28:22 +0000120
Georg Brandl02c30562007-09-07 17:52:53 +0000121Assignment of an object to a target list, optionally enclosed in parentheses or
122square brackets, is recursively defined as follows.
Georg Brandl116aa622007-08-15 14:28:22 +0000123
Berker Peksag094c9c92016-05-18 08:44:29 +0300124* If the target list is empty: The object must also be an empty iterable.
Georg Brandl116aa622007-08-15 14:28:22 +0000125
Berker Peksag094c9c92016-05-18 08:44:29 +0300126* If the target list is a single target in parentheses: The object is assigned
127 to that target.
128
129* If the target list is a comma-separated list of targets, or a single target
130 in square brackets: The object must be an iterable with the same number of
131 items as there are targets in the target list, and the items are assigned,
132 from left to right, to the corresponding targets.
Georg Brandl02c30562007-09-07 17:52:53 +0000133
134 * If the target list contains one target prefixed with an asterisk, called a
Berker Peksag094c9c92016-05-18 08:44:29 +0300135 "starred" target: The object must be an iterable with at least as many items
Georg Brandl02c30562007-09-07 17:52:53 +0000136 as there are targets in the target list, minus one. The first items of the
Berker Peksag094c9c92016-05-18 08:44:29 +0300137 iterable are assigned, from left to right, to the targets before the starred
138 target. The final items of the iterable are assigned to the targets after
139 the starred target. A list of the remaining items in the iterable is then
Georg Brandl02c30562007-09-07 17:52:53 +0000140 assigned to the starred target (the list can be empty).
141
Berker Peksag094c9c92016-05-18 08:44:29 +0300142 * Else: The object must be an iterable with the same number of items as there
Georg Brandl02c30562007-09-07 17:52:53 +0000143 are targets in the target list, and the items are assigned, from left to
144 right, to the corresponding targets.
Georg Brandl116aa622007-08-15 14:28:22 +0000145
146Assignment of an object to a single target is recursively defined as follows.
147
148* If the target is an identifier (name):
149
Georg Brandl02c30562007-09-07 17:52:53 +0000150 * If the name does not occur in a :keyword:`global` or :keyword:`nonlocal`
151 statement in the current code block: the name is bound to the object in the
152 current local namespace.
Georg Brandl116aa622007-08-15 14:28:22 +0000153
Georg Brandl02c30562007-09-07 17:52:53 +0000154 * Otherwise: the name is bound to the object in the global namespace or the
155 outer namespace determined by :keyword:`nonlocal`, respectively.
Georg Brandl116aa622007-08-15 14:28:22 +0000156
Georg Brandl482b1512010-03-21 09:02:59 +0000157 .. index:: single: destructor
158
Georg Brandl02c30562007-09-07 17:52:53 +0000159 The name is rebound if it was already bound. This may cause the reference
160 count for the object previously bound to the name to reach zero, causing the
161 object to be deallocated and its destructor (if it has one) to be called.
Georg Brandl116aa622007-08-15 14:28:22 +0000162
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000163 .. index:: pair: attribute; assignment
164
Georg Brandl116aa622007-08-15 14:28:22 +0000165* If the target is an attribute reference: The primary expression in the
166 reference is evaluated. It should yield an object with assignable attributes;
Georg Brandl02c30562007-09-07 17:52:53 +0000167 if this is not the case, :exc:`TypeError` is raised. That object is then
168 asked to assign the assigned object to the given attribute; if it cannot
169 perform the assignment, it raises an exception (usually but not necessarily
Georg Brandl116aa622007-08-15 14:28:22 +0000170 :exc:`AttributeError`).
171
Georg Brandlee8783d2009-09-16 16:00:31 +0000172 .. _attr-target-note:
173
174 Note: If the object is a class instance and the attribute reference occurs on
175 both sides of the assignment operator, the RHS expression, ``a.x`` can access
176 either an instance attribute or (if no instance attribute exists) a class
177 attribute. The LHS target ``a.x`` is always set as an instance attribute,
178 creating it if necessary. Thus, the two occurrences of ``a.x`` do not
179 necessarily refer to the same attribute: if the RHS expression refers to a
180 class attribute, the LHS creates a new instance attribute as the target of the
181 assignment::
182
183 class Cls:
184 x = 3 # class variable
185 inst = Cls()
186 inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x as 3
187
188 This description does not necessarily apply to descriptor attributes, such as
189 properties created with :func:`property`.
190
Georg Brandl116aa622007-08-15 14:28:22 +0000191 .. index::
192 pair: subscription; assignment
193 object: mutable
194
195* If the target is a subscription: The primary expression in the reference is
Georg Brandl02c30562007-09-07 17:52:53 +0000196 evaluated. It should yield either a mutable sequence object (such as a list)
197 or a mapping object (such as a dictionary). Next, the subscript expression is
Georg Brandl116aa622007-08-15 14:28:22 +0000198 evaluated.
199
200 .. index::
201 object: sequence
202 object: list
203
Georg Brandl02c30562007-09-07 17:52:53 +0000204 If the primary is a mutable sequence object (such as a list), the subscript
205 must yield an integer. If it is negative, the sequence's length is added to
206 it. The resulting value must be a nonnegative integer less than the
207 sequence's length, and the sequence is asked to assign the assigned object to
208 its item with that index. If the index is out of range, :exc:`IndexError` is
209 raised (assignment to a subscripted sequence cannot add new items to a list).
Georg Brandl116aa622007-08-15 14:28:22 +0000210
211 .. index::
212 object: mapping
213 object: dictionary
214
215 If the primary is a mapping object (such as a dictionary), the subscript must
216 have a type compatible with the mapping's key type, and the mapping is then
217 asked to create a key/datum pair which maps the subscript to the assigned
218 object. This can either replace an existing key/value pair with the same key
219 value, or insert a new key/value pair (if no key with the same value existed).
220
Georg Brandl02c30562007-09-07 17:52:53 +0000221 For user-defined objects, the :meth:`__setitem__` method is called with
222 appropriate arguments.
223
Georg Brandl116aa622007-08-15 14:28:22 +0000224 .. index:: pair: slicing; assignment
225
226* If the target is a slicing: The primary expression in the reference is
227 evaluated. It should yield a mutable sequence object (such as a list). The
228 assigned object should be a sequence object of the same type. Next, the lower
229 and upper bound expressions are evaluated, insofar they are present; defaults
Georg Brandl02c30562007-09-07 17:52:53 +0000230 are zero and the sequence's length. The bounds should evaluate to integers.
231 If either bound is negative, the sequence's length is added to it. The
232 resulting bounds are clipped to lie between zero and the sequence's length,
233 inclusive. Finally, the sequence object is asked to replace the slice with
234 the items of the assigned sequence. The length of the slice may be different
235 from the length of the assigned sequence, thus changing the length of the
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700236 target sequence, if the target sequence allows it.
Georg Brandl116aa622007-08-15 14:28:22 +0000237
Georg Brandl495f7b52009-10-27 15:28:25 +0000238.. impl-detail::
239
240 In the current implementation, the syntax for targets is taken to be the same
241 as for expressions, and invalid syntax is rejected during the code generation
242 phase, causing less detailed error messages.
Georg Brandl116aa622007-08-15 14:28:22 +0000243
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700244Although the definition of assignment implies that overlaps between the
Martin Panterf05641642016-05-08 13:48:10 +0000245left-hand side and the right-hand side are 'simultaneous' (for example ``a, b =
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700246b, a`` swaps two variables), overlaps *within* the collection of assigned-to
247variables occur left-to-right, sometimes resulting in confusion. For instance,
248the following program prints ``[0, 2]``::
Georg Brandl116aa622007-08-15 14:28:22 +0000249
250 x = [0, 1]
251 i = 0
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700252 i, x[i] = 1, 2 # i is updated, then x[i] is updated
Georg Brandl6911e3c2007-09-04 07:15:32 +0000253 print(x)
Georg Brandl116aa622007-08-15 14:28:22 +0000254
255
Georg Brandl02c30562007-09-07 17:52:53 +0000256.. seealso::
257
258 :pep:`3132` - Extended Iterable Unpacking
259 The specification for the ``*target`` feature.
260
261
Georg Brandl116aa622007-08-15 14:28:22 +0000262.. _augassign:
263
264Augmented assignment statements
265-------------------------------
266
267.. index::
268 pair: augmented; assignment
269 single: statement; assignment, augmented
Terry Jan Reedy9cc90262014-04-29 01:19:17 -0400270 single: +=; augmented assignment
271 single: -=; augmented assignment
272 single: *=; augmented assignment
273 single: /=; augmented assignment
274 single: %=; augmented assignment
275 single: &=; augmented assignment
276 single: ^=; augmented assignment
277 single: |=; augmented assignment
278 single: **=; augmented assignment
279 single: //=; augmented assignment
280 single: >>=; augmented assignment
281 single: <<=; augmented assignment
Georg Brandl116aa622007-08-15 14:28:22 +0000282
283Augmented assignment is the combination, in a single statement, of a binary
284operation and an assignment statement:
285
286.. productionlist::
Benjamin Petersonb58dda72009-01-18 22:27:04 +0000287 augmented_assignment_stmt: `augtarget` `augop` (`expression_list` | `yield_expression`)
288 augtarget: `identifier` | `attributeref` | `subscription` | `slicing`
Benjamin Petersond51374e2014-04-09 23:55:56 -0400289 augop: "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**="
Georg Brandl116aa622007-08-15 14:28:22 +0000290 : | ">>=" | "<<=" | "&=" | "^=" | "|="
291
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700292(See section :ref:`primaries` for the syntax definitions of the last three
Georg Brandl116aa622007-08-15 14:28:22 +0000293symbols.)
294
295An augmented assignment evaluates the target (which, unlike normal assignment
296statements, cannot be an unpacking) and the expression list, performs the binary
297operation specific to the type of assignment on the two operands, and assigns
298the result to the original target. The target is only evaluated once.
299
300An augmented assignment expression like ``x += 1`` can be rewritten as ``x = x +
3011`` to achieve a similar, but not exactly equal effect. In the augmented
302version, ``x`` is only evaluated once. Also, when possible, the actual operation
303is performed *in-place*, meaning that rather than creating a new object and
304assigning that to the target, the old object is modified instead.
305
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700306Unlike normal assignments, augmented assignments evaluate the left-hand side
307*before* evaluating the right-hand side. For example, ``a[i] += f(x)`` first
308looks-up ``a[i]``, then it evaluates ``f(x)`` and performs the addition, and
309lastly, it writes the result back to ``a[i]``.
310
Georg Brandl116aa622007-08-15 14:28:22 +0000311With the exception of assigning to tuples and multiple targets in a single
312statement, the assignment done by augmented assignment statements is handled the
313same way as normal assignments. Similarly, with the exception of the possible
314*in-place* behavior, the binary operation performed by augmented assignment is
315the same as the normal binary operations.
316
Georg Brandlee8783d2009-09-16 16:00:31 +0000317For targets which are attribute references, the same :ref:`caveat about class
318and instance attributes <attr-target-note>` applies as for regular assignments.
Georg Brandl116aa622007-08-15 14:28:22 +0000319
320
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700321.. _annassign:
322
323Annotated assignment statements
324-------------------------------
325
326.. index::
327 pair: annotated; assignment
328 single: statement; assignment, annotated
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200329 single: : (colon); annotated variable
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700330
331Annotation assignment is the combination, in a single statement,
332of a variable or attribute annotation and an optional assignment statement:
333
334.. productionlist::
335 annotated_assignment_stmt: `augtarget` ":" `expression` ["=" `expression`]
336
337The difference from normal :ref:`assignment` is that only single target and
338only single right hand side value is allowed.
339
340For simple names as assignment targets, if in class or module scope,
341the annotations are evaluated and stored in a special class or module
342attribute :attr:`__annotations__`
Guido van Rossum015d8742016-09-11 09:45:24 -0700343that is a dictionary mapping from variable names (mangled if private) to
344evaluated annotations. This attribute is writable and is automatically
345created at the start of class or module body execution, if annotations
346are found statically.
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700347
348For expressions as assignment targets, the annotations are evaluated if
349in class or module scope, but not stored.
350
351If a name is annotated in a function scope, then this name is local for
352that scope. Annotations are never evaluated and stored in function scopes.
353
354If the right hand side is present, an annotated
355assignment performs the actual assignment before evaluating annotations
356(where applicable). If the right hand side is not present for an expression
357target, then the interpreter evaluates the target except for the last
358:meth:`__setitem__` or :meth:`__setattr__` call.
359
360.. seealso::
361
Andrés Delfino0f14fc12018-10-19 20:31:15 -0300362 :pep:`526` - Syntax for Variable Annotations
363 The proposal that added syntax for annotating the types of variables
364 (including class variables and instance variables), instead of expressing
365 them through comments.
366
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700367 :pep:`484` - Type hints
Andrés Delfino0f14fc12018-10-19 20:31:15 -0300368 The proposal that added the :mod:`typing` module to provide a standard
369 syntax for type annotations that can be used in static analysis tools and
370 IDEs.
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700371
372
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000373.. _assert:
374
375The :keyword:`assert` statement
376===============================
377
378.. index::
379 statement: assert
380 pair: debugging; assertions
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200381 single: , (comma); expression list
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000382
383Assert statements are a convenient way to insert debugging assertions into a
384program:
385
386.. productionlist::
387 assert_stmt: "assert" `expression` ["," `expression`]
388
389The simple form, ``assert expression``, is equivalent to ::
390
391 if __debug__:
Serhiy Storchakadba90392016-05-10 12:01:23 +0300392 if not expression: raise AssertionError
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000393
394The extended form, ``assert expression1, expression2``, is equivalent to ::
395
396 if __debug__:
Serhiy Storchakadba90392016-05-10 12:01:23 +0300397 if not expression1: raise AssertionError(expression2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000398
399.. index::
400 single: __debug__
401 exception: AssertionError
402
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000403These equivalences assume that :const:`__debug__` and :exc:`AssertionError` refer to
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000404the built-in variables with those names. In the current implementation, the
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000405built-in variable :const:`__debug__` is ``True`` under normal circumstances,
Andrés Delfinoea6a28c2018-11-07 14:06:45 -0300406``False`` when optimization is requested (command line option :option:`-O`). The current
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000407code generator emits no code for an assert statement when optimization is
408requested at compile time. Note that it is unnecessary to include the source
409code for the expression that failed in the error message; it will be displayed
410as part of the stack trace.
411
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000412Assignments to :const:`__debug__` are illegal. The value for the built-in variable
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000413is determined when the interpreter starts.
414
415
Georg Brandl116aa622007-08-15 14:28:22 +0000416.. _pass:
417
418The :keyword:`pass` statement
419=============================
420
Christian Heimesfaf2f632008-01-06 16:59:19 +0000421.. index::
422 statement: pass
423 pair: null; operation
Georg Brandl02c30562007-09-07 17:52:53 +0000424 pair: null; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000425
426.. productionlist::
427 pass_stmt: "pass"
428
Georg Brandl116aa622007-08-15 14:28:22 +0000429:keyword:`pass` is a null operation --- when it is executed, nothing happens.
430It is useful as a placeholder when a statement is required syntactically, but no
431code needs to be executed, for example::
432
433 def f(arg): pass # a function that does nothing (yet)
434
435 class C: pass # a class with no methods (yet)
436
437
438.. _del:
439
440The :keyword:`del` statement
441============================
442
Christian Heimesfaf2f632008-01-06 16:59:19 +0000443.. index::
444 statement: del
445 pair: deletion; target
446 triple: deletion; target; list
Georg Brandl116aa622007-08-15 14:28:22 +0000447
448.. productionlist::
449 del_stmt: "del" `target_list`
450
Georg Brandl116aa622007-08-15 14:28:22 +0000451Deletion is recursively defined very similar to the way assignment is defined.
Sandro Tosi75c71cc2011-12-24 19:56:04 +0100452Rather than spelling it out in full details, here are some hints.
Georg Brandl116aa622007-08-15 14:28:22 +0000453
454Deletion of a target list recursively deletes each target, from left to right.
455
456.. index::
457 statement: global
458 pair: unbinding; name
459
Georg Brandl02c30562007-09-07 17:52:53 +0000460Deletion of a name removes the binding of that name from the local or global
Georg Brandl116aa622007-08-15 14:28:22 +0000461namespace, depending on whether the name occurs in a :keyword:`global` statement
462in the same code block. If the name is unbound, a :exc:`NameError` exception
463will be raised.
464
Georg Brandl116aa622007-08-15 14:28:22 +0000465.. index:: pair: attribute; deletion
466
467Deletion of attribute references, subscriptions and slicings is passed to the
468primary object involved; deletion of a slicing is in general equivalent to
469assignment of an empty slice of the right type (but even this is determined by
470the sliced object).
471
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000472.. versionchanged:: 3.2
473 Previously it was illegal to delete a name from the local namespace if it
474 occurs as a free variable in a nested block.
475
Georg Brandl116aa622007-08-15 14:28:22 +0000476
477.. _return:
478
479The :keyword:`return` statement
480===============================
481
Christian Heimesfaf2f632008-01-06 16:59:19 +0000482.. index::
483 statement: return
484 pair: function; definition
485 pair: class; definition
Georg Brandl116aa622007-08-15 14:28:22 +0000486
487.. productionlist::
488 return_stmt: "return" [`expression_list`]
489
Georg Brandl116aa622007-08-15 14:28:22 +0000490:keyword:`return` may only occur syntactically nested in a function definition,
491not within a nested class definition.
492
493If an expression list is present, it is evaluated, else ``None`` is substituted.
494
495:keyword:`return` leaves the current function call with the expression list (or
496``None``) as return value.
497
498.. index:: keyword: finally
499
500When :keyword:`return` passes control out of a :keyword:`try` statement with a
501:keyword:`finally` clause, that :keyword:`finally` clause is executed before
502really leaving the function.
503
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000504In a generator function, the :keyword:`return` statement indicates that the
505generator is done and will cause :exc:`StopIteration` to be raised. The returned
506value (if any) is used as an argument to construct :exc:`StopIteration` and
507becomes the :attr:`StopIteration.value` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000508
Yury Selivanov03660042016-12-15 17:36:05 -0500509In an asynchronous generator function, an empty :keyword:`return` statement
510indicates that the asynchronous generator is done and will cause
511:exc:`StopAsyncIteration` to be raised. A non-empty :keyword:`return`
512statement is a syntax error in an asynchronous generator function.
Georg Brandl116aa622007-08-15 14:28:22 +0000513
514.. _yield:
515
516The :keyword:`yield` statement
517==============================
518
Christian Heimesfaf2f632008-01-06 16:59:19 +0000519.. index::
520 statement: yield
521 single: generator; function
522 single: generator; iterator
523 single: function; generator
524 exception: StopIteration
525
Georg Brandl116aa622007-08-15 14:28:22 +0000526.. productionlist::
527 yield_stmt: `yield_expression`
528
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500529A :keyword:`yield` statement is semantically equivalent to a :ref:`yield
530expression <yieldexpr>`. The yield statement can be used to omit the parentheses
531that would otherwise be required in the equivalent yield expression
532statement. For example, the yield statements ::
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000533
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500534 yield <expr>
535 yield from <expr>
Christian Heimes33fe8092008-04-13 13:53:33 +0000536
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500537are equivalent to the yield expression statements ::
Christian Heimes33fe8092008-04-13 13:53:33 +0000538
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500539 (yield <expr>)
540 (yield from <expr>)
Christian Heimes33fe8092008-04-13 13:53:33 +0000541
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500542Yield expressions and statements are only used when defining a :term:`generator`
543function, and are only used in the body of the generator function. Using yield
544in a function definition is sufficient to cause that definition to create a
545generator function instead of a normal function.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000546
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500547For full details of :keyword:`yield` semantics, refer to the
548:ref:`yieldexpr` section.
Georg Brandl116aa622007-08-15 14:28:22 +0000549
550.. _raise:
551
552The :keyword:`raise` statement
553==============================
554
Christian Heimesfaf2f632008-01-06 16:59:19 +0000555.. index::
556 statement: raise
557 single: exception
558 pair: raising; exception
Georg Brandl1aea30a2008-07-19 15:51:07 +0000559 single: __traceback__ (exception attribute)
Georg Brandl116aa622007-08-15 14:28:22 +0000560
561.. productionlist::
Georg Brandle06de8b2008-05-05 21:42:51 +0000562 raise_stmt: "raise" [`expression` ["from" `expression`]]
Georg Brandl116aa622007-08-15 14:28:22 +0000563
564If no expressions are present, :keyword:`raise` re-raises the last exception
565that was active in the current scope. If no exception is active in the current
Sandro Tosib2794c82012-01-01 12:17:15 +0100566scope, a :exc:`RuntimeError` exception is raised indicating that this is an
567error.
Georg Brandl116aa622007-08-15 14:28:22 +0000568
Georg Brandl02c30562007-09-07 17:52:53 +0000569Otherwise, :keyword:`raise` evaluates the first expression as the exception
570object. It must be either a subclass or an instance of :class:`BaseException`.
571If it is a class, the exception instance will be obtained when needed by
572instantiating the class with no arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000573
Georg Brandl02c30562007-09-07 17:52:53 +0000574The :dfn:`type` of the exception is the exception instance's class, the
575:dfn:`value` is the instance itself.
Georg Brandl116aa622007-08-15 14:28:22 +0000576
577.. index:: object: traceback
578
Georg Brandl02c30562007-09-07 17:52:53 +0000579A traceback object is normally created automatically when an exception is raised
Georg Brandle06de8b2008-05-05 21:42:51 +0000580and attached to it as the :attr:`__traceback__` attribute, which is writable.
581You can create an exception and set your own traceback in one step using the
582:meth:`with_traceback` exception method (which returns the same exception
583instance, with its traceback set to its argument), like so::
Georg Brandl02c30562007-09-07 17:52:53 +0000584
Benjamin Petersonb7851692009-02-16 16:15:34 +0000585 raise Exception("foo occurred").with_traceback(tracebackobj)
Georg Brandl02c30562007-09-07 17:52:53 +0000586
Georg Brandl1aea30a2008-07-19 15:51:07 +0000587.. index:: pair: exception; chaining
588 __cause__ (exception attribute)
589 __context__ (exception attribute)
Georg Brandl48310cd2009-01-03 21:18:54 +0000590
Georg Brandl1aea30a2008-07-19 15:51:07 +0000591The ``from`` clause is used for exception chaining: if given, the second
592*expression* must be another exception class or instance, which will then be
593attached to the raised exception as the :attr:`__cause__` attribute (which is
594writable). If the raised exception is not handled, both exceptions will be
595printed::
Georg Brandl02c30562007-09-07 17:52:53 +0000596
Georg Brandl1aea30a2008-07-19 15:51:07 +0000597 >>> try:
598 ... print(1 / 0)
599 ... except Exception as exc:
600 ... raise RuntimeError("Something bad happened") from exc
601 ...
602 Traceback (most recent call last):
603 File "<stdin>", line 2, in <module>
csabella763557e2017-05-20 02:48:28 -0400604 ZeroDivisionError: division by zero
Georg Brandl1aea30a2008-07-19 15:51:07 +0000605
606 The above exception was the direct cause of the following exception:
607
608 Traceback (most recent call last):
609 File "<stdin>", line 4, in <module>
610 RuntimeError: Something bad happened
611
612A similar mechanism works implicitly if an exception is raised inside an
Georg Brandla4c8c472014-10-31 10:38:49 +0100613exception handler or a :keyword:`finally` clause: the previous exception is then
614attached as the new exception's :attr:`__context__` attribute::
Georg Brandl1aea30a2008-07-19 15:51:07 +0000615
616 >>> try:
617 ... print(1 / 0)
618 ... except:
619 ... raise RuntimeError("Something bad happened")
620 ...
621 Traceback (most recent call last):
622 File "<stdin>", line 2, in <module>
csabella763557e2017-05-20 02:48:28 -0400623 ZeroDivisionError: division by zero
Georg Brandl1aea30a2008-07-19 15:51:07 +0000624
625 During handling of the above exception, another exception occurred:
626
627 Traceback (most recent call last):
628 File "<stdin>", line 4, in <module>
629 RuntimeError: Something bad happened
Georg Brandl116aa622007-08-15 14:28:22 +0000630
csabella763557e2017-05-20 02:48:28 -0400631Exception chaining can be explicitly suppressed by specifying :const:`None` in
632the ``from`` clause::
633
634 >>> try:
635 ... print(1 / 0)
636 ... except:
637 ... raise RuntimeError("Something bad happened") from None
638 ...
639 Traceback (most recent call last):
640 File "<stdin>", line 4, in <module>
641 RuntimeError: Something bad happened
642
Georg Brandl116aa622007-08-15 14:28:22 +0000643Additional information on exceptions can be found in section :ref:`exceptions`,
644and information about handling exceptions is in section :ref:`try`.
645
csabella763557e2017-05-20 02:48:28 -0400646.. versionchanged:: 3.3
Mariatta9efad1e2017-05-30 15:26:42 -0700647 :const:`None` is now permitted as ``Y`` in ``raise X from Y``.
csabella763557e2017-05-20 02:48:28 -0400648
649.. versionadded:: 3.3
650 The ``__suppress_context__`` attribute to suppress automatic display of the
Mariatta9efad1e2017-05-30 15:26:42 -0700651 exception context.
Georg Brandl116aa622007-08-15 14:28:22 +0000652
653.. _break:
654
655The :keyword:`break` statement
656==============================
657
Christian Heimesfaf2f632008-01-06 16:59:19 +0000658.. index::
659 statement: break
660 statement: for
661 statement: while
662 pair: loop; statement
Georg Brandl116aa622007-08-15 14:28:22 +0000663
664.. productionlist::
665 break_stmt: "break"
666
Georg Brandl116aa622007-08-15 14:28:22 +0000667:keyword:`break` may only occur syntactically nested in a :keyword:`for` or
668:keyword:`while` loop, but not nested in a function or class definition within
669that loop.
670
671.. index:: keyword: else
Georg Brandl02c30562007-09-07 17:52:53 +0000672 pair: loop control; target
Georg Brandl116aa622007-08-15 14:28:22 +0000673
674It terminates the nearest enclosing loop, skipping the optional :keyword:`else`
675clause if the loop has one.
676
Georg Brandl116aa622007-08-15 14:28:22 +0000677If a :keyword:`for` loop is terminated by :keyword:`break`, the loop control
678target keeps its current value.
679
680.. index:: keyword: finally
681
682When :keyword:`break` passes control out of a :keyword:`try` statement with a
683:keyword:`finally` clause, that :keyword:`finally` clause is executed before
684really leaving the loop.
685
686
687.. _continue:
688
689The :keyword:`continue` statement
690=================================
691
Christian Heimesfaf2f632008-01-06 16:59:19 +0000692.. index::
693 statement: continue
694 statement: for
695 statement: while
696 pair: loop; statement
697 keyword: finally
Georg Brandl116aa622007-08-15 14:28:22 +0000698
699.. productionlist::
700 continue_stmt: "continue"
701
Georg Brandl116aa622007-08-15 14:28:22 +0000702:keyword:`continue` may only occur syntactically nested in a :keyword:`for` or
Serhiy Storchakafe2bbb12018-03-18 09:56:52 +0200703:keyword:`while` loop, but not nested in a function or class definition within
704that loop. It continues with the next cycle of the nearest enclosing loop.
Georg Brandl116aa622007-08-15 14:28:22 +0000705
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000706When :keyword:`continue` passes control out of a :keyword:`try` statement with a
707:keyword:`finally` clause, that :keyword:`finally` clause is executed before
708really starting the next loop cycle.
709
Georg Brandl116aa622007-08-15 14:28:22 +0000710
711.. _import:
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000712.. _from:
Georg Brandl116aa622007-08-15 14:28:22 +0000713
714The :keyword:`import` statement
715===============================
716
717.. index::
718 statement: import
719 single: module; importing
720 pair: name; binding
721 keyword: from
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300722 keyword: as
723 exception: ImportError
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200724 single: , (comma); import statement
Georg Brandl116aa622007-08-15 14:28:22 +0000725
726.. productionlist::
Andrés Delfinocaccca782018-07-07 17:24:46 -0300727 import_stmt: "import" `module` ["as" `identifier`] ("," `module` ["as" `identifier`])*
728 : | "from" `relative_module` "import" `identifier` ["as" `identifier`]
729 : ("," `identifier` ["as" `identifier`])*
730 : | "from" `relative_module` "import" "(" `identifier` ["as" `identifier`]
731 : ("," `identifier` ["as" `identifier`])* [","] ")"
Georg Brandl116aa622007-08-15 14:28:22 +0000732 : | "from" `module` "import" "*"
733 module: (`identifier` ".")* `identifier`
734 relative_module: "."* `module` | "."+
Georg Brandl116aa622007-08-15 14:28:22 +0000735
Nick Coghlane3376ef2012-08-02 22:02:35 +1000736The basic import statement (no :keyword:`from` clause) is executed in two
737steps:
Barry Warsawdadebab2012-07-31 16:03:09 -0400738
Nick Coghlane3376ef2012-08-02 22:02:35 +1000739#. find a module, loading and initializing it if necessary
740#. define a name or names in the local namespace for the scope where
741 the :keyword:`import` statement occurs.
Georg Brandl116aa622007-08-15 14:28:22 +0000742
Nick Coghlane3376ef2012-08-02 22:02:35 +1000743When the statement contains multiple clauses (separated by
744commas) the two steps are carried out separately for each clause, just
Ned Deilycec95812016-05-17 21:44:46 -0400745as though the clauses had been separated out into individual import
Nick Coghlane3376ef2012-08-02 22:02:35 +1000746statements.
Georg Brandl116aa622007-08-15 14:28:22 +0000747
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700748The details of the first step, finding and loading modules are described in
Nick Coghlane3376ef2012-08-02 22:02:35 +1000749greater detail in the section on the :ref:`import system <importsystem>`,
750which also describes the various types of packages and modules that can
751be imported, as well as all the hooks that can be used to customize
752the import system. Note that failures in this step may indicate either
753that the module could not be located, *or* that an error occurred while
754initializing the module, which includes execution of the module's code.
Georg Brandl116aa622007-08-15 14:28:22 +0000755
Nick Coghlane3376ef2012-08-02 22:02:35 +1000756If the requested module is retrieved successfully, it will be made
757available in the local namespace in one of three ways:
758
Terry Jan Reedy7c895ed2014-04-29 00:58:56 -0400759.. index:: single: as; import statement
760
Nick Coghlane3376ef2012-08-02 22:02:35 +1000761* If the module name is followed by :keyword:`as`, then the name
762 following :keyword:`as` is bound directly to the imported module.
763* If no other name is specified, and the module being imported is a top
764 level module, the module's name is bound in the local namespace as a
765 reference to the imported module
766* If the module being imported is *not* a top level module, then the name
767 of the top level package that contains the module is bound in the local
768 namespace as a reference to the top level package. The imported module
769 must be accessed using its full qualified name rather than directly
770
Georg Brandl116aa622007-08-15 14:28:22 +0000771
772.. index::
773 pair: name; binding
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300774 single: from; import statement
Georg Brandl116aa622007-08-15 14:28:22 +0000775
Nick Coghlane3376ef2012-08-02 22:02:35 +1000776The :keyword:`from` form uses a slightly more complex process:
777
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700778#. find the module specified in the :keyword:`from` clause, loading and
Nick Coghlane3376ef2012-08-02 22:02:35 +1000779 initializing it if necessary;
780#. for each of the identifiers specified in the :keyword:`import` clauses:
781
782 #. check if the imported module has an attribute by that name
783 #. if not, attempt to import a submodule with that name and then
784 check the imported module again for that attribute
785 #. if the attribute is not found, :exc:`ImportError` is raised.
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700786 #. otherwise, a reference to that value is stored in the local namespace,
Nick Coghlane3376ef2012-08-02 22:02:35 +1000787 using the name in the :keyword:`as` clause if it is present,
788 otherwise using the attribute name
789
790Examples::
791
792 import foo # foo imported and bound locally
793 import foo.bar.baz # foo.bar.baz imported, foo bound locally
794 import foo.bar.baz as fbb # foo.bar.baz imported and bound as fbb
795 from foo.bar import baz # foo.bar.baz imported and bound as baz
796 from foo import attr # foo imported and foo.attr bound as attr
797
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200798.. index:: single: * (asterisk); import statement
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300799
Nick Coghlane3376ef2012-08-02 22:02:35 +1000800If the list of identifiers is replaced by a star (``'*'``), all public
801names defined in the module are bound in the local namespace for the scope
802where the :keyword:`import` statement occurs.
803
804.. index:: single: __all__ (optional module attribute)
805
806The *public names* defined by a module are determined by checking the module's
807namespace for a variable named ``__all__``; if defined, it must be a sequence
808of strings which are names defined or imported by that module. The names
809given in ``__all__`` are all considered public and are required to exist. If
810``__all__`` is not defined, the set of public names includes all names found
811in the module's namespace which do not begin with an underscore character
812(``'_'``). ``__all__`` should contain the entire public API. It is intended
813to avoid accidentally exporting items that are not part of the API (such as
814library modules which were imported and used within the module).
815
Georg Brandla4c8c472014-10-31 10:38:49 +0100816The wild card form of import --- ``from module import *`` --- is only allowed at
817the module level. Attempting to use it in class or function definitions will
818raise a :exc:`SyntaxError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000819
820.. index::
Brett Cannone43b0602009-03-21 03:11:16 +0000821 single: relative; import
Georg Brandl116aa622007-08-15 14:28:22 +0000822
Brett Cannone43b0602009-03-21 03:11:16 +0000823When specifying what module to import you do not have to specify the absolute
824name of the module. When a module or package is contained within another
825package it is possible to make a relative import within the same top package
826without having to mention the package name. By using leading dots in the
827specified module or package after :keyword:`from` you can specify how high to
828traverse up the current package hierarchy without specifying exact names. One
829leading dot means the current package where the module making the import
830exists. Two dots means up one package level. Three dots is up two levels, etc.
831So if you execute ``from . import mod`` from a module in the ``pkg`` package
832then you will end up importing ``pkg.mod``. If you execute ``from ..subpkg2
Florent Xicluna0c8414e2010-09-03 20:23:40 +0000833import mod`` from within ``pkg.subpkg1`` you will import ``pkg.subpkg2.mod``.
Brett Cannone43b0602009-03-21 03:11:16 +0000834The specification for relative imports is contained within :pep:`328`.
Georg Brandl5b318c02008-08-03 09:47:27 +0000835
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000836:func:`importlib.import_module` is provided to support applications that
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700837determine dynamically the modules to be loaded.
Georg Brandl116aa622007-08-15 14:28:22 +0000838
839
840.. _future:
841
842Future statements
843-----------------
844
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300845.. index::
846 pair: future; statement
847 single: __future__; future statement
Georg Brandl116aa622007-08-15 14:28:22 +0000848
849A :dfn:`future statement` is a directive to the compiler that a particular
850module should be compiled using syntax or semantics that will be available in a
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700851specified future release of Python where the feature becomes standard.
852
853The future statement is intended to ease migration to future versions of Python
854that introduce incompatible changes to the language. It allows use of the new
855features on a per-module basis before the release in which the feature becomes
856standard.
Georg Brandl116aa622007-08-15 14:28:22 +0000857
858.. productionlist:: *
Andrés Delfinocaccca782018-07-07 17:24:46 -0300859 future_stmt: "from" "__future__" "import" `feature` ["as" `identifier`]
860 : ("," `feature` ["as" `identifier`])*
861 : | "from" "__future__" "import" "(" `feature` ["as" `identifier`]
862 : ("," `feature` ["as" `identifier`])* [","] ")"
863 feature: `identifier`
Georg Brandl116aa622007-08-15 14:28:22 +0000864
865A future statement must appear near the top of the module. The only lines that
866can appear before a future statement are:
867
868* the module docstring (if any),
869* comments,
870* blank lines, and
871* other future statements.
872
Guido van Rossum95e4d582018-01-26 08:20:18 -0800873The only feature in Python 3.7 that requires using the future statement is
874``annotations``.
Georg Brandl02c30562007-09-07 17:52:53 +0000875
Guido van Rossum95e4d582018-01-26 08:20:18 -0800876All historical features enabled by the future statement are still recognized
877by Python 3. The list includes ``absolute_import``, ``division``,
878``generators``, ``generator_stop``, ``unicode_literals``,
879``print_function``, ``nested_scopes`` and ``with_statement``. They are
880all redundant because they are always enabled, and only kept for
881backwards compatibility.
Georg Brandl116aa622007-08-15 14:28:22 +0000882
883A future statement is recognized and treated specially at compile time: Changes
884to the semantics of core constructs are often implemented by generating
885different code. It may even be the case that a new feature introduces new
886incompatible syntax (such as a new reserved word), in which case the compiler
887may need to parse the module differently. Such decisions cannot be pushed off
888until runtime.
889
890For any given release, the compiler knows which feature names have been defined,
891and raises a compile-time error if a future statement contains a feature not
892known to it.
893
894The direct runtime semantics are the same as for any import statement: there is
895a standard module :mod:`__future__`, described later, and it will be imported in
896the usual way at the time the future statement is executed.
897
898The interesting runtime semantics depend on the specific feature enabled by the
899future statement.
900
901Note that there is nothing special about the statement::
902
903 import __future__ [as name]
904
905That is not a future statement; it's an ordinary import statement with no
906special semantics or syntax restrictions.
907
Georg Brandl22b34312009-07-26 14:54:51 +0000908Code compiled by calls to the built-in functions :func:`exec` and :func:`compile`
Georg Brandl02c30562007-09-07 17:52:53 +0000909that occur in a module :mod:`M` containing a future statement will, by default,
910use the new syntax or semantics associated with the future statement. This can
911be controlled by optional arguments to :func:`compile` --- see the documentation
912of that function for details.
Georg Brandl116aa622007-08-15 14:28:22 +0000913
914A future statement typed at an interactive interpreter prompt will take effect
915for the rest of the interpreter session. If an interpreter is started with the
916:option:`-i` option, is passed a script name to execute, and the script includes
917a future statement, it will be in effect in the interactive session started
918after the script is executed.
919
Georg Brandlff2ad0e2009-04-27 16:51:45 +0000920.. seealso::
921
922 :pep:`236` - Back to the __future__
923 The original proposal for the __future__ mechanism.
924
Georg Brandl116aa622007-08-15 14:28:22 +0000925
926.. _global:
927
928The :keyword:`global` statement
929===============================
930
Christian Heimesfaf2f632008-01-06 16:59:19 +0000931.. index::
932 statement: global
933 triple: global; name; binding
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200934 single: , (comma); identifier list
Georg Brandl116aa622007-08-15 14:28:22 +0000935
936.. productionlist::
937 global_stmt: "global" `identifier` ("," `identifier`)*
938
Georg Brandl116aa622007-08-15 14:28:22 +0000939The :keyword:`global` statement is a declaration which holds for the entire
940current code block. It means that the listed identifiers are to be interpreted
941as globals. It would be impossible to assign to a global variable without
942:keyword:`global`, although free variables may refer to globals without being
943declared global.
944
945Names listed in a :keyword:`global` statement must not be used in the same code
946block textually preceding that :keyword:`global` statement.
947
948Names listed in a :keyword:`global` statement must not be defined as formal
949parameters or in a :keyword:`for` loop control target, :keyword:`class`
Guido van Rossum6cff8742016-09-09 09:36:26 -0700950definition, function definition, :keyword:`import` statement, or variable
951annotation.
Georg Brandl116aa622007-08-15 14:28:22 +0000952
Georg Brandl495f7b52009-10-27 15:28:25 +0000953.. impl-detail::
954
kms708478d59aca2017-09-28 15:54:48 -0400955 The current implementation does not enforce some of these restrictions, but
Georg Brandl495f7b52009-10-27 15:28:25 +0000956 programs should not abuse this freedom, as future implementations may enforce
957 them or silently change the meaning of the program.
Georg Brandl116aa622007-08-15 14:28:22 +0000958
959.. index::
960 builtin: exec
961 builtin: eval
962 builtin: compile
963
Jim Fasarakis-Hilliardf34c68502017-05-08 14:36:29 +0300964**Programmer's note:** :keyword:`global` is a directive to the parser. It
Georg Brandl116aa622007-08-15 14:28:22 +0000965applies only to code parsed at the same time as the :keyword:`global` statement.
966In particular, a :keyword:`global` statement contained in a string or code
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000967object supplied to the built-in :func:`exec` function does not affect the code
Georg Brandl116aa622007-08-15 14:28:22 +0000968block *containing* the function call, and code contained in such a string is
969unaffected by :keyword:`global` statements in the code containing the function
970call. The same applies to the :func:`eval` and :func:`compile` functions.
971
Georg Brandl02c30562007-09-07 17:52:53 +0000972
973.. _nonlocal:
974
975The :keyword:`nonlocal` statement
976=================================
977
978.. index:: statement: nonlocal
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200979 single: , (comma); identifier list
Georg Brandl02c30562007-09-07 17:52:53 +0000980
981.. productionlist::
982 nonlocal_stmt: "nonlocal" `identifier` ("," `identifier`)*
983
Georg Brandlc5d98b42007-12-04 18:11:03 +0000984.. XXX add when implemented
Martin Panter0c0da482016-06-12 01:46:50 +0000985 : ["=" (`target_list` "=")+ starred_expression]
Georg Brandl06788c92009-01-03 21:31:47 +0000986 : | "nonlocal" identifier augop expression_list
Georg Brandlc5d98b42007-12-04 18:11:03 +0000987
Georg Brandl48310cd2009-01-03 21:18:54 +0000988The :keyword:`nonlocal` statement causes the listed identifiers to refer to
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700989previously bound variables in the nearest enclosing scope excluding globals.
990This is important because the default behavior for binding is to search the
991local namespace first. The statement allows encapsulated code to rebind
992variables outside of the local scope besides the global (module) scope.
Georg Brandlc5d98b42007-12-04 18:11:03 +0000993
Georg Brandlc5d98b42007-12-04 18:11:03 +0000994.. XXX not implemented
995 The :keyword:`nonlocal` statement may prepend an assignment or augmented
996 assignment, but not an expression.
997
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700998Names listed in a :keyword:`nonlocal` statement, unlike those listed in a
Georg Brandlc5d98b42007-12-04 18:11:03 +0000999:keyword:`global` statement, must refer to pre-existing bindings in an
1000enclosing scope (the scope in which a new binding should be created cannot
1001be determined unambiguously).
1002
Georg Brandl48310cd2009-01-03 21:18:54 +00001003Names listed in a :keyword:`nonlocal` statement must not collide with
Georg Brandlc5d98b42007-12-04 18:11:03 +00001004pre-existing bindings in the local scope.
1005
1006.. seealso::
1007
1008 :pep:`3104` - Access to Names in Outer Scopes
1009 The specification for the :keyword:`nonlocal` statement.