1.. _compound: 2 3******************* 4Compound statements 5******************* 6 7.. index:: pair: compound; statement 8 9Compound statements contain (groups of) other statements; they affect or control 10the execution of those other statements in some way. In general, compound 11statements span multiple lines, although in simple incarnations a whole compound 12statement may be contained in one line. 13 14The :keyword:`if`, :keyword:`while` and :keyword:`for` statements implement 15traditional control flow constructs. :keyword:`try` specifies exception 16handlers and/or cleanup code for a group of statements, while the 17:keyword:`with` statement allows the execution of initialization and 18finalization code around a block of code. Function and class definitions are 19also syntactically compound statements. 20 21.. index:: 22 single: clause 23 single: suite 24 single: ; (semicolon) 25 26A compound statement consists of one or more 'clauses.' A clause consists of a 27header and a 'suite.' The clause headers of a particular compound statement are 28all at the same indentation level. Each clause header begins with a uniquely 29identifying keyword and ends with a colon. A suite is a group of statements 30controlled by a clause. A suite can be one or more semicolon-separated simple 31statements on the same line as the header, following the header's colon, or it 32can be one or more indented statements on subsequent lines. Only the latter 33form of a suite can contain nested compound statements; the following is illegal, 34mostly because it wouldn't be clear to which :keyword:`if` clause a following 35:keyword:`else` clause would belong:: 36 37 if test1: if test2: print(x) 38 39Also note that the semicolon binds tighter than the colon in this context, so 40that in the following example, either all or none of the :func:`print` calls are 41executed:: 42 43 if x < y < z: print(x); print(y); print(z) 44 45Summarizing: 46 47 48.. productionlist:: python-grammar 49 compound_stmt: `if_stmt` 50 : | `while_stmt` 51 : | `for_stmt` 52 : | `try_stmt` 53 : | `with_stmt` 54 : | `match_stmt` 55 : | `funcdef` 56 : | `classdef` 57 : | `async_with_stmt` 58 : | `async_for_stmt` 59 : | `async_funcdef` 60 suite: `stmt_list` NEWLINE | NEWLINE INDENT `statement`+ DEDENT 61 statement: `stmt_list` NEWLINE | `compound_stmt` 62 stmt_list: `simple_stmt` (";" `simple_stmt`)* [";"] 63 64.. index:: 65 single: NEWLINE token 66 single: DEDENT token 67 pair: dangling; else 68 69Note that statements always end in a ``NEWLINE`` possibly followed by a 70``DEDENT``. Also note that optional continuation clauses always begin with a 71keyword that cannot start a statement, thus there are no ambiguities (the 72'dangling :keyword:`else`' problem is solved in Python by requiring nested 73:keyword:`if` statements to be indented). 74 75The formatting of the grammar rules in the following sections places each clause 76on a separate line for clarity. 77 78 79.. _if: 80.. _elif: 81.. _else: 82 83The :keyword:`!if` statement 84============================ 85 86.. index:: 87 ! statement: if 88 keyword: elif 89 keyword: else 90 single: : (colon); compound statement 91 92The :keyword:`if` statement is used for conditional execution: 93 94.. productionlist:: python-grammar 95 if_stmt: "if" `assignment_expression` ":" `suite` 96 : ("elif" `assignment_expression` ":" `suite`)* 97 : ["else" ":" `suite`] 98 99It selects exactly one of the suites by evaluating the expressions one by one 100until one is found to be true (see section :ref:`booleans` for the definition of 101true and false); then that suite is executed (and no other part of the 102:keyword:`if` statement is executed or evaluated). If all expressions are 103false, the suite of the :keyword:`else` clause, if present, is executed. 104 105 106.. _while: 107 108The :keyword:`!while` statement 109=============================== 110 111.. index:: 112 ! statement: while 113 keyword: else 114 pair: loop; statement 115 single: : (colon); compound statement 116 117The :keyword:`while` statement is used for repeated execution as long as an 118expression is true: 119 120.. productionlist:: python-grammar 121 while_stmt: "while" `assignment_expression` ":" `suite` 122 : ["else" ":" `suite`] 123 124This repeatedly tests the expression and, if it is true, executes the first 125suite; if the expression is false (which may be the first time it is tested) the 126suite of the :keyword:`!else` clause, if present, is executed and the loop 127terminates. 128 129.. index:: 130 statement: break 131 statement: continue 132 133A :keyword:`break` statement executed in the first suite terminates the loop 134without executing the :keyword:`!else` clause's suite. A :keyword:`continue` 135statement executed in the first suite skips the rest of the suite and goes back 136to testing the expression. 137 138 139.. _for: 140 141The :keyword:`!for` statement 142============================= 143 144.. index:: 145 ! statement: for 146 keyword: in 147 keyword: else 148 pair: target; list 149 pair: loop; statement 150 object: sequence 151 single: : (colon); compound statement 152 153The :keyword:`for` statement is used to iterate over the elements of a sequence 154(such as a string, tuple or list) or other iterable object: 155 156.. productionlist:: python-grammar 157 for_stmt: "for" `target_list` "in" `expression_list` ":" `suite` 158 : ["else" ":" `suite`] 159 160The expression list is evaluated once; it should yield an iterable object. An 161iterator is created for the result of the ``expression_list``. The suite is 162then executed once for each item provided by the iterator, in the order returned 163by the iterator. Each item in turn is assigned to the target list using the 164standard rules for assignments (see :ref:`assignment`), and then the suite is 165executed. When the items are exhausted (which is immediately when the sequence 166is empty or an iterator raises a :exc:`StopIteration` exception), the suite in 167the :keyword:`!else` clause, if present, is executed, and the loop terminates. 168 169.. index:: 170 statement: break 171 statement: continue 172 173A :keyword:`break` statement executed in the first suite terminates the loop 174without executing the :keyword:`!else` clause's suite. A :keyword:`continue` 175statement executed in the first suite skips the rest of the suite and continues 176with the next item, or with the :keyword:`!else` clause if there is no next 177item. 178 179The for-loop makes assignments to the variables in the target list. 180This overwrites all previous assignments to those variables including 181those made in the suite of the for-loop:: 182 183 for i in range(10): 184 print(i) 185 i = 5 # this will not affect the for-loop 186 # because i will be overwritten with the next 187 # index in the range 188 189 190.. index:: 191 builtin: range 192 193Names in the target list are not deleted when the loop is finished, but if the 194sequence is empty, they will not have been assigned to at all by the loop. Hint: 195the built-in function :func:`range` returns an iterator of integers suitable to 196emulate the effect of Pascal's ``for i := a to b do``; e.g., ``list(range(3))`` 197returns the list ``[0, 1, 2]``. 198 199 200.. _try: 201.. _except: 202.. _finally: 203 204The :keyword:`!try` statement 205============================= 206 207.. index:: 208 ! statement: try 209 keyword: except 210 keyword: finally 211 keyword: else 212 keyword: as 213 single: : (colon); compound statement 214 215The :keyword:`try` statement specifies exception handlers and/or cleanup code 216for a group of statements: 217 218.. productionlist:: python-grammar 219 try_stmt: `try1_stmt` | `try2_stmt` 220 try1_stmt: "try" ":" `suite` 221 : ("except" [`expression` ["as" `identifier`]] ":" `suite`)+ 222 : ["else" ":" `suite`] 223 : ["finally" ":" `suite`] 224 try2_stmt: "try" ":" `suite` 225 : "finally" ":" `suite` 226 227 228The :keyword:`except` clause(s) specify one or more exception handlers. When no 229exception occurs in the :keyword:`try` clause, no exception handler is executed. 230When an exception occurs in the :keyword:`!try` suite, a search for an exception 231handler is started. This search inspects the except clauses in turn until one 232is found that matches the exception. An expression-less except clause, if 233present, must be last; it matches any exception. For an except clause with an 234expression, that expression is evaluated, and the clause matches the exception 235if the resulting object is "compatible" with the exception. An object is 236compatible with an exception if it is the class or a base class of the exception 237object, or a tuple containing an item that is the class or a base class of 238the exception object. 239 240If no except clause matches the exception, the search for an exception handler 241continues in the surrounding code and on the invocation stack. [#]_ 242 243If the evaluation of an expression in the header of an except clause raises an 244exception, the original search for a handler is canceled and a search starts for 245the new exception in the surrounding code and on the call stack (it is treated 246as if the entire :keyword:`try` statement raised the exception). 247 248.. index:: single: as; except clause 249 250When a matching except clause is found, the exception is assigned to the target 251specified after the :keyword:`!as` keyword in that except clause, if present, and 252the except clause's suite is executed. All except clauses must have an 253executable block. When the end of this block is reached, execution continues 254normally after the entire try statement. (This means that if two nested 255handlers exist for the same exception, and the exception occurs in the try 256clause of the inner handler, the outer handler will not handle the exception.) 257 258When an exception has been assigned using ``as target``, it is cleared at the 259end of the except clause. This is as if :: 260 261 except E as N: 262 foo 263 264was translated to :: 265 266 except E as N: 267 try: 268 foo 269 finally: 270 del N 271 272This means the exception must be assigned to a different name to be able to 273refer to it after the except clause. Exceptions are cleared because with the 274traceback attached to them, they form a reference cycle with the stack frame, 275keeping all locals in that frame alive until the next garbage collection occurs. 276 277.. index:: 278 module: sys 279 object: traceback 280 281Before an except clause's suite is executed, details about the exception are 282stored in the :mod:`sys` module and can be accessed via :func:`sys.exc_info`. 283:func:`sys.exc_info` returns a 3-tuple consisting of the exception class, the 284exception instance and a traceback object (see section :ref:`types`) identifying 285the point in the program where the exception occurred. The details about the 286exception accessed via :func:`sys.exc_info` are restored to their previous values 287when leaving an exception handler:: 288 289 >>> print(sys.exc_info()) 290 (None, None, None) 291 >>> try: 292 ... raise TypeError 293 ... except: 294 ... print(sys.exc_info()) 295 ... try: 296 ... raise ValueError 297 ... except: 298 ... print(sys.exc_info()) 299 ... print(sys.exc_info()) 300 ... 301 (<class 'TypeError'>, TypeError(), <traceback object at 0x10efad080>) 302 (<class 'ValueError'>, ValueError(), <traceback object at 0x10efad040>) 303 (<class 'TypeError'>, TypeError(), <traceback object at 0x10efad080>) 304 >>> print(sys.exc_info()) 305 (None, None, None) 306 307.. index:: 308 keyword: else 309 statement: return 310 statement: break 311 statement: continue 312 313The optional :keyword:`!else` clause is executed if the control flow leaves the 314:keyword:`try` suite, no exception was raised, and no :keyword:`return`, 315:keyword:`continue`, or :keyword:`break` statement was executed. Exceptions in 316the :keyword:`!else` clause are not handled by the preceding :keyword:`except` 317clauses. 318 319.. index:: keyword: finally 320 321If :keyword:`finally` is present, it specifies a 'cleanup' handler. The 322:keyword:`try` clause is executed, including any :keyword:`except` and 323:keyword:`!else` clauses. If an exception occurs in any of the clauses and is 324not handled, the exception is temporarily saved. The :keyword:`!finally` clause 325is executed. If there is a saved exception it is re-raised at the end of the 326:keyword:`!finally` clause. If the :keyword:`!finally` clause raises another 327exception, the saved exception is set as the context of the new exception. 328If the :keyword:`!finally` clause executes a :keyword:`return`, :keyword:`break` 329or :keyword:`continue` statement, the saved exception is discarded:: 330 331 >>> def f(): 332 ... try: 333 ... 1/0 334 ... finally: 335 ... return 42 336 ... 337 >>> f() 338 42 339 340The exception information is not available to the program during execution of 341the :keyword:`finally` clause. 342 343.. index:: 344 statement: return 345 statement: break 346 statement: continue 347 348When a :keyword:`return`, :keyword:`break` or :keyword:`continue` statement is 349executed in the :keyword:`try` suite of a :keyword:`!try`...\ :keyword:`!finally` 350statement, the :keyword:`finally` clause is also executed 'on the way out.' 351 352The return value of a function is determined by the last :keyword:`return` 353statement executed. Since the :keyword:`finally` clause always executes, a 354:keyword:`!return` statement executed in the :keyword:`!finally` clause will 355always be the last one executed:: 356 357 >>> def foo(): 358 ... try: 359 ... return 'try' 360 ... finally: 361 ... return 'finally' 362 ... 363 >>> foo() 364 'finally' 365 366Additional information on exceptions can be found in section :ref:`exceptions`, 367and information on using the :keyword:`raise` statement to generate exceptions 368may be found in section :ref:`raise`. 369 370.. versionchanged:: 3.8 371 Prior to Python 3.8, a :keyword:`continue` statement was illegal in the 372 :keyword:`finally` clause due to a problem with the implementation. 373 374 375.. _with: 376.. _as: 377 378The :keyword:`!with` statement 379============================== 380 381.. index:: 382 ! statement: with 383 keyword: as 384 single: as; with statement 385 single: , (comma); with statement 386 single: : (colon); compound statement 387 388The :keyword:`with` statement is used to wrap the execution of a block with 389methods defined by a context manager (see section :ref:`context-managers`). 390This allows common :keyword:`try`...\ :keyword:`except`...\ :keyword:`finally` 391usage patterns to be encapsulated for convenient reuse. 392 393.. productionlist:: python-grammar 394 with_stmt: "with" ( "(" `with_stmt_contents` ","? ")" | `with_stmt_contents` ) ":" `suite` 395 with_stmt_contents: `with_item` ("," `with_item`)* 396 with_item: `expression` ["as" `target`] 397 398The execution of the :keyword:`with` statement with one "item" proceeds as follows: 399 400#. The context expression (the expression given in the 401 :token:`~python-grammar:with_item`) is evaluated to obtain a context manager. 402 403#. The context manager's :meth:`__enter__` is loaded for later use. 404 405#. The context manager's :meth:`__exit__` is loaded for later use. 406 407#. The context manager's :meth:`__enter__` method is invoked. 408 409#. If a target was included in the :keyword:`with` statement, the return value 410 from :meth:`__enter__` is assigned to it. 411 412 .. note:: 413 414 The :keyword:`with` statement guarantees that if the :meth:`__enter__` 415 method returns without an error, then :meth:`__exit__` will always be 416 called. Thus, if an error occurs during the assignment to the target list, 417 it will be treated the same as an error occurring within the suite would 418 be. See step 6 below. 419 420#. The suite is executed. 421 422#. The context manager's :meth:`__exit__` method is invoked. If an exception 423 caused the suite to be exited, its type, value, and traceback are passed as 424 arguments to :meth:`__exit__`. Otherwise, three :const:`None` arguments are 425 supplied. 426 427 If the suite was exited due to an exception, and the return value from the 428 :meth:`__exit__` method was false, the exception is reraised. If the return 429 value was true, the exception is suppressed, and execution continues with the 430 statement following the :keyword:`with` statement. 431 432 If the suite was exited for any reason other than an exception, the return 433 value from :meth:`__exit__` is ignored, and execution proceeds at the normal 434 location for the kind of exit that was taken. 435 436The following code:: 437 438 with EXPRESSION as TARGET: 439 SUITE 440 441is semantically equivalent to:: 442 443 manager = (EXPRESSION) 444 enter = type(manager).__enter__ 445 exit = type(manager).__exit__ 446 value = enter(manager) 447 hit_except = False 448 449 try: 450 TARGET = value 451 SUITE 452 except: 453 hit_except = True 454 if not exit(manager, *sys.exc_info()): 455 raise 456 finally: 457 if not hit_except: 458 exit(manager, None, None, None) 459 460With more than one item, the context managers are processed as if multiple 461:keyword:`with` statements were nested:: 462 463 with A() as a, B() as b: 464 SUITE 465 466is semantically equivalent to:: 467 468 with A() as a: 469 with B() as b: 470 SUITE 471 472You can also write multi-item context managers in multiple lines if 473the items are surrounded by parentheses. For example:: 474 475 with ( 476 A() as a, 477 B() as b, 478 ): 479 SUITE 480 481.. versionchanged:: 3.1 482 Support for multiple context expressions. 483 484.. versionchanged:: 3.10 485 Support for using grouping parentheses to break the statement in multiple lines. 486 487.. seealso:: 488 489 :pep:`343` - The "with" statement 490 The specification, background, and examples for the Python :keyword:`with` 491 statement. 492 493.. _match: 494 495The :keyword:`!match` statement 496=============================== 497 498.. index:: 499 ! statement: match 500 ! keyword: case 501 ! single: pattern matching 502 keyword: if 503 keyword: as 504 pair: match; case 505 single: : (colon); compound statement 506 507.. versionadded:: 3.10 508 509The match statement is used for pattern matching. Syntax: 510 511.. productionlist:: python-grammar 512 match_stmt: 'match' `subject_expr` ":" NEWLINE INDENT `case_block`+ DEDENT 513 subject_expr: `star_named_expression` "," `star_named_expressions`? 514 : | `named_expression` 515 case_block: 'case' `patterns` [`guard`] ":" `block` 516 517.. note:: 518 This section uses single quotes to denote 519 :ref:`soft keywords <soft-keywords>`. 520 521Pattern matching takes a pattern as input (following ``case``) and a subject 522value (following ``match``). The pattern (which may contain subpatterns) is 523matched against the subject value. The outcomes are: 524 525* A match success or failure (also termed a pattern success or failure). 526 527* Possible binding of matched values to a name. The prerequisites for this are 528 further discussed below. 529 530The ``match`` and ``case`` keywords are :ref:`soft keywords <soft-keywords>`. 531 532.. seealso:: 533 534 * :pep:`634` -- Structural Pattern Matching: Specification 535 * :pep:`636` -- Structural Pattern Matching: Tutorial 536 537 538Overview 539-------- 540 541Here's an overview of the logical flow of a match statement: 542 543 544#. The subject expression ``subject_expr`` is evaluated and a resulting subject 545 value obtained. If the subject expression contains a comma, a tuple is 546 constructed using :ref:`the standard rules <typesseq-tuple>`. 547 548#. Each pattern in a ``case_block`` is attempted to match with the subject value. The 549 specific rules for success or failure are described below. The match attempt can also 550 bind some or all of the standalone names within the pattern. The precise 551 pattern binding rules vary per pattern type and are 552 specified below. **Name bindings made during a successful pattern match 553 outlive the executed block and can be used after the match statement**. 554 555 .. note:: 556 557 During failed pattern matches, some subpatterns may succeed. Do not 558 rely on bindings being made for a failed match. Conversely, do not 559 rely on variables remaining unchanged after a failed match. The exact 560 behavior is dependent on implementation and may vary. This is an 561 intentional decision made to allow different implementations to add 562 optimizations. 563 564#. If the pattern succeeds, the corresponding guard (if present) is evaluated. In 565 this case all name bindings are guaranteed to have happened. 566 567 * If the guard evaluates as true or is missing, the ``block`` inside 568 ``case_block`` is executed. 569 570 * Otherwise, the next ``case_block`` is attempted as described above. 571 572 * If there are no further case blocks, the match statement is completed. 573 574.. note:: 575 576 Users should generally never rely on a pattern being evaluated. Depending on 577 implementation, the interpreter may cache values or use other optimizations 578 which skip repeated evaluations. 579 580A sample match statement:: 581 582 >>> flag = False 583 >>> match (100, 200): 584 ... case (100, 300): # Mismatch: 200 != 300 585 ... print('Case 1') 586 ... case (100, 200) if flag: # Successful match, but guard fails 587 ... print('Case 2') 588 ... case (100, y): # Matches and binds y to 200 589 ... print(f'Case 3, y: {y}') 590 ... case _: # Pattern not attempted 591 ... print('Case 4, I match anything!') 592 ... 593 Case 3, y: 200 594 595 596In this case, ``if flag`` is a guard. Read more about that in the next section. 597 598Guards 599------ 600 601.. index:: ! guard 602 603.. productionlist:: python-grammar 604 guard: "if" `named_expression` 605 606A ``guard`` (which is part of the ``case``) must succeed for code inside 607the ``case`` block to execute. It takes the form: :keyword:`if` followed by an 608expression. 609 610 611The logical flow of a ``case`` block with a ``guard`` follows: 612 613#. Check that the pattern in the ``case`` block succeeded. If the pattern 614 failed, the ``guard`` is not evaluated and the next ``case`` block is 615 checked. 616 617#. If the pattern succeeded, evaluate the ``guard``. 618 619 * If the ``guard`` condition evaluates as true, the case block is 620 selected. 621 622 * If the ``guard`` condition evaluates as false, the case block is not 623 selected. 624 625 * If the ``guard`` raises an exception during evaluation, the exception 626 bubbles up. 627 628Guards are allowed to have side effects as they are expressions. Guard 629evaluation must proceed from the first to the last case block, one at a time, 630skipping case blocks whose pattern(s) don't all succeed. (I.e., 631guard evaluation must happen in order.) Guard evaluation must stop once a case 632block is selected. 633 634 635.. _irrefutable_case: 636 637Irrefutable Case Blocks 638----------------------- 639 640.. index:: irrefutable case block, case block 641 642An irrefutable case block is a match-all case block. A match statement may have 643at most one irrefutable case block, and it must be last. 644 645A case block is considered irrefutable if it has no guard and its pattern is 646irrefutable. A pattern is considered irrefutable if we can prove from its 647syntax alone that it will always succeed. Only the following patterns are 648irrefutable: 649 650* :ref:`as-patterns` whose left-hand side is irrefutable 651 652* :ref:`or-patterns` containing at least one irrefutable pattern 653 654* :ref:`capture-patterns` 655 656* :ref:`wildcard-patterns` 657 658* parenthesized irrefutable patterns 659 660 661Patterns 662-------- 663 664.. index:: 665 single: ! patterns 666 single: AS pattern, OR pattern, capture pattern, wildcard pattern 667 668.. note:: 669 This section uses grammar notations beyond standard EBNF: 670 671 * the notation ``SEP.RULE+`` is shorthand for ``RULE (SEP RULE)*`` 672 673 * the notation ``!RULE`` is shorthand for a negative lookahead assertion 674 675 676The top-level syntax for ``patterns`` is: 677 678.. productionlist:: python-grammar 679 patterns: `open_sequence_pattern` | `pattern` 680 pattern: `as_pattern` | `or_pattern` 681 closed_pattern: | `literal_pattern` 682 : | `capture_pattern` 683 : | `wildcard_pattern` 684 : | `value_pattern` 685 : | `group_pattern` 686 : | `sequence_pattern` 687 : | `mapping_pattern` 688 : | `class_pattern` 689 690The descriptions below will include a description "in simple terms" of what a pattern 691does for illustration purposes (credits to Raymond Hettinger for a document that 692inspired most of the descriptions). Note that these descriptions are purely for 693illustration purposes and **may not** reflect 694the underlying implementation. Furthermore, they do not cover all valid forms. 695 696 697.. _or-patterns: 698 699OR Patterns 700^^^^^^^^^^^ 701 702An OR pattern is two or more patterns separated by vertical 703bars ``|``. Syntax: 704 705.. productionlist:: python-grammar 706 or_pattern: "|".`closed_pattern`+ 707 708Only the final subpattern may be :ref:`irrefutable <irrefutable_case>`, and each 709subpattern must bind the same set of names to avoid ambiguity. 710 711An OR pattern matches each of its subpatterns in turn to the subject value, 712until one succeeds. The OR pattern is then considered successful. Otherwise, 713if none of the subpatterns succeed, the OR pattern fails. 714 715In simple terms, ``P1 | P2 | ...`` will try to match ``P1``, if it fails it will try to 716match ``P2``, succeeding immediately if any succeeds, failing otherwise. 717 718.. _as-patterns: 719 720AS Patterns 721^^^^^^^^^^^ 722 723An AS pattern matches an OR pattern on the left of the :keyword:`as` 724keyword against a subject. Syntax: 725 726.. productionlist:: python-grammar 727 as_pattern: `or_pattern` "as" `capture_pattern` 728 729If the OR pattern fails, the AS pattern fails. Otherwise, the AS pattern binds 730the subject to the name on the right of the as keyword and succeeds. 731``capture_pattern`` cannot be a a ``_``. 732 733In simple terms ``P as NAME`` will match with ``P``, and on success it will 734set ``NAME = <subject>``. 735 736 737.. _literal-patterns: 738 739Literal Patterns 740^^^^^^^^^^^^^^^^ 741 742A literal pattern corresponds to most 743:ref:`literals <literals>` in Python. Syntax: 744 745.. productionlist:: python-grammar 746 literal_pattern: `signed_number` 747 : | `signed_number` "+" NUMBER 748 : | `signed_number` "-" NUMBER 749 : | `strings` 750 : | "None" 751 : | "True" 752 : | "False" 753 : | `signed_number`: NUMBER | "-" NUMBER 754 755The rule ``strings`` and the token ``NUMBER`` are defined in the 756:doc:`standard Python grammar <./grammar>`. Triple-quoted strings are 757supported. Raw strings and byte strings are supported. :ref:`f-strings` are 758not supported. 759 760The forms ``signed_number '+' NUMBER`` and ``signed_number '-' NUMBER`` are 761for expressing :ref:`complex numbers <imaginary>`; they require a real number 762on the left and an imaginary number on the right. E.g. ``3 + 4j``. 763 764In simple terms, ``LITERAL`` will succeed only if ``<subject> == LITERAL``. For 765the singletons ``None``, ``True`` and ``False``, the :keyword:`is` operator is used. 766 767.. _capture-patterns: 768 769Capture Patterns 770^^^^^^^^^^^^^^^^ 771 772A capture pattern binds the subject value to a name. 773Syntax: 774 775.. productionlist:: python-grammar 776 capture_pattern: !'_' NAME 777 778A single underscore ``_`` is not a capture pattern (this is what ``!'_'`` 779expresses). It is instead treated as a 780:token:`~python-grammar:wildcard_pattern`. 781 782In a given pattern, a given name can only be bound once. E.g. 783``case x, x: ...`` is invalid while ``case [x] | x: ...`` is allowed. 784 785Capture patterns always succeed. The binding follows scoping rules 786established by the assignment expression operator in :pep:`572`; the 787name becomes a local variable in the closest containing function scope unless 788there's an applicable :keyword:`global` or :keyword:`nonlocal` statement. 789 790In simple terms ``NAME`` will always succeed and it will set ``NAME = <subject>``. 791 792.. _wildcard-patterns: 793 794Wildcard Patterns 795^^^^^^^^^^^^^^^^^ 796 797A wildcard pattern always succeeds (matches anything) 798and binds no name. Syntax: 799 800.. productionlist:: python-grammar 801 wildcard_pattern: '_' 802 803``_`` is a :ref:`soft keyword <soft-keywords>` within any pattern, 804but only within patterns. It is an identifier, as usual, even within 805``match`` subject expressions, ``guard``\ s, and ``case`` blocks. 806 807In simple terms, ``_`` will always succeed. 808 809.. _value-patterns: 810 811Value Patterns 812^^^^^^^^^^^^^^ 813 814A value pattern represents a named value in Python. 815Syntax: 816 817.. productionlist:: python-grammar 818 value_pattern: `attr` 819 attr: `name_or_attr` "." NAME 820 name_or_attr: `attr` | NAME 821 822The dotted name in the pattern is looked up using standard Python 823:ref:`name resolution rules <resolve_names>`. The pattern succeeds if the 824value found compares equal to the subject value (using the ``==`` equality 825operator). 826 827In simple terms ``NAME1.NAME2`` will succeed only if ``<subject> == NAME1.NAME2`` 828 829.. note:: 830 831 If the same value occurs multiple times in the same match statement, the 832 interpreter may cache the first value found and reuse it rather than repeat 833 the same lookup. This cache is strictly tied to a given execution of a 834 given match statement. 835 836.. _group-patterns: 837 838Group Patterns 839^^^^^^^^^^^^^^ 840 841A group pattern allows users to add parentheses around patterns to 842emphasize the intended grouping. Otherwise, it has no additional syntax. 843Syntax: 844 845.. productionlist:: python-grammar 846 group_pattern: "(" `pattern` ")" 847 848In simple terms ``(P)`` has the same effect as ``P``. 849 850.. _sequence-patterns: 851 852Sequence Patterns 853^^^^^^^^^^^^^^^^^ 854 855A sequence pattern contains several subpatterns to be matched against sequence elements. 856The syntax is similar to the unpacking of a list or tuple. 857 858.. productionlist:: python-grammar 859 sequence_pattern: "[" [`maybe_sequence_pattern`] "]" 860 : | "(" [`open_sequence_pattern`] ")" 861 open_sequence_pattern: `maybe_star_pattern` "," [`maybe_sequence_pattern`] 862 maybe_sequence_pattern: ",".`maybe_star_pattern`+ ","? 863 maybe_star_pattern: `star_pattern` | `pattern` 864 star_pattern: "*" (`capture_pattern` | `wildcard_pattern`) 865 866There is no difference if parentheses or square brackets 867are used for sequence patterns (i.e. ``(...)`` vs ``[...]`` ). 868 869.. note:: 870 A single pattern enclosed in parentheses without a trailing comma 871 (e.g. ``(3 | 4)``) is a :ref:`group pattern <group-patterns>`. 872 While a single pattern enclosed in square brackets (e.g. ``[3 | 4]``) is 873 still a sequence pattern. 874 875At most one star subpattern may be in a sequence pattern. The star subpattern 876may occur in any position. If no star subpattern is present, the sequence 877pattern is a fixed-length sequence pattern; otherwise it is a variable-length 878sequence pattern. 879 880The following is the logical flow for matching a sequence pattern against a 881subject value: 882 883#. If the subject value is not a sequence [#]_, the sequence pattern 884 fails. 885 886#. If the subject value is an instance of ``str``, ``bytes`` or ``bytearray`` 887 the sequence pattern fails. 888 889#. The subsequent steps depend on whether the sequence pattern is fixed or 890 variable-length. 891 892 If the sequence pattern is fixed-length: 893 894 #. If the length of the subject sequence is not equal to the number of 895 subpatterns, the sequence pattern fails 896 897 #. Subpatterns in the sequence pattern are matched to their corresponding 898 items in the subject sequence from left to right. Matching stops as soon 899 as a subpattern fails. If all subpatterns succeed in matching their 900 corresponding item, the sequence pattern succeeds. 901 902 Otherwise, if the sequence pattern is variable-length: 903 904 #. If the length of the subject sequence is less than the number of non-star 905 subpatterns, the sequence pattern fails. 906 907 #. The leading non-star subpatterns are matched to their corresponding items 908 as for fixed-length sequences. 909 910 #. If the previous step succeeds, the star subpattern matches a list formed 911 of the remaining subject items, excluding the remaining items 912 corresponding to non-star subpatterns following the star subpattern. 913 914 #. Remaining non-star subpatterns are matched to their corresponding subject 915 items, as for a fixed-length sequence. 916 917 .. note:: The length of the subject sequence is obtained via 918 :func:`len` (i.e. via the :meth:`__len__` protocol). This length may be 919 cached by the interpreter in a similar manner as 920 :ref:`value patterns <value-patterns>`. 921 922 923In simple terms ``[P1, P2, P3,`` ... ``, P<N>]`` matches only if all the following 924happens: 925 926* check ``<subject>`` is a sequence 927* ``len(subject) == <N>`` 928* ``P1`` matches ``<subject>[0]`` (note that this match can also bind names) 929* ``P2`` matches ``<subject>[1]`` (note that this match can also bind names) 930* ... and so on for the corresponding pattern/element. 931 932.. _mapping-patterns: 933 934Mapping Patterns 935^^^^^^^^^^^^^^^^ 936 937A mapping pattern contains one or more key-value patterns. The syntax is 938similar to the construction of a dictionary. 939Syntax: 940 941.. productionlist:: python-grammar 942 mapping_pattern: "{" [`items_pattern`] "}" 943 items_pattern: ",".`key_value_pattern`+ ","? 944 key_value_pattern: (`literal_pattern` | `value_pattern`) ":" `pattern` 945 : | `double_star_pattern` 946 double_star_pattern: "**" `capture_pattern` 947 948At most one double star pattern may be in a mapping pattern. The double star 949pattern must be the last subpattern in the mapping pattern. 950 951Duplicate keys in mapping patterns are disallowed. Duplicate literal keys will 952raise a :exc:`SyntaxError`. Two keys that otherwise have the same value will 953raise a :exc:`ValueError` at runtime. 954 955The following is the logical flow for matching a mapping pattern against a 956subject value: 957 958#. If the subject value is not a mapping [#]_,the mapping pattern fails. 959 960#. If every key given in the mapping pattern is present in the subject mapping, 961 and the pattern for each key matches the corresponding item of the subject 962 mapping, the mapping pattern succeeds. 963 964#. If duplicate keys are detected in the mapping pattern, the pattern is 965 considered invalid. A :exc:`SyntaxError` is raised for duplicate literal 966 values; or a :exc:`ValueError` for named keys of the same value. 967 968.. note:: Key-value pairs are matched using the two-argument form of the mapping 969 subject's ``get()`` method. Matched key-value pairs must already be present 970 in the mapping, and not created on-the-fly via :meth:`__missing__` or 971 :meth:`__getitem__`. 972 973In simple terms ``{KEY1: P1, KEY2: P2, ... }`` matches only if all the following 974happens: 975 976* check ``<subject>`` is a mapping 977* ``KEY1 in <subject>`` 978* ``P1`` matches ``<subject>[KEY1]`` 979* ... and so on for the corresponding KEY/pattern pair. 980 981 982.. _class-patterns: 983 984Class Patterns 985^^^^^^^^^^^^^^ 986 987A class pattern represents a class and its positional and keyword arguments 988(if any). Syntax: 989 990.. productionlist:: python-grammar 991 class_pattern: `name_or_attr` "(" [`pattern_arguments` ","?] ")" 992 pattern_arguments: `positional_patterns` ["," `keyword_patterns`] 993 : | `keyword_patterns` 994 positional_patterns: ",".`pattern`+ 995 keyword_patterns: ",".`keyword_pattern`+ 996 keyword_pattern: NAME "=" `pattern` 997 998The same keyword should not be repeated in class patterns. 999 1000The following is the logical flow for matching a class pattern against a 1001subject value: 1002 1003#. If ``name_or_attr`` is not an instance of the builtin :class:`type` , raise 1004 :exc:`TypeError`. 1005 1006#. If the subject value is not an instance of ``name_or_attr`` (tested via 1007 :func:`isinstance`), the class pattern fails. 1008 1009#. If no pattern arguments are present, the pattern succeeds. Otherwise, 1010 the subsequent steps depend on whether keyword or positional argument patterns 1011 are present. 1012 1013 For a number of built-in types (specified below), a single positional 1014 subpattern is accepted which will match the entire subject; for these types 1015 keyword patterns also work as for other types. 1016 1017 If only keyword patterns are present, they are processed as follows, 1018 one by one: 1019 1020 I. The keyword is looked up as an attribute on the subject. 1021 1022 * If this raises an exception other than :exc:`AttributeError`, the 1023 exception bubbles up. 1024 1025 * If this raises :exc:`AttributeError`, the class pattern has failed. 1026 1027 * Else, the subpattern associated with the keyword pattern is matched 1028 against the subject's attribute value. If this fails, the class 1029 pattern fails; if this succeeds, the match proceeds to the next keyword. 1030 1031 1032 II. If all keyword patterns succeed, the class pattern succeeds. 1033 1034 If any positional patterns are present, they are converted to keyword 1035 patterns using the :data:`~object.__match_args__` attribute on the class 1036 ``name_or_attr`` before matching: 1037 1038 I. The equivalent of ``getattr(cls, "__match_args__", ())`` is called. 1039 1040 * If this raises an exception, the exception bubbles up. 1041 1042 * If the returned value is not a tuple, the conversion fails and 1043 :exc:`TypeError` is raised. 1044 1045 * If there are more positional patterns than ``len(cls.__match_args__)``, 1046 :exc:`TypeError` is raised. 1047 1048 * Otherwise, positional pattern ``i`` is converted to a keyword pattern 1049 using ``__match_args__[i]`` as the keyword. ``__match_args__[i]`` must 1050 be a string; if not :exc:`TypeError` is raised. 1051 1052 * If there are duplicate keywords, :exc:`TypeError` is raised. 1053 1054 .. seealso:: :ref:`class-pattern-matching` 1055 1056 II. Once all positional patterns have been converted to keyword patterns, 1057 the match proceeds as if there were only keyword patterns. 1058 1059 For the following built-in types the handling of positional subpatterns is 1060 different: 1061 1062 * :class:`bool` 1063 * :class:`bytearray` 1064 * :class:`bytes` 1065 * :class:`dict` 1066 * :class:`float` 1067 * :class:`frozenset` 1068 * :class:`int` 1069 * :class:`list` 1070 * :class:`set` 1071 * :class:`str` 1072 * :class:`tuple` 1073 1074 These classes accept a single positional argument, and the pattern there is matched 1075 against the whole object rather than an attribute. For example ``int(0|1)`` matches 1076 the value ``0``, but not the values ``0.0`` or ``False``. 1077 1078In simple terms ``CLS(P1, attr=P2)`` matches only if the following happens: 1079 1080* ``isinstance(<subject>, CLS)`` 1081* convert ``P1`` to a keyword pattern using ``CLS.__match_args__`` 1082* For each keyword argument ``attr=P2``: 1083 * ``hasattr(<subject>, "attr")`` 1084 * ``P2`` matches ``<subject>.attr`` 1085* ... and so on for the corresponding keyword argument/pattern pair. 1086 1087.. seealso:: 1088 1089 * :pep:`634` -- Structural Pattern Matching: Specification 1090 * :pep:`636` -- Structural Pattern Matching: Tutorial 1091 1092 1093.. index:: 1094 single: parameter; function definition 1095 1096.. _function: 1097.. _def: 1098 1099Function definitions 1100==================== 1101 1102.. index:: 1103 statement: def 1104 pair: function; definition 1105 pair: function; name 1106 pair: name; binding 1107 object: user-defined function 1108 object: function 1109 pair: function; name 1110 pair: name; binding 1111 single: () (parentheses); function definition 1112 single: , (comma); parameter list 1113 single: : (colon); compound statement 1114 1115A function definition defines a user-defined function object (see section 1116:ref:`types`): 1117 1118.. productionlist:: python-grammar 1119 funcdef: [`decorators`] "def" `funcname` "(" [`parameter_list`] ")" 1120 : ["->" `expression`] ":" `suite` 1121 decorators: `decorator`+ 1122 decorator: "@" `assignment_expression` NEWLINE 1123 parameter_list: `defparameter` ("," `defparameter`)* "," "/" ["," [`parameter_list_no_posonly`]] 1124 : | `parameter_list_no_posonly` 1125 parameter_list_no_posonly: `defparameter` ("," `defparameter`)* ["," [`parameter_list_starargs`]] 1126 : | `parameter_list_starargs` 1127 parameter_list_starargs: "*" [`parameter`] ("," `defparameter`)* ["," ["**" `parameter` [","]]] 1128 : | "**" `parameter` [","] 1129 parameter: `identifier` [":" `expression`] 1130 defparameter: `parameter` ["=" `expression`] 1131 funcname: `identifier` 1132 1133 1134A function definition is an executable statement. Its execution binds the 1135function name in the current local namespace to a function object (a wrapper 1136around the executable code for the function). This function object contains a 1137reference to the current global namespace as the global namespace to be used 1138when the function is called. 1139 1140The function definition does not execute the function body; this gets executed 1141only when the function is called. [#]_ 1142 1143.. index:: 1144 single: @ (at); function definition 1145 1146A function definition may be wrapped by one or more :term:`decorator` expressions. 1147Decorator expressions are evaluated when the function is defined, in the scope 1148that contains the function definition. The result must be a callable, which is 1149invoked with the function object as the only argument. The returned value is 1150bound to the function name instead of the function object. Multiple decorators 1151are applied in nested fashion. For example, the following code :: 1152 1153 @f1(arg) 1154 @f2 1155 def func(): pass 1156 1157is roughly equivalent to :: 1158 1159 def func(): pass 1160 func = f1(arg)(f2(func)) 1161 1162except that the original function is not temporarily bound to the name ``func``. 1163 1164.. versionchanged:: 3.9 1165 Functions may be decorated with any valid 1166 :token:`~python-grammar:assignment_expression`. Previously, the grammar was 1167 much more restrictive; see :pep:`614` for details. 1168 1169.. index:: 1170 triple: default; parameter; value 1171 single: argument; function definition 1172 single: = (equals); function definition 1173 1174When one or more :term:`parameters <parameter>` have the form *parameter* ``=`` 1175*expression*, the function is said to have "default parameter values." For a 1176parameter with a default value, the corresponding :term:`argument` may be 1177omitted from a call, in which 1178case the parameter's default value is substituted. If a parameter has a default 1179value, all following parameters up until the "``*``" must also have a default 1180value --- this is a syntactic restriction that is not expressed by the grammar. 1181 1182**Default parameter values are evaluated from left to right when the function 1183definition is executed.** This means that the expression is evaluated once, when 1184the function is defined, and that the same "pre-computed" value is used for each 1185call. This is especially important to understand when a default parameter value is a 1186mutable object, such as a list or a dictionary: if the function modifies the 1187object (e.g. by appending an item to a list), the default parameter value is in effect 1188modified. This is generally not what was intended. A way around this is to use 1189``None`` as the default, and explicitly test for it in the body of the function, 1190e.g.:: 1191 1192 def whats_on_the_telly(penguin=None): 1193 if penguin is None: 1194 penguin = [] 1195 penguin.append("property of the zoo") 1196 return penguin 1197 1198.. index:: 1199 single: / (slash); function definition 1200 single: * (asterisk); function definition 1201 single: **; function definition 1202 1203Function call semantics are described in more detail in section :ref:`calls`. A 1204function call always assigns values to all parameters mentioned in the parameter 1205list, either from positional arguments, from keyword arguments, or from default 1206values. If the form "``*identifier``" is present, it is initialized to a tuple 1207receiving any excess positional parameters, defaulting to the empty tuple. 1208If the form "``**identifier``" is present, it is initialized to a new 1209ordered mapping receiving any excess keyword arguments, defaulting to a 1210new empty mapping of the same type. Parameters after "``*``" or 1211"``*identifier``" are keyword-only parameters and may only be passed 1212by keyword arguments. Parameters before "``/``" are positional-only parameters 1213and may only be passed by positional arguments. 1214 1215.. versionchanged:: 3.8 1216 The ``/`` function parameter syntax may be used to indicate positional-only 1217 parameters. See :pep:`570` for details. 1218 1219.. index:: 1220 pair: function; annotations 1221 single: ->; function annotations 1222 single: : (colon); function annotations 1223 1224Parameters may have an :term:`annotation <function annotation>` of the form "``: expression``" 1225following the parameter name. Any parameter may have an annotation, even those of the form 1226``*identifier`` or ``**identifier``. Functions may have "return" annotation of 1227the form "``-> expression``" after the parameter list. These annotations can be 1228any valid Python expression. The presence of annotations does not change the 1229semantics of a function. The annotation values are available as values of 1230a dictionary keyed by the parameters' names in the :attr:`__annotations__` 1231attribute of the function object. If the ``annotations`` import from 1232:mod:`__future__` is used, annotations are preserved as strings at runtime which 1233enables postponed evaluation. Otherwise, they are evaluated when the function 1234definition is executed. In this case annotations may be evaluated in 1235a different order than they appear in the source code. 1236 1237.. index:: pair: lambda; expression 1238 1239It is also possible to create anonymous functions (functions not bound to a 1240name), for immediate use in expressions. This uses lambda expressions, described in 1241section :ref:`lambda`. Note that the lambda expression is merely a shorthand for a 1242simplified function definition; a function defined in a ":keyword:`def`" 1243statement can be passed around or assigned to another name just like a function 1244defined by a lambda expression. The ":keyword:`!def`" form is actually more powerful 1245since it allows the execution of multiple statements and annotations. 1246 1247**Programmer's note:** Functions are first-class objects. A "``def``" statement 1248executed inside a function definition defines a local function that can be 1249returned or passed around. Free variables used in the nested function can 1250access the local variables of the function containing the def. See section 1251:ref:`naming` for details. 1252 1253.. seealso:: 1254 1255 :pep:`3107` - Function Annotations 1256 The original specification for function annotations. 1257 1258 :pep:`484` - Type Hints 1259 Definition of a standard meaning for annotations: type hints. 1260 1261 :pep:`526` - Syntax for Variable Annotations 1262 Ability to type hint variable declarations, including class 1263 variables and instance variables 1264 1265 :pep:`563` - Postponed Evaluation of Annotations 1266 Support for forward references within annotations by preserving 1267 annotations in a string form at runtime instead of eager evaluation. 1268 1269 1270.. _class: 1271 1272Class definitions 1273================= 1274 1275.. index:: 1276 object: class 1277 statement: class 1278 pair: class; definition 1279 pair: class; name 1280 pair: name; binding 1281 pair: execution; frame 1282 single: inheritance 1283 single: docstring 1284 single: () (parentheses); class definition 1285 single: , (comma); expression list 1286 single: : (colon); compound statement 1287 1288A class definition defines a class object (see section :ref:`types`): 1289 1290.. productionlist:: python-grammar 1291 classdef: [`decorators`] "class" `classname` [`inheritance`] ":" `suite` 1292 inheritance: "(" [`argument_list`] ")" 1293 classname: `identifier` 1294 1295A class definition is an executable statement. The inheritance list usually 1296gives a list of base classes (see :ref:`metaclasses` for more advanced uses), so 1297each item in the list should evaluate to a class object which allows 1298subclassing. Classes without an inheritance list inherit, by default, from the 1299base class :class:`object`; hence, :: 1300 1301 class Foo: 1302 pass 1303 1304is equivalent to :: 1305 1306 class Foo(object): 1307 pass 1308 1309The class's suite is then executed in a new execution frame (see :ref:`naming`), 1310using a newly created local namespace and the original global namespace. 1311(Usually, the suite contains mostly function definitions.) When the class's 1312suite finishes execution, its execution frame is discarded but its local 1313namespace is saved. [#]_ A class object is then created using the inheritance 1314list for the base classes and the saved local namespace for the attribute 1315dictionary. The class name is bound to this class object in the original local 1316namespace. 1317 1318The order in which attributes are defined in the class body is preserved 1319in the new class's ``__dict__``. Note that this is reliable only right 1320after the class is created and only for classes that were defined using 1321the definition syntax. 1322 1323Class creation can be customized heavily using :ref:`metaclasses <metaclasses>`. 1324 1325.. index:: 1326 single: @ (at); class definition 1327 1328Classes can also be decorated: just like when decorating functions, :: 1329 1330 @f1(arg) 1331 @f2 1332 class Foo: pass 1333 1334is roughly equivalent to :: 1335 1336 class Foo: pass 1337 Foo = f1(arg)(f2(Foo)) 1338 1339The evaluation rules for the decorator expressions are the same as for function 1340decorators. The result is then bound to the class name. 1341 1342.. versionchanged:: 3.9 1343 Classes may be decorated with any valid 1344 :token:`~python-grammar:assignment_expression`. Previously, the grammar was 1345 much more restrictive; see :pep:`614` for details. 1346 1347**Programmer's note:** Variables defined in the class definition are class 1348attributes; they are shared by instances. Instance attributes can be set in a 1349method with ``self.name = value``. Both class and instance attributes are 1350accessible through the notation "``self.name``", and an instance attribute hides 1351a class attribute with the same name when accessed in this way. Class 1352attributes can be used as defaults for instance attributes, but using mutable 1353values there can lead to unexpected results. :ref:`Descriptors <descriptors>` 1354can be used to create instance variables with different implementation details. 1355 1356 1357.. seealso:: 1358 1359 :pep:`3115` - Metaclasses in Python 3000 1360 The proposal that changed the declaration of metaclasses to the current 1361 syntax, and the semantics for how classes with metaclasses are 1362 constructed. 1363 1364 :pep:`3129` - Class Decorators 1365 The proposal that added class decorators. Function and method decorators 1366 were introduced in :pep:`318`. 1367 1368 1369.. _async: 1370 1371Coroutines 1372========== 1373 1374.. versionadded:: 3.5 1375 1376.. index:: statement: async def 1377.. _`async def`: 1378 1379Coroutine function definition 1380----------------------------- 1381 1382.. productionlist:: python-grammar 1383 async_funcdef: [`decorators`] "async" "def" `funcname` "(" [`parameter_list`] ")" 1384 : ["->" `expression`] ":" `suite` 1385 1386.. index:: 1387 keyword: async 1388 keyword: await 1389 1390Execution of Python coroutines can be suspended and resumed at many points 1391(see :term:`coroutine`). :keyword:`await` expressions, :keyword:`async for` and 1392:keyword:`async with` can only be used in the body of a coroutine function. 1393 1394Functions defined with ``async def`` syntax are always coroutine functions, 1395even if they do not contain ``await`` or ``async`` keywords. 1396 1397It is a :exc:`SyntaxError` to use a ``yield from`` expression inside the body 1398of a coroutine function. 1399 1400An example of a coroutine function:: 1401 1402 async def func(param1, param2): 1403 do_stuff() 1404 await some_coroutine() 1405 1406.. versionchanged:: 3.7 1407 ``await`` and ``async`` are now keywords; previously they were only 1408 treated as such inside the body of a coroutine function. 1409 1410.. index:: statement: async for 1411.. _`async for`: 1412 1413The :keyword:`!async for` statement 1414----------------------------------- 1415 1416.. productionlist:: python-grammar 1417 async_for_stmt: "async" `for_stmt` 1418 1419An :term:`asynchronous iterable` provides an ``__aiter__`` method that directly 1420returns an :term:`asynchronous iterator`, which can call asynchronous code in 1421its ``__anext__`` method. 1422 1423The ``async for`` statement allows convenient iteration over asynchronous 1424iterables. 1425 1426The following code:: 1427 1428 async for TARGET in ITER: 1429 SUITE 1430 else: 1431 SUITE2 1432 1433Is semantically equivalent to:: 1434 1435 iter = (ITER) 1436 iter = type(iter).__aiter__(iter) 1437 running = True 1438 1439 while running: 1440 try: 1441 TARGET = await type(iter).__anext__(iter) 1442 except StopAsyncIteration: 1443 running = False 1444 else: 1445 SUITE 1446 else: 1447 SUITE2 1448 1449See also :meth:`__aiter__` and :meth:`__anext__` for details. 1450 1451It is a :exc:`SyntaxError` to use an ``async for`` statement outside the 1452body of a coroutine function. 1453 1454 1455.. index:: statement: async with 1456.. _`async with`: 1457 1458The :keyword:`!async with` statement 1459------------------------------------ 1460 1461.. productionlist:: python-grammar 1462 async_with_stmt: "async" `with_stmt` 1463 1464An :term:`asynchronous context manager` is a :term:`context manager` that is 1465able to suspend execution in its *enter* and *exit* methods. 1466 1467The following code:: 1468 1469 async with EXPRESSION as TARGET: 1470 SUITE 1471 1472is semantically equivalent to:: 1473 1474 manager = (EXPRESSION) 1475 aenter = type(manager).__aenter__ 1476 aexit = type(manager).__aexit__ 1477 value = await aenter(manager) 1478 hit_except = False 1479 1480 try: 1481 TARGET = value 1482 SUITE 1483 except: 1484 hit_except = True 1485 if not await aexit(manager, *sys.exc_info()): 1486 raise 1487 finally: 1488 if not hit_except: 1489 await aexit(manager, None, None, None) 1490 1491See also :meth:`__aenter__` and :meth:`__aexit__` for details. 1492 1493It is a :exc:`SyntaxError` to use an ``async with`` statement outside the 1494body of a coroutine function. 1495 1496.. seealso:: 1497 1498 :pep:`492` - Coroutines with async and await syntax 1499 The proposal that made coroutines a proper standalone concept in Python, 1500 and added supporting syntax. 1501 1502 1503.. rubric:: Footnotes 1504 1505.. [#] The exception is propagated to the invocation stack unless 1506 there is a :keyword:`finally` clause which happens to raise another 1507 exception. That new exception causes the old one to be lost. 1508 1509.. [#] In pattern matching, a sequence is defined as one of the following: 1510 1511 * a class that inherits from :class:`collections.abc.Sequence` 1512 * a Python class that has been registered as :class:`collections.abc.Sequence` 1513 * a builtin class that has its (CPython) :data:`Py_TPFLAGS_SEQUENCE` bit set 1514 * a class that inherits from any of the above 1515 1516 The following standard library classes are sequences: 1517 1518 * :class:`array.array` 1519 * :class:`collections.deque` 1520 * :class:`list` 1521 * :class:`memoryview` 1522 * :class:`range` 1523 * :class:`tuple` 1524 1525 .. note:: Subject values of type ``str``, ``bytes``, and ``bytearray`` 1526 do not match sequence patterns. 1527 1528.. [#] In pattern matching, a mapping is defined as one of the following: 1529 1530 * a class that inherits from :class:`collections.abc.Mapping` 1531 * a Python class that has been registered as :class:`collections.abc.Mapping` 1532 * a builtin class that has its (CPython) :data:`Py_TPFLAGS_MAPPING` bit set 1533 * a class that inherits from any of the above 1534 1535 The standard library classes :class:`dict` and :class:`types.MappingProxyType` 1536 are mappings. 1537 1538.. [#] A string literal appearing as the first statement in the function body is 1539 transformed into the function's ``__doc__`` attribute and therefore the 1540 function's :term:`docstring`. 1541 1542.. [#] A string literal appearing as the first statement in the class body is 1543 transformed into the namespace's ``__doc__`` item and therefore the class's 1544 :term:`docstring`. 1545