blob: 04ed499701c1859415ed2b7fac2c046d93802a54 [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`
28 : | `global_stmt`
Georg Brandl02c30562007-09-07 17:52:53 +000029 : | `nonlocal_stmt`
Georg Brandl116aa622007-08-15 14:28:22 +000030
31
32.. _exprstmts:
33
34Expression statements
35=====================
36
Christian Heimesfaf2f632008-01-06 16:59:19 +000037.. index::
38 pair: expression; statement
39 pair: expression; list
Georg Brandl02c30562007-09-07 17:52:53 +000040.. index:: pair: expression; list
Georg Brandl116aa622007-08-15 14:28:22 +000041
42Expression statements are used (mostly interactively) to compute and write a
43value, or (usually) to call a procedure (a function that returns no meaningful
44result; in Python, procedures return the value ``None``). Other uses of
45expression statements are allowed and occasionally useful. The syntax for an
46expression statement is:
47
48.. productionlist::
Martin Panter0c0da482016-06-12 01:46:50 +000049 expression_stmt: `starred_expression`
Georg Brandl116aa622007-08-15 14:28:22 +000050
Georg Brandl116aa622007-08-15 14:28:22 +000051An expression statement evaluates the expression list (which may be a single
52expression).
53
54.. index::
55 builtin: repr
56 object: None
57 pair: string; conversion
58 single: output
59 pair: standard; output
60 pair: writing; values
61 pair: procedure; call
62
63In interactive mode, if the value is not ``None``, it is converted to a string
64using the built-in :func:`repr` function and the resulting string is written to
Georg Brandl02c30562007-09-07 17:52:53 +000065standard output on a line by itself (except if the result is ``None``, so that
66procedure calls do not cause any output.)
Georg Brandl116aa622007-08-15 14:28:22 +000067
Georg Brandl116aa622007-08-15 14:28:22 +000068.. _assignment:
69
70Assignment statements
71=====================
72
73.. index::
Terry Jan Reedy9cc90262014-04-29 01:19:17 -040074 single: =; assignment statement
Georg Brandl116aa622007-08-15 14:28:22 +000075 pair: assignment; statement
76 pair: binding; name
77 pair: rebinding; name
78 object: mutable
79 pair: attribute; assignment
80
81Assignment statements are used to (re)bind names to values and to modify
82attributes or items of mutable objects:
83
84.. productionlist::
Martin Panter0c0da482016-06-12 01:46:50 +000085 assignment_stmt: (`target_list` "=")+ (`starred_expression` | `yield_expression`)
Georg Brandl116aa622007-08-15 14:28:22 +000086 target_list: `target` ("," `target`)* [","]
87 target: `identifier`
Berker Peksag094c9c92016-05-18 08:44:29 +030088 : | "(" [`target_list`] ")"
89 : | "[" [`target_list`] "]"
Georg Brandl116aa622007-08-15 14:28:22 +000090 : | `attributeref`
91 : | `subscription`
92 : | `slicing`
Georg Brandl02c30562007-09-07 17:52:53 +000093 : | "*" `target`
Georg Brandl116aa622007-08-15 14:28:22 +000094
Raymond Hettingeraa7886d2014-05-26 22:20:37 -070095(See section :ref:`primaries` for the syntax definitions for *attributeref*,
96*subscription*, and *slicing*.)
Georg Brandl116aa622007-08-15 14:28:22 +000097
Georg Brandl116aa622007-08-15 14:28:22 +000098An assignment statement evaluates the expression list (remember that this can be
99a single expression or a comma-separated list, the latter yielding a tuple) and
100assigns the single resulting object to each of the target lists, from left to
101right.
102
103.. index::
104 single: target
105 pair: target; list
106
107Assignment is defined recursively depending on the form of the target (list).
108When a target is part of a mutable object (an attribute reference, subscription
109or slicing), the mutable object must ultimately perform the assignment and
110decide about its validity, and may raise an exception if the assignment is
111unacceptable. The rules observed by various types and the exceptions raised are
112given with the definition of the object types (see section :ref:`types`).
113
114.. index:: triple: target; list; assignment
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300115 single: ,; in target list
116 single: *; in assignment target list
117 single: [; in assignment target list
118 single: ]; in assignment target list
119 single: (; in assignment target list
120 single: ); in assignment target list
Georg Brandl116aa622007-08-15 14:28:22 +0000121
Georg Brandl02c30562007-09-07 17:52:53 +0000122Assignment of an object to a target list, optionally enclosed in parentheses or
123square brackets, is recursively defined as follows.
Georg Brandl116aa622007-08-15 14:28:22 +0000124
Berker Peksag094c9c92016-05-18 08:44:29 +0300125* If the target list is empty: The object must also be an empty iterable.
Georg Brandl116aa622007-08-15 14:28:22 +0000126
Berker Peksag094c9c92016-05-18 08:44:29 +0300127* If the target list is a single target in parentheses: The object is assigned
128 to that target.
129
130* If the target list is a comma-separated list of targets, or a single target
131 in square brackets: The object must be an iterable with the same number of
132 items as there are targets in the target list, and the items are assigned,
133 from left to right, to the corresponding targets.
Georg Brandl02c30562007-09-07 17:52:53 +0000134
135 * If the target list contains one target prefixed with an asterisk, called a
Berker Peksag094c9c92016-05-18 08:44:29 +0300136 "starred" target: The object must be an iterable with at least as many items
Georg Brandl02c30562007-09-07 17:52:53 +0000137 as there are targets in the target list, minus one. The first items of the
Berker Peksag094c9c92016-05-18 08:44:29 +0300138 iterable are assigned, from left to right, to the targets before the starred
139 target. The final items of the iterable are assigned to the targets after
140 the starred target. A list of the remaining items in the iterable is then
Georg Brandl02c30562007-09-07 17:52:53 +0000141 assigned to the starred target (the list can be empty).
142
Berker Peksag094c9c92016-05-18 08:44:29 +0300143 * Else: The object must be an iterable with the same number of items as there
Georg Brandl02c30562007-09-07 17:52:53 +0000144 are targets in the target list, and the items are assigned, from left to
145 right, to the corresponding targets.
Georg Brandl116aa622007-08-15 14:28:22 +0000146
147Assignment of an object to a single target is recursively defined as follows.
148
149* If the target is an identifier (name):
150
Georg Brandl02c30562007-09-07 17:52:53 +0000151 * If the name does not occur in a :keyword:`global` or :keyword:`nonlocal`
152 statement in the current code block: the name is bound to the object in the
153 current local namespace.
Georg Brandl116aa622007-08-15 14:28:22 +0000154
Georg Brandl02c30562007-09-07 17:52:53 +0000155 * Otherwise: the name is bound to the object in the global namespace or the
156 outer namespace determined by :keyword:`nonlocal`, respectively.
Georg Brandl116aa622007-08-15 14:28:22 +0000157
Georg Brandl482b1512010-03-21 09:02:59 +0000158 .. index:: single: destructor
159
Georg Brandl02c30562007-09-07 17:52:53 +0000160 The name is rebound if it was already bound. This may cause the reference
161 count for the object previously bound to the name to reach zero, causing the
162 object to be deallocated and its destructor (if it has one) to be called.
Georg Brandl116aa622007-08-15 14:28:22 +0000163
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000164 .. index:: pair: attribute; assignment
165
Georg Brandl116aa622007-08-15 14:28:22 +0000166* If the target is an attribute reference: The primary expression in the
167 reference is evaluated. It should yield an object with assignable attributes;
Georg Brandl02c30562007-09-07 17:52:53 +0000168 if this is not the case, :exc:`TypeError` is raised. That object is then
169 asked to assign the assigned object to the given attribute; if it cannot
170 perform the assignment, it raises an exception (usually but not necessarily
Georg Brandl116aa622007-08-15 14:28:22 +0000171 :exc:`AttributeError`).
172
Georg Brandlee8783d2009-09-16 16:00:31 +0000173 .. _attr-target-note:
174
175 Note: If the object is a class instance and the attribute reference occurs on
176 both sides of the assignment operator, the RHS expression, ``a.x`` can access
177 either an instance attribute or (if no instance attribute exists) a class
178 attribute. The LHS target ``a.x`` is always set as an instance attribute,
179 creating it if necessary. Thus, the two occurrences of ``a.x`` do not
180 necessarily refer to the same attribute: if the RHS expression refers to a
181 class attribute, the LHS creates a new instance attribute as the target of the
182 assignment::
183
184 class Cls:
185 x = 3 # class variable
186 inst = Cls()
187 inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x as 3
188
189 This description does not necessarily apply to descriptor attributes, such as
190 properties created with :func:`property`.
191
Georg Brandl116aa622007-08-15 14:28:22 +0000192 .. index::
193 pair: subscription; assignment
194 object: mutable
195
196* If the target is a subscription: The primary expression in the reference is
Georg Brandl02c30562007-09-07 17:52:53 +0000197 evaluated. It should yield either a mutable sequence object (such as a list)
198 or a mapping object (such as a dictionary). Next, the subscript expression is
Georg Brandl116aa622007-08-15 14:28:22 +0000199 evaluated.
200
201 .. index::
202 object: sequence
203 object: list
204
Georg Brandl02c30562007-09-07 17:52:53 +0000205 If the primary is a mutable sequence object (such as a list), the subscript
206 must yield an integer. If it is negative, the sequence's length is added to
207 it. The resulting value must be a nonnegative integer less than the
208 sequence's length, and the sequence is asked to assign the assigned object to
209 its item with that index. If the index is out of range, :exc:`IndexError` is
210 raised (assignment to a subscripted sequence cannot add new items to a list).
Georg Brandl116aa622007-08-15 14:28:22 +0000211
212 .. index::
213 object: mapping
214 object: dictionary
215
216 If the primary is a mapping object (such as a dictionary), the subscript must
217 have a type compatible with the mapping's key type, and the mapping is then
218 asked to create a key/datum pair which maps the subscript to the assigned
219 object. This can either replace an existing key/value pair with the same key
220 value, or insert a new key/value pair (if no key with the same value existed).
221
Georg Brandl02c30562007-09-07 17:52:53 +0000222 For user-defined objects, the :meth:`__setitem__` method is called with
223 appropriate arguments.
224
Georg Brandl116aa622007-08-15 14:28:22 +0000225 .. index:: pair: slicing; assignment
226
227* If the target is a slicing: The primary expression in the reference is
228 evaluated. It should yield a mutable sequence object (such as a list). The
229 assigned object should be a sequence object of the same type. Next, the lower
230 and upper bound expressions are evaluated, insofar they are present; defaults
Georg Brandl02c30562007-09-07 17:52:53 +0000231 are zero and the sequence's length. The bounds should evaluate to integers.
232 If either bound is negative, the sequence's length is added to it. The
233 resulting bounds are clipped to lie between zero and the sequence's length,
234 inclusive. Finally, the sequence object is asked to replace the slice with
235 the items of the assigned sequence. The length of the slice may be different
236 from the length of the assigned sequence, thus changing the length of the
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700237 target sequence, if the target sequence allows it.
Georg Brandl116aa622007-08-15 14:28:22 +0000238
Georg Brandl495f7b52009-10-27 15:28:25 +0000239.. impl-detail::
240
241 In the current implementation, the syntax for targets is taken to be the same
242 as for expressions, and invalid syntax is rejected during the code generation
243 phase, causing less detailed error messages.
Georg Brandl116aa622007-08-15 14:28:22 +0000244
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700245Although the definition of assignment implies that overlaps between the
Martin Panterf05641642016-05-08 13:48:10 +0000246left-hand side and the right-hand side are 'simultaneous' (for example ``a, b =
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700247b, a`` swaps two variables), overlaps *within* the collection of assigned-to
248variables occur left-to-right, sometimes resulting in confusion. For instance,
249the following program prints ``[0, 2]``::
Georg Brandl116aa622007-08-15 14:28:22 +0000250
251 x = [0, 1]
252 i = 0
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700253 i, x[i] = 1, 2 # i is updated, then x[i] is updated
Georg Brandl6911e3c2007-09-04 07:15:32 +0000254 print(x)
Georg Brandl116aa622007-08-15 14:28:22 +0000255
256
Georg Brandl02c30562007-09-07 17:52:53 +0000257.. seealso::
258
259 :pep:`3132` - Extended Iterable Unpacking
260 The specification for the ``*target`` feature.
261
262
Georg Brandl116aa622007-08-15 14:28:22 +0000263.. _augassign:
264
265Augmented assignment statements
266-------------------------------
267
268.. index::
269 pair: augmented; assignment
270 single: statement; assignment, augmented
Terry Jan Reedy9cc90262014-04-29 01:19:17 -0400271 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
282 single: <<=; augmented assignment
Georg Brandl116aa622007-08-15 14:28:22 +0000283
284Augmented assignment is the combination, in a single statement, of a binary
285operation and an assignment statement:
286
287.. productionlist::
Benjamin Petersonb58dda72009-01-18 22:27:04 +0000288 augmented_assignment_stmt: `augtarget` `augop` (`expression_list` | `yield_expression`)
289 augtarget: `identifier` | `attributeref` | `subscription` | `slicing`
Benjamin Petersond51374e2014-04-09 23:55:56 -0400290 augop: "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**="
Georg Brandl116aa622007-08-15 14:28:22 +0000291 : | ">>=" | "<<=" | "&=" | "^=" | "|="
292
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700293(See section :ref:`primaries` for the syntax definitions of the last three
Georg Brandl116aa622007-08-15 14:28:22 +0000294symbols.)
295
296An augmented assignment evaluates the target (which, unlike normal assignment
297statements, cannot be an unpacking) and the expression list, performs the binary
298operation specific to the type of assignment on the two operands, and assigns
299the result to the original target. The target is only evaluated once.
300
301An augmented assignment expression like ``x += 1`` can be rewritten as ``x = x +
3021`` to achieve a similar, but not exactly equal effect. In the augmented
303version, ``x`` is only evaluated once. Also, when possible, the actual operation
304is performed *in-place*, meaning that rather than creating a new object and
305assigning that to the target, the old object is modified instead.
306
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700307Unlike normal assignments, augmented assignments evaluate the left-hand side
308*before* evaluating the right-hand side. For example, ``a[i] += f(x)`` first
309looks-up ``a[i]``, then it evaluates ``f(x)`` and performs the addition, and
310lastly, it writes the result back to ``a[i]``.
311
Georg Brandl116aa622007-08-15 14:28:22 +0000312With the exception of assigning to tuples and multiple targets in a single
313statement, the assignment done by augmented assignment statements is handled the
314same way as normal assignments. Similarly, with the exception of the possible
315*in-place* behavior, the binary operation performed by augmented assignment is
316the same as the normal binary operations.
317
Georg Brandlee8783d2009-09-16 16:00:31 +0000318For targets which are attribute references, the same :ref:`caveat about class
319and instance attributes <attr-target-note>` applies as for regular assignments.
Georg Brandl116aa622007-08-15 14:28:22 +0000320
321
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700322.. _annassign:
323
324Annotated assignment statements
325-------------------------------
326
327.. index::
328 pair: annotated; assignment
329 single: statement; assignment, annotated
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300330 single: :; annotated variable
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700331
332Annotation assignment is the combination, in a single statement,
333of a variable or attribute annotation and an optional assignment statement:
334
335.. productionlist::
336 annotated_assignment_stmt: `augtarget` ":" `expression` ["=" `expression`]
337
338The difference from normal :ref:`assignment` is that only single target and
339only single right hand side value is allowed.
340
341For simple names as assignment targets, if in class or module scope,
342the annotations are evaluated and stored in a special class or module
343attribute :attr:`__annotations__`
Guido van Rossum015d8742016-09-11 09:45:24 -0700344that is a dictionary mapping from variable names (mangled if private) to
345evaluated annotations. This attribute is writable and is automatically
346created at the start of class or module body execution, if annotations
347are found statically.
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700348
349For expressions as assignment targets, the annotations are evaluated if
350in class or module scope, but not stored.
351
352If a name is annotated in a function scope, then this name is local for
353that scope. Annotations are never evaluated and stored in function scopes.
354
355If the right hand side is present, an annotated
356assignment performs the actual assignment before evaluating annotations
357(where applicable). If the right hand side is not present for an expression
358target, then the interpreter evaluates the target except for the last
359:meth:`__setitem__` or :meth:`__setattr__` call.
360
361.. seealso::
362
Miss Islington (bot)2a6cf442018-10-19 16:43:55 -0700363 :pep:`526` - Syntax for Variable Annotations
364 The proposal that added syntax for annotating the types of variables
365 (including class variables and instance variables), instead of expressing
366 them through comments.
367
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700368 :pep:`484` - Type hints
Miss Islington (bot)2a6cf442018-10-19 16:43:55 -0700369 The proposal that added the :mod:`typing` module to provide a standard
370 syntax for type annotations that can be used in static analysis tools and
371 IDEs.
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700372
373
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000374.. _assert:
375
376The :keyword:`assert` statement
377===============================
378
379.. index::
380 statement: assert
381 pair: debugging; assertions
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300382 single: ,; expression list
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000383
384Assert statements are a convenient way to insert debugging assertions into a
385program:
386
387.. productionlist::
388 assert_stmt: "assert" `expression` ["," `expression`]
389
390The simple form, ``assert expression``, is equivalent to ::
391
392 if __debug__:
Serhiy Storchakadba90392016-05-10 12:01:23 +0300393 if not expression: raise AssertionError
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000394
395The extended form, ``assert expression1, expression2``, is equivalent to ::
396
397 if __debug__:
Serhiy Storchakadba90392016-05-10 12:01:23 +0300398 if not expression1: raise AssertionError(expression2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000399
400.. index::
401 single: __debug__
402 exception: AssertionError
403
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000404These equivalences assume that :const:`__debug__` and :exc:`AssertionError` refer to
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000405the built-in variables with those names. In the current implementation, the
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000406built-in variable :const:`__debug__` is ``True`` under normal circumstances,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000407``False`` when optimization is requested (command line option -O). The current
408code generator emits no code for an assert statement when optimization is
409requested at compile time. Note that it is unnecessary to include the source
410code for the expression that failed in the error message; it will be displayed
411as part of the stack trace.
412
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000413Assignments to :const:`__debug__` are illegal. The value for the built-in variable
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000414is determined when the interpreter starts.
415
416
Georg Brandl116aa622007-08-15 14:28:22 +0000417.. _pass:
418
419The :keyword:`pass` statement
420=============================
421
Christian Heimesfaf2f632008-01-06 16:59:19 +0000422.. index::
423 statement: pass
424 pair: null; operation
Georg Brandl02c30562007-09-07 17:52:53 +0000425 pair: null; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000426
427.. productionlist::
428 pass_stmt: "pass"
429
Georg Brandl116aa622007-08-15 14:28:22 +0000430:keyword:`pass` is a null operation --- when it is executed, nothing happens.
431It is useful as a placeholder when a statement is required syntactically, but no
432code needs to be executed, for example::
433
434 def f(arg): pass # a function that does nothing (yet)
435
436 class C: pass # a class with no methods (yet)
437
438
439.. _del:
440
441The :keyword:`del` statement
442============================
443
Christian Heimesfaf2f632008-01-06 16:59:19 +0000444.. index::
445 statement: del
446 pair: deletion; target
447 triple: deletion; target; list
Georg Brandl116aa622007-08-15 14:28:22 +0000448
449.. productionlist::
450 del_stmt: "del" `target_list`
451
Georg Brandl116aa622007-08-15 14:28:22 +0000452Deletion is recursively defined very similar to the way assignment is defined.
Sandro Tosi75c71cc2011-12-24 19:56:04 +0100453Rather than spelling it out in full details, here are some hints.
Georg Brandl116aa622007-08-15 14:28:22 +0000454
455Deletion of a target list recursively deletes each target, from left to right.
456
457.. index::
458 statement: global
459 pair: unbinding; name
460
Georg Brandl02c30562007-09-07 17:52:53 +0000461Deletion of a name removes the binding of that name from the local or global
Georg Brandl116aa622007-08-15 14:28:22 +0000462namespace, depending on whether the name occurs in a :keyword:`global` statement
463in the same code block. If the name is unbound, a :exc:`NameError` exception
464will be raised.
465
Georg Brandl116aa622007-08-15 14:28:22 +0000466.. index:: pair: attribute; deletion
467
468Deletion of attribute references, subscriptions and slicings is passed to the
469primary object involved; deletion of a slicing is in general equivalent to
470assignment of an empty slice of the right type (but even this is determined by
471the sliced object).
472
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000473.. versionchanged:: 3.2
474 Previously it was illegal to delete a name from the local namespace if it
475 occurs as a free variable in a nested block.
476
Georg Brandl116aa622007-08-15 14:28:22 +0000477
478.. _return:
479
480The :keyword:`return` statement
481===============================
482
Christian Heimesfaf2f632008-01-06 16:59:19 +0000483.. index::
484 statement: return
485 pair: function; definition
486 pair: class; definition
Georg Brandl116aa622007-08-15 14:28:22 +0000487
488.. productionlist::
489 return_stmt: "return" [`expression_list`]
490
Georg Brandl116aa622007-08-15 14:28:22 +0000491:keyword:`return` may only occur syntactically nested in a function definition,
492not within a nested class definition.
493
494If an expression list is present, it is evaluated, else ``None`` is substituted.
495
496:keyword:`return` leaves the current function call with the expression list (or
497``None``) as return value.
498
499.. index:: keyword: finally
500
501When :keyword:`return` passes control out of a :keyword:`try` statement with a
502:keyword:`finally` clause, that :keyword:`finally` clause is executed before
503really leaving the function.
504
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000505In a generator function, the :keyword:`return` statement indicates that the
506generator is done and will cause :exc:`StopIteration` to be raised. The returned
507value (if any) is used as an argument to construct :exc:`StopIteration` and
508becomes the :attr:`StopIteration.value` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000509
Yury Selivanov03660042016-12-15 17:36:05 -0500510In an asynchronous generator function, an empty :keyword:`return` statement
511indicates that the asynchronous generator is done and will cause
512:exc:`StopAsyncIteration` to be raised. A non-empty :keyword:`return`
513statement is a syntax error in an asynchronous generator function.
Georg Brandl116aa622007-08-15 14:28:22 +0000514
515.. _yield:
516
517The :keyword:`yield` statement
518==============================
519
Christian Heimesfaf2f632008-01-06 16:59:19 +0000520.. index::
521 statement: yield
522 single: generator; function
523 single: generator; iterator
524 single: function; generator
525 exception: StopIteration
526
Georg Brandl116aa622007-08-15 14:28:22 +0000527.. productionlist::
528 yield_stmt: `yield_expression`
529
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500530A :keyword:`yield` statement is semantically equivalent to a :ref:`yield
531expression <yieldexpr>`. The yield statement can be used to omit the parentheses
532that would otherwise be required in the equivalent yield expression
533statement. For example, the yield statements ::
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000534
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500535 yield <expr>
536 yield from <expr>
Christian Heimes33fe8092008-04-13 13:53:33 +0000537
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500538are equivalent to the yield expression statements ::
Christian Heimes33fe8092008-04-13 13:53:33 +0000539
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500540 (yield <expr>)
541 (yield from <expr>)
Christian Heimes33fe8092008-04-13 13:53:33 +0000542
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500543Yield expressions and statements are only used when defining a :term:`generator`
544function, and are only used in the body of the generator function. Using yield
545in a function definition is sufficient to cause that definition to create a
546generator function instead of a normal function.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000547
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500548For full details of :keyword:`yield` semantics, refer to the
549:ref:`yieldexpr` section.
Georg Brandl116aa622007-08-15 14:28:22 +0000550
551.. _raise:
552
553The :keyword:`raise` statement
554==============================
555
Christian Heimesfaf2f632008-01-06 16:59:19 +0000556.. index::
557 statement: raise
558 single: exception
559 pair: raising; exception
Georg Brandl1aea30a2008-07-19 15:51:07 +0000560 single: __traceback__ (exception attribute)
Georg Brandl116aa622007-08-15 14:28:22 +0000561
562.. productionlist::
Georg Brandle06de8b2008-05-05 21:42:51 +0000563 raise_stmt: "raise" [`expression` ["from" `expression`]]
Georg Brandl116aa622007-08-15 14:28:22 +0000564
565If no expressions are present, :keyword:`raise` re-raises the last exception
566that was active in the current scope. If no exception is active in the current
Sandro Tosib2794c82012-01-01 12:17:15 +0100567scope, a :exc:`RuntimeError` exception is raised indicating that this is an
568error.
Georg Brandl116aa622007-08-15 14:28:22 +0000569
Georg Brandl02c30562007-09-07 17:52:53 +0000570Otherwise, :keyword:`raise` evaluates the first expression as the exception
571object. It must be either a subclass or an instance of :class:`BaseException`.
572If it is a class, the exception instance will be obtained when needed by
573instantiating the class with no arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000574
Georg Brandl02c30562007-09-07 17:52:53 +0000575The :dfn:`type` of the exception is the exception instance's class, the
576:dfn:`value` is the instance itself.
Georg Brandl116aa622007-08-15 14:28:22 +0000577
578.. index:: object: traceback
579
Georg Brandl02c30562007-09-07 17:52:53 +0000580A traceback object is normally created automatically when an exception is raised
Georg Brandle06de8b2008-05-05 21:42:51 +0000581and attached to it as the :attr:`__traceback__` attribute, which is writable.
582You can create an exception and set your own traceback in one step using the
583:meth:`with_traceback` exception method (which returns the same exception
584instance, with its traceback set to its argument), like so::
Georg Brandl02c30562007-09-07 17:52:53 +0000585
Benjamin Petersonb7851692009-02-16 16:15:34 +0000586 raise Exception("foo occurred").with_traceback(tracebackobj)
Georg Brandl02c30562007-09-07 17:52:53 +0000587
Georg Brandl1aea30a2008-07-19 15:51:07 +0000588.. index:: pair: exception; chaining
589 __cause__ (exception attribute)
590 __context__ (exception attribute)
Georg Brandl48310cd2009-01-03 21:18:54 +0000591
Georg Brandl1aea30a2008-07-19 15:51:07 +0000592The ``from`` clause is used for exception chaining: if given, the second
593*expression* must be another exception class or instance, which will then be
594attached to the raised exception as the :attr:`__cause__` attribute (which is
595writable). If the raised exception is not handled, both exceptions will be
596printed::
Georg Brandl02c30562007-09-07 17:52:53 +0000597
Georg Brandl1aea30a2008-07-19 15:51:07 +0000598 >>> try:
599 ... print(1 / 0)
600 ... except Exception as exc:
601 ... raise RuntimeError("Something bad happened") from exc
602 ...
603 Traceback (most recent call last):
604 File "<stdin>", line 2, in <module>
csabella763557e2017-05-20 02:48:28 -0400605 ZeroDivisionError: division by zero
Georg Brandl1aea30a2008-07-19 15:51:07 +0000606
607 The above exception was the direct cause of the following exception:
608
609 Traceback (most recent call last):
610 File "<stdin>", line 4, in <module>
611 RuntimeError: Something bad happened
612
613A similar mechanism works implicitly if an exception is raised inside an
Georg Brandla4c8c472014-10-31 10:38:49 +0100614exception handler or a :keyword:`finally` clause: the previous exception is then
615attached as the new exception's :attr:`__context__` attribute::
Georg Brandl1aea30a2008-07-19 15:51:07 +0000616
617 >>> try:
618 ... print(1 / 0)
619 ... except:
620 ... raise RuntimeError("Something bad happened")
621 ...
622 Traceback (most recent call last):
623 File "<stdin>", line 2, in <module>
csabella763557e2017-05-20 02:48:28 -0400624 ZeroDivisionError: division by zero
Georg Brandl1aea30a2008-07-19 15:51:07 +0000625
626 During handling of the above exception, another exception occurred:
627
628 Traceback (most recent call last):
629 File "<stdin>", line 4, in <module>
630 RuntimeError: Something bad happened
Georg Brandl116aa622007-08-15 14:28:22 +0000631
csabella763557e2017-05-20 02:48:28 -0400632Exception chaining can be explicitly suppressed by specifying :const:`None` in
633the ``from`` clause::
634
635 >>> try:
636 ... print(1 / 0)
637 ... except:
638 ... raise RuntimeError("Something bad happened") from None
639 ...
640 Traceback (most recent call last):
641 File "<stdin>", line 4, in <module>
642 RuntimeError: Something bad happened
643
Georg Brandl116aa622007-08-15 14:28:22 +0000644Additional information on exceptions can be found in section :ref:`exceptions`,
645and information about handling exceptions is in section :ref:`try`.
646
csabella763557e2017-05-20 02:48:28 -0400647.. versionchanged:: 3.3
Mariatta9efad1e2017-05-30 15:26:42 -0700648 :const:`None` is now permitted as ``Y`` in ``raise X from Y``.
csabella763557e2017-05-20 02:48:28 -0400649
650.. versionadded:: 3.3
651 The ``__suppress_context__`` attribute to suppress automatic display of the
Mariatta9efad1e2017-05-30 15:26:42 -0700652 exception context.
Georg Brandl116aa622007-08-15 14:28:22 +0000653
654.. _break:
655
656The :keyword:`break` statement
657==============================
658
Christian Heimesfaf2f632008-01-06 16:59:19 +0000659.. index::
660 statement: break
661 statement: for
662 statement: while
663 pair: loop; statement
Georg Brandl116aa622007-08-15 14:28:22 +0000664
665.. productionlist::
666 break_stmt: "break"
667
Georg Brandl116aa622007-08-15 14:28:22 +0000668:keyword:`break` may only occur syntactically nested in a :keyword:`for` or
669:keyword:`while` loop, but not nested in a function or class definition within
670that loop.
671
672.. index:: keyword: else
Georg Brandl02c30562007-09-07 17:52:53 +0000673 pair: loop control; target
Georg Brandl116aa622007-08-15 14:28:22 +0000674
675It terminates the nearest enclosing loop, skipping the optional :keyword:`else`
676clause if the loop has one.
677
Georg Brandl116aa622007-08-15 14:28:22 +0000678If a :keyword:`for` loop is terminated by :keyword:`break`, the loop control
679target keeps its current value.
680
681.. index:: keyword: finally
682
683When :keyword:`break` passes control out of a :keyword:`try` statement with a
684:keyword:`finally` clause, that :keyword:`finally` clause is executed before
685really leaving the loop.
686
687
688.. _continue:
689
690The :keyword:`continue` statement
691=================================
692
Christian Heimesfaf2f632008-01-06 16:59:19 +0000693.. index::
694 statement: continue
695 statement: for
696 statement: while
697 pair: loop; statement
698 keyword: finally
Georg Brandl116aa622007-08-15 14:28:22 +0000699
700.. productionlist::
701 continue_stmt: "continue"
702
Georg Brandl116aa622007-08-15 14:28:22 +0000703:keyword:`continue` may only occur syntactically nested in a :keyword:`for` or
704:keyword:`while` loop, but not nested in a function or class definition or
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000705:keyword:`finally` clause within that loop. It continues with the next
Georg Brandl116aa622007-08-15 14:28:22 +0000706cycle of the nearest enclosing loop.
707
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000708When :keyword:`continue` passes control out of a :keyword:`try` statement with a
709:keyword:`finally` clause, that :keyword:`finally` clause is executed before
710really starting the next loop cycle.
711
Georg Brandl116aa622007-08-15 14:28:22 +0000712
713.. _import:
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000714.. _from:
Georg Brandl116aa622007-08-15 14:28:22 +0000715
716The :keyword:`import` statement
717===============================
718
719.. index::
720 statement: import
721 single: module; importing
722 pair: name; binding
723 keyword: from
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300724 keyword: as
725 exception: ImportError
726 single: ,; import statement
Georg Brandl116aa622007-08-15 14:28:22 +0000727
728.. productionlist::
Miss Islington (bot)80c188f2018-07-07 14:09:09 -0700729 import_stmt: "import" `module` ["as" `identifier`] ("," `module` ["as" `identifier`])*
730 : | "from" `relative_module` "import" `identifier` ["as" `identifier`]
731 : ("," `identifier` ["as" `identifier`])*
732 : | "from" `relative_module` "import" "(" `identifier` ["as" `identifier`]
733 : ("," `identifier` ["as" `identifier`])* [","] ")"
Georg Brandl116aa622007-08-15 14:28:22 +0000734 : | "from" `module` "import" "*"
735 module: (`identifier` ".")* `identifier`
736 relative_module: "."* `module` | "."+
Georg Brandl116aa622007-08-15 14:28:22 +0000737
Nick Coghlane3376ef2012-08-02 22:02:35 +1000738The basic import statement (no :keyword:`from` clause) is executed in two
739steps:
Barry Warsawdadebab2012-07-31 16:03:09 -0400740
Nick Coghlane3376ef2012-08-02 22:02:35 +1000741#. find a module, loading and initializing it if necessary
742#. define a name or names in the local namespace for the scope where
743 the :keyword:`import` statement occurs.
Georg Brandl116aa622007-08-15 14:28:22 +0000744
Nick Coghlane3376ef2012-08-02 22:02:35 +1000745When the statement contains multiple clauses (separated by
746commas) the two steps are carried out separately for each clause, just
Ned Deilycec95812016-05-17 21:44:46 -0400747as though the clauses had been separated out into individual import
Nick Coghlane3376ef2012-08-02 22:02:35 +1000748statements.
Georg Brandl116aa622007-08-15 14:28:22 +0000749
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700750The details of the first step, finding and loading modules are described in
Nick Coghlane3376ef2012-08-02 22:02:35 +1000751greater detail in the section on the :ref:`import system <importsystem>`,
752which also describes the various types of packages and modules that can
753be imported, as well as all the hooks that can be used to customize
754the import system. Note that failures in this step may indicate either
755that the module could not be located, *or* that an error occurred while
756initializing the module, which includes execution of the module's code.
Georg Brandl116aa622007-08-15 14:28:22 +0000757
Nick Coghlane3376ef2012-08-02 22:02:35 +1000758If the requested module is retrieved successfully, it will be made
759available in the local namespace in one of three ways:
760
Terry Jan Reedy7c895ed2014-04-29 00:58:56 -0400761.. index:: single: as; import statement
762
Nick Coghlane3376ef2012-08-02 22:02:35 +1000763* If the module name is followed by :keyword:`as`, then the name
764 following :keyword:`as` is bound directly to the imported module.
765* If no other name is specified, and the module being imported is a top
766 level module, the module's name is bound in the local namespace as a
767 reference to the imported module
768* If the module being imported is *not* a top level module, then the name
769 of the top level package that contains the module is bound in the local
770 namespace as a reference to the top level package. The imported module
771 must be accessed using its full qualified name rather than directly
772
Georg Brandl116aa622007-08-15 14:28:22 +0000773
774.. index::
775 pair: name; binding
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300776 single: from; import statement
Georg Brandl116aa622007-08-15 14:28:22 +0000777
Nick Coghlane3376ef2012-08-02 22:02:35 +1000778The :keyword:`from` form uses a slightly more complex process:
779
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700780#. find the module specified in the :keyword:`from` clause, loading and
Nick Coghlane3376ef2012-08-02 22:02:35 +1000781 initializing it if necessary;
782#. for each of the identifiers specified in the :keyword:`import` clauses:
783
784 #. check if the imported module has an attribute by that name
785 #. if not, attempt to import a submodule with that name and then
786 check the imported module again for that attribute
787 #. if the attribute is not found, :exc:`ImportError` is raised.
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700788 #. otherwise, a reference to that value is stored in the local namespace,
Nick Coghlane3376ef2012-08-02 22:02:35 +1000789 using the name in the :keyword:`as` clause if it is present,
790 otherwise using the attribute name
791
792Examples::
793
794 import foo # foo imported and bound locally
795 import foo.bar.baz # foo.bar.baz imported, foo bound locally
796 import foo.bar.baz as fbb # foo.bar.baz imported and bound as fbb
797 from foo.bar import baz # foo.bar.baz imported and bound as baz
798 from foo import attr # foo imported and foo.attr bound as attr
799
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300800.. index:: single: *; import statement
801
Nick Coghlane3376ef2012-08-02 22:02:35 +1000802If the list of identifiers is replaced by a star (``'*'``), all public
803names defined in the module are bound in the local namespace for the scope
804where the :keyword:`import` statement occurs.
805
806.. index:: single: __all__ (optional module attribute)
807
808The *public names* defined by a module are determined by checking the module's
809namespace for a variable named ``__all__``; if defined, it must be a sequence
810of strings which are names defined or imported by that module. The names
811given in ``__all__`` are all considered public and are required to exist. If
812``__all__`` is not defined, the set of public names includes all names found
813in the module's namespace which do not begin with an underscore character
814(``'_'``). ``__all__`` should contain the entire public API. It is intended
815to avoid accidentally exporting items that are not part of the API (such as
816library modules which were imported and used within the module).
817
Georg Brandla4c8c472014-10-31 10:38:49 +0100818The wild card form of import --- ``from module import *`` --- is only allowed at
819the module level. Attempting to use it in class or function definitions will
820raise a :exc:`SyntaxError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000821
822.. index::
Brett Cannone43b0602009-03-21 03:11:16 +0000823 single: relative; import
Georg Brandl116aa622007-08-15 14:28:22 +0000824
Brett Cannone43b0602009-03-21 03:11:16 +0000825When specifying what module to import you do not have to specify the absolute
826name of the module. When a module or package is contained within another
827package it is possible to make a relative import within the same top package
828without having to mention the package name. By using leading dots in the
829specified module or package after :keyword:`from` you can specify how high to
830traverse up the current package hierarchy without specifying exact names. One
831leading dot means the current package where the module making the import
832exists. Two dots means up one package level. Three dots is up two levels, etc.
833So if you execute ``from . import mod`` from a module in the ``pkg`` package
834then you will end up importing ``pkg.mod``. If you execute ``from ..subpkg2
Florent Xicluna0c8414e2010-09-03 20:23:40 +0000835import mod`` from within ``pkg.subpkg1`` you will import ``pkg.subpkg2.mod``.
Brett Cannone43b0602009-03-21 03:11:16 +0000836The specification for relative imports is contained within :pep:`328`.
Georg Brandl5b318c02008-08-03 09:47:27 +0000837
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000838:func:`importlib.import_module` is provided to support applications that
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700839determine dynamically the modules to be loaded.
Georg Brandl116aa622007-08-15 14:28:22 +0000840
841
842.. _future:
843
844Future statements
845-----------------
846
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300847.. index::
848 pair: future; statement
849 single: __future__; future statement
Georg Brandl116aa622007-08-15 14:28:22 +0000850
851A :dfn:`future statement` is a directive to the compiler that a particular
852module should be compiled using syntax or semantics that will be available in a
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700853specified future release of Python where the feature becomes standard.
854
855The future statement is intended to ease migration to future versions of Python
856that introduce incompatible changes to the language. It allows use of the new
857features on a per-module basis before the release in which the feature becomes
858standard.
Georg Brandl116aa622007-08-15 14:28:22 +0000859
860.. productionlist:: *
Miss Islington (bot)80c188f2018-07-07 14:09:09 -0700861 future_stmt: "from" "__future__" "import" `feature` ["as" `identifier`]
862 : ("," `feature` ["as" `identifier`])*
863 : | "from" "__future__" "import" "(" `feature` ["as" `identifier`]
864 : ("," `feature` ["as" `identifier`])* [","] ")"
865 feature: `identifier`
Georg Brandl116aa622007-08-15 14:28:22 +0000866
867A future statement must appear near the top of the module. The only lines that
868can appear before a future statement are:
869
870* the module docstring (if any),
871* comments,
872* blank lines, and
873* other future statements.
874
Guido van Rossum95e4d582018-01-26 08:20:18 -0800875The only feature in Python 3.7 that requires using the future statement is
876``annotations``.
Georg Brandl02c30562007-09-07 17:52:53 +0000877
Guido van Rossum95e4d582018-01-26 08:20:18 -0800878All historical features enabled by the future statement are still recognized
879by Python 3. The list includes ``absolute_import``, ``division``,
880``generators``, ``generator_stop``, ``unicode_literals``,
881``print_function``, ``nested_scopes`` and ``with_statement``. They are
882all redundant because they are always enabled, and only kept for
883backwards compatibility.
Georg Brandl116aa622007-08-15 14:28:22 +0000884
885A future statement is recognized and treated specially at compile time: Changes
886to the semantics of core constructs are often implemented by generating
887different code. It may even be the case that a new feature introduces new
888incompatible syntax (such as a new reserved word), in which case the compiler
889may need to parse the module differently. Such decisions cannot be pushed off
890until runtime.
891
892For any given release, the compiler knows which feature names have been defined,
893and raises a compile-time error if a future statement contains a feature not
894known to it.
895
896The direct runtime semantics are the same as for any import statement: there is
897a standard module :mod:`__future__`, described later, and it will be imported in
898the usual way at the time the future statement is executed.
899
900The interesting runtime semantics depend on the specific feature enabled by the
901future statement.
902
903Note that there is nothing special about the statement::
904
905 import __future__ [as name]
906
907That is not a future statement; it's an ordinary import statement with no
908special semantics or syntax restrictions.
909
Georg Brandl22b34312009-07-26 14:54:51 +0000910Code compiled by calls to the built-in functions :func:`exec` and :func:`compile`
Georg Brandl02c30562007-09-07 17:52:53 +0000911that occur in a module :mod:`M` containing a future statement will, by default,
912use the new syntax or semantics associated with the future statement. This can
913be controlled by optional arguments to :func:`compile` --- see the documentation
914of that function for details.
Georg Brandl116aa622007-08-15 14:28:22 +0000915
916A future statement typed at an interactive interpreter prompt will take effect
917for the rest of the interpreter session. If an interpreter is started with the
918:option:`-i` option, is passed a script name to execute, and the script includes
919a future statement, it will be in effect in the interactive session started
920after the script is executed.
921
Georg Brandlff2ad0e2009-04-27 16:51:45 +0000922.. seealso::
923
924 :pep:`236` - Back to the __future__
925 The original proposal for the __future__ mechanism.
926
Georg Brandl116aa622007-08-15 14:28:22 +0000927
928.. _global:
929
930The :keyword:`global` statement
931===============================
932
Christian Heimesfaf2f632008-01-06 16:59:19 +0000933.. index::
934 statement: global
935 triple: global; name; binding
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300936 single: ,; identifier list
Georg Brandl116aa622007-08-15 14:28:22 +0000937
938.. productionlist::
939 global_stmt: "global" `identifier` ("," `identifier`)*
940
Georg Brandl116aa622007-08-15 14:28:22 +0000941The :keyword:`global` statement is a declaration which holds for the entire
942current code block. It means that the listed identifiers are to be interpreted
943as globals. It would be impossible to assign to a global variable without
944:keyword:`global`, although free variables may refer to globals without being
945declared global.
946
947Names listed in a :keyword:`global` statement must not be used in the same code
948block textually preceding that :keyword:`global` statement.
949
950Names listed in a :keyword:`global` statement must not be defined as formal
951parameters or in a :keyword:`for` loop control target, :keyword:`class`
Guido van Rossum6cff8742016-09-09 09:36:26 -0700952definition, function definition, :keyword:`import` statement, or variable
953annotation.
Georg Brandl116aa622007-08-15 14:28:22 +0000954
Georg Brandl495f7b52009-10-27 15:28:25 +0000955.. impl-detail::
956
kms708478d59aca2017-09-28 15:54:48 -0400957 The current implementation does not enforce some of these restrictions, but
Georg Brandl495f7b52009-10-27 15:28:25 +0000958 programs should not abuse this freedom, as future implementations may enforce
959 them or silently change the meaning of the program.
Georg Brandl116aa622007-08-15 14:28:22 +0000960
961.. index::
962 builtin: exec
963 builtin: eval
964 builtin: compile
965
Jim Fasarakis-Hilliardf34c68502017-05-08 14:36:29 +0300966**Programmer's note:** :keyword:`global` is a directive to the parser. It
Georg Brandl116aa622007-08-15 14:28:22 +0000967applies only to code parsed at the same time as the :keyword:`global` statement.
968In particular, a :keyword:`global` statement contained in a string or code
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000969object supplied to the built-in :func:`exec` function does not affect the code
Georg Brandl116aa622007-08-15 14:28:22 +0000970block *containing* the function call, and code contained in such a string is
971unaffected by :keyword:`global` statements in the code containing the function
972call. The same applies to the :func:`eval` and :func:`compile` functions.
973
Georg Brandl02c30562007-09-07 17:52:53 +0000974
975.. _nonlocal:
976
977The :keyword:`nonlocal` statement
978=================================
979
980.. index:: statement: nonlocal
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300981 single: ,; identifier list
Georg Brandl02c30562007-09-07 17:52:53 +0000982
983.. productionlist::
984 nonlocal_stmt: "nonlocal" `identifier` ("," `identifier`)*
985
Georg Brandlc5d98b42007-12-04 18:11:03 +0000986.. XXX add when implemented
Martin Panter0c0da482016-06-12 01:46:50 +0000987 : ["=" (`target_list` "=")+ starred_expression]
Georg Brandl06788c92009-01-03 21:31:47 +0000988 : | "nonlocal" identifier augop expression_list
Georg Brandlc5d98b42007-12-04 18:11:03 +0000989
Georg Brandl48310cd2009-01-03 21:18:54 +0000990The :keyword:`nonlocal` statement causes the listed identifiers to refer to
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700991previously bound variables in the nearest enclosing scope excluding globals.
992This is important because the default behavior for binding is to search the
993local namespace first. The statement allows encapsulated code to rebind
994variables outside of the local scope besides the global (module) scope.
Georg Brandlc5d98b42007-12-04 18:11:03 +0000995
Georg Brandlc5d98b42007-12-04 18:11:03 +0000996.. XXX not implemented
997 The :keyword:`nonlocal` statement may prepend an assignment or augmented
998 assignment, but not an expression.
999
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001000Names listed in a :keyword:`nonlocal` statement, unlike those listed in a
Georg Brandlc5d98b42007-12-04 18:11:03 +00001001:keyword:`global` statement, must refer to pre-existing bindings in an
1002enclosing scope (the scope in which a new binding should be created cannot
1003be determined unambiguously).
1004
Georg Brandl48310cd2009-01-03 21:18:54 +00001005Names listed in a :keyword:`nonlocal` statement must not collide with
Georg Brandlc5d98b42007-12-04 18:11:03 +00001006pre-existing bindings in the local scope.
1007
1008.. seealso::
1009
1010 :pep:`3104` - Access to Names in Outer Scopes
1011 The specification for the :keyword:`nonlocal` statement.