blob: bb1209dfc33bebe9e5b34cadd4e90bcef57610c9 [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
Victor Stinner8af239e2020-09-18 09:10:15 +020014.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +000015 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
Victor Stinner8af239e2020-09-18 09:10:15 +020049.. productionlist:: python-grammar
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
Victor Stinner8af239e2020-09-18 09:10:15 +020085.. productionlist:: python-grammar
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
Julien Palard082875d2018-11-12 00:59:39 +0100124* If the target list is a single target with no trailing comma,
125 optionally in parentheses, the object is assigned to that target.
Georg Brandl116aa622007-08-15 14:28:22 +0000126
Julien Palard082875d2018-11-12 00:59:39 +0100127* Else: The object must be an iterable with the same number of
Berker Peksag094c9c92016-05-18 08:44:29 +0300128 items as there are targets in the target list, and the items are assigned,
129 from left to right, to the corresponding targets.
Georg Brandl02c30562007-09-07 17:52:53 +0000130
131 * If the target list contains one target prefixed with an asterisk, called a
Berker Peksag094c9c92016-05-18 08:44:29 +0300132 "starred" target: The object must be an iterable with at least as many items
Georg Brandl02c30562007-09-07 17:52:53 +0000133 as there are targets in the target list, minus one. The first items of the
Berker Peksag094c9c92016-05-18 08:44:29 +0300134 iterable are assigned, from left to right, to the targets before the starred
135 target. The final items of the iterable are assigned to the targets after
136 the starred target. A list of the remaining items in the iterable is then
Georg Brandl02c30562007-09-07 17:52:53 +0000137 assigned to the starred target (the list can be empty).
138
Berker Peksag094c9c92016-05-18 08:44:29 +0300139 * Else: The object must be an iterable with the same number of items as there
Georg Brandl02c30562007-09-07 17:52:53 +0000140 are targets in the target list, and the items are assigned, from left to
141 right, to the corresponding targets.
Georg Brandl116aa622007-08-15 14:28:22 +0000142
143Assignment of an object to a single target is recursively defined as follows.
144
145* If the target is an identifier (name):
146
Georg Brandl02c30562007-09-07 17:52:53 +0000147 * If the name does not occur in a :keyword:`global` or :keyword:`nonlocal`
148 statement in the current code block: the name is bound to the object in the
149 current local namespace.
Georg Brandl116aa622007-08-15 14:28:22 +0000150
Georg Brandl02c30562007-09-07 17:52:53 +0000151 * Otherwise: the name is bound to the object in the global namespace or the
152 outer namespace determined by :keyword:`nonlocal`, respectively.
Georg Brandl116aa622007-08-15 14:28:22 +0000153
Georg Brandl482b1512010-03-21 09:02:59 +0000154 .. index:: single: destructor
155
Georg Brandl02c30562007-09-07 17:52:53 +0000156 The name is rebound if it was already bound. This may cause the reference
157 count for the object previously bound to the name to reach zero, causing the
158 object to be deallocated and its destructor (if it has one) to be called.
Georg Brandl116aa622007-08-15 14:28:22 +0000159
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000160 .. index:: pair: attribute; assignment
161
Georg Brandl116aa622007-08-15 14:28:22 +0000162* If the target is an attribute reference: The primary expression in the
163 reference is evaluated. It should yield an object with assignable attributes;
Georg Brandl02c30562007-09-07 17:52:53 +0000164 if this is not the case, :exc:`TypeError` is raised. That object is then
165 asked to assign the assigned object to the given attribute; if it cannot
166 perform the assignment, it raises an exception (usually but not necessarily
Georg Brandl116aa622007-08-15 14:28:22 +0000167 :exc:`AttributeError`).
168
Georg Brandlee8783d2009-09-16 16:00:31 +0000169 .. _attr-target-note:
170
171 Note: If the object is a class instance and the attribute reference occurs on
Andre Delfino5861cdd2019-05-03 11:59:05 -0300172 both sides of the assignment operator, the right-hand side expression, ``a.x`` can access
Georg Brandlee8783d2009-09-16 16:00:31 +0000173 either an instance attribute or (if no instance attribute exists) a class
Andre Delfino5861cdd2019-05-03 11:59:05 -0300174 attribute. The left-hand side target ``a.x`` is always set as an instance attribute,
Georg Brandlee8783d2009-09-16 16:00:31 +0000175 creating it if necessary. Thus, the two occurrences of ``a.x`` do not
Andre Delfino5861cdd2019-05-03 11:59:05 -0300176 necessarily refer to the same attribute: if the right-hand side expression refers to a
177 class attribute, the left-hand side creates a new instance attribute as the target of the
Georg Brandlee8783d2009-09-16 16:00:31 +0000178 assignment::
179
180 class Cls:
181 x = 3 # class variable
182 inst = Cls()
183 inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x as 3
184
185 This description does not necessarily apply to descriptor attributes, such as
186 properties created with :func:`property`.
187
Georg Brandl116aa622007-08-15 14:28:22 +0000188 .. index::
189 pair: subscription; assignment
190 object: mutable
191
192* If the target is a subscription: The primary expression in the reference is
Georg Brandl02c30562007-09-07 17:52:53 +0000193 evaluated. It should yield either a mutable sequence object (such as a list)
194 or a mapping object (such as a dictionary). Next, the subscript expression is
Georg Brandl116aa622007-08-15 14:28:22 +0000195 evaluated.
196
197 .. index::
198 object: sequence
199 object: list
200
Georg Brandl02c30562007-09-07 17:52:53 +0000201 If the primary is a mutable sequence object (such as a list), the subscript
202 must yield an integer. If it is negative, the sequence's length is added to
203 it. The resulting value must be a nonnegative integer less than the
204 sequence's length, and the sequence is asked to assign the assigned object to
205 its item with that index. If the index is out of range, :exc:`IndexError` is
206 raised (assignment to a subscripted sequence cannot add new items to a list).
Georg Brandl116aa622007-08-15 14:28:22 +0000207
208 .. index::
209 object: mapping
210 object: dictionary
211
212 If the primary is a mapping object (such as a dictionary), the subscript must
213 have a type compatible with the mapping's key type, and the mapping is then
214 asked to create a key/datum pair which maps the subscript to the assigned
215 object. This can either replace an existing key/value pair with the same key
216 value, or insert a new key/value pair (if no key with the same value existed).
217
Georg Brandl02c30562007-09-07 17:52:53 +0000218 For user-defined objects, the :meth:`__setitem__` method is called with
219 appropriate arguments.
220
Georg Brandl116aa622007-08-15 14:28:22 +0000221 .. index:: pair: slicing; assignment
222
223* If the target is a slicing: The primary expression in the reference is
224 evaluated. It should yield a mutable sequence object (such as a list). The
225 assigned object should be a sequence object of the same type. Next, the lower
226 and upper bound expressions are evaluated, insofar they are present; defaults
Georg Brandl02c30562007-09-07 17:52:53 +0000227 are zero and the sequence's length. The bounds should evaluate to integers.
228 If either bound is negative, the sequence's length is added to it. The
229 resulting bounds are clipped to lie between zero and the sequence's length,
230 inclusive. Finally, the sequence object is asked to replace the slice with
231 the items of the assigned sequence. The length of the slice may be different
232 from the length of the assigned sequence, thus changing the length of the
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700233 target sequence, if the target sequence allows it.
Georg Brandl116aa622007-08-15 14:28:22 +0000234
Georg Brandl495f7b52009-10-27 15:28:25 +0000235.. impl-detail::
236
237 In the current implementation, the syntax for targets is taken to be the same
238 as for expressions, and invalid syntax is rejected during the code generation
239 phase, causing less detailed error messages.
Georg Brandl116aa622007-08-15 14:28:22 +0000240
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700241Although the definition of assignment implies that overlaps between the
Martin Panterf05641642016-05-08 13:48:10 +0000242left-hand side and the right-hand side are 'simultaneous' (for example ``a, b =
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700243b, a`` swaps two variables), overlaps *within* the collection of assigned-to
244variables occur left-to-right, sometimes resulting in confusion. For instance,
245the following program prints ``[0, 2]``::
Georg Brandl116aa622007-08-15 14:28:22 +0000246
247 x = [0, 1]
248 i = 0
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700249 i, x[i] = 1, 2 # i is updated, then x[i] is updated
Georg Brandl6911e3c2007-09-04 07:15:32 +0000250 print(x)
Georg Brandl116aa622007-08-15 14:28:22 +0000251
252
Georg Brandl02c30562007-09-07 17:52:53 +0000253.. seealso::
254
255 :pep:`3132` - Extended Iterable Unpacking
256 The specification for the ``*target`` feature.
257
258
Georg Brandl116aa622007-08-15 14:28:22 +0000259.. _augassign:
260
261Augmented assignment statements
262-------------------------------
263
264.. index::
265 pair: augmented; assignment
266 single: statement; assignment, augmented
Terry Jan Reedy9cc90262014-04-29 01:19:17 -0400267 single: +=; augmented assignment
268 single: -=; augmented assignment
269 single: *=; augmented assignment
270 single: /=; augmented assignment
271 single: %=; augmented assignment
272 single: &=; augmented assignment
273 single: ^=; augmented assignment
274 single: |=; augmented assignment
275 single: **=; augmented assignment
276 single: //=; augmented assignment
277 single: >>=; augmented assignment
278 single: <<=; augmented assignment
Georg Brandl116aa622007-08-15 14:28:22 +0000279
280Augmented assignment is the combination, in a single statement, of a binary
281operation and an assignment statement:
282
Victor Stinner8af239e2020-09-18 09:10:15 +0200283.. productionlist:: python-grammar
Benjamin Petersonb58dda72009-01-18 22:27:04 +0000284 augmented_assignment_stmt: `augtarget` `augop` (`expression_list` | `yield_expression`)
285 augtarget: `identifier` | `attributeref` | `subscription` | `slicing`
Benjamin Petersond51374e2014-04-09 23:55:56 -0400286 augop: "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**="
Georg Brandl116aa622007-08-15 14:28:22 +0000287 : | ">>=" | "<<=" | "&=" | "^=" | "|="
288
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700289(See section :ref:`primaries` for the syntax definitions of the last three
Georg Brandl116aa622007-08-15 14:28:22 +0000290symbols.)
291
292An augmented assignment evaluates the target (which, unlike normal assignment
293statements, cannot be an unpacking) and the expression list, performs the binary
294operation specific to the type of assignment on the two operands, and assigns
295the result to the original target. The target is only evaluated once.
296
297An augmented assignment expression like ``x += 1`` can be rewritten as ``x = x +
2981`` to achieve a similar, but not exactly equal effect. In the augmented
299version, ``x`` is only evaluated once. Also, when possible, the actual operation
300is performed *in-place*, meaning that rather than creating a new object and
301assigning that to the target, the old object is modified instead.
302
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700303Unlike normal assignments, augmented assignments evaluate the left-hand side
304*before* evaluating the right-hand side. For example, ``a[i] += f(x)`` first
305looks-up ``a[i]``, then it evaluates ``f(x)`` and performs the addition, and
306lastly, it writes the result back to ``a[i]``.
307
Georg Brandl116aa622007-08-15 14:28:22 +0000308With the exception of assigning to tuples and multiple targets in a single
309statement, the assignment done by augmented assignment statements is handled the
310same way as normal assignments. Similarly, with the exception of the possible
311*in-place* behavior, the binary operation performed by augmented assignment is
312the same as the normal binary operations.
313
Georg Brandlee8783d2009-09-16 16:00:31 +0000314For targets which are attribute references, the same :ref:`caveat about class
315and instance attributes <attr-target-note>` applies as for regular assignments.
Georg Brandl116aa622007-08-15 14:28:22 +0000316
317
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700318.. _annassign:
319
320Annotated assignment statements
321-------------------------------
322
323.. index::
324 pair: annotated; assignment
325 single: statement; assignment, annotated
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200326 single: : (colon); annotated variable
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700327
Cheryl Sabellab7105c92018-12-24 00:09:09 -0500328:term:`Annotation <variable annotation>` assignment is the combination, in a single
329statement, of a variable or attribute annotation and an optional assignment statement:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700330
Victor Stinner8af239e2020-09-18 09:10:15 +0200331.. productionlist:: python-grammar
Ivan Levkivskyi82eac262019-06-03 00:41:00 +0100332 annotated_assignment_stmt: `augtarget` ":" `expression`
Ivan Levkivskyi8bcf2622019-06-04 11:37:46 +0100333 : ["=" (`starred_expression` | `yield_expression`)]
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700334
Ivan Levkivskyi8bcf2622019-06-04 11:37:46 +0100335The difference from normal :ref:`assignment` is that only single target is allowed.
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700336
337For simple names as assignment targets, if in class or module scope,
338the annotations are evaluated and stored in a special class or module
339attribute :attr:`__annotations__`
Guido van Rossum015d8742016-09-11 09:45:24 -0700340that is a dictionary mapping from variable names (mangled if private) to
341evaluated annotations. This attribute is writable and is automatically
342created at the start of class or module body execution, if annotations
343are found statically.
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700344
345For expressions as assignment targets, the annotations are evaluated if
346in class or module scope, but not stored.
347
348If a name is annotated in a function scope, then this name is local for
349that scope. Annotations are never evaluated and stored in function scopes.
350
351If the right hand side is present, an annotated
352assignment performs the actual assignment before evaluating annotations
353(where applicable). If the right hand side is not present for an expression
354target, then the interpreter evaluates the target except for the last
355:meth:`__setitem__` or :meth:`__setattr__` call.
356
357.. seealso::
358
Andrés Delfino0f14fc12018-10-19 20:31:15 -0300359 :pep:`526` - Syntax for Variable Annotations
360 The proposal that added syntax for annotating the types of variables
361 (including class variables and instance variables), instead of expressing
362 them through comments.
363
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700364 :pep:`484` - Type hints
Andrés Delfino0f14fc12018-10-19 20:31:15 -0300365 The proposal that added the :mod:`typing` module to provide a standard
366 syntax for type annotations that can be used in static analysis tools and
367 IDEs.
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700368
Ivan Levkivskyi82eac262019-06-03 00:41:00 +0100369.. versionchanged:: 3.8
370 Now annotated assignments allow same expressions in the right hand side as
Ivan Levkivskyi8bcf2622019-06-04 11:37:46 +0100371 the regular assignments. Previously, some expressions (like un-parenthesized
Ivan Levkivskyi82eac262019-06-03 00:41:00 +0100372 tuple expressions) caused a syntax error.
373
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700374
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000375.. _assert:
376
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200377The :keyword:`!assert` statement
378================================
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000379
380.. index::
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200381 ! statement: assert
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000382 pair: debugging; assertions
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200383 single: , (comma); expression list
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000384
385Assert statements are a convenient way to insert debugging assertions into a
386program:
387
Victor Stinner8af239e2020-09-18 09:10:15 +0200388.. productionlist:: python-grammar
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000389 assert_stmt: "assert" `expression` ["," `expression`]
390
391The simple form, ``assert expression``, is equivalent to ::
392
393 if __debug__:
Serhiy Storchakadba90392016-05-10 12:01:23 +0300394 if not expression: raise AssertionError
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000395
396The extended form, ``assert expression1, expression2``, is equivalent to ::
397
398 if __debug__:
Serhiy Storchakadba90392016-05-10 12:01:23 +0300399 if not expression1: raise AssertionError(expression2)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000400
401.. index::
402 single: __debug__
403 exception: AssertionError
404
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000405These equivalences assume that :const:`__debug__` and :exc:`AssertionError` refer to
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000406the built-in variables with those names. In the current implementation, the
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000407built-in variable :const:`__debug__` is ``True`` under normal circumstances,
Andrés Delfinoea6a28c2018-11-07 14:06:45 -0300408``False`` when optimization is requested (command line option :option:`-O`). The current
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000409code generator emits no code for an assert statement when optimization is
410requested at compile time. Note that it is unnecessary to include the source
411code for the expression that failed in the error message; it will be displayed
412as part of the stack trace.
413
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000414Assignments to :const:`__debug__` are illegal. The value for the built-in variable
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000415is determined when the interpreter starts.
416
417
Georg Brandl116aa622007-08-15 14:28:22 +0000418.. _pass:
419
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200420The :keyword:`!pass` statement
421==============================
Georg Brandl116aa622007-08-15 14:28:22 +0000422
Christian Heimesfaf2f632008-01-06 16:59:19 +0000423.. index::
424 statement: pass
425 pair: null; operation
Georg Brandl02c30562007-09-07 17:52:53 +0000426 pair: null; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000427
Victor Stinner8af239e2020-09-18 09:10:15 +0200428.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +0000429 pass_stmt: "pass"
430
Georg Brandl116aa622007-08-15 14:28:22 +0000431:keyword:`pass` is a null operation --- when it is executed, nothing happens.
432It is useful as a placeholder when a statement is required syntactically, but no
433code needs to be executed, for example::
434
435 def f(arg): pass # a function that does nothing (yet)
436
437 class C: pass # a class with no methods (yet)
438
439
440.. _del:
441
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200442The :keyword:`!del` statement
443=============================
Georg Brandl116aa622007-08-15 14:28:22 +0000444
Christian Heimesfaf2f632008-01-06 16:59:19 +0000445.. index::
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200446 ! statement: del
Christian Heimesfaf2f632008-01-06 16:59:19 +0000447 pair: deletion; target
448 triple: deletion; target; list
Georg Brandl116aa622007-08-15 14:28:22 +0000449
Victor Stinner8af239e2020-09-18 09:10:15 +0200450.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +0000451 del_stmt: "del" `target_list`
452
Georg Brandl116aa622007-08-15 14:28:22 +0000453Deletion is recursively defined very similar to the way assignment is defined.
Sandro Tosi75c71cc2011-12-24 19:56:04 +0100454Rather than spelling it out in full details, here are some hints.
Georg Brandl116aa622007-08-15 14:28:22 +0000455
456Deletion of a target list recursively deletes each target, from left to right.
457
458.. index::
459 statement: global
460 pair: unbinding; name
461
Georg Brandl02c30562007-09-07 17:52:53 +0000462Deletion of a name removes the binding of that name from the local or global
Georg Brandl116aa622007-08-15 14:28:22 +0000463namespace, depending on whether the name occurs in a :keyword:`global` statement
464in the same code block. If the name is unbound, a :exc:`NameError` exception
465will be raised.
466
Georg Brandl116aa622007-08-15 14:28:22 +0000467.. index:: pair: attribute; deletion
468
469Deletion of attribute references, subscriptions and slicings is passed to the
470primary object involved; deletion of a slicing is in general equivalent to
471assignment of an empty slice of the right type (but even this is determined by
472the sliced object).
473
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000474.. versionchanged:: 3.2
475 Previously it was illegal to delete a name from the local namespace if it
476 occurs as a free variable in a nested block.
477
Georg Brandl116aa622007-08-15 14:28:22 +0000478
479.. _return:
480
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200481The :keyword:`!return` statement
482================================
Georg Brandl116aa622007-08-15 14:28:22 +0000483
Christian Heimesfaf2f632008-01-06 16:59:19 +0000484.. index::
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200485 ! statement: return
Christian Heimesfaf2f632008-01-06 16:59:19 +0000486 pair: function; definition
487 pair: class; definition
Georg Brandl116aa622007-08-15 14:28:22 +0000488
Victor Stinner8af239e2020-09-18 09:10:15 +0200489.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +0000490 return_stmt: "return" [`expression_list`]
491
Georg Brandl116aa622007-08-15 14:28:22 +0000492:keyword:`return` may only occur syntactically nested in a function definition,
493not within a nested class definition.
494
495If an expression list is present, it is evaluated, else ``None`` is substituted.
496
497:keyword:`return` leaves the current function call with the expression list (or
498``None``) as return value.
499
500.. index:: keyword: finally
501
502When :keyword:`return` passes control out of a :keyword:`try` statement with a
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200503:keyword:`finally` clause, that :keyword:`!finally` clause is executed before
Georg Brandl116aa622007-08-15 14:28:22 +0000504really leaving the function.
505
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000506In a generator function, the :keyword:`return` statement indicates that the
507generator is done and will cause :exc:`StopIteration` to be raised. The returned
508value (if any) is used as an argument to construct :exc:`StopIteration` and
509becomes the :attr:`StopIteration.value` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000510
Yury Selivanov03660042016-12-15 17:36:05 -0500511In an asynchronous generator function, an empty :keyword:`return` statement
512indicates that the asynchronous generator is done and will cause
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200513:exc:`StopAsyncIteration` to be raised. A non-empty :keyword:`!return`
Yury Selivanov03660042016-12-15 17:36:05 -0500514statement is a syntax error in an asynchronous generator function.
Georg Brandl116aa622007-08-15 14:28:22 +0000515
516.. _yield:
517
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200518The :keyword:`!yield` statement
519===============================
Georg Brandl116aa622007-08-15 14:28:22 +0000520
Christian Heimesfaf2f632008-01-06 16:59:19 +0000521.. index::
522 statement: yield
523 single: generator; function
524 single: generator; iterator
525 single: function; generator
526 exception: StopIteration
527
Victor Stinner8af239e2020-09-18 09:10:15 +0200528.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +0000529 yield_stmt: `yield_expression`
530
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500531A :keyword:`yield` statement is semantically equivalent to a :ref:`yield
532expression <yieldexpr>`. The yield statement can be used to omit the parentheses
533that would otherwise be required in the equivalent yield expression
534statement. For example, the yield statements ::
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000535
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500536 yield <expr>
537 yield from <expr>
Christian Heimes33fe8092008-04-13 13:53:33 +0000538
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500539are equivalent to the yield expression statements ::
Christian Heimes33fe8092008-04-13 13:53:33 +0000540
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500541 (yield <expr>)
542 (yield from <expr>)
Christian Heimes33fe8092008-04-13 13:53:33 +0000543
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500544Yield expressions and statements are only used when defining a :term:`generator`
545function, and are only used in the body of the generator function. Using yield
546in a function definition is sufficient to cause that definition to create a
547generator function instead of a normal function.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000548
Benjamin Petersond1c85fd2014-01-26 22:52:08 -0500549For full details of :keyword:`yield` semantics, refer to the
550:ref:`yieldexpr` section.
Georg Brandl116aa622007-08-15 14:28:22 +0000551
552.. _raise:
553
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200554The :keyword:`!raise` statement
555===============================
Georg Brandl116aa622007-08-15 14:28:22 +0000556
Christian Heimesfaf2f632008-01-06 16:59:19 +0000557.. index::
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200558 ! statement: raise
Christian Heimesfaf2f632008-01-06 16:59:19 +0000559 single: exception
560 pair: raising; exception
Georg Brandl1aea30a2008-07-19 15:51:07 +0000561 single: __traceback__ (exception attribute)
Georg Brandl116aa622007-08-15 14:28:22 +0000562
Victor Stinner8af239e2020-09-18 09:10:15 +0200563.. productionlist:: python-grammar
Georg Brandle06de8b2008-05-05 21:42:51 +0000564 raise_stmt: "raise" [`expression` ["from" `expression`]]
Georg Brandl116aa622007-08-15 14:28:22 +0000565
566If no expressions are present, :keyword:`raise` re-raises the last exception
567that was active in the current scope. If no exception is active in the current
Sandro Tosib2794c82012-01-01 12:17:15 +0100568scope, a :exc:`RuntimeError` exception is raised indicating that this is an
569error.
Georg Brandl116aa622007-08-15 14:28:22 +0000570
Georg Brandl02c30562007-09-07 17:52:53 +0000571Otherwise, :keyword:`raise` evaluates the first expression as the exception
572object. It must be either a subclass or an instance of :class:`BaseException`.
573If it is a class, the exception instance will be obtained when needed by
574instantiating the class with no arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000575
Georg Brandl02c30562007-09-07 17:52:53 +0000576The :dfn:`type` of the exception is the exception instance's class, the
577:dfn:`value` is the instance itself.
Georg Brandl116aa622007-08-15 14:28:22 +0000578
579.. index:: object: traceback
580
Georg Brandl02c30562007-09-07 17:52:53 +0000581A traceback object is normally created automatically when an exception is raised
Georg Brandle06de8b2008-05-05 21:42:51 +0000582and attached to it as the :attr:`__traceback__` attribute, which is writable.
583You can create an exception and set your own traceback in one step using the
584:meth:`with_traceback` exception method (which returns the same exception
585instance, with its traceback set to its argument), like so::
Georg Brandl02c30562007-09-07 17:52:53 +0000586
Benjamin Petersonb7851692009-02-16 16:15:34 +0000587 raise Exception("foo occurred").with_traceback(tracebackobj)
Georg Brandl02c30562007-09-07 17:52:53 +0000588
Georg Brandl1aea30a2008-07-19 15:51:07 +0000589.. index:: pair: exception; chaining
590 __cause__ (exception attribute)
591 __context__ (exception attribute)
Georg Brandl48310cd2009-01-03 21:18:54 +0000592
Georg Brandl1aea30a2008-07-19 15:51:07 +0000593The ``from`` clause is used for exception chaining: if given, the second
Mark Dickinson79650d02021-04-11 09:33:59 +0100594*expression* must be another exception class or instance. If the second
595expression is an exception instance, it will be attached to the raised
596exception as the :attr:`__cause__` attribute (which is writable). If the
597expression is an exception class, the class will be instantiated and the
598resulting exception instance will be attached to the raised exception as the
599:attr:`__cause__` attribute. If the raised exception is not handled, both
600exceptions will be printed::
Georg Brandl02c30562007-09-07 17:52:53 +0000601
Georg Brandl1aea30a2008-07-19 15:51:07 +0000602 >>> try:
603 ... print(1 / 0)
604 ... except Exception as exc:
605 ... raise RuntimeError("Something bad happened") from exc
606 ...
607 Traceback (most recent call last):
608 File "<stdin>", line 2, in <module>
csabella763557e2017-05-20 02:48:28 -0400609 ZeroDivisionError: division by zero
Georg Brandl1aea30a2008-07-19 15:51:07 +0000610
611 The above exception was the direct cause of the following exception:
612
613 Traceback (most recent call last):
614 File "<stdin>", line 4, in <module>
615 RuntimeError: Something bad happened
616
617A similar mechanism works implicitly if an exception is raised inside an
Georg Brandla4c8c472014-10-31 10:38:49 +0100618exception handler or a :keyword:`finally` clause: the previous exception is then
619attached as the new exception's :attr:`__context__` attribute::
Georg Brandl1aea30a2008-07-19 15:51:07 +0000620
621 >>> try:
622 ... print(1 / 0)
623 ... except:
624 ... raise RuntimeError("Something bad happened")
625 ...
626 Traceback (most recent call last):
627 File "<stdin>", line 2, in <module>
csabella763557e2017-05-20 02:48:28 -0400628 ZeroDivisionError: division by zero
Georg Brandl1aea30a2008-07-19 15:51:07 +0000629
630 During handling of the above exception, another exception occurred:
631
632 Traceback (most recent call last):
633 File "<stdin>", line 4, in <module>
634 RuntimeError: Something bad happened
Georg Brandl116aa622007-08-15 14:28:22 +0000635
csabella763557e2017-05-20 02:48:28 -0400636Exception chaining can be explicitly suppressed by specifying :const:`None` in
637the ``from`` clause::
638
639 >>> try:
640 ... print(1 / 0)
641 ... except:
642 ... raise RuntimeError("Something bad happened") from None
643 ...
644 Traceback (most recent call last):
645 File "<stdin>", line 4, in <module>
646 RuntimeError: Something bad happened
647
Georg Brandl116aa622007-08-15 14:28:22 +0000648Additional information on exceptions can be found in section :ref:`exceptions`,
649and information about handling exceptions is in section :ref:`try`.
650
csabella763557e2017-05-20 02:48:28 -0400651.. versionchanged:: 3.3
Mariatta9efad1e2017-05-30 15:26:42 -0700652 :const:`None` is now permitted as ``Y`` in ``raise X from Y``.
csabella763557e2017-05-20 02:48:28 -0400653
654.. versionadded:: 3.3
655 The ``__suppress_context__`` attribute to suppress automatic display of the
Mariatta9efad1e2017-05-30 15:26:42 -0700656 exception context.
Georg Brandl116aa622007-08-15 14:28:22 +0000657
658.. _break:
659
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200660The :keyword:`!break` statement
661===============================
Georg Brandl116aa622007-08-15 14:28:22 +0000662
Christian Heimesfaf2f632008-01-06 16:59:19 +0000663.. index::
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200664 ! statement: break
Christian Heimesfaf2f632008-01-06 16:59:19 +0000665 statement: for
666 statement: while
667 pair: loop; statement
Georg Brandl116aa622007-08-15 14:28:22 +0000668
Victor Stinner8af239e2020-09-18 09:10:15 +0200669.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +0000670 break_stmt: "break"
671
Georg Brandl116aa622007-08-15 14:28:22 +0000672:keyword:`break` may only occur syntactically nested in a :keyword:`for` or
673:keyword:`while` loop, but not nested in a function or class definition within
674that loop.
675
676.. index:: keyword: else
Georg Brandl02c30562007-09-07 17:52:53 +0000677 pair: loop control; target
Georg Brandl116aa622007-08-15 14:28:22 +0000678
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200679It terminates the nearest enclosing loop, skipping the optional :keyword:`!else`
Georg Brandl116aa622007-08-15 14:28:22 +0000680clause if the loop has one.
681
Georg Brandl116aa622007-08-15 14:28:22 +0000682If a :keyword:`for` loop is terminated by :keyword:`break`, the loop control
683target keeps its current value.
684
685.. index:: keyword: finally
686
687When :keyword:`break` passes control out of a :keyword:`try` statement with a
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200688:keyword:`finally` clause, that :keyword:`!finally` clause is executed before
Georg Brandl116aa622007-08-15 14:28:22 +0000689really leaving the loop.
690
691
692.. _continue:
693
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200694The :keyword:`!continue` statement
695==================================
Georg Brandl116aa622007-08-15 14:28:22 +0000696
Christian Heimesfaf2f632008-01-06 16:59:19 +0000697.. index::
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200698 ! statement: continue
Christian Heimesfaf2f632008-01-06 16:59:19 +0000699 statement: for
700 statement: while
701 pair: loop; statement
702 keyword: finally
Georg Brandl116aa622007-08-15 14:28:22 +0000703
Victor Stinner8af239e2020-09-18 09:10:15 +0200704.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +0000705 continue_stmt: "continue"
706
Georg Brandl116aa622007-08-15 14:28:22 +0000707:keyword:`continue` may only occur syntactically nested in a :keyword:`for` or
Serhiy Storchakafe2bbb12018-03-18 09:56:52 +0200708:keyword:`while` loop, but not nested in a function or class definition within
709that loop. It continues with the next cycle of the nearest enclosing loop.
Georg Brandl116aa622007-08-15 14:28:22 +0000710
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000711When :keyword:`continue` passes control out of a :keyword:`try` statement with a
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200712:keyword:`finally` clause, that :keyword:`!finally` clause is executed before
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000713really starting the next loop cycle.
714
Georg Brandl116aa622007-08-15 14:28:22 +0000715
716.. _import:
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000717.. _from:
Georg Brandl116aa622007-08-15 14:28:22 +0000718
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200719The :keyword:`!import` statement
720================================
Georg Brandl116aa622007-08-15 14:28:22 +0000721
722.. index::
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200723 ! statement: import
Georg Brandl116aa622007-08-15 14:28:22 +0000724 single: module; importing
725 pair: name; binding
726 keyword: from
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300727 keyword: as
728 exception: ImportError
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200729 single: , (comma); import statement
Georg Brandl116aa622007-08-15 14:28:22 +0000730
Victor Stinner8af239e2020-09-18 09:10:15 +0200731.. productionlist:: python-grammar
Andrés Delfinocaccca782018-07-07 17:24:46 -0300732 import_stmt: "import" `module` ["as" `identifier`] ("," `module` ["as" `identifier`])*
733 : | "from" `relative_module` "import" `identifier` ["as" `identifier`]
734 : ("," `identifier` ["as" `identifier`])*
735 : | "from" `relative_module` "import" "(" `identifier` ["as" `identifier`]
736 : ("," `identifier` ["as" `identifier`])* [","] ")"
Miss Islington (bot)89409162021-05-14 07:26:40 -0700737 : | "from" `relative_module` "import" "*"
Georg Brandl116aa622007-08-15 14:28:22 +0000738 module: (`identifier` ".")* `identifier`
739 relative_module: "."* `module` | "."+
Georg Brandl116aa622007-08-15 14:28:22 +0000740
Nick Coghlane3376ef2012-08-02 22:02:35 +1000741The basic import statement (no :keyword:`from` clause) is executed in two
742steps:
Barry Warsawdadebab2012-07-31 16:03:09 -0400743
Nick Coghlane3376ef2012-08-02 22:02:35 +1000744#. find a module, loading and initializing it if necessary
745#. define a name or names in the local namespace for the scope where
746 the :keyword:`import` statement occurs.
Georg Brandl116aa622007-08-15 14:28:22 +0000747
Nick Coghlane3376ef2012-08-02 22:02:35 +1000748When the statement contains multiple clauses (separated by
749commas) the two steps are carried out separately for each clause, just
Ned Deilycec95812016-05-17 21:44:46 -0400750as though the clauses had been separated out into individual import
Nick Coghlane3376ef2012-08-02 22:02:35 +1000751statements.
Georg Brandl116aa622007-08-15 14:28:22 +0000752
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700753The details of the first step, finding and loading modules are described in
Nick Coghlane3376ef2012-08-02 22:02:35 +1000754greater detail in the section on the :ref:`import system <importsystem>`,
755which also describes the various types of packages and modules that can
756be imported, as well as all the hooks that can be used to customize
757the import system. Note that failures in this step may indicate either
758that the module could not be located, *or* that an error occurred while
759initializing the module, which includes execution of the module's code.
Georg Brandl116aa622007-08-15 14:28:22 +0000760
Nick Coghlane3376ef2012-08-02 22:02:35 +1000761If the requested module is retrieved successfully, it will be made
762available in the local namespace in one of three ways:
763
Terry Jan Reedy7c895ed2014-04-29 00:58:56 -0400764.. index:: single: as; import statement
765
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200766* If the module name is followed by :keyword:`!as`, then the name
767 following :keyword:`!as` is bound directly to the imported module.
Nick Coghlane3376ef2012-08-02 22:02:35 +1000768* If no other name is specified, and the module being imported is a top
769 level module, the module's name is bound in the local namespace as a
770 reference to the imported module
771* If the module being imported is *not* a top level module, then the name
772 of the top level package that contains the module is bound in the local
773 namespace as a reference to the top level package. The imported module
774 must be accessed using its full qualified name rather than directly
775
Georg Brandl116aa622007-08-15 14:28:22 +0000776
777.. index::
778 pair: name; binding
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300779 single: from; import statement
Georg Brandl116aa622007-08-15 14:28:22 +0000780
Nick Coghlane3376ef2012-08-02 22:02:35 +1000781The :keyword:`from` form uses a slightly more complex process:
782
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700783#. find the module specified in the :keyword:`from` clause, loading and
Nick Coghlane3376ef2012-08-02 22:02:35 +1000784 initializing it if necessary;
785#. for each of the identifiers specified in the :keyword:`import` clauses:
786
787 #. check if the imported module has an attribute by that name
788 #. if not, attempt to import a submodule with that name and then
789 check the imported module again for that attribute
790 #. if the attribute is not found, :exc:`ImportError` is raised.
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700791 #. otherwise, a reference to that value is stored in the local namespace,
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200792 using the name in the :keyword:`!as` clause if it is present,
Nick Coghlane3376ef2012-08-02 22:02:35 +1000793 otherwise using the attribute name
794
795Examples::
796
797 import foo # foo imported and bound locally
798 import foo.bar.baz # foo.bar.baz imported, foo bound locally
799 import foo.bar.baz as fbb # foo.bar.baz imported and bound as fbb
800 from foo.bar import baz # foo.bar.baz imported and bound as baz
801 from foo import attr # foo imported and foo.attr bound as attr
802
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200803.. index:: single: * (asterisk); import statement
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300804
Nick Coghlane3376ef2012-08-02 22:02:35 +1000805If the list of identifiers is replaced by a star (``'*'``), all public
806names defined in the module are bound in the local namespace for the scope
807where the :keyword:`import` statement occurs.
808
809.. index:: single: __all__ (optional module attribute)
810
811The *public names* defined by a module are determined by checking the module's
812namespace for a variable named ``__all__``; if defined, it must be a sequence
813of strings which are names defined or imported by that module. The names
814given in ``__all__`` are all considered public and are required to exist. If
815``__all__`` is not defined, the set of public names includes all names found
816in the module's namespace which do not begin with an underscore character
817(``'_'``). ``__all__`` should contain the entire public API. It is intended
818to avoid accidentally exporting items that are not part of the API (such as
819library modules which were imported and used within the module).
820
Georg Brandla4c8c472014-10-31 10:38:49 +0100821The wild card form of import --- ``from module import *`` --- is only allowed at
822the module level. Attempting to use it in class or function definitions will
823raise a :exc:`SyntaxError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000824
825.. index::
Brett Cannone43b0602009-03-21 03:11:16 +0000826 single: relative; import
Georg Brandl116aa622007-08-15 14:28:22 +0000827
Brett Cannone43b0602009-03-21 03:11:16 +0000828When specifying what module to import you do not have to specify the absolute
829name of the module. When a module or package is contained within another
830package it is possible to make a relative import within the same top package
831without having to mention the package name. By using leading dots in the
832specified module or package after :keyword:`from` you can specify how high to
833traverse up the current package hierarchy without specifying exact names. One
834leading dot means the current package where the module making the import
835exists. Two dots means up one package level. Three dots is up two levels, etc.
836So if you execute ``from . import mod`` from a module in the ``pkg`` package
837then you will end up importing ``pkg.mod``. If you execute ``from ..subpkg2
Florent Xicluna0c8414e2010-09-03 20:23:40 +0000838import mod`` from within ``pkg.subpkg1`` you will import ``pkg.subpkg2.mod``.
Joannah Nanjekye70bf7132019-04-24 11:14:44 -0400839The specification for relative imports is contained in
840the :ref:`relativeimports` section.
Georg Brandl5b318c02008-08-03 09:47:27 +0000841
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000842:func:`importlib.import_module` is provided to support applications that
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700843determine dynamically the modules to be loaded.
Georg Brandl116aa622007-08-15 14:28:22 +0000844
Steve Dower894e30c2019-10-26 13:02:30 -0700845.. audit-event:: import module,filename,sys.path,sys.meta_path,sys.path_hooks import
Georg Brandl116aa622007-08-15 14:28:22 +0000846
847.. _future:
848
849Future statements
850-----------------
851
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300852.. index::
853 pair: future; statement
854 single: __future__; future statement
Georg Brandl116aa622007-08-15 14:28:22 +0000855
856A :dfn:`future statement` is a directive to the compiler that a particular
857module should be compiled using syntax or semantics that will be available in a
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700858specified future release of Python where the feature becomes standard.
859
860The future statement is intended to ease migration to future versions of Python
861that introduce incompatible changes to the language. It allows use of the new
862features on a per-module basis before the release in which the feature becomes
863standard.
Georg Brandl116aa622007-08-15 14:28:22 +0000864
Victor Stinner8af239e2020-09-18 09:10:15 +0200865.. productionlist:: python-grammar
Andrés Delfinocaccca782018-07-07 17:24:46 -0300866 future_stmt: "from" "__future__" "import" `feature` ["as" `identifier`]
867 : ("," `feature` ["as" `identifier`])*
868 : | "from" "__future__" "import" "(" `feature` ["as" `identifier`]
869 : ("," `feature` ["as" `identifier`])* [","] ")"
870 feature: `identifier`
Georg Brandl116aa622007-08-15 14:28:22 +0000871
872A future statement must appear near the top of the module. The only lines that
873can appear before a future statement are:
874
875* the module docstring (if any),
876* comments,
877* blank lines, and
878* other future statements.
879
Pablo Galindob0544ba2021-04-21 12:41:19 +0100880The only feature that requires using the future statement is
881``annotations`` (see :pep:`563`).
882
Guido van Rossum95e4d582018-01-26 08:20:18 -0800883All historical features enabled by the future statement are still recognized
884by Python 3. The list includes ``absolute_import``, ``division``,
885``generators``, ``generator_stop``, ``unicode_literals``,
Pablo Galindob0544ba2021-04-21 12:41:19 +0100886``print_function``, ``nested_scopes`` and ``with_statement``. They are
887all redundant because they are always enabled, and only kept for
Guido van Rossum95e4d582018-01-26 08:20:18 -0800888backwards compatibility.
Georg Brandl116aa622007-08-15 14:28:22 +0000889
890A future statement is recognized and treated specially at compile time: Changes
891to the semantics of core constructs are often implemented by generating
892different code. It may even be the case that a new feature introduces new
893incompatible syntax (such as a new reserved word), in which case the compiler
894may need to parse the module differently. Such decisions cannot be pushed off
895until runtime.
896
897For any given release, the compiler knows which feature names have been defined,
898and raises a compile-time error if a future statement contains a feature not
899known to it.
900
901The direct runtime semantics are the same as for any import statement: there is
902a standard module :mod:`__future__`, described later, and it will be imported in
903the usual way at the time the future statement is executed.
904
905The interesting runtime semantics depend on the specific feature enabled by the
906future statement.
907
908Note that there is nothing special about the statement::
909
910 import __future__ [as name]
911
912That is not a future statement; it's an ordinary import statement with no
913special semantics or syntax restrictions.
914
Georg Brandl22b34312009-07-26 14:54:51 +0000915Code compiled by calls to the built-in functions :func:`exec` and :func:`compile`
Georg Brandl02c30562007-09-07 17:52:53 +0000916that occur in a module :mod:`M` containing a future statement will, by default,
917use the new syntax or semantics associated with the future statement. This can
918be controlled by optional arguments to :func:`compile` --- see the documentation
919of that function for details.
Georg Brandl116aa622007-08-15 14:28:22 +0000920
921A future statement typed at an interactive interpreter prompt will take effect
922for the rest of the interpreter session. If an interpreter is started with the
923:option:`-i` option, is passed a script name to execute, and the script includes
924a future statement, it will be in effect in the interactive session started
925after the script is executed.
926
Georg Brandlff2ad0e2009-04-27 16:51:45 +0000927.. seealso::
928
929 :pep:`236` - Back to the __future__
930 The original proposal for the __future__ mechanism.
931
Georg Brandl116aa622007-08-15 14:28:22 +0000932
933.. _global:
934
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200935The :keyword:`!global` statement
936================================
Georg Brandl116aa622007-08-15 14:28:22 +0000937
Christian Heimesfaf2f632008-01-06 16:59:19 +0000938.. index::
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200939 ! statement: global
Christian Heimesfaf2f632008-01-06 16:59:19 +0000940 triple: global; name; binding
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200941 single: , (comma); identifier list
Georg Brandl116aa622007-08-15 14:28:22 +0000942
Victor Stinner8af239e2020-09-18 09:10:15 +0200943.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +0000944 global_stmt: "global" `identifier` ("," `identifier`)*
945
Georg Brandl116aa622007-08-15 14:28:22 +0000946The :keyword:`global` statement is a declaration which holds for the entire
947current code block. It means that the listed identifiers are to be interpreted
948as globals. It would be impossible to assign to a global variable without
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200949:keyword:`!global`, although free variables may refer to globals without being
Georg Brandl116aa622007-08-15 14:28:22 +0000950declared global.
951
952Names listed in a :keyword:`global` statement must not be used in the same code
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200953block textually preceding that :keyword:`!global` statement.
Georg Brandl116aa622007-08-15 14:28:22 +0000954
955Names listed in a :keyword:`global` statement must not be defined as formal
Andre Delfinoc56f9df2020-12-19 12:48:06 -0300956parameters, or as targets in :keyword:`with` statements or :keyword:`except` clauses, or in a :keyword:`for` target list, :keyword:`class`
Guido van Rossum6cff8742016-09-09 09:36:26 -0700957definition, function definition, :keyword:`import` statement, or variable
958annotation.
Georg Brandl116aa622007-08-15 14:28:22 +0000959
Georg Brandl495f7b52009-10-27 15:28:25 +0000960.. impl-detail::
961
kms708478d59aca2017-09-28 15:54:48 -0400962 The current implementation does not enforce some of these restrictions, but
Georg Brandl495f7b52009-10-27 15:28:25 +0000963 programs should not abuse this freedom, as future implementations may enforce
964 them or silently change the meaning of the program.
Georg Brandl116aa622007-08-15 14:28:22 +0000965
966.. index::
967 builtin: exec
968 builtin: eval
969 builtin: compile
970
Jim Fasarakis-Hilliardf34c68502017-05-08 14:36:29 +0300971**Programmer's note:** :keyword:`global` is a directive to the parser. It
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200972applies only to code parsed at the same time as the :keyword:`!global` statement.
973In particular, a :keyword:`!global` statement contained in a string or code
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000974object supplied to the built-in :func:`exec` function does not affect the code
Georg Brandl116aa622007-08-15 14:28:22 +0000975block *containing* the function call, and code contained in such a string is
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200976unaffected by :keyword:`!global` statements in the code containing the function
Georg Brandl116aa622007-08-15 14:28:22 +0000977call. The same applies to the :func:`eval` and :func:`compile` functions.
978
Georg Brandl02c30562007-09-07 17:52:53 +0000979
980.. _nonlocal:
981
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200982The :keyword:`!nonlocal` statement
983==================================
Georg Brandl02c30562007-09-07 17:52:53 +0000984
985.. index:: statement: nonlocal
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200986 single: , (comma); identifier list
Georg Brandl02c30562007-09-07 17:52:53 +0000987
Victor Stinner8af239e2020-09-18 09:10:15 +0200988.. productionlist:: python-grammar
Georg Brandl02c30562007-09-07 17:52:53 +0000989 nonlocal_stmt: "nonlocal" `identifier` ("," `identifier`)*
990
Georg Brandlc5d98b42007-12-04 18:11:03 +0000991.. XXX add when implemented
Martin Panter0c0da482016-06-12 01:46:50 +0000992 : ["=" (`target_list` "=")+ starred_expression]
Georg Brandl06788c92009-01-03 21:31:47 +0000993 : | "nonlocal" identifier augop expression_list
Georg Brandlc5d98b42007-12-04 18:11:03 +0000994
Georg Brandl48310cd2009-01-03 21:18:54 +0000995The :keyword:`nonlocal` statement causes the listed identifiers to refer to
Raymond Hettingeraa7886d2014-05-26 22:20:37 -0700996previously bound variables in the nearest enclosing scope excluding globals.
997This is important because the default behavior for binding is to search the
998local namespace first. The statement allows encapsulated code to rebind
999variables outside of the local scope besides the global (module) scope.
Georg Brandlc5d98b42007-12-04 18:11:03 +00001000
Georg Brandlc5d98b42007-12-04 18:11:03 +00001001.. XXX not implemented
1002 The :keyword:`nonlocal` statement may prepend an assignment or augmented
1003 assignment, but not an expression.
1004
Raymond Hettingeraa7886d2014-05-26 22:20:37 -07001005Names listed in a :keyword:`nonlocal` statement, unlike those listed in a
Georg Brandlc5d98b42007-12-04 18:11:03 +00001006:keyword:`global` statement, must refer to pre-existing bindings in an
1007enclosing scope (the scope in which a new binding should be created cannot
1008be determined unambiguously).
1009
Georg Brandl48310cd2009-01-03 21:18:54 +00001010Names listed in a :keyword:`nonlocal` statement must not collide with
Georg Brandlc5d98b42007-12-04 18:11:03 +00001011pre-existing bindings in the local scope.
1012
1013.. seealso::
1014
1015 :pep:`3104` - Access to Names in Outer Scopes
1016 The specification for the :keyword:`nonlocal` statement.