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