• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1
2.. _simple:
3
4*****************
5Simple statements
6*****************
7
8.. index:: pair: simple; statement
9
10A simple statement is comprised within a single logical line. Several simple
11statements may occur on a single line separated by semicolons.  The syntax for
12simple 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
36Expression statements
37=====================
38
39.. index::
40   pair: expression; statement
41   pair: expression; list
42.. index:: pair: expression; list
43
44Expression statements are used (mostly interactively) to compute and write a
45value, or (usually) to call a procedure (a function that returns no meaningful
46result; in Python, procedures return the value ``None``).  Other uses of
47expression statements are allowed and occasionally useful.  The syntax for an
48expression statement is:
49
50.. productionlist:: python-grammar
51   expression_stmt: `starred_expression`
52
53An expression statement evaluates the expression list (which may be a single
54expression).
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
65In interactive mode, if the value is not ``None``, it is converted to a string
66using the built-in :func:`repr` function and the resulting string is written to
67standard output on a line by itself (except if the result is ``None``, so that
68procedure calls do not cause any output.)
69
70.. _assignment:
71
72Assignment 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
83Assignment statements are used to (re)bind names to values and to modify
84attributes 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
100An assignment statement evaluates the expression list (remember that this can be
101a single expression or a comma-separated list, the latter yielding a tuple) and
102assigns the single resulting object to each of the target lists, from left to
103right.
104
105.. index::
106   single: target
107   pair: target; list
108
109Assignment is defined recursively depending on the form of the target (list).
110When a target is part of a mutable object (an attribute reference, subscription
111or slicing), the mutable object must ultimately perform the assignment and
112decide about its validity, and may raise an exception if the assignment is
113unacceptable.  The rules observed by various types and the exceptions raised are
114given 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
122Assignment of an object to a target list, optionally enclosed in parentheses or
123square 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
142Assignment 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
240Although the definition of assignment implies that overlaps between the
241left-hand side and the right-hand side are 'simultaneous' (for example ``a, b =
242b, a`` swaps two variables), overlaps *within* the collection of assigned-to
243variables occur left-to-right, sometimes resulting in confusion.  For instance,
244the 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
260Augmented 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
279Augmented assignment is the combination, in a single statement, of a binary
280operation 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
289symbols.)
290
291An augmented assignment evaluates the target (which, unlike normal assignment
292statements, cannot be an unpacking) and the expression list, performs the binary
293operation specific to the type of assignment on the two operands, and assigns
294the result to the original target.  The target is only evaluated once.
295
296An augmented assignment statement like ``x += 1`` can be rewritten as ``x = x +
2971`` to achieve a similar, but not exactly equal effect. In the augmented
298version, ``x`` is only evaluated once. Also, when possible, the actual operation
299is performed *in-place*, meaning that rather than creating a new object and
300assigning that to the target, the old object is modified instead.
301
302Unlike normal assignments, augmented assignments evaluate the left-hand side
303*before* evaluating the right-hand side.  For example, ``a[i] += f(x)`` first
304looks-up ``a[i]``, then it evaluates ``f(x)`` and performs the addition, and
305lastly, it writes the result back to ``a[i]``.
306
307With the exception of assigning to tuples and multiple targets in a single
308statement, the assignment done by augmented assignment statements is handled the
309same way as normal assignments. Similarly, with the exception of the possible
310*in-place* behavior, the binary operation performed by augmented assignment is
311the same as the normal binary operations.
312
313For targets which are attribute references, the same :ref:`caveat about class
314and instance attributes <attr-target-note>` applies as for regular assignments.
315
316
317.. _annassign:
318
319Annotated 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
328statement, 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
334The difference from normal :ref:`assignment` is that only a single target is allowed.
335
336The assignment target is considered "simple" if it consists of a single
337name that is not enclosed in parentheses.
338For simple assignment targets, if in class or module scope,
339the annotations are evaluated and stored in a special class or module
340attribute :attr:`__annotations__`
341that is a dictionary mapping from variable names (mangled if private) to
342evaluated annotations. This attribute is writable and is automatically
343created at the start of class or module body execution, if annotations
344are found statically.
345
346If the assignment target is not simple (an attribute, subscript node, or
347parenthesized name), the annotation is evaluated if
348in class or module scope, but not stored.
349
350If a name is annotated in a function scope, then this name is local for
351that scope. Annotations are never evaluated and stored in function scopes.
352
353If the right hand side is present, an annotated
354assignment performs the actual assignment before evaluating annotations
355(where applicable). If the right hand side is not present for an expression
356target, 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
379The :keyword:`!assert` statement
380================================
381
382.. index::
383   ! pair: statement; assert
384   pair: debugging; assertions
385   single: , (comma); expression list
386
387Assert statements are a convenient way to insert debugging assertions into a
388program:
389
390.. productionlist:: python-grammar
391   assert_stmt: "assert" `expression` ["," `expression`]
392
393The simple form, ``assert expression``, is equivalent to ::
394
395   if __debug__:
396       if not expression: raise AssertionError
397
398The 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
407These equivalences assume that :const:`__debug__` and :exc:`AssertionError` refer to
408the built-in variables with those names.  In the current implementation, the
409built-in variable ``__debug__`` is ``True`` under normal circumstances,
410``False`` when optimization is requested (command line option :option:`-O`).  The current
411code generator emits no code for an :keyword:`assert` statement when optimization is
412requested at compile time.  Note that it is unnecessary to include the source
413code for the expression that failed in the error message; it will be displayed
414as part of the stack trace.
415
416Assignments to :const:`__debug__` are illegal.  The value for the built-in variable
417is determined when the interpreter starts.
418
419
420.. _pass:
421
422The :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.
434It is useful as a placeholder when a statement is required syntactically, but no
435code 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
444The :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
455Deletion is recursively defined very similar to the way assignment is defined.
456Rather than spelling it out in full details, here are some hints.
457
458Deletion of a target list recursively deletes each target, from left to right.
459
460.. index::
461   pair: statement; global
462   pair: unbinding; name
463
464Deletion of a name removes the binding of that name from the local or global
465namespace, depending on whether the name occurs in a :keyword:`global` statement
466in the same code block.  If the name is unbound, a :exc:`NameError` exception
467will be raised.
468
469.. index:: pair: attribute; deletion
470
471Deletion of attribute references, subscriptions and slicings is passed to the
472primary object involved; deletion of a slicing is in general equivalent to
473assignment of an empty slice of the right type (but even this is determined by
474the 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
483The :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,
495not within a nested class definition.
496
497If 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
504When :keyword:`return` passes control out of a :keyword:`try` statement with a
505:keyword:`finally` clause, that :keyword:`!finally` clause is executed before
506really leaving the function.
507
508In a generator function, the :keyword:`return` statement indicates that the
509generator is done and will cause :exc:`StopIteration` to be raised. The returned
510value (if any) is used as an argument to construct :exc:`StopIteration` and
511becomes the :attr:`StopIteration.value` attribute.
512
513In an asynchronous generator function, an empty :keyword:`return` statement
514indicates that the asynchronous generator is done and will cause
515:exc:`StopAsyncIteration` to be raised.  A non-empty :keyword:`!return`
516statement is a syntax error in an asynchronous generator function.
517
518.. _yield:
519
520The :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
533A :keyword:`yield` statement is semantically equivalent to a :ref:`yield
534expression <yieldexpr>`. The ``yield`` statement can be used to omit the
535parentheses that would otherwise be required in the equivalent yield expression
536statement. For example, the yield statements ::
537
538  yield <expr>
539  yield from <expr>
540
541are equivalent to the yield expression statements ::
542
543  (yield <expr>)
544  (yield from <expr>)
545
546Yield expressions and statements are only used when defining a :term:`generator`
547function, and are only used in the body of the generator function.  Using :keyword:`yield`
548in a function definition is sufficient to cause that definition to create a
549generator function instead of a normal function.
550
551For full details of :keyword:`yield` semantics, refer to the
552:ref:`yieldexpr` section.
553
554.. _raise:
555
556The :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
568If no expressions are present, :keyword:`raise` re-raises the
569exception that is currently being handled, which is also known as the *active exception*.
570If there isn't currently an active exception, a :exc:`RuntimeError` exception is raised
571indicating that this is an error.
572
573Otherwise, :keyword:`raise` evaluates the first expression as the exception
574object.  It must be either a subclass or an instance of :class:`BaseException`.
575If it is a class, the exception instance will be obtained when needed by
576instantiating the class with no arguments.
577
578The :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
583A traceback object is normally created automatically when an exception is raised
584and attached to it as the :attr:`~BaseException.__traceback__` attribute.
585You can create an exception and set your own traceback in one step using the
586:meth:`~BaseException.with_traceback` exception method (which returns the
587same 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
595The ``from`` clause is used for exception chaining: if given, the second
596*expression* must be another exception class or instance. If the second
597expression is an exception instance, it will be attached to the raised
598exception as the :attr:`~BaseException.__cause__` attribute (which is writable). If the
599expression is an exception class, the class will be instantiated and the
600resulting exception instance will be attached to the raised exception as the
601:attr:`!__cause__` attribute. If the raised exception is not handled, both
602exceptions 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
624A similar mechanism works implicitly if a new exception is raised when
625an exception is already being handled.  An exception may be handled
626when an :keyword:`except` or :keyword:`finally` clause, or a
627:keyword:`with` statement, is used.  The previous exception is then
628attached 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
650Exception chaining can be explicitly suppressed by specifying :const:`None` in
651the ``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
664Additional information on exceptions can be found in section :ref:`exceptions`,
665and 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
681The :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
695that loop.
696
697.. index:: pair: keyword; else
698           pair: loop control; target
699
700It terminates the nearest enclosing loop, skipping the optional :keyword:`!else`
701clause if the loop has one.
702
703If a :keyword:`for` loop is terminated by :keyword:`break`, the loop control
704target keeps its current value.
705
706.. index:: pair: keyword; finally
707
708When :keyword:`break` passes control out of a :keyword:`try` statement with a
709:keyword:`finally` clause, that :keyword:`!finally` clause is executed before
710really leaving the loop.
711
712
713.. _continue:
714
715The :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
730that loop.  It continues with the next cycle of the nearest enclosing loop.
731
732When :keyword:`continue` passes control out of a :keyword:`try` statement with a
733:keyword:`finally` clause, that :keyword:`!finally` clause is executed before
734really starting the next loop cycle.
735
736
737.. _import:
738.. _from:
739
740The :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
762The basic import statement (no :keyword:`from` clause) is executed in two
763steps:
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
769When the statement contains multiple clauses (separated by
770commas) the two steps are carried out separately for each clause, just
771as though the clauses had been separated out into individual import
772statements.
773
774The details of the first step, finding and loading modules, are described in
775greater detail in the section on the :ref:`import system <importsystem>`,
776which also describes the various types of packages and modules that can
777be imported, as well as all the hooks that can be used to customize
778the import system. Note that failures in this step may indicate either
779that the module could not be located, *or* that an error occurred while
780initializing the module, which includes execution of the module's code.
781
782If the requested module is retrieved successfully, it will be made
783available 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
802The :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
816Examples::
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
826If the list of identifiers is replaced by a star (``'*'``), all public
827names defined in the module are bound in the local namespace for the scope
828where the :keyword:`import` statement occurs.
829
830.. index:: single: __all__ (optional module attribute)
831
832The *public names* defined by a module are determined by checking the module's
833namespace for a variable named ``__all__``; if defined, it must be a sequence
834of strings which are names defined or imported by that module.  The names
835given in ``__all__`` are all considered public and are required to exist.  If
836``__all__`` is not defined, the set of public names includes all names found
837in the module's namespace which do not begin with an underscore character
838(``'_'``).  ``__all__`` should contain the entire public API. It is intended
839to avoid accidentally exporting items that are not part of the API (such as
840library modules which were imported and used within the module).
841
842The wild card form of import --- ``from module import *`` --- is only allowed at
843the module level.  Attempting to use it in class or function definitions will
844raise a :exc:`SyntaxError`.
845
846.. index::
847    single: relative; import
848
849When specifying what module to import you do not have to specify the absolute
850name of the module. When a module or package is contained within another
851package it is possible to make a relative import within the same top package
852without having to mention the package name. By using leading dots in the
853specified module or package after :keyword:`from` you can specify how high to
854traverse up the current package hierarchy without specifying exact names. One
855leading dot means the current package where the module making the import
856exists. Two dots means up one package level. Three dots is up two levels, etc.
857So if you execute ``from . import mod`` from a module in the ``pkg`` package
858then you will end up importing ``pkg.mod``. If you execute ``from ..subpkg2
859import mod`` from within ``pkg.subpkg1`` you will import ``pkg.subpkg2.mod``.
860The specification for relative imports is contained in
861the :ref:`relativeimports` section.
862
863:func:`importlib.import_module` is provided to support applications that
864determine dynamically the modules to be loaded.
865
866.. audit-event:: import module,filename,sys.path,sys.meta_path,sys.path_hooks import
867
868.. _future:
869
870Future statements
871-----------------
872
873.. index::
874   pair: future; statement
875   single: __future__; future statement
876
877A :dfn:`future statement` is a directive to the compiler that a particular
878module should be compiled using syntax or semantics that will be available in a
879specified future release of Python where the feature becomes standard.
880
881The future statement is intended to ease migration to future versions of Python
882that introduce incompatible changes to the language.  It allows use of the new
883features on a per-module basis before the release in which the feature becomes
884standard.
885
886.. productionlist:: python-grammar
887   future_stmt: "from" "__future__" "import" `feature` ["as" `identifier`]
888              : ("," `feature` ["as" `identifier`])*
889              : | "from" "__future__" "import" "(" `feature` ["as" `identifier`]
890              : ("," `feature` ["as" `identifier`])* [","] ")"
891   feature: `identifier`
892
893A future statement must appear near the top of the module.  The only lines that
894can appear before a future statement are:
895
896* the module docstring (if any),
897* comments,
898* blank lines, and
899* other future statements.
900
901The only feature that requires using the future statement is
902``annotations`` (see :pep:`563`).
903
904All historical features enabled by the future statement are still recognized
905by Python 3.  The list includes ``absolute_import``, ``division``,
906``generators``, ``generator_stop``, ``unicode_literals``,
907``print_function``, ``nested_scopes`` and ``with_statement``.  They are
908all redundant because they are always enabled, and only kept for
909backwards compatibility.
910
911A future statement is recognized and treated specially at compile time: Changes
912to the semantics of core constructs are often implemented by generating
913different code.  It may even be the case that a new feature introduces new
914incompatible syntax (such as a new reserved word), in which case the compiler
915may need to parse the module differently.  Such decisions cannot be pushed off
916until runtime.
917
918For any given release, the compiler knows which feature names have been defined,
919and raises a compile-time error if a future statement contains a feature not
920known to it.
921
922The direct runtime semantics are the same as for any import statement: there is
923a standard module :mod:`__future__`, described later, and it will be imported in
924the usual way at the time the future statement is executed.
925
926The interesting runtime semantics depend on the specific feature enabled by the
927future statement.
928
929Note that there is nothing special about the statement::
930
931   import __future__ [as name]
932
933That is not a future statement; it's an ordinary import statement with no
934special semantics or syntax restrictions.
935
936Code compiled by calls to the built-in functions :func:`exec` and :func:`compile`
937that occur in a module :mod:`!M` containing a future statement will, by default,
938use the new syntax or semantics associated with the future statement.  This can
939be controlled by optional arguments to :func:`compile` --- see the documentation
940of that function for details.
941
942A future statement typed at an interactive interpreter prompt will take effect
943for the rest of the interpreter session.  If an interpreter is started with the
944:option:`-i` option, is passed a script name to execute, and the script includes
945a future statement, it will be in effect in the interactive session started
946after the script is executed.
947
948.. seealso::
949
950   :pep:`236` - Back to the __future__
951      The original proposal for the __future__ mechanism.
952
953
954.. _global:
955
956The :keyword:`!global` statement
957================================
958
959.. index::
960   ! pair: statement; global
961   triple: global; name; binding
962   single: , (comma); identifier list
963
964.. productionlist:: python-grammar
965   global_stmt: "global" `identifier` ("," `identifier`)*
966
967The :keyword:`global` statement causes the listed identifiers to be interpreted
968as globals. It would be impossible to assign to a global variable without
969:keyword:`!global`, although free variables may refer to globals without being
970declared global.
971
972The :keyword:`global` statement applies to the entire scope of a function or
973class body. A :exc:`SyntaxError` is raised if a variable is used or
974assigned to prior to its global declaration in the scope.
975
976.. index::
977   pair: built-in function; exec
978   pair: built-in function; eval
979   pair: built-in function; compile
980
981**Programmer's note:** :keyword:`global` is a directive to the parser.  It
982applies only to code parsed at the same time as the :keyword:`!global` statement.
983In particular, a :keyword:`!global` statement contained in a string or code
984object supplied to the built-in :func:`exec` function does not affect the code
985block *containing* the function call, and code contained in such a string is
986unaffected by :keyword:`!global` statements in the code containing the function
987call.  The same applies to the :func:`eval` and :func:`compile` functions.
988
989
990.. _nonlocal:
991
992The :keyword:`!nonlocal` statement
993==================================
994
995.. index:: pair: statement; nonlocal
996   single: , (comma); identifier list
997
998.. productionlist:: python-grammar
999   nonlocal_stmt: "nonlocal" `identifier` ("," `identifier`)*
1000
1001When the definition of a function or class is nested (enclosed) within
1002the definitions of other functions, its nonlocal scopes are the local
1003scopes of the enclosing functions. The :keyword:`nonlocal` statement
1004causes the listed identifiers to refer to names previously bound in
1005nonlocal scopes. It allows encapsulated code to rebind such nonlocal
1006identifiers.  If a name is bound in more than one nonlocal scope, the
1007nearest binding is used. If a name is not bound in any nonlocal scope,
1008or if there is no nonlocal scope, a :exc:`SyntaxError` is raised.
1009
1010The :keyword:`nonlocal` statement applies to the entire scope of a function or
1011class body. A :exc:`SyntaxError` is raised if a variable is used or
1012assigned to prior to its nonlocal declaration in the scope.
1013
1014.. seealso::
1015
1016   :pep:`3104` - Access to Names in Outer Scopes
1017      The specification for the :keyword:`nonlocal` statement.
1018
1019**Programmer's note:** :keyword:`nonlocal` is a directive to the parser
1020and applies only to code parsed along with it.  See the note for the
1021:keyword:`global` statement.
1022
1023
1024.. _type:
1025
1026The :keyword:`!type` statement
1027==============================
1028
1029.. index:: pair: statement; type
1030
1031.. productionlist:: python-grammar
1032   type_stmt: 'type' `identifier` [`type_params`] "=" `expression`
1033
1034The :keyword:`!type` statement declares a type alias, which is an instance
1035of :class:`typing.TypeAliasType`.
1036
1037For example, the following statement creates a type alias::
1038
1039   type Point = tuple[float, float]
1040
1041This code is roughly equivalent to::
1042
1043   annotation-def VALUE_OF_Point():
1044       return tuple[float, float]
1045   Point = typing.TypeAliasType("Point", VALUE_OF_Point())
1046
1047``annotation-def`` indicates an :ref:`annotation scope <annotation-scopes>`, which behaves
1048mostly like a function, but with several small differences.
1049
1050The value of the
1051type alias is evaluated in the annotation scope. It is not evaluated when the
1052type alias is created, but only when the value is accessed through the type alias's
1053:attr:`!__value__` attribute (see :ref:`lazy-evaluation`).
1054This allows the type alias to refer to names that are not yet defined.
1055
1056Type aliases may be made generic by adding a :ref:`type parameter list <type-params>`
1057after the name. See :ref:`generic-type-aliases` for more.
1058
1059:keyword:`!type` is a :ref:`soft keyword <soft-keywords>`.
1060
1061.. versionadded:: 3.12
1062
1063.. seealso::
1064
1065   :pep:`695` - Type Parameter Syntax
1066      Introduced the :keyword:`!type` statement and syntax for
1067      generic classes and functions.
1068