Debian Codegraph @

Doc/reference/simple_stmts.rst

raw
1
2 .. _simple:
3
4 *****************
5 Simple statements
6 *****************
7
8 .. index:: pair: simple; statement
9
10 A simple statement is comprised within a single logical line. Several simple
11 statements may occur on a single line separated by semicolons. The syntax for
12 simple statements is:
13
14 .. productionlist:: python-grammar
15 simple_stmt: `expression_stmt`
16 : | `assert_stmt`
17 : | `assignment_stmt`
18 : | `augmented_assignment_stmt`
19 : | `annotated_assignment_stmt`
20 : | `pass_stmt`
21 : | `del_stmt`
22 : | `return_stmt`
23 : | `yield_stmt`
24 : | `raise_stmt`
25 : | `break_stmt`
26 : | `continue_stmt`
27 : | `import_stmt`
28 : | `future_stmt`
29 : | `global_stmt`
30 : | `nonlocal_stmt`
31 : | `type_stmt`
32
33
34 .. _exprstmts:
35
36 Expression statements
37 =====================
38
39 .. index::
40 pair: expression; statement
41 pair: expression; list
42 .. index:: pair: expression; list
43
44 Expression statements are used (mostly interactively) to compute and write a
45 value, or (usually) to call a procedure (a function that returns no meaningful
46 result; in Python, procedures return the value ``None``). Other uses of
47 expression statements are allowed and occasionally useful. The syntax for an
48 expression statement is:
49
50 .. productionlist:: python-grammar
51 expression_stmt: `starred_expression`
52
53 An expression statement evaluates the expression list (which may be a single
54 expression).
55
56 .. index::
57 pair: built-in function; repr
58 pair: object; None
59 pair: string; conversion
60 single: output
61 pair: standard; output
62 pair: writing; values
63 pair: procedure; call
64
65 In interactive mode, if the value is not ``None``, it is converted to a string
66 using the built-in :func:`repr` function and the resulting string is written to
67 standard output on a line by itself (except if the result is ``None``, so that
68 procedure calls do not cause any output.)
69
70 .. _assignment:
71
72 Assignment statements
73 =====================
74
75 .. index::
76 single: = (equals); assignment statement
77 pair: assignment; statement
78 pair: binding; name
79 pair: rebinding; name
80 pair: object; mutable
81 pair: attribute; assignment
82
83 Assignment statements are used to (re)bind names to values and to modify
84 attributes or items of mutable objects:
85
86 .. productionlist:: python-grammar
87 assignment_stmt: (`target_list` "=")+ (`starred_expression` | `yield_expression`)
88 target_list: `target` ("," `target`)* [","]
89 target: `identifier`
90 : | "(" [`target_list`] ")"
91 : | "[" [`target_list`] "]"
92 : | `attributeref`
93 : | `subscription`
94 : | "*" `target`
95
96 (See section :ref:`primaries` for the syntax definitions for *attributeref*
97 and *subscription*.)
98
99 An assignment statement evaluates the expression list (remember that this can be
100 a single expression or a comma-separated list, the latter yielding a tuple) and
101 assigns the single resulting object to each of the target lists, from left to
102 right.
103
104 .. index::
105 single: target
106 pair: target; list
107
108 Assignment is defined recursively depending on the form of the target (list).
109 When a target is part of a mutable object (an attribute reference or
110 subscription), the mutable object must ultimately perform the assignment and
111 decide about its validity, and may raise an exception if the assignment is
112 unacceptable. The rules observed by various types and the exceptions raised are
113 given with the definition of the object types (see section :ref:`types`).
114
115 .. index:: triple: target; list; assignment
116 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
120
121 Assignment of an object to a target list, optionally enclosed in parentheses or
122 square brackets, is recursively defined as follows.
123
124 * If the target list is a single target with no trailing comma,
125 optionally in parentheses, the object is assigned to that target.
126
127 * Else:
128
129 * If the target list contains one target prefixed with an asterisk, called a
130 "starred" target: The object must be an iterable with at least as many items
131 as there are targets in the target list, minus one. The first items of the
132 iterable are assigned, from left to right, to the targets before the starred
133 target. The final items of the iterable are assigned to the targets after
134 the starred target. A list of the remaining items in the iterable is then
135 assigned to the starred target (the list can be empty).
136
137 * Else: The object must be an iterable with the same number of items as there
138 are targets in the target list, and the items are assigned, from left to
139 right, to the corresponding targets.
140
141 Assignment of an object to a single target is recursively defined as follows.
142
143 * If the target is an identifier (name):
144
145 * If the name does not occur in a :keyword:`global` or :keyword:`nonlocal`
146 statement in the current code block: the name is bound to the object in the
147 current local namespace.
148
149 * Otherwise: the name is bound to the object in the global namespace or the
150 outer namespace determined by :keyword:`nonlocal`, respectively.
151
152 .. index:: single: destructor
153
154 The name is rebound if it was already bound. This may cause the reference
155 count for the object previously bound to the name to reach zero, causing the
156 object to be deallocated and its destructor (if it has one) to be called.
157
158 .. index:: pair: attribute; assignment
159
160 * If the target is an attribute reference: The primary expression in the
161 reference is evaluated. It should yield an object with assignable attributes;
162 if this is not the case, :exc:`TypeError` is raised. That object is then
163 asked to assign the assigned object to the given attribute; if it cannot
164 perform the assignment, it raises an exception (usually but not necessarily
165 :exc:`AttributeError`).
166
167 .. _attr-target-note:
168
169 Note: If the object is a class instance and the attribute reference occurs on
170 both sides of the assignment operator, the right-hand side expression, ``a.x`` can access
171 either an instance attribute or (if no instance attribute exists) a class
172 attribute. The left-hand side target ``a.x`` is always set as an instance attribute,
173 creating it if necessary. Thus, the two occurrences of ``a.x`` do not
174 necessarily refer to the same attribute: if the right-hand side expression refers to a
175 class attribute, the left-hand side creates a new instance attribute as the target of the
176 assignment::
177
178 class Cls:
179 x = 3 # class variable
180 inst = Cls()
181 inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x as 3
182
183 This description does not necessarily apply to descriptor attributes, such as
184 properties created with :func:`property`.
185
186 .. index::
187 pair: subscription; assignment
188 pair: object; mutable
189
190 * If the target is a subscription: The primary expression in the reference is
191 evaluated.
192 Next, the subscript expression is evaluated.
193 Then, the primary's :meth:`~object.__setitem__` method is called with
194 two arguments: the subscript and the assigned object.
195
196 Typically, :meth:`~object.__setitem__` is defined on mutable sequence objects
197 (such as lists) and mapping objects (such as dictionaries), and behaves as
198 follows.
199
200 .. index::
201 pair: object; sequence
202 pair: object; list
203
204 If the primary is a mutable sequence object (such as a list), the subscript
205 must yield an integer. If it is negative, the sequence's length is added to
206 it. The resulting value must be a nonnegative integer less than the
207 sequence's length, and the sequence is asked to assign the assigned object to
208 its item with that index. If the index is out of range, :exc:`IndexError` is
209 raised (assignment to a subscripted sequence cannot add new items to a list).
210
211 .. index::
212 pair: object; mapping
213 pair: object; dictionary
214
215 If the primary is a mapping object (such as a dictionary), the subscript must
216 have a type compatible with the mapping's key type, and the mapping is then
217 asked to create a key/value pair which maps the subscript to the assigned
218 object. This can either replace an existing key/value pair with the same key
219 value, or insert a new key/value pair (if no key with the same value existed).
220
221 .. index:: pair: slicing; assignment
222
223 If the target is a slicing: The primary expression should evaluate to
224 a mutable sequence object (such as a list).
225 The assigned object should be :term:`iterable`.
226 The slicing's lower and upper bounds should be integers; if they are ``None``
227 (or not present), the defaults are zero and the sequence's length.
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
233 target sequence, if the target sequence allows it.
234
235 Although the definition of assignment implies that overlaps between the
236 left-hand side and the right-hand side are 'simultaneous' (for example ``a, b =
237 b, a`` swaps two variables), overlaps *within* the collection of assigned-to
238 variables occur left-to-right, sometimes resulting in confusion. For instance,
239 the following program prints ``[0, 2]``::
240
241 x = [0, 1]
242 i = 0
243 i, x[i] = 1, 2 # i is updated, then x[i] is updated
244 print(x)
245
246
247 .. seealso::
248
249 :pep:`3132` - Extended Iterable Unpacking
250 The specification for the ``*target`` feature.
251
252
253 .. _augassign:
254
255 Augmented assignment statements
256 -------------------------------
257
258 .. index::
259 pair: augmented; assignment
260 single: statement; assignment, augmented
261 single: +=; augmented assignment
262 single: -=; augmented assignment
263 single: *=; augmented assignment
264 single: /=; augmented assignment
265 single: %=; augmented assignment
266 single: &=; augmented assignment
267 single: ^=; augmented assignment
268 single: |=; augmented assignment
269 single: **=; augmented assignment
270 single: //=; augmented assignment
271 single: >>=; augmented assignment
272 single: <<=; augmented assignment
273
274 Augmented assignment is the combination, in a single statement, of a binary
275 operation and an assignment statement:
276
277 .. productionlist:: python-grammar
278 augmented_assignment_stmt: `augtarget` `augop` (`expression_list` | `yield_expression`)
279 augtarget: `identifier` | `attributeref` | `subscription`
280 augop: "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**="
281 : | ">>=" | "<<=" | "&=" | "^=" | "|="
282
283 (See section :ref:`primaries` for the syntax definitions of the last three
284 symbols.)
285
286 An augmented assignment evaluates the target (which, unlike normal assignment
287 statements, cannot be an unpacking) and the expression list, performs the binary
288 operation specific to the type of assignment on the two operands, and assigns
289 the result to the original target. The target is only evaluated once.
290
291 An augmented assignment statement like ``x += 1`` can be rewritten as ``x = x +
292 1`` to achieve a similar, but not exactly equal effect. In the augmented
293 version, ``x`` is only evaluated once. Also, when possible, the actual operation
294 is performed *in-place*, meaning that rather than creating a new object and
295 assigning that to the target, the old object is modified instead.
296
297 Unlike normal assignments, augmented assignments evaluate the left-hand side
298 *before* evaluating the right-hand side. For example, ``a[i] += f(x)`` first
299 looks-up ``a[i]``, then it evaluates ``f(x)`` and performs the addition, and
300 lastly, it writes the result back to ``a[i]``.
301
302 With the exception of assigning to tuples and multiple targets in a single
303 statement, the assignment done by augmented assignment statements is handled the
304 same way as normal assignments. Similarly, with the exception of the possible
305 *in-place* behavior, the binary operation performed by augmented assignment is
306 the same as the normal binary operations.
307
308 For targets which are attribute references, the same :ref:`caveat about class
309 and instance attributes <attr-target-note>` applies as for regular assignments.
310
311
312 .. _annassign:
313
314 Annotated assignment statements
315 -------------------------------
316
317 .. index::
318 pair: annotated; assignment
319 single: statement; assignment, annotated
320 single: : (colon); annotated variable
321
322 :term:`Annotation <variable annotation>` assignment is the combination, in a single
323 statement, of a variable or attribute annotation and an optional assignment statement:
324
325 .. productionlist:: python-grammar
326 annotated_assignment_stmt: `augtarget` ":" `expression`
327 : ["=" (`starred_expression` | `yield_expression`)]
328
329 The difference from normal :ref:`assignment` is that only a single target is allowed.
330
331 The assignment target is considered "simple" if it consists of a single
332 name that is not enclosed in parentheses.
333 For simple assignment targets, if in class or module scope,
334 the annotations are gathered in a lazily evaluated
335 :ref:`annotation scope <annotation-scopes>`. The annotations can be
336 evaluated using the :attr:`~object.__annotations__` attribute of a
337 class or module, or using the facilities in the :mod:`annotationlib`
338 module.
339
340 If the assignment target is not simple (an attribute, subscript node, or
341 parenthesized name), the annotation is never evaluated.
342
343 If a name is annotated in a function scope, then this name is local for
344 that scope. Annotations are never evaluated and stored in function scopes.
345
346 If the right hand side is present, an annotated
347 assignment performs the actual assignment as if there was no annotation
348 present. If the right hand side is not present for an expression
349 target, then the interpreter evaluates the target except for the last
350 :meth:`~object.__setitem__` or :meth:`~object.__setattr__` call.
351
352 .. seealso::
353
354 :pep:`526` - Syntax for Variable Annotations
355 The proposal that added syntax for annotating the types of variables
356 (including class variables and instance variables), instead of expressing
357 them through comments.
358
359 :pep:`484` - Type hints
360 The proposal that added the :mod:`typing` module to provide a standard
361 syntax for type annotations that can be used in static analysis tools and
362 IDEs.
363
364 .. versionchanged:: 3.8
365 Now annotated assignments allow the same expressions in the right hand side as
366 regular assignments. Previously, some expressions (like un-parenthesized
367 tuple expressions) caused a syntax error.
368
369 .. versionchanged:: 3.14
370 Annotations are now lazily evaluated in a separate :ref:`annotation scope <annotation-scopes>`.
371 If the assignment target is not simple, annotations are never evaluated.
372
373
374 .. _assert:
375
376 The :keyword:`!assert` statement
377 ================================
378
379 .. index::
380 ! pair: statement; assert
381 pair: debugging; assertions
382 single: , (comma); expression list
383
384 Assert statements are a convenient way to insert debugging assertions into a
385 program:
386
387 .. productionlist:: python-grammar
388 assert_stmt: "assert" `expression` ["," `expression`]
389
390 The simple form, ``assert expression``, is equivalent to ::
391
392 if __debug__:
393 if not expression: raise AssertionError
394
395 The extended form, ``assert expression1, expression2``, is equivalent to ::
396
397 if __debug__:
398 if not expression1: raise AssertionError(expression2)
399
400 .. index::
401 single: __debug__
402 pair: exception; AssertionError
403
404 These equivalences assume that :const:`__debug__` and :exc:`AssertionError` refer to
405 the built-in variables with those names. In the current implementation, the
406 built-in variable ``__debug__`` is ``True`` under normal circumstances,
407 ``False`` when optimization is requested (command line option :option:`-O`). The current
408 code generator emits no code for an :keyword:`assert` statement when optimization is
409 requested at compile time. Note that it is unnecessary to include the source
410 code for the expression that failed in the error message; it will be displayed
411 as part of the stack trace.
412
413 Assignments to :const:`__debug__` are illegal. The value for the built-in variable
414 is determined when the interpreter starts.
415
416
417 .. _pass:
418
419 The :keyword:`!pass` statement
420 ==============================
421
422 .. index::
423 pair: statement; pass
424 pair: null; operation
425 pair: null; operation
426
427 .. productionlist:: python-grammar
428 pass_stmt: "pass"
429
430 :keyword:`pass` is a null operation --- when it is executed, nothing happens.
431 It is useful as a placeholder when a statement is required syntactically, but no
432 code 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
441 The :keyword:`!del` statement
442 =============================
443
444 .. index::
445 ! pair: statement; del
446 pair: deletion; target
447 triple: deletion; target; list
448
449 .. productionlist:: python-grammar
450 del_stmt: "del" `target_list`
451
452 Deletion is recursively defined very similar to the way assignment is defined.
453 Rather than spelling it out in full details, here are some hints.
454
455 Deletion of a target list recursively deletes each target, from left to right.
456
457 .. index::
458 pair: statement; global
459 pair: unbinding; name
460
461 Deletion of a name removes the binding of that name from the local or global
462 namespace, depending on whether the name occurs in a :keyword:`global` statement
463 in the same code block. Trying to delete an unbound name raises a
464 :exc:`NameError` exception.
465
466 .. index:: pair: attribute; deletion
467
468 Deletion of attribute references and subscriptions is passed to the
469 primary object involved; deletion of a slicing is in general equivalent to
470 assignment of an empty slice of the right type (but even this is determined by
471 the sliced object).
472
473 .. 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
477
478 .. _return:
479
480 The :keyword:`!return` statement
481 ================================
482
483 .. index::
484 ! pair: statement; return
485 pair: function; definition
486 pair: class; definition
487
488 .. productionlist:: python-grammar
489 return_stmt: "return" [`expression_list`]
490
491 :keyword:`return` may only occur syntactically nested in a function definition,
492 not within a nested class definition.
493
494 If 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:: pair: keyword; finally
500
501 When :keyword:`return` passes control out of a :keyword:`try` statement with a
502 :keyword:`finally` clause, that :keyword:`!finally` clause is executed before
503 really leaving the function.
504
505 In a generator function, the :keyword:`return` statement indicates that the
506 generator is done and will cause :exc:`StopIteration` to be raised. The returned
507 value (if any) is used as an argument to construct :exc:`StopIteration` and
508 becomes the :attr:`StopIteration.value` attribute.
509
510 In an asynchronous generator function, an empty :keyword:`return` statement
511 indicates that the asynchronous generator is done and will cause
512 :exc:`StopAsyncIteration` to be raised. A non-empty :keyword:`!return`
513 statement is a syntax error in an asynchronous generator function.
514
515 .. _yield:
516
517 The :keyword:`!yield` statement
518 ===============================
519
520 .. index::
521 pair: statement; yield
522 single: generator; function
523 single: generator; iterator
524 single: function; generator
525 pair: exception; StopIteration
526
527 .. productionlist:: python-grammar
528 yield_stmt: `yield_expression`
529
530 A :keyword:`yield` statement is semantically equivalent to a :ref:`yield
531 expression <yieldexpr>`. The ``yield`` statement can be used to omit the
532 parentheses that would otherwise be required in the equivalent yield expression
533 statement. For example, the yield statements ::
534
535 yield <expr>
536 yield from <expr>
537
538 are equivalent to the yield expression statements ::
539
540 (yield <expr>)
541 (yield from <expr>)
542
543 Yield expressions and statements are only used when defining a :term:`generator`
544 function, and are only used in the body of the generator function. Using :keyword:`yield`
545 in a function definition is sufficient to cause that definition to create a
546 generator function instead of a normal function.
547
548 For full details of :keyword:`yield` semantics, refer to the
549 :ref:`yieldexpr` section.
550
551 .. _raise:
552
553 The :keyword:`!raise` statement
554 ===============================
555
556 .. index::
557 ! pair: statement; raise
558 single: exception
559 pair: raising; exception
560 single: __traceback__ (exception attribute)
561
562 .. productionlist:: python-grammar
563 raise_stmt: "raise" [`expression` ["from" `expression`]]
564
565 If no expressions are present, :keyword:`raise` re-raises the
566 exception that is currently being handled, which is also known as the *active exception*.
567 If there isn't currently an active exception, a :exc:`RuntimeError` exception is raised
568 indicating that this is an error.
569
570 Otherwise, :keyword:`raise` evaluates the first expression as the exception
571 object. It must be either a subclass or an instance of :class:`BaseException`.
572 If it is a class, the exception instance will be obtained when needed by
573 instantiating the class with no arguments.
574
575 The :dfn:`type` of the exception is the exception instance's class, the
576 :dfn:`value` is the instance itself.
577
578 .. index:: pair: object; traceback
579
580 A traceback object is normally created automatically when an exception is raised
581 and attached to it as the :attr:`~BaseException.__traceback__` attribute.
582 You can create an exception and set your own traceback in one step using the
583 :meth:`~BaseException.with_traceback` exception method (which returns the
584 same exception instance, with its traceback set to its argument), like so::
585
586 raise Exception("foo occurred").with_traceback(tracebackobj)
587
588 .. index:: pair: exception; chaining
589 __cause__ (exception attribute)
590 __context__ (exception attribute)
591
592 The ``from`` clause is used for exception chaining: if given, the second
593 *expression* must be another exception class or instance. If the second
594 expression is an exception instance, it will be attached to the raised
595 exception as the :attr:`~BaseException.__cause__` attribute (which is writable). If the
596 expression is an exception class, the class will be instantiated and the
597 resulting exception instance will be attached to the raised exception as the
598 :attr:`!__cause__` attribute. If the raised exception is not handled, both
599 exceptions will be printed:
600
601 .. code-block:: pycon
602
603 >>> try:
604 ... print(1 / 0)
605 ... except Exception as exc:
606 ... raise RuntimeError("Something bad happened") from exc
607 ...
608 Traceback (most recent call last):
609 File "<stdin>", line 2, in <module>
610 print(1 / 0)
611 ~~^~~
612 ZeroDivisionError: division by zero
613
614 The above exception was the direct cause of the following exception:
615
616 Traceback (most recent call last):
617 File "<stdin>", line 4, in <module>
618 raise RuntimeError("Something bad happened") from exc
619 RuntimeError: Something bad happened
620
621 A similar mechanism works implicitly if a new exception is raised when
622 an exception is already being handled. An exception may be handled
623 when an :keyword:`except` or :keyword:`finally` clause, or a
624 :keyword:`with` statement, is used. The previous exception is then
625 attached as the new exception's :attr:`~BaseException.__context__` attribute:
626
627 .. code-block:: pycon
628
629 >>> try:
630 ... print(1 / 0)
631 ... except:
632 ... raise RuntimeError("Something bad happened")
633 ...
634 Traceback (most recent call last):
635 File "<stdin>", line 2, in <module>
636 print(1 / 0)
637 ~~^~~
638 ZeroDivisionError: division by zero
639
640 During handling of the above exception, another exception occurred:
641
642 Traceback (most recent call last):
643 File "<stdin>", line 4, in <module>
644 raise RuntimeError("Something bad happened")
645 RuntimeError: Something bad happened
646
647 Exception chaining can be explicitly suppressed by specifying :const:`None` in
648 the ``from`` clause:
649
650 .. doctest::
651
652 >>> try:
653 ... print(1 / 0)
654 ... except:
655 ... raise RuntimeError("Something bad happened") from None
656 ...
657 Traceback (most recent call last):
658 File "<stdin>", line 4, in <module>
659 RuntimeError: Something bad happened
660
661 Additional information on exceptions can be found in section :ref:`exceptions`,
662 and information about handling exceptions is in section :ref:`try`.
663
664 .. versionchanged:: 3.3
665 :const:`None` is now permitted as ``Y`` in ``raise X from Y``.
666
667 Added the :attr:`~BaseException.__suppress_context__` attribute to suppress
668 automatic display of the exception context.
669
670 .. versionchanged:: 3.11
671 If the traceback of the active exception is modified in an :keyword:`except`
672 clause, a subsequent ``raise`` statement re-raises the exception with the
673 modified traceback. Previously, the exception was re-raised with the
674 traceback it had when it was caught.
675
676 .. _break:
677
678 The :keyword:`!break` statement
679 ===============================
680
681 .. index::
682 ! pair: statement; break
683 pair: statement; for
684 pair: statement; while
685 pair: loop; statement
686
687 .. productionlist:: python-grammar
688 break_stmt: "break"
689
690 :keyword:`break` may only occur syntactically nested in a :keyword:`for` or
691 :keyword:`while` loop, but not nested in a function or class definition within
692 that loop.
693
694 .. index:: pair: keyword; else
695 pair: loop control; target
696
697 It terminates the nearest enclosing loop, skipping the optional :keyword:`!else`
698 clause if the loop has one.
699
700 If a :keyword:`for` loop is terminated by :keyword:`break`, the loop control
701 target keeps its current value.
702
703 .. index:: pair: keyword; finally
704
705 When :keyword:`break` passes control out of a :keyword:`try` statement with a
706 :keyword:`finally` clause, that :keyword:`!finally` clause is executed before
707 really leaving the loop.
708
709
710 .. _continue:
711
712 The :keyword:`!continue` statement
713 ==================================
714
715 .. index::
716 ! pair: statement; continue
717 pair: statement; for
718 pair: statement; while
719 pair: loop; statement
720 pair: keyword; finally
721
722 .. productionlist:: python-grammar
723 continue_stmt: "continue"
724
725 :keyword:`continue` may only occur syntactically nested in a :keyword:`for` or
726 :keyword:`while` loop, but not nested in a function or class definition within
727 that loop. It continues with the next cycle of the nearest enclosing loop.
728
729 When :keyword:`continue` passes control out of a :keyword:`try` statement with a
730 :keyword:`finally` clause, that :keyword:`!finally` clause is executed before
731 really starting the next loop cycle.
732
733
734 .. _import:
735 .. _from:
736
737 The :keyword:`!import` statement
738 ================================
739
740 .. index::
741 ! pair: statement; import
742 single: module; importing
743 pair: name; binding
744 pair: keyword; from
745 pair: keyword; as
746 pair: exception; ImportError
747 single: , (comma); import statement
748
749 .. productionlist:: python-grammar
750 import_stmt: "import" `module` ["as" `identifier`] ("," `module` ["as" `identifier`])*
751 : | "from" `relative_module` "import" `identifier` ["as" `identifier`]
752 : ("," `identifier` ["as" `identifier`])*
753 : | "from" `relative_module` "import" "(" `identifier` ["as" `identifier`]
754 : ("," `identifier` ["as" `identifier`])* [","] ")"
755 : | "from" `relative_module` "import" "*"
756 module: (`identifier` ".")* `identifier`
757 relative_module: "."* `module` | "."+
758
759 The basic import statement (no :keyword:`from` clause) is executed in two
760 steps:
761
762 #. find a module, loading and initializing it if necessary
763 #. define a name or names in the current namespace for the scope where
764 the :keyword:`import` statement occurs, just as an assignment statement
765 would (including :keyword:`global` and :keyword:`nonlocal` semantics).
766
767 When the statement contains multiple clauses (separated by
768 commas) the two steps are carried out separately for each clause, just
769 as though the clauses had been separated out into individual import
770 statements.
771
772 The details of the first step, finding and loading modules, are described in
773 greater detail in the section on the :ref:`import system <importsystem>`,
774 which also describes the various types of packages and modules that can
775 be imported, as well as all the hooks that can be used to customize
776 the import system. Note that failures in this step may indicate either
777 that the module could not be located, *or* that an error occurred while
778 initializing the module, which includes execution of the module's code.
779
780 If the requested module is retrieved successfully, it will be made
781 available in the local namespace in one of three ways:
782
783 .. index:: single: as; import statement
784
785 * If the module name is followed by :keyword:`!as`, then the name
786 following :keyword:`!as` is bound directly to the imported module.
787 * If no other name is specified, and the module being imported is a top
788 level module, the module's name is bound in the local namespace as a
789 reference to the imported module
790 * If the module being imported is *not* a top level module, then the name
791 of the top level package that contains the module is bound in the local
792 namespace as a reference to the top level package. The imported module
793 must be accessed using its full qualified name rather than directly
794
795
796 .. index::
797 pair: name; binding
798 single: from; import statement
799
800 The :keyword:`from` form uses a slightly more complex process:
801
802 #. find the module specified in the :keyword:`from` clause, loading and
803 initializing it if necessary;
804 #. for each of the identifiers specified in the :keyword:`import` clauses:
805
806 #. check if the imported module has an attribute by that name
807 #. if not, attempt to import a submodule with that name and then
808 check the imported module again for that attribute
809 #. if the attribute is not found, :exc:`ImportError` is raised.
810 #. otherwise, a reference to that value is stored in the current namespace,
811 using the name in the :keyword:`!as` clause if it is present,
812 otherwise using the attribute name
813
814 Examples::
815
816 import foo # foo imported and bound locally
817 import foo.bar.baz # foo, foo.bar, and foo.bar.baz imported, foo bound locally
818 import foo.bar.baz as fbb # foo, foo.bar, and foo.bar.baz imported, foo.bar.baz bound as fbb
819 from foo.bar import baz # foo, foo.bar, and foo.bar.baz imported, foo.bar.baz bound as baz
820 from foo import attr # foo imported and foo.attr bound as attr
821
822 .. index:: single: * (asterisk); import statement
823
824 If the list of identifiers is replaced by a star (``'*'``), all public
825 names defined in the module are bound in the local namespace for the scope
826 where the :keyword:`import` statement occurs.
827
828 .. index:: single: __all__ (optional module attribute)
829
830 .. attribute:: module.__all__
831 :no-typesetting:
832
833 The *public names* defined by a module are determined by checking the module's
834 namespace for a variable named ``__all__``; if defined, it must be a sequence
835 of strings which are names defined or imported by that module.
836 Names containing non-ASCII characters must be in the `normalization form`_
837 NFKC; see :ref:`lexical-names-nonascii` for details. The names
838 given in ``__all__`` are all considered public and are required to exist. If
839 ``__all__`` is not defined, the set of public names includes all names found
840 in the module's namespace which do not begin with an underscore character
841 (``'_'``). ``__all__`` should contain the entire public API. It is intended
842 to avoid accidentally exporting items that are not part of the API (such as
843 library modules which were imported and used within the module).
844
845 The wild card form of import --- ``from module import *`` --- is only allowed at
846 the module level. Attempting to use it in class or function definitions will
847 raise a :exc:`SyntaxError`.
848
849 .. index::
850 single: relative; import
851
852 When specifying what module to import you do not have to specify the absolute
853 name of the module. When a module or package is contained within another
854 package it is possible to make a relative import within the same top package
855 without having to mention the package name. By using leading dots in the
856 specified module or package after :keyword:`from` you can specify how high to
857 traverse up the current package hierarchy without specifying exact names. One
858 leading dot means the current package where the module making the import
859 exists. Two dots means up one package level. Three dots is up two levels, etc.
860 So if you execute ``from . import mod`` from a module in the ``pkg`` package
861 then you will end up importing ``pkg.mod``. If you execute ``from ..subpkg2
862 import mod`` from within ``pkg.subpkg1`` you will import ``pkg.subpkg2.mod``.
863 The specification for relative imports is contained in
864 the :ref:`relativeimports` section.
865
866 :func:`importlib.import_module` is provided to support applications that
867 determine dynamically the modules to be loaded.
868
869 .. audit-event:: import module,filename,sys.path,sys.meta_path,sys.path_hooks import
870
871 .. _normalization form: https://www.unicode.org/reports/tr15/#Norm_Forms
872
873 .. _future:
874
875 Future statements
876 -----------------
877
878 .. index::
879 pair: future; statement
880 single: __future__; future statement
881
882 A :dfn:`future statement` is a directive to the compiler that a particular
883 module should be compiled using syntax or semantics that will be available in a
884 specified future release of Python where the feature becomes standard.
885
886 The future statement is intended to ease migration to future versions of Python
887 that introduce incompatible changes to the language. It allows use of the new
888 features on a per-module basis before the release in which the feature becomes
889 standard.
890
891 .. productionlist:: python-grammar
892 future_stmt: "from" "__future__" "import" `feature` ["as" `identifier`]
893 : ("," `feature` ["as" `identifier`])*
894 : | "from" "__future__" "import" "(" `feature` ["as" `identifier`]
895 : ("," `feature` ["as" `identifier`])* [","] ")"
896 feature: `identifier`
897
898 A future statement must appear near the top of the module. The only lines that
899 can appear before a future statement are:
900
901 * the module docstring (if any),
902 * comments,
903 * blank lines, and
904 * other future statements.
905
906 The only feature that requires using the future statement is
907 ``annotations`` (see :pep:`563`).
908
909 All historical features enabled by the future statement are still recognized
910 by Python 3. The list includes ``absolute_import``, ``division``,
911 ``generators``, ``generator_stop``, ``unicode_literals``,
912 ``print_function``, ``nested_scopes`` and ``with_statement``. They are
913 all redundant because they are always enabled, and only kept for
914 backwards compatibility.
915
916 A future statement is recognized and treated specially at compile time: Changes
917 to the semantics of core constructs are often implemented by generating
918 different code. It may even be the case that a new feature introduces new
919 incompatible syntax (such as a new reserved word), in which case the compiler
920 may need to parse the module differently. Such decisions cannot be pushed off
921 until runtime.
922
923 For any given release, the compiler knows which feature names have been defined,
924 and raises a compile-time error if a future statement contains a feature not
925 known to it.
926
927 The direct runtime semantics are the same as for any import statement: there is
928 a standard module :mod:`__future__`, described later, and it will be imported in
929 the usual way at the time the future statement is executed.
930
931 The interesting runtime semantics depend on the specific feature enabled by the
932 future statement.
933
934 Note that there is nothing special about the statement::
935
936 import __future__ [as name]
937
938 That is not a future statement; it's an ordinary import statement with no
939 special semantics or syntax restrictions.
940
941 Code compiled by calls to the built-in functions :func:`exec` and :func:`compile`
942 that occur in a module :mod:`!M` containing a future statement will, by default,
943 use the new syntax or semantics associated with the future statement. This can
944 be controlled by optional arguments to :func:`compile` --- see the documentation
945 of that function for details.
946
947 A future statement typed at an interactive interpreter prompt will take effect
948 for the rest of the interpreter session. If an interpreter is started with the
949 :option:`-i` option, is passed a script name to execute, and the script includes
950 a future statement, it will be in effect in the interactive session started
951 after the script is executed.
952
953 .. seealso::
954
955 :pep:`236` - Back to the __future__
956 The original proposal for the __future__ mechanism.
957
958
959 .. _global:
960
961 The :keyword:`!global` statement
962 ================================
963
964 .. index::
965 ! pair: statement; global
966 triple: global; name; binding
967 single: , (comma); identifier list
968
969 .. productionlist:: python-grammar
970 global_stmt: "global" `identifier` ("," `identifier`)*
971
972 The :keyword:`global` statement causes the listed identifiers to be interpreted
973 as globals. It would be impossible to assign to a global variable without
974 :keyword:`!global`, although free variables may refer to globals without being
975 declared global.
976
977 The :keyword:`!global` statement applies to the entire current scope
978 (module, function body or class definition).
979 A :exc:`SyntaxError` is raised if a variable is used or
980 assigned to prior to its global declaration in the scope.
981
982 At the module level, all variables are global, so a :keyword:`!global`
983 statement has no effect.
984 However, variables must still not be used or
985 assigned to prior to their :keyword:`!global` declaration.
986 This requirement is relaxed in the interactive prompt (:term:`REPL`).
987
988 .. index::
989 pair: built-in function; exec
990 pair: built-in function; eval
991 pair: built-in function; compile
992
993 **Programmer's note:** :keyword:`global` is a directive to the parser. It
994 applies only to code parsed at the same time as the :keyword:`!global` statement.
995 In particular, a :keyword:`!global` statement contained in a string or code
996 object supplied to the built-in :func:`exec` function does not affect the code
997 block *containing* the function call, and code contained in such a string is
998 unaffected by :keyword:`!global` statements in the code containing the function
999 call. The same applies to the :func:`eval` and :func:`compile` functions.
1000
1001
1002 .. _nonlocal:
1003
1004 The :keyword:`!nonlocal` statement
1005 ==================================
1006
1007 .. index:: pair: statement; nonlocal
1008 single: , (comma); identifier list
1009
1010 .. productionlist:: python-grammar
1011 nonlocal_stmt: "nonlocal" `identifier` ("," `identifier`)*
1012
1013 When the definition of a function or class is nested (enclosed) within
1014 the definitions of other functions, its nonlocal scopes are the local
1015 scopes of the enclosing functions. The :keyword:`nonlocal` statement
1016 causes the listed identifiers to refer to names previously bound in
1017 nonlocal scopes. It allows encapsulated code to rebind such nonlocal
1018 identifiers. If a name is bound in more than one nonlocal scope, the
1019 nearest binding is used. If a name is not bound in any nonlocal scope,
1020 or if there is no nonlocal scope, a :exc:`SyntaxError` is raised.
1021
1022 The :keyword:`nonlocal` statement applies to the entire scope of a function or
1023 class body. A :exc:`SyntaxError` is raised if a variable is used or
1024 assigned to prior to its nonlocal declaration in the scope.
1025
1026 .. seealso::
1027
1028 :pep:`3104` - Access to Names in Outer Scopes
1029 The specification for the :keyword:`nonlocal` statement.
1030
1031 **Programmer's note:** :keyword:`nonlocal` is a directive to the parser
1032 and applies only to code parsed along with it. See the note for the
1033 :keyword:`global` statement.
1034
1035
1036 .. _type:
1037
1038 The :keyword:`!type` statement
1039 ==============================
1040
1041 .. index:: pair: statement; type
1042
1043 .. productionlist:: python-grammar
1044 type_stmt: 'type' `identifier` [`type_params`] "=" `expression`
1045
1046 The :keyword:`!type` statement declares a type alias, which is an instance
1047 of :class:`typing.TypeAliasType`.
1048
1049 For example, the following statement creates a type alias::
1050
1051 type Point = tuple[float, float]
1052
1053 This code is roughly equivalent to::
1054
1055 annotation-def VALUE_OF_Point():
1056 return tuple[float, float]
1057 Point = typing.TypeAliasType("Point", VALUE_OF_Point())
1058
1059 ``annotation-def`` indicates an :ref:`annotation scope <annotation-scopes>`, which behaves
1060 mostly like a function, but with several small differences.
1061
1062 The value of the
1063 type alias is evaluated in the annotation scope. It is not evaluated when the
1064 type alias is created, but only when the value is accessed through the type alias's
1065 :attr:`!__value__` attribute (see :ref:`lazy-evaluation`).
1066 This allows the type alias to refer to names that are not yet defined.
1067
1068 Type aliases may be made generic by adding a :ref:`type parameter list <type-params>`
1069 after the name. See :ref:`generic-type-aliases` for more.
1070
1071 :keyword:`!type` is a :ref:`soft keyword <soft-keywords>`.
1072
1073 .. versionadded:: 3.12
1074
1075 .. seealso::
1076
1077 :pep:`695` - Type Parameter Syntax
1078 Introduced the :keyword:`!type` statement and syntax for
1079 generic classes and functions.