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 :deco:`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 current namespace for the scope where
767 the :keyword:`import` statement occurs, just as an assignment statement
768 would (including :keyword:`global` and :keyword:`nonlocal` semantics).
769
770 When the statement contains multiple clauses (separated by
771 commas) the two steps are carried out separately for each clause, just
772 as though the clauses had been separated out into individual import
773 statements.
774
775 The details of the first step, finding and loading modules, are described in
776 greater detail in the section on the :ref:`import system <importsystem>`,
777 which also describes the various types of packages and modules that can
778 be imported, as well as all the hooks that can be used to customize
779 the import system. Note that failures in this step may indicate either
780 that the module could not be located, *or* that an error occurred while
781 initializing the module, which includes execution of the module's code.
782
783 If the requested module is retrieved successfully, it will be made
784 available in the local namespace in one of three ways:
785
786 .. index:: single: as; import statement
787
788 * If the module name is followed by :keyword:`!as`, then the name
789 following :keyword:`!as` is bound directly to the imported module.
790 * If no other name is specified, and the module being imported is a top
791 level module, the module's name is bound in the local namespace as a
792 reference to the imported module
793 * If the module being imported is *not* a top level module, then the name
794 of the top level package that contains the module is bound in the local
795 namespace as a reference to the top level package. The imported module
796 must be accessed using its full qualified name rather than directly
797
798
799 .. index::
800 pair: name; binding
801 single: from; import statement
802
803 The :keyword:`from` form uses a slightly more complex process:
804
805 #. find the module specified in the :keyword:`from` clause, loading and
806 initializing it if necessary;
807 #. for each of the identifiers specified in the :keyword:`import` clauses:
808
809 #. check if the imported module has an attribute by that name
810 #. if not, attempt to import a submodule with that name and then
811 check the imported module again for that attribute
812 #. if the attribute is not found, :exc:`ImportError` is raised.
813 #. otherwise, a reference to that value is stored in the current namespace,
814 using the name in the :keyword:`!as` clause if it is present,
815 otherwise using the attribute name
816
817 Examples::
818
819 import foo # foo imported and bound locally
820 import foo.bar.baz # foo, foo.bar, and foo.bar.baz imported, foo bound locally
821 import foo.bar.baz as fbb # foo, foo.bar, and foo.bar.baz imported, foo.bar.baz bound as fbb
822 from foo.bar import baz # foo, foo.bar, and foo.bar.baz imported, foo.bar.baz bound as baz
823 from foo import attr # foo imported and foo.attr bound as attr
824
825 .. index:: single: * (asterisk); import statement
826
827 If the list of identifiers is replaced by a star (``'*'``), all public
828 names defined in the module are bound in the local namespace for the scope
829 where the :keyword:`import` statement occurs.
830
831 .. index:: single: __all__ (optional module attribute)
832
833 .. attribute:: module.__all__
834 :no-typesetting:
835
836 The *public names* defined by a module are determined by checking the module's
837 namespace for a variable named ``__all__``; if defined, it must be a sequence
838 of strings which are names defined or imported by that module.
839 Names containing non-ASCII characters must be in the `normalization form`_
840 NFKC. The names
841 given in ``__all__`` are all considered public and are required to exist. If
842 ``__all__`` is not defined, the set of public names includes all names found
843 in the module's namespace which do not begin with an underscore character
844 (``'_'``). ``__all__`` should contain the entire public API. It is intended
845 to avoid accidentally exporting items that are not part of the API (such as
846 library modules which were imported and used within the module).
847
848 The wild card form of import --- ``from module import *`` --- is only allowed at
849 the module level. Attempting to use it in class or function definitions will
850 raise a :exc:`SyntaxError`.
851
852 .. index::
853 single: relative; import
854
855 When specifying what module to import you do not have to specify the absolute
856 name of the module. When a module or package is contained within another
857 package it is possible to make a relative import within the same top package
858 without having to mention the package name. By using leading dots in the
859 specified module or package after :keyword:`from` you can specify how high to
860 traverse up the current package hierarchy without specifying exact names. One
861 leading dot means the current package where the module making the import
862 exists. Two dots means up one package level. Three dots is up two levels, etc.
863 So if you execute ``from . import mod`` from a module in the ``pkg`` package
864 then you will end up importing ``pkg.mod``. If you execute ``from ..subpkg2
865 import mod`` from within ``pkg.subpkg1`` you will import ``pkg.subpkg2.mod``.
866 The specification for relative imports is contained in
867 the :ref:`relativeimports` section.
868
869 :func:`importlib.import_module` is provided to support applications that
870 determine dynamically the modules to be loaded.
871
872 .. audit-event:: import module,filename,sys.path,sys.meta_path,sys.path_hooks import
873
874 .. _normalization form: https://www.unicode.org/reports/tr15/#Norm_Forms
875
876 .. _future:
877
878 Future statements
879 -----------------
880
881 .. index::
882 pair: future; statement
883 single: __future__; future statement
884
885 A :dfn:`future statement` is a directive to the compiler that a particular
886 module should be compiled using syntax or semantics that will be available in a
887 specified future release of Python where the feature becomes standard.
888
889 The future statement is intended to ease migration to future versions of Python
890 that introduce incompatible changes to the language. It allows use of the new
891 features on a per-module basis before the release in which the feature becomes
892 standard.
893
894 .. productionlist:: python-grammar
895 future_stmt: "from" "__future__" "import" `feature` ["as" `identifier`]
896 : ("," `feature` ["as" `identifier`])*
897 : | "from" "__future__" "import" "(" `feature` ["as" `identifier`]
898 : ("," `feature` ["as" `identifier`])* [","] ")"
899 feature: `identifier`
900
901 A future statement must appear near the top of the module. The only lines that
902 can appear before a future statement are:
903
904 * the module docstring (if any),
905 * comments,
906 * blank lines, and
907 * other future statements.
908
909 The only feature that requires using the future statement is
910 ``annotations`` (see :pep:`563`).
911
912 All historical features enabled by the future statement are still recognized
913 by Python 3. The list includes ``absolute_import``, ``division``,
914 ``generators``, ``generator_stop``, ``unicode_literals``,
915 ``print_function``, ``nested_scopes`` and ``with_statement``. They are
916 all redundant because they are always enabled, and only kept for
917 backwards compatibility.
918
919 A future statement is recognized and treated specially at compile time: Changes
920 to the semantics of core constructs are often implemented by generating
921 different code. It may even be the case that a new feature introduces new
922 incompatible syntax (such as a new reserved word), in which case the compiler
923 may need to parse the module differently. Such decisions cannot be pushed off
924 until runtime.
925
926 For any given release, the compiler knows which feature names have been defined,
927 and raises a compile-time error if a future statement contains a feature not
928 known to it.
929
930 The direct runtime semantics are the same as for any import statement: there is
931 a standard module :mod:`__future__`, described later, and it will be imported in
932 the usual way at the time the future statement is executed.
933
934 The interesting runtime semantics depend on the specific feature enabled by the
935 future statement.
936
937 Note that there is nothing special about the statement::
938
939 import __future__ [as name]
940
941 That is not a future statement; it's an ordinary import statement with no
942 special semantics or syntax restrictions.
943
944 Code compiled by calls to the built-in functions :func:`exec` and :func:`compile`
945 that occur in a module :mod:`!M` containing a future statement will, by default,
946 use the new syntax or semantics associated with the future statement. This can
947 be controlled by optional arguments to :func:`compile` --- see the documentation
948 of that function for details.
949
950 A future statement typed at an interactive interpreter prompt will take effect
951 for the rest of the interpreter session. If an interpreter is started with the
952 :option:`-i` option, is passed a script name to execute, and the script includes
953 a future statement, it will be in effect in the interactive session started
954 after the script is executed.
955
956 .. seealso::
957
958 :pep:`236` - Back to the __future__
959 The original proposal for the __future__ mechanism.
960
961
962 .. _global:
963
964 The :keyword:`!global` statement
965 ================================
966
967 .. index::
968 ! pair: statement; global
969 triple: global; name; binding
970 single: , (comma); identifier list
971
972 .. productionlist:: python-grammar
973 global_stmt: "global" `identifier` ("," `identifier`)*
974
975 The :keyword:`global` statement causes the listed identifiers to be interpreted
976 as globals. It would be impossible to assign to a global variable without
977 :keyword:`!global`, although free variables may refer to globals without being
978 declared global.
979
980 The :keyword:`!global` statement applies to the entire current scope
981 (module, function body or class definition).
982 A :exc:`SyntaxError` is raised if a variable is used or
983 assigned to prior to its global declaration in the scope.
984
985 At the module level, all variables are global, so a :keyword:`!global`
986 statement has no effect.
987 However, variables must still not be used or
988 assigned to prior to their :keyword:`!global` declaration.
989 This requirement is relaxed in the interactive prompt (:term:`REPL`).
990
991 .. index::
992 pair: built-in function; exec
993 pair: built-in function; eval
994 pair: built-in function; compile
995
996 **Programmer's note:** :keyword:`global` is a directive to the parser. It
997 applies only to code parsed at the same time as the :keyword:`!global` statement.
998 In particular, a :keyword:`!global` statement contained in a string or code
999 object supplied to the built-in :func:`exec` function does not affect the code
1000 block *containing* the function call, and code contained in such a string is
1001 unaffected by :keyword:`!global` statements in the code containing the function
1002 call. The same applies to the :func:`eval` and :func:`compile` functions.
1003
1004
1005 .. _nonlocal:
1006
1007 The :keyword:`!nonlocal` statement
1008 ==================================
1009
1010 .. index:: pair: statement; nonlocal
1011 single: , (comma); identifier list
1012
1013 .. productionlist:: python-grammar
1014 nonlocal_stmt: "nonlocal" `identifier` ("," `identifier`)*
1015
1016 When the definition of a function or class is nested (enclosed) within
1017 the definitions of other functions, its nonlocal scopes are the local
1018 scopes of the enclosing functions. The :keyword:`nonlocal` statement
1019 causes the listed identifiers to refer to names previously bound in
1020 nonlocal scopes. It allows encapsulated code to rebind such nonlocal
1021 identifiers. If a name is bound in more than one nonlocal scope, the
1022 nearest binding is used. If a name is not bound in any nonlocal scope,
1023 or if there is no nonlocal scope, a :exc:`SyntaxError` is raised.
1024
1025 The :keyword:`nonlocal` statement applies to the entire scope of a function or
1026 class body. A :exc:`SyntaxError` is raised if a variable is used or
1027 assigned to prior to its nonlocal declaration in the scope.
1028
1029 .. seealso::
1030
1031 :pep:`3104` - Access to Names in Outer Scopes
1032 The specification for the :keyword:`nonlocal` statement.
1033
1034 **Programmer's note:** :keyword:`nonlocal` is a directive to the parser
1035 and applies only to code parsed along with it. See the note for the
1036 :keyword:`global` statement.
1037
1038
1039 .. _type:
1040
1041 The :keyword:`!type` statement
1042 ==============================
1043
1044 .. index:: pair: statement; type
1045
1046 .. productionlist:: python-grammar
1047 type_stmt: 'type' `identifier` [`type_params`] "=" `expression`
1048
1049 The :keyword:`!type` statement declares a type alias, which is an instance
1050 of :class:`typing.TypeAliasType`.
1051
1052 For example, the following statement creates a type alias::
1053
1054 type Point = tuple[float, float]
1055
1056 This code is roughly equivalent to::
1057
1058 annotation-def VALUE_OF_Point():
1059 return tuple[float, float]
1060 Point = typing.TypeAliasType("Point", VALUE_OF_Point())
1061
1062 ``annotation-def`` indicates an :ref:`annotation scope <annotation-scopes>`, which behaves
1063 mostly like a function, but with several small differences.
1064
1065 The value of the
1066 type alias is evaluated in the annotation scope. It is not evaluated when the
1067 type alias is created, but only when the value is accessed through the type alias's
1068 :attr:`!__value__` attribute (see :ref:`lazy-evaluation`).
1069 This allows the type alias to refer to names that are not yet defined.
1070
1071 Type aliases may be made generic by adding a :ref:`type parameter list <type-params>`
1072 after the name. See :ref:`generic-type-aliases` for more.
1073
1074 :keyword:`!type` is a :ref:`soft keyword <soft-keywords>`.
1075
1076 .. versionadded:: 3.12
1077
1078 .. seealso::
1079
1080 :pep:`695` - Type Parameter Syntax
1081 Introduced the :keyword:`!type` statement and syntax for
1082 generic classes and functions.