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