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