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