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