summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/reference%2Fcompound_stmts.html
diff options
context:
space:
mode:
Diffstat (limited to 'devdocs/python~3.12/reference%2Fcompound_stmts.html')
-rw-r--r--devdocs/python~3.12/reference%2Fcompound_stmts.html487
1 files changed, 487 insertions, 0 deletions
diff --git a/devdocs/python~3.12/reference%2Fcompound_stmts.html b/devdocs/python~3.12/reference%2Fcompound_stmts.html
new file mode 100644
index 00000000..f6989d47
--- /dev/null
+++ b/devdocs/python~3.12/reference%2Fcompound_stmts.html
@@ -0,0 +1,487 @@
+ <span id="compound"></span><h1> Compound statements</h1> <p id="index-0">Compound statements contain (groups of) other statements; they affect or control the execution of those other statements in some way. In general, compound statements span multiple lines, although in simple incarnations a whole compound statement may be contained in one line.</p> <p>The <a class="reference internal" href="#if"><code>if</code></a>, <a class="reference internal" href="#while"><code>while</code></a> and <a class="reference internal" href="#for"><code>for</code></a> statements implement traditional control flow constructs. <a class="reference internal" href="#try"><code>try</code></a> specifies exception handlers and/or cleanup code for a group of statements, while the <a class="reference internal" href="#with"><code>with</code></a> statement allows the execution of initialization and finalization code around a block of code. Function and class definitions are also syntactically compound statements.</p> <p id="index-1">A compound statement consists of one or more ‘clauses.’ A clause consists of a header and a ‘suite.’ The clause headers of a particular compound statement are all at the same indentation level. Each clause header begins with a uniquely identifying keyword and ends with a colon. A suite is a group of statements controlled by a clause. A suite can be one or more semicolon-separated simple statements on the same line as the header, following the header’s colon, or it can be one or more indented statements on subsequent lines. Only the latter form of a suite can contain nested compound statements; the following is illegal, mostly because it wouldn’t be clear to which <a class="reference internal" href="#if"><code>if</code></a> clause a following <a class="reference internal" href="#else"><code>else</code></a> clause would belong:</p> <pre data-language="python">if test1: if test2: print(x)
+</pre> <p>Also note that the semicolon binds tighter than the colon in this context, so that in the following example, either all or none of the <a class="reference internal" href="../library/functions#print" title="print"><code>print()</code></a> calls are executed:</p> <pre data-language="python">if x &lt; y &lt; z: print(x); print(y); print(z)
+</pre> <p>Summarizing:</p> <pre>
+<strong id="grammar-token-python-grammar-compound_stmt"><span id="grammar-token-compound-stmt"></span>compound_stmt</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-if_stmt">if_stmt</a>
+ | <a class="reference internal" href="#grammar-token-python-grammar-while_stmt">while_stmt</a>
+ | <a class="reference internal" href="#grammar-token-python-grammar-for_stmt">for_stmt</a>
+ | <a class="reference internal" href="#grammar-token-python-grammar-try_stmt">try_stmt</a>
+ | <a class="reference internal" href="#grammar-token-python-grammar-with_stmt">with_stmt</a>
+ | <a class="reference internal" href="#grammar-token-python-grammar-match_stmt">match_stmt</a>
+ | <a class="reference internal" href="#grammar-token-python-grammar-funcdef">funcdef</a>
+ | <a class="reference internal" href="#grammar-token-python-grammar-classdef">classdef</a>
+ | <a class="reference internal" href="#grammar-token-python-grammar-async_with_stmt">async_with_stmt</a>
+ | <a class="reference internal" href="#grammar-token-python-grammar-async_for_stmt">async_for_stmt</a>
+ | <a class="reference internal" href="#grammar-token-python-grammar-async_funcdef">async_funcdef</a>
+<strong id="grammar-token-python-grammar-suite"><span id="grammar-token-suite"></span>suite </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-stmt_list">stmt_list</a> NEWLINE | NEWLINE INDENT <a class="reference internal" href="#grammar-token-python-grammar-statement">statement</a>+ DEDENT
+<strong id="grammar-token-python-grammar-statement"><span id="grammar-token-statement"></span>statement </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-stmt_list">stmt_list</a> NEWLINE | <a class="reference internal" href="#grammar-token-python-grammar-compound_stmt">compound_stmt</a>
+<strong id="grammar-token-python-grammar-stmt_list"><span id="grammar-token-stmt-list"></span>stmt_list </strong> ::= <a class="reference internal" href="simple_stmts#grammar-token-python-grammar-simple_stmt">simple_stmt</a> (";" <a class="reference internal" href="simple_stmts#grammar-token-python-grammar-simple_stmt">simple_stmt</a>)* [";"]
+</pre> <p id="index-2">Note that statements always end in a <code>NEWLINE</code> possibly followed by a <code>DEDENT</code>. Also note that optional continuation clauses always begin with a keyword that cannot start a statement, thus there are no ambiguities (the ‘dangling <a class="reference internal" href="#else"><code>else</code></a>’ problem is solved in Python by requiring nested <a class="reference internal" href="#if"><code>if</code></a> statements to be indented).</p> <p>The formatting of the grammar rules in the following sections places each clause on a separate line for clarity.</p> <section id="the-if-statement"> <span id="else"></span><span id="elif"></span><span id="if"></span><h2>
+<span class="section-number">8.1. </span>The <code>if</code> statement</h2> <p id="index-3">The <a class="reference internal" href="#if"><code>if</code></a> statement is used for conditional execution:</p> <pre>
+<strong id="grammar-token-python-grammar-if_stmt"><span id="grammar-token-if-stmt"></span>if_stmt</strong> ::= "if" <a class="reference internal" href="expressions#grammar-token-python-grammar-assignment_expression">assignment_expression</a> ":" <a class="reference internal" href="#grammar-token-python-grammar-suite">suite</a>
+ ("elif" <a class="reference internal" href="expressions#grammar-token-python-grammar-assignment_expression">assignment_expression</a> ":" <a class="reference internal" href="#grammar-token-python-grammar-suite">suite</a>)*
+ ["else" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite">suite</a>]
+</pre> <p>It selects exactly one of the suites by evaluating the expressions one by one until one is found to be true (see section <a class="reference internal" href="expressions#booleans"><span class="std std-ref">Boolean operations</span></a> for the definition of true and false); then that suite is executed (and no other part of the <a class="reference internal" href="#if"><code>if</code></a> statement is executed or evaluated). If all expressions are false, the suite of the <a class="reference internal" href="#else"><code>else</code></a> clause, if present, is executed.</p> </section> <section id="the-while-statement"> <span id="while"></span><h2>
+<span class="section-number">8.2. </span>The <code>while</code> statement</h2> <p id="index-4">The <a class="reference internal" href="#while"><code>while</code></a> statement is used for repeated execution as long as an expression is true:</p> <pre>
+<strong id="grammar-token-python-grammar-while_stmt"><span id="grammar-token-while-stmt"></span>while_stmt</strong> ::= "while" <a class="reference internal" href="expressions#grammar-token-python-grammar-assignment_expression">assignment_expression</a> ":" <a class="reference internal" href="#grammar-token-python-grammar-suite">suite</a>
+ ["else" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite">suite</a>]
+</pre> <p>This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the <code>else</code> clause, if present, is executed and the loop terminates.</p> <p id="index-5">A <a class="reference internal" href="simple_stmts#break"><code>break</code></a> statement executed in the first suite terminates the loop without executing the <code>else</code> clause’s suite. A <a class="reference internal" href="simple_stmts#continue"><code>continue</code></a> statement executed in the first suite skips the rest of the suite and goes back to testing the expression.</p> </section> <section id="the-for-statement"> <span id="for"></span><h2>
+<span class="section-number">8.3. </span>The <code>for</code> statement</h2> <p id="index-6">The <a class="reference internal" href="#for"><code>for</code></a> statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object:</p> <pre>
+<strong id="grammar-token-python-grammar-for_stmt"><span id="grammar-token-for-stmt"></span>for_stmt</strong> ::= "for" <a class="reference internal" href="simple_stmts#grammar-token-python-grammar-target_list">target_list</a> "in" <a class="reference internal" href="expressions#grammar-token-python-grammar-starred_list">starred_list</a> ":" <a class="reference internal" href="#grammar-token-python-grammar-suite">suite</a>
+ ["else" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite">suite</a>]
+</pre> <p>The <code>starred_list</code> expression is evaluated once; it should yield an <a class="reference internal" href="../glossary#term-iterable"><span class="xref std std-term">iterable</span></a> object. An <a class="reference internal" href="../glossary#term-iterator"><span class="xref std std-term">iterator</span></a> is created for that iterable. The first item provided by the iterator is then assigned to the target list using the standard rules for assignments (see <a class="reference internal" href="simple_stmts#assignment"><span class="std std-ref">Assignment statements</span></a>), and the suite is executed. This repeats for each item provided by the iterator. When the iterator is exhausted, the suite in the <code>else</code> clause, if present, is executed, and the loop terminates.</p> <p id="index-7">A <a class="reference internal" href="simple_stmts#break"><code>break</code></a> statement executed in the first suite terminates the loop without executing the <code>else</code> clause’s suite. A <a class="reference internal" href="simple_stmts#continue"><code>continue</code></a> statement executed in the first suite skips the rest of the suite and continues with the next item, or with the <code>else</code> clause if there is no next item.</p> <p>The for-loop makes assignments to the variables in the target list. This overwrites all previous assignments to those variables including those made in the suite of the for-loop:</p> <pre data-language="python">for i in range(10):
+ print(i)
+ i = 5 # this will not affect the for-loop
+ # because i will be overwritten with the next
+ # index in the range
+</pre> <p id="index-8">Names in the target list are not deleted when the loop is finished, but if the sequence is empty, they will not have been assigned to at all by the loop. Hint: the built-in type <a class="reference internal" href="../library/stdtypes#range" title="range"><code>range()</code></a> represents immutable arithmetic sequences of integers. For instance, iterating <code>range(3)</code> successively yields 0, 1, and then 2.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Starred elements are now allowed in the expression list.</p> </div> </section> <section id="the-try-statement"> <span id="try"></span><h2>
+<span class="section-number">8.4. </span>The <code>try</code> statement</h2> <p id="index-9">The <code>try</code> statement specifies exception handlers and/or cleanup code for a group of statements:</p> <pre>
+<strong id="grammar-token-python-grammar-try_stmt"><span id="grammar-token-try-stmt"></span>try_stmt </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-try1_stmt">try1_stmt</a> | <a class="reference internal" href="#grammar-token-python-grammar-try2_stmt">try2_stmt</a> | <a class="reference internal" href="#grammar-token-python-grammar-try3_stmt">try3_stmt</a>
+<strong id="grammar-token-python-grammar-try1_stmt"><span id="grammar-token-try1-stmt"></span>try1_stmt</strong> ::= "try" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite">suite</a>
+ ("except" [<a class="reference internal" href="expressions#grammar-token-python-grammar-expression">expression</a> ["as" <a class="reference internal" href="lexical_analysis#grammar-token-python-grammar-identifier">identifier</a>]] ":" <a class="reference internal" href="#grammar-token-python-grammar-suite">suite</a>)+
+ ["else" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite">suite</a>]
+ ["finally" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite">suite</a>]
+<strong id="grammar-token-python-grammar-try2_stmt"><span id="grammar-token-try2-stmt"></span>try2_stmt</strong> ::= "try" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite">suite</a>
+ ("except" "*" <a class="reference internal" href="expressions#grammar-token-python-grammar-expression">expression</a> ["as" <a class="reference internal" href="lexical_analysis#grammar-token-python-grammar-identifier">identifier</a>] ":" <a class="reference internal" href="#grammar-token-python-grammar-suite">suite</a>)+
+ ["else" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite">suite</a>]
+ ["finally" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite">suite</a>]
+<strong id="grammar-token-python-grammar-try3_stmt"><span id="grammar-token-try3-stmt"></span>try3_stmt</strong> ::= "try" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite">suite</a>
+ "finally" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite">suite</a>
+</pre> <p>Additional information on exceptions can be found in section <a class="reference internal" href="executionmodel#exceptions"><span class="std std-ref">Exceptions</span></a>, and information on using the <a class="reference internal" href="simple_stmts#raise"><code>raise</code></a> statement to generate exceptions may be found in section <a class="reference internal" href="simple_stmts#raise"><span class="std std-ref">The raise statement</span></a>.</p> <section id="except-clause"> <span id="except"></span><h3>
+<span class="section-number">8.4.1. </span><code>except</code> clause</h3> <p>The <code>except</code> clause(s) specify one or more exception handlers. When no exception occurs in the <a class="reference internal" href="#try"><code>try</code></a> clause, no exception handler is executed. When an exception occurs in the <code>try</code> suite, a search for an exception handler is started. This search inspects the <code>except</code> clauses in turn until one is found that matches the exception. An expression-less <code>except</code> clause, if present, must be last; it matches any exception. For an <code>except</code> clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is “compatible” with the exception. An object is compatible with an exception if the object is the class or a <a class="reference internal" href="../glossary#term-abstract-base-class"><span class="xref std std-term">non-virtual base class</span></a> of the exception object, or a tuple containing an item that is the class or a non-virtual base class of the exception object.</p> <p>If no <code>except</code> clause matches the exception, the search for an exception handler continues in the surrounding code and on the invocation stack. <a class="footnote-reference brackets" href="#id20" id="id1">1</a></p> <p>If the evaluation of an expression in the header of an <code>except</code> clause raises an exception, the original search for a handler is canceled and a search starts for the new exception in the surrounding code and on the call stack (it is treated as if the entire <a class="reference internal" href="#try"><code>try</code></a> statement raised the exception).</p> <p id="index-10">When a matching <code>except</code> clause is found, the exception is assigned to the target specified after the <code>as</code> keyword in that <code>except</code> clause, if present, and the <code>except</code> clause’s suite is executed. All <code>except</code> clauses must have an executable block. When the end of this block is reached, execution continues normally after the entire <a class="reference internal" href="#try"><code>try</code></a> statement. (This means that if two nested handlers exist for the same exception, and the exception occurs in the <code>try</code> clause of the inner handler, the outer handler will not handle the exception.)</p> <p>When an exception has been assigned using <code>as target</code>, it is cleared at the end of the <code>except</code> clause. This is as if</p> <pre data-language="python">except E as N:
+ foo
+</pre> <p>was translated to</p> <pre data-language="python">except E as N:
+ try:
+ foo
+ finally:
+ del N
+</pre> <p>This means the exception must be assigned to a different name to be able to refer to it after the <code>except</code> clause. Exceptions are cleared because with the traceback attached to them, they form a reference cycle with the stack frame, keeping all locals in that frame alive until the next garbage collection occurs.</p> <p id="index-11">Before an <code>except</code> clause’s suite is executed, the exception is stored in the <a class="reference internal" href="../library/sys#module-sys" title="sys: Access system-specific parameters and functions."><code>sys</code></a> module, where it can be accessed from within the body of the <code>except</code> clause by calling <a class="reference internal" href="../library/sys#sys.exception" title="sys.exception"><code>sys.exception()</code></a>. When leaving an exception handler, the exception stored in the <a class="reference internal" href="../library/sys#module-sys" title="sys: Access system-specific parameters and functions."><code>sys</code></a> module is reset to its previous value:</p> <pre data-language="python">&gt;&gt;&gt; print(sys.exception())
+None
+&gt;&gt;&gt; try:
+... raise TypeError
+... except:
+... print(repr(sys.exception()))
+... try:
+... raise ValueError
+... except:
+... print(repr(sys.exception()))
+... print(repr(sys.exception()))
+...
+TypeError()
+ValueError()
+TypeError()
+&gt;&gt;&gt; print(sys.exception())
+None
+</pre> </section> <section id="except-star"> <span id="index-12"></span><span id="id2"></span><h3>
+<span class="section-number">8.4.2. </span><code>except*</code> clause</h3> <p>The <code>except*</code> clause(s) are used for handling <a class="reference internal" href="../library/exceptions#ExceptionGroup" title="ExceptionGroup"><code>ExceptionGroup</code></a>s. The exception type for matching is interpreted as in the case of <a class="reference internal" href="#except"><code>except</code></a>, but in the case of exception groups we can have partial matches when the type matches some of the exceptions in the group. This means that multiple <code>except*</code> clauses can execute, each handling part of the exception group. Each clause executes at most once and handles an exception group of all matching exceptions. Each exception in the group is handled by at most one <code>except*</code> clause, the first that matches it.</p> <pre data-language="python">&gt;&gt;&gt; try:
+... raise ExceptionGroup("eg",
+... [ValueError(1), TypeError(2), OSError(3), OSError(4)])
+... except* TypeError as e:
+... print(f'caught {type(e)} with nested {e.exceptions}')
+... except* OSError as e:
+... print(f'caught {type(e)} with nested {e.exceptions}')
+...
+caught &lt;class 'ExceptionGroup'&gt; with nested (TypeError(2),)
+caught &lt;class 'ExceptionGroup'&gt; with nested (OSError(3), OSError(4))
+ + Exception Group Traceback (most recent call last):
+ | File "&lt;stdin&gt;", line 2, in &lt;module&gt;
+ | ExceptionGroup: eg
+ +-+---------------- 1 ----------------
+ | ValueError: 1
+ +------------------------------------
+</pre> <p>Any remaining exceptions that were not handled by any <code>except*</code> clause are re-raised at the end, along with all exceptions that were raised from within the <code>except*</code> clauses. If this list contains more than one exception to reraise, they are combined into an exception group.</p> <p>If the raised exception is not an exception group and its type matches one of the <code>except*</code> clauses, it is caught and wrapped by an exception group with an empty message string.</p> <pre data-language="python">&gt;&gt;&gt; try:
+... raise BlockingIOError
+... except* BlockingIOError as e:
+... print(repr(e))
+...
+ExceptionGroup('', (BlockingIOError()))
+</pre> <p>An <code>except*</code> clause must have a matching type, and this type cannot be a subclass of <a class="reference internal" href="../library/exceptions#BaseExceptionGroup" title="BaseExceptionGroup"><code>BaseExceptionGroup</code></a>. It is not possible to mix <a class="reference internal" href="#except"><code>except</code></a> and <code>except*</code> in the same <a class="reference internal" href="#try"><code>try</code></a>. <a class="reference internal" href="simple_stmts#break"><code>break</code></a>, <a class="reference internal" href="simple_stmts#continue"><code>continue</code></a> and <a class="reference internal" href="simple_stmts#return"><code>return</code></a> cannot appear in an <code>except*</code> clause.</p> </section> <section id="else-clause"> <span id="except-else"></span><span id="index-13"></span><h3>
+<span class="section-number">8.4.3. </span><code>else</code> clause</h3> <p>The optional <code>else</code> clause is executed if the control flow leaves the <a class="reference internal" href="#try"><code>try</code></a> suite, no exception was raised, and no <a class="reference internal" href="simple_stmts#return"><code>return</code></a>, <a class="reference internal" href="simple_stmts#continue"><code>continue</code></a>, or <a class="reference internal" href="simple_stmts#break"><code>break</code></a> statement was executed. Exceptions in the <code>else</code> clause are not handled by the preceding <a class="reference internal" href="#except"><code>except</code></a> clauses.</p> </section> <section id="finally-clause"> <span id="finally"></span><span id="index-14"></span><h3>
+<span class="section-number">8.4.4. </span><code>finally</code> clause</h3> <p>If <code>finally</code> is present, it specifies a ‘cleanup’ handler. The <a class="reference internal" href="#try"><code>try</code></a> clause is executed, including any <a class="reference internal" href="#except"><code>except</code></a> and <a class="reference internal" href="#else"><code>else</code></a> clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The <code>finally</code> clause is executed. If there is a saved exception it is re-raised at the end of the <code>finally</code> clause. If the <code>finally</code> clause raises another exception, the saved exception is set as the context of the new exception. If the <code>finally</code> clause executes a <a class="reference internal" href="simple_stmts#return"><code>return</code></a>, <a class="reference internal" href="simple_stmts#break"><code>break</code></a> or <a class="reference internal" href="simple_stmts#continue"><code>continue</code></a> statement, the saved exception is discarded:</p> <pre data-language="python">&gt;&gt;&gt; def f():
+... try:
+... 1/0
+... finally:
+... return 42
+...
+&gt;&gt;&gt; f()
+42
+</pre> <p>The exception information is not available to the program during execution of the <code>finally</code> clause.</p> <p id="index-15">When a <a class="reference internal" href="simple_stmts#return"><code>return</code></a>, <a class="reference internal" href="simple_stmts#break"><code>break</code></a> or <a class="reference internal" href="simple_stmts#continue"><code>continue</code></a> statement is executed in the <a class="reference internal" href="#try"><code>try</code></a> suite of a <code>try</code>…<code>finally</code> statement, the <code>finally</code> clause is also executed ‘on the way out.’</p> <p>The return value of a function is determined by the last <a class="reference internal" href="simple_stmts#return"><code>return</code></a> statement executed. Since the <code>finally</code> clause always executes, a <code>return</code> statement executed in the <code>finally</code> clause will always be the last one executed:</p> <pre data-language="python">&gt;&gt;&gt; def foo():
+... try:
+... return 'try'
+... finally:
+... return 'finally'
+...
+&gt;&gt;&gt; foo()
+'finally'
+</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>Prior to Python 3.8, a <a class="reference internal" href="simple_stmts#continue"><code>continue</code></a> statement was illegal in the <code>finally</code> clause due to a problem with the implementation.</p> </div> </section> </section> <section id="the-with-statement"> <span id="as"></span><span id="with"></span><h2>
+<span class="section-number">8.5. </span>The <code>with</code> statement</h2> <p id="index-16">The <a class="reference internal" href="#with"><code>with</code></a> statement is used to wrap the execution of a block with methods defined by a context manager (see section <a class="reference internal" href="datamodel#context-managers"><span class="std std-ref">With Statement Context Managers</span></a>). This allows common <a class="reference internal" href="#try"><code>try</code></a>…<a class="reference internal" href="#except"><code>except</code></a>…<a class="reference internal" href="#finally"><code>finally</code></a> usage patterns to be encapsulated for convenient reuse.</p> <pre>
+<strong id="grammar-token-python-grammar-with_stmt"><span id="grammar-token-with-stmt"></span>with_stmt </strong> ::= "with" ( "(" <a class="reference internal" href="#grammar-token-python-grammar-with_stmt_contents">with_stmt_contents</a> ","? ")" | <a class="reference internal" href="#grammar-token-python-grammar-with_stmt_contents">with_stmt_contents</a> ) ":" <a class="reference internal" href="#grammar-token-python-grammar-suite">suite</a>
+<strong id="grammar-token-python-grammar-with_stmt_contents"><span id="grammar-token-with-stmt-contents"></span>with_stmt_contents</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-with_item">with_item</a> ("," <a class="reference internal" href="#grammar-token-python-grammar-with_item">with_item</a>)*
+<strong id="grammar-token-python-grammar-with_item"><span id="grammar-token-with-item"></span>with_item </strong> ::= <a class="reference internal" href="expressions#grammar-token-python-grammar-expression">expression</a> ["as" <a class="reference internal" href="simple_stmts#grammar-token-python-grammar-target">target</a>]
+</pre> <p>The execution of the <a class="reference internal" href="#with"><code>with</code></a> statement with one “item” proceeds as follows:</p> <ol class="arabic"> <li>The context expression (the expression given in the <a class="reference internal" href="#grammar-token-python-grammar-with_item"><code>with_item</code></a>) is evaluated to obtain a context manager.</li> <li>The context manager’s <a class="reference internal" href="datamodel#object.__enter__" title="object.__enter__"><code>__enter__()</code></a> is loaded for later use.</li> <li>The context manager’s <a class="reference internal" href="datamodel#object.__exit__" title="object.__exit__"><code>__exit__()</code></a> is loaded for later use.</li> <li>The context manager’s <a class="reference internal" href="datamodel#object.__enter__" title="object.__enter__"><code>__enter__()</code></a> method is invoked.</li> <li>
+<p>If a target was included in the <a class="reference internal" href="#with"><code>with</code></a> statement, the return value from <a class="reference internal" href="datamodel#object.__enter__" title="object.__enter__"><code>__enter__()</code></a> is assigned to it.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The <a class="reference internal" href="#with"><code>with</code></a> statement guarantees that if the <a class="reference internal" href="datamodel#object.__enter__" title="object.__enter__"><code>__enter__()</code></a> method returns without an error, then <a class="reference internal" href="datamodel#object.__exit__" title="object.__exit__"><code>__exit__()</code></a> will always be called. Thus, if an error occurs during the assignment to the target list, it will be treated the same as an error occurring within the suite would be. See step 7 below.</p> </div> </li> <li>The suite is executed.</li> <li>
+<p>The context manager’s <a class="reference internal" href="datamodel#object.__exit__" title="object.__exit__"><code>__exit__()</code></a> method is invoked. If an exception caused the suite to be exited, its type, value, and traceback are passed as arguments to <a class="reference internal" href="datamodel#object.__exit__" title="object.__exit__"><code>__exit__()</code></a>. Otherwise, three <a class="reference internal" href="../library/constants#None" title="None"><code>None</code></a> arguments are supplied.</p> <p>If the suite was exited due to an exception, and the return value from the <a class="reference internal" href="datamodel#object.__exit__" title="object.__exit__"><code>__exit__()</code></a> method was false, the exception is reraised. If the return value was true, the exception is suppressed, and execution continues with the statement following the <a class="reference internal" href="#with"><code>with</code></a> statement.</p> <p>If the suite was exited for any reason other than an exception, the return value from <a class="reference internal" href="datamodel#object.__exit__" title="object.__exit__"><code>__exit__()</code></a> is ignored, and execution proceeds at the normal location for the kind of exit that was taken.</p> </li> </ol> <p>The following code:</p> <pre data-language="python">with EXPRESSION as TARGET:
+ SUITE
+</pre> <p>is semantically equivalent to:</p> <pre data-language="python">manager = (EXPRESSION)
+enter = type(manager).__enter__
+exit = type(manager).__exit__
+value = enter(manager)
+hit_except = False
+
+try:
+ TARGET = value
+ SUITE
+except:
+ hit_except = True
+ if not exit(manager, *sys.exc_info()):
+ raise
+finally:
+ if not hit_except:
+ exit(manager, None, None, None)
+</pre> <p>With more than one item, the context managers are processed as if multiple <a class="reference internal" href="#with"><code>with</code></a> statements were nested:</p> <pre data-language="python">with A() as a, B() as b:
+ SUITE
+</pre> <p>is semantically equivalent to:</p> <pre data-language="python">with A() as a:
+ with B() as b:
+ SUITE
+</pre> <p>You can also write multi-item context managers in multiple lines if the items are surrounded by parentheses. For example:</p> <pre data-language="python">with (
+ A() as a,
+ B() as b,
+):
+ SUITE
+</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.1: </span>Support for multiple context expressions.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>Support for using grouping parentheses to break the statement in multiple lines.</p> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt>
+<span class="target" id="index-17"></span><a class="pep reference external" href="https://peps.python.org/pep-0343/"><strong>PEP 343</strong></a> - The “with” statement</dt>
+<dd>
+<p>The specification, background, and examples for the Python <a class="reference internal" href="#with"><code>with</code></a> statement.</p> </dd> </dl> </div> </section> <section id="the-match-statement"> <span id="match"></span><h2>
+<span class="section-number">8.6. </span>The <code>match</code> statement</h2> <div class="versionadded" id="index-18"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> <p>The match statement is used for pattern matching. Syntax:</p> <pre>
+<strong id="grammar-token-python-grammar-match_stmt"><span id="grammar-token-match-stmt"></span>match_stmt </strong> ::= 'match' <a class="reference internal" href="#grammar-token-python-grammar-subject_expr">subject_expr</a> ":" NEWLINE INDENT <a class="reference internal" href="#grammar-token-python-grammar-case_block">case_block</a>+ DEDENT
+<strong id="grammar-token-python-grammar-subject_expr"><span id="grammar-token-subject-expr"></span>subject_expr</strong> ::= <code>star_named_expression</code> "," <code>star_named_expressions</code>?
+ | <code>named_expression</code>
+<strong id="grammar-token-python-grammar-case_block"><span id="grammar-token-case-block"></span>case_block </strong> ::= 'case' <a class="reference internal" href="#grammar-token-python-grammar-patterns">patterns</a> [<a class="reference internal" href="#grammar-token-python-grammar-guard">guard</a>] ":" <code>block</code>
+</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p>This section uses single quotes to denote <a class="reference internal" href="lexical_analysis#soft-keywords"><span class="std std-ref">soft keywords</span></a>.</p> </div> <p>Pattern matching takes a pattern as input (following <code>case</code>) and a subject value (following <code>match</code>). The pattern (which may contain subpatterns) is matched against the subject value. The outcomes are:</p> <ul class="simple"> <li>A match success or failure (also termed a pattern success or failure).</li> <li>Possible binding of matched values to a name. The prerequisites for this are further discussed below.</li> </ul> <p>The <code>match</code> and <code>case</code> keywords are <a class="reference internal" href="lexical_analysis#soft-keywords"><span class="std std-ref">soft keywords</span></a>.</p> <div class="admonition seealso"> <p class="admonition-title">See also</p> <ul class="simple"> <li>
+<span class="target" id="index-19"></span><a class="pep reference external" href="https://peps.python.org/pep-0634/"><strong>PEP 634</strong></a> – Structural Pattern Matching: Specification</li> <li>
+<span class="target" id="index-20"></span><a class="pep reference external" href="https://peps.python.org/pep-0636/"><strong>PEP 636</strong></a> – Structural Pattern Matching: Tutorial</li> </ul> </div> <section id="overview"> <h3>
+<span class="section-number">8.6.1. </span>Overview</h3> <p>Here’s an overview of the logical flow of a match statement:</p> <ol class="arabic"> <li>The subject expression <code>subject_expr</code> is evaluated and a resulting subject value obtained. If the subject expression contains a comma, a tuple is constructed using <a class="reference internal" href="../library/stdtypes#typesseq-tuple"><span class="std std-ref">the standard rules</span></a>.</li> <li>
+<p>Each pattern in a <code>case_block</code> is attempted to match with the subject value. The specific rules for success or failure are described below. The match attempt can also bind some or all of the standalone names within the pattern. The precise pattern binding rules vary per pattern type and are specified below. <strong>Name bindings made during a successful pattern match outlive the executed block and can be used after the match statement</strong>.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>During failed pattern matches, some subpatterns may succeed. Do not rely on bindings being made for a failed match. Conversely, do not rely on variables remaining unchanged after a failed match. The exact behavior is dependent on implementation and may vary. This is an intentional decision made to allow different implementations to add optimizations.</p> </div> </li> <li>
+<p>If the pattern succeeds, the corresponding guard (if present) is evaluated. In this case all name bindings are guaranteed to have happened.</p> <ul class="simple"> <li>If the guard evaluates as true or is missing, the <code>block</code> inside <code>case_block</code> is executed.</li> <li>Otherwise, the next <code>case_block</code> is attempted as described above.</li> <li>If there are no further case blocks, the match statement is completed.</li> </ul> </li> </ol> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Users should generally never rely on a pattern being evaluated. Depending on implementation, the interpreter may cache values or use other optimizations which skip repeated evaluations.</p> </div> <p>A sample match statement:</p> <pre data-language="python">&gt;&gt;&gt; flag = False
+&gt;&gt;&gt; match (100, 200):
+... case (100, 300): # Mismatch: 200 != 300
+... print('Case 1')
+... case (100, 200) if flag: # Successful match, but guard fails
+... print('Case 2')
+... case (100, y): # Matches and binds y to 200
+... print(f'Case 3, y: {y}')
+... case _: # Pattern not attempted
+... print('Case 4, I match anything!')
+...
+Case 3, y: 200
+</pre> <p>In this case, <code>if flag</code> is a guard. Read more about that in the next section.</p> </section> <section id="guards"> <h3>
+<span class="section-number">8.6.2. </span>Guards</h3> <pre id="index-21">
+<strong id="grammar-token-python-grammar-guard"><span id="grammar-token-guard"></span>guard</strong> ::= "if" <code>named_expression</code>
+</pre> <p>A <code>guard</code> (which is part of the <code>case</code>) must succeed for code inside the <code>case</code> block to execute. It takes the form: <a class="reference internal" href="#if"><code>if</code></a> followed by an expression.</p> <p>The logical flow of a <code>case</code> block with a <code>guard</code> follows:</p> <ol class="arabic simple"> <li>Check that the pattern in the <code>case</code> block succeeded. If the pattern failed, the <code>guard</code> is not evaluated and the next <code>case</code> block is checked.</li> <li>
+<p>If the pattern succeeded, evaluate the <code>guard</code>.</p> <ul class="simple"> <li>If the <code>guard</code> condition evaluates as true, the case block is selected.</li> <li>If the <code>guard</code> condition evaluates as false, the case block is not selected.</li> <li>If the <code>guard</code> raises an exception during evaluation, the exception bubbles up.</li> </ul> </li> </ol> <p>Guards are allowed to have side effects as they are expressions. Guard evaluation must proceed from the first to the last case block, one at a time, skipping case blocks whose pattern(s) don’t all succeed. (I.e., guard evaluation must happen in order.) Guard evaluation must stop once a case block is selected.</p> </section> <section id="irrefutable-case-blocks"> <span id="irrefutable-case"></span><h3>
+<span class="section-number">8.6.3. </span>Irrefutable Case Blocks</h3> <p id="index-22">An irrefutable case block is a match-all case block. A match statement may have at most one irrefutable case block, and it must be last.</p> <p>A case block is considered irrefutable if it has no guard and its pattern is irrefutable. A pattern is considered irrefutable if we can prove from its syntax alone that it will always succeed. Only the following patterns are irrefutable:</p> <ul class="simple"> <li>
+<a class="reference internal" href="#as-patterns"><span class="std std-ref">AS Patterns</span></a> whose left-hand side is irrefutable</li> <li>
+<a class="reference internal" href="#or-patterns"><span class="std std-ref">OR Patterns</span></a> containing at least one irrefutable pattern</li> <li><a class="reference internal" href="#capture-patterns"><span class="std std-ref">Capture Patterns</span></a></li> <li><a class="reference internal" href="#wildcard-patterns"><span class="std std-ref">Wildcard Patterns</span></a></li> <li>parenthesized irrefutable patterns</li> </ul> </section> <section id="patterns"> <h3>
+<span class="section-number">8.6.4. </span>Patterns</h3> <div class="admonition note" id="index-23"> <p class="admonition-title">Note</p> <p>This section uses grammar notations beyond standard EBNF:</p> <ul class="simple"> <li>the notation <code>SEP.RULE+</code> is shorthand for <code>RULE (SEP RULE)*</code>
+</li> <li>the notation <code>!RULE</code> is shorthand for a negative lookahead assertion</li> </ul> </div> <p>The top-level syntax for <code>patterns</code> is:</p> <pre>
+<strong id="grammar-token-python-grammar-patterns"><span id="grammar-token-patterns"></span>patterns </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-open_sequence_pattern">open_sequence_pattern</a> | <a class="reference internal" href="#grammar-token-python-grammar-pattern">pattern</a>
+<strong id="grammar-token-python-grammar-pattern"><span id="grammar-token-pattern"></span>pattern </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-as_pattern">as_pattern</a> | <a class="reference internal" href="#grammar-token-python-grammar-or_pattern">or_pattern</a>
+<strong id="grammar-token-python-grammar-closed_pattern"><span id="grammar-token-closed-pattern"></span>closed_pattern</strong> ::= | <a class="reference internal" href="#grammar-token-python-grammar-literal_pattern">literal_pattern</a>
+ | <a class="reference internal" href="#grammar-token-python-grammar-capture_pattern">capture_pattern</a>
+ | <a class="reference internal" href="#grammar-token-python-grammar-wildcard_pattern">wildcard_pattern</a>
+ | <a class="reference internal" href="#grammar-token-python-grammar-value_pattern">value_pattern</a>
+ | <a class="reference internal" href="#grammar-token-python-grammar-group_pattern">group_pattern</a>
+ | <a class="reference internal" href="#grammar-token-python-grammar-sequence_pattern">sequence_pattern</a>
+ | <a class="reference internal" href="#grammar-token-python-grammar-mapping_pattern">mapping_pattern</a>
+ | <a class="reference internal" href="#grammar-token-python-grammar-class_pattern">class_pattern</a>
+</pre> <p>The descriptions below will include a description “in simple terms” of what a pattern does for illustration purposes (credits to Raymond Hettinger for a document that inspired most of the descriptions). Note that these descriptions are purely for illustration purposes and <strong>may not</strong> reflect the underlying implementation. Furthermore, they do not cover all valid forms.</p> <section id="or-patterns"> <span id="id3"></span><h4>
+<span class="section-number">8.6.4.1. </span>OR Patterns</h4> <p>An OR pattern is two or more patterns separated by vertical bars <code>|</code>. Syntax:</p> <pre>
+<strong id="grammar-token-python-grammar-or_pattern"><span id="grammar-token-or-pattern"></span>or_pattern</strong> ::= "|".<a class="reference internal" href="#grammar-token-python-grammar-closed_pattern">closed_pattern</a>+
+</pre> <p>Only the final subpattern may be <a class="reference internal" href="#irrefutable-case"><span class="std std-ref">irrefutable</span></a>, and each subpattern must bind the same set of names to avoid ambiguity.</p> <p>An OR pattern matches each of its subpatterns in turn to the subject value, until one succeeds. The OR pattern is then considered successful. Otherwise, if none of the subpatterns succeed, the OR pattern fails.</p> <p>In simple terms, <code>P1 | P2 | ...</code> will try to match <code>P1</code>, if it fails it will try to match <code>P2</code>, succeeding immediately if any succeeds, failing otherwise.</p> </section> <section id="as-patterns"> <span id="id4"></span><h4>
+<span class="section-number">8.6.4.2. </span>AS Patterns</h4> <p>An AS pattern matches an OR pattern on the left of the <a class="reference internal" href="#as"><code>as</code></a> keyword against a subject. Syntax:</p> <pre>
+<strong id="grammar-token-python-grammar-as_pattern"><span id="grammar-token-as-pattern"></span>as_pattern</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-or_pattern">or_pattern</a> "as" <a class="reference internal" href="#grammar-token-python-grammar-capture_pattern">capture_pattern</a>
+</pre> <p>If the OR pattern fails, the AS pattern fails. Otherwise, the AS pattern binds the subject to the name on the right of the as keyword and succeeds. <code>capture_pattern</code> cannot be a <code>_</code>.</p> <p>In simple terms <code>P as NAME</code> will match with <code>P</code>, and on success it will set <code>NAME = &lt;subject&gt;</code>.</p> </section> <section id="literal-patterns"> <span id="id5"></span><h4>
+<span class="section-number">8.6.4.3. </span>Literal Patterns</h4> <p>A literal pattern corresponds to most <a class="reference internal" href="lexical_analysis#literals"><span class="std std-ref">literals</span></a> in Python. Syntax:</p> <pre>
+<strong id="grammar-token-python-grammar-literal_pattern"><span id="grammar-token-literal-pattern"></span>literal_pattern</strong> ::= <code>signed_number</code>
+ | <code>signed_number</code> "+" NUMBER
+ | <code>signed_number</code> "-" NUMBER
+ | <code>strings</code>
+ | "None"
+ | "True"
+ | "False"
+ | <code>signed_number</code>: NUMBER | "-" NUMBER
+</pre> <p>The rule <code>strings</code> and the token <code>NUMBER</code> are defined in the <a class="reference internal" href="grammar"><span class="doc">standard Python grammar</span></a>. Triple-quoted strings are supported. Raw strings and byte strings are supported. <a class="reference internal" href="lexical_analysis#f-strings"><span class="std std-ref">f-strings</span></a> are not supported.</p> <p>The forms <code>signed_number '+' NUMBER</code> and <code>signed_number '-' NUMBER</code> are for expressing <a class="reference internal" href="lexical_analysis#imaginary"><span class="std std-ref">complex numbers</span></a>; they require a real number on the left and an imaginary number on the right. E.g. <code>3 + 4j</code>.</p> <p>In simple terms, <code>LITERAL</code> will succeed only if <code>&lt;subject&gt; == LITERAL</code>. For the singletons <code>None</code>, <code>True</code> and <code>False</code>, the <a class="reference internal" href="expressions#is"><code>is</code></a> operator is used.</p> </section> <section id="capture-patterns"> <span id="id6"></span><h4>
+<span class="section-number">8.6.4.4. </span>Capture Patterns</h4> <p>A capture pattern binds the subject value to a name. Syntax:</p> <pre>
+<strong id="grammar-token-python-grammar-capture_pattern"><span id="grammar-token-capture-pattern"></span>capture_pattern</strong> ::= !'_' NAME
+</pre> <p>A single underscore <code>_</code> is not a capture pattern (this is what <code>!'_'</code> expresses). It is instead treated as a <a class="reference internal" href="#grammar-token-python-grammar-wildcard_pattern"><code>wildcard_pattern</code></a>.</p> <p>In a given pattern, a given name can only be bound once. E.g. <code>case x, x: ...</code> is invalid while <code>case [x] | x: ...</code> is allowed.</p> <p>Capture patterns always succeed. The binding follows scoping rules established by the assignment expression operator in <span class="target" id="index-24"></span><a class="pep reference external" href="https://peps.python.org/pep-0572/"><strong>PEP 572</strong></a>; the name becomes a local variable in the closest containing function scope unless there’s an applicable <a class="reference internal" href="simple_stmts#global"><code>global</code></a> or <a class="reference internal" href="simple_stmts#nonlocal"><code>nonlocal</code></a> statement.</p> <p>In simple terms <code>NAME</code> will always succeed and it will set <code>NAME = &lt;subject&gt;</code>.</p> </section> <section id="wildcard-patterns"> <span id="id7"></span><h4>
+<span class="section-number">8.6.4.5. </span>Wildcard Patterns</h4> <p>A wildcard pattern always succeeds (matches anything) and binds no name. Syntax:</p> <pre>
+<strong id="grammar-token-python-grammar-wildcard_pattern"><span id="grammar-token-wildcard-pattern"></span>wildcard_pattern</strong> ::= '_'
+</pre> <p><code>_</code> is a <a class="reference internal" href="lexical_analysis#soft-keywords"><span class="std std-ref">soft keyword</span></a> within any pattern, but only within patterns. It is an identifier, as usual, even within <code>match</code> subject expressions, <code>guard</code>s, and <code>case</code> blocks.</p> <p>In simple terms, <code>_</code> will always succeed.</p> </section> <section id="value-patterns"> <span id="id8"></span><h4>
+<span class="section-number">8.6.4.6. </span>Value Patterns</h4> <p>A value pattern represents a named value in Python. Syntax:</p> <pre>
+<strong id="grammar-token-python-grammar-value_pattern"><span id="grammar-token-value-pattern"></span>value_pattern</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-attr">attr</a>
+<strong id="grammar-token-python-grammar-attr"><span id="grammar-token-attr"></span>attr </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-name_or_attr">name_or_attr</a> "." NAME
+<strong id="grammar-token-python-grammar-name_or_attr"><span id="grammar-token-name-or-attr"></span>name_or_attr </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-attr">attr</a> | NAME
+</pre> <p>The dotted name in the pattern is looked up using standard Python <a class="reference internal" href="executionmodel#resolve-names"><span class="std std-ref">name resolution rules</span></a>. The pattern succeeds if the value found compares equal to the subject value (using the <code>==</code> equality operator).</p> <p>In simple terms <code>NAME1.NAME2</code> will succeed only if <code>&lt;subject&gt; == NAME1.NAME2</code></p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>If the same value occurs multiple times in the same match statement, the interpreter may cache the first value found and reuse it rather than repeat the same lookup. This cache is strictly tied to a given execution of a given match statement.</p> </div> </section> <section id="group-patterns"> <span id="id9"></span><h4>
+<span class="section-number">8.6.4.7. </span>Group Patterns</h4> <p>A group pattern allows users to add parentheses around patterns to emphasize the intended grouping. Otherwise, it has no additional syntax. Syntax:</p> <pre>
+<strong id="grammar-token-python-grammar-group_pattern"><span id="grammar-token-group-pattern"></span>group_pattern</strong> ::= "(" <a class="reference internal" href="#grammar-token-python-grammar-pattern">pattern</a> ")"
+</pre> <p>In simple terms <code>(P)</code> has the same effect as <code>P</code>.</p> </section> <section id="sequence-patterns"> <span id="id10"></span><h4>
+<span class="section-number">8.6.4.8. </span>Sequence Patterns</h4> <p>A sequence pattern contains several subpatterns to be matched against sequence elements. The syntax is similar to the unpacking of a list or tuple.</p> <pre>
+<strong id="grammar-token-python-grammar-sequence_pattern"><span id="grammar-token-sequence-pattern"></span>sequence_pattern </strong> ::= "[" [<a class="reference internal" href="#grammar-token-python-grammar-maybe_sequence_pattern">maybe_sequence_pattern</a>] "]"
+ | "(" [<a class="reference internal" href="#grammar-token-python-grammar-open_sequence_pattern">open_sequence_pattern</a>] ")"
+<strong id="grammar-token-python-grammar-open_sequence_pattern"><span id="grammar-token-open-sequence-pattern"></span>open_sequence_pattern </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-maybe_star_pattern">maybe_star_pattern</a> "," [<a class="reference internal" href="#grammar-token-python-grammar-maybe_sequence_pattern">maybe_sequence_pattern</a>]
+<strong id="grammar-token-python-grammar-maybe_sequence_pattern"><span id="grammar-token-maybe-sequence-pattern"></span>maybe_sequence_pattern</strong> ::= ",".<a class="reference internal" href="#grammar-token-python-grammar-maybe_star_pattern">maybe_star_pattern</a>+ ","?
+<strong id="grammar-token-python-grammar-maybe_star_pattern"><span id="grammar-token-maybe-star-pattern"></span>maybe_star_pattern </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-star_pattern">star_pattern</a> | <a class="reference internal" href="#grammar-token-python-grammar-pattern">pattern</a>
+<strong id="grammar-token-python-grammar-star_pattern"><span id="grammar-token-star-pattern"></span>star_pattern </strong> ::= "*" (<a class="reference internal" href="#grammar-token-python-grammar-capture_pattern">capture_pattern</a> | <a class="reference internal" href="#grammar-token-python-grammar-wildcard_pattern">wildcard_pattern</a>)
+</pre> <p>There is no difference if parentheses or square brackets are used for sequence patterns (i.e. <code>(...)</code> vs <code>[...]</code> ).</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>A single pattern enclosed in parentheses without a trailing comma (e.g. <code>(3 | 4)</code>) is a <a class="reference internal" href="#group-patterns"><span class="std std-ref">group pattern</span></a>. While a single pattern enclosed in square brackets (e.g. <code>[3 | 4]</code>) is still a sequence pattern.</p> </div> <p>At most one star subpattern may be in a sequence pattern. The star subpattern may occur in any position. If no star subpattern is present, the sequence pattern is a fixed-length sequence pattern; otherwise it is a variable-length sequence pattern.</p> <p>The following is the logical flow for matching a sequence pattern against a subject value:</p> <ol class="arabic"> <li>If the subject value is not a sequence <a class="footnote-reference brackets" href="#id21" id="id11">2</a>, the sequence pattern fails.</li> <li>If the subject value is an instance of <code>str</code>, <code>bytes</code> or <code>bytearray</code> the sequence pattern fails.</li> <li>
+<p>The subsequent steps depend on whether the sequence pattern is fixed or variable-length.</p> <p>If the sequence pattern is fixed-length:</p> <ol class="arabic simple"> <li>If the length of the subject sequence is not equal to the number of subpatterns, the sequence pattern fails</li> <li>Subpatterns in the sequence pattern are matched to their corresponding items in the subject sequence from left to right. Matching stops as soon as a subpattern fails. If all subpatterns succeed in matching their corresponding item, the sequence pattern succeeds.</li> </ol> <p>Otherwise, if the sequence pattern is variable-length:</p> <ol class="arabic simple"> <li>If the length of the subject sequence is less than the number of non-star subpatterns, the sequence pattern fails.</li> <li>The leading non-star subpatterns are matched to their corresponding items as for fixed-length sequences.</li> <li>If the previous step succeeds, the star subpattern matches a list formed of the remaining subject items, excluding the remaining items corresponding to non-star subpatterns following the star subpattern.</li> <li>Remaining non-star subpatterns are matched to their corresponding subject items, as for a fixed-length sequence.</li> </ol> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The length of the subject sequence is obtained via <a class="reference internal" href="../library/functions#len" title="len"><code>len()</code></a> (i.e. via the <code>__len__()</code> protocol). This length may be cached by the interpreter in a similar manner as <a class="reference internal" href="#value-patterns"><span class="std std-ref">value patterns</span></a>.</p> </div> </li> </ol> <p>In simple terms <code>[P1, P2, P3,</code> … <code>, P&lt;N&gt;]</code> matches only if all the following happens:</p> <ul class="simple"> <li>check <code>&lt;subject&gt;</code> is a sequence</li> <li><code>len(subject) == &lt;N&gt;</code></li> <li>
+<code>P1</code> matches <code>&lt;subject&gt;[0]</code> (note that this match can also bind names)</li> <li>
+<code>P2</code> matches <code>&lt;subject&gt;[1]</code> (note that this match can also bind names)</li> <li>… and so on for the corresponding pattern/element.</li> </ul> </section> <section id="mapping-patterns"> <span id="id12"></span><h4>
+<span class="section-number">8.6.4.9. </span>Mapping Patterns</h4> <p>A mapping pattern contains one or more key-value patterns. The syntax is similar to the construction of a dictionary. Syntax:</p> <pre>
+<strong id="grammar-token-python-grammar-mapping_pattern"><span id="grammar-token-mapping-pattern"></span>mapping_pattern </strong> ::= "{" [<a class="reference internal" href="#grammar-token-python-grammar-items_pattern">items_pattern</a>] "}"
+<strong id="grammar-token-python-grammar-items_pattern"><span id="grammar-token-items-pattern"></span>items_pattern </strong> ::= ",".<a class="reference internal" href="#grammar-token-python-grammar-key_value_pattern">key_value_pattern</a>+ ","?
+<strong id="grammar-token-python-grammar-key_value_pattern"><span id="grammar-token-key-value-pattern"></span>key_value_pattern </strong> ::= (<a class="reference internal" href="#grammar-token-python-grammar-literal_pattern">literal_pattern</a> | <a class="reference internal" href="#grammar-token-python-grammar-value_pattern">value_pattern</a>) ":" <a class="reference internal" href="#grammar-token-python-grammar-pattern">pattern</a>
+ | <a class="reference internal" href="#grammar-token-python-grammar-double_star_pattern">double_star_pattern</a>
+<strong id="grammar-token-python-grammar-double_star_pattern"><span id="grammar-token-double-star-pattern"></span>double_star_pattern</strong> ::= "**" <a class="reference internal" href="#grammar-token-python-grammar-capture_pattern">capture_pattern</a>
+</pre> <p>At most one double star pattern may be in a mapping pattern. The double star pattern must be the last subpattern in the mapping pattern.</p> <p>Duplicate keys in mapping patterns are disallowed. Duplicate literal keys will raise a <a class="reference internal" href="../library/exceptions#SyntaxError" title="SyntaxError"><code>SyntaxError</code></a>. Two keys that otherwise have the same value will raise a <a class="reference internal" href="../library/exceptions#ValueError" title="ValueError"><code>ValueError</code></a> at runtime.</p> <p>The following is the logical flow for matching a mapping pattern against a subject value:</p> <ol class="arabic simple"> <li>If the subject value is not a mapping <a class="footnote-reference brackets" href="#id22" id="id13">3</a>,the mapping pattern fails.</li> <li>If every key given in the mapping pattern is present in the subject mapping, and the pattern for each key matches the corresponding item of the subject mapping, the mapping pattern succeeds.</li> <li>If duplicate keys are detected in the mapping pattern, the pattern is considered invalid. A <a class="reference internal" href="../library/exceptions#SyntaxError" title="SyntaxError"><code>SyntaxError</code></a> is raised for duplicate literal values; or a <a class="reference internal" href="../library/exceptions#ValueError" title="ValueError"><code>ValueError</code></a> for named keys of the same value.</li> </ol> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Key-value pairs are matched using the two-argument form of the mapping subject’s <code>get()</code> method. Matched key-value pairs must already be present in the mapping, and not created on-the-fly via <code>__missing__()</code> or <a class="reference internal" href="datamodel#object.__getitem__" title="object.__getitem__"><code>__getitem__()</code></a>.</p> </div> <p>In simple terms <code>{KEY1: P1, KEY2: P2, ... }</code> matches only if all the following happens:</p> <ul class="simple"> <li>check <code>&lt;subject&gt;</code> is a mapping</li> <li><code>KEY1 in &lt;subject&gt;</code></li> <li>
+<code>P1</code> matches <code>&lt;subject&gt;[KEY1]</code>
+</li> <li>… and so on for the corresponding KEY/pattern pair.</li> </ul> </section> <section id="class-patterns"> <span id="id14"></span><h4>
+<span class="section-number">8.6.4.10. </span>Class Patterns</h4> <p>A class pattern represents a class and its positional and keyword arguments (if any). Syntax:</p> <pre>
+<strong id="grammar-token-python-grammar-class_pattern"><span id="grammar-token-class-pattern"></span>class_pattern </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-name_or_attr">name_or_attr</a> "(" [<a class="reference internal" href="#grammar-token-python-grammar-pattern_arguments">pattern_arguments</a> ","?] ")"
+<strong id="grammar-token-python-grammar-pattern_arguments"><span id="grammar-token-pattern-arguments"></span>pattern_arguments </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-positional_patterns">positional_patterns</a> ["," <a class="reference internal" href="#grammar-token-python-grammar-keyword_patterns">keyword_patterns</a>]
+ | <a class="reference internal" href="#grammar-token-python-grammar-keyword_patterns">keyword_patterns</a>
+<strong id="grammar-token-python-grammar-positional_patterns"><span id="grammar-token-positional-patterns"></span>positional_patterns</strong> ::= ",".<a class="reference internal" href="#grammar-token-python-grammar-pattern">pattern</a>+
+<strong id="grammar-token-python-grammar-keyword_patterns"><span id="grammar-token-keyword-patterns"></span>keyword_patterns </strong> ::= ",".<a class="reference internal" href="#grammar-token-python-grammar-keyword_pattern">keyword_pattern</a>+
+<strong id="grammar-token-python-grammar-keyword_pattern"><span id="grammar-token-keyword-pattern"></span>keyword_pattern </strong> ::= NAME "=" <a class="reference internal" href="#grammar-token-python-grammar-pattern">pattern</a>
+</pre> <p>The same keyword should not be repeated in class patterns.</p> <p>The following is the logical flow for matching a class pattern against a subject value:</p> <ol class="arabic"> <li>If <code>name_or_attr</code> is not an instance of the builtin <a class="reference internal" href="../library/functions#type" title="type"><code>type</code></a> , raise <a class="reference internal" href="../library/exceptions#TypeError" title="TypeError"><code>TypeError</code></a>.</li> <li>If the subject value is not an instance of <code>name_or_attr</code> (tested via <a class="reference internal" href="../library/functions#isinstance" title="isinstance"><code>isinstance()</code></a>), the class pattern fails.</li> <li>
+<p>If no pattern arguments are present, the pattern succeeds. Otherwise, the subsequent steps depend on whether keyword or positional argument patterns are present.</p> <p>For a number of built-in types (specified below), a single positional subpattern is accepted which will match the entire subject; for these types keyword patterns also work as for other types.</p> <p>If only keyword patterns are present, they are processed as follows, one by one:</p> <p>I. The keyword is looked up as an attribute on the subject.</p> <ul class="simple"> <li>If this raises an exception other than <a class="reference internal" href="../library/exceptions#AttributeError" title="AttributeError"><code>AttributeError</code></a>, the exception bubbles up.</li> <li>If this raises <a class="reference internal" href="../library/exceptions#AttributeError" title="AttributeError"><code>AttributeError</code></a>, the class pattern has failed.</li> <li>Else, the subpattern associated with the keyword pattern is matched against the subject’s attribute value. If this fails, the class pattern fails; if this succeeds, the match proceeds to the next keyword.</li> </ul> <p>II. If all keyword patterns succeed, the class pattern succeeds.</p> <p>If any positional patterns are present, they are converted to keyword patterns using the <a class="reference internal" href="datamodel#object.__match_args__" title="object.__match_args__"><code>__match_args__</code></a> attribute on the class <code>name_or_attr</code> before matching:</p> <p>I. The equivalent of <code>getattr(cls, "__match_args__", ())</code> is called.</p> <ul class="simple"> <li>If this raises an exception, the exception bubbles up.</li> <li>If the returned value is not a tuple, the conversion fails and <a class="reference internal" href="../library/exceptions#TypeError" title="TypeError"><code>TypeError</code></a> is raised.</li> <li>If there are more positional patterns than <code>len(cls.__match_args__)</code>, <a class="reference internal" href="../library/exceptions#TypeError" title="TypeError"><code>TypeError</code></a> is raised.</li> <li>Otherwise, positional pattern <code>i</code> is converted to a keyword pattern using <code>__match_args__[i]</code> as the keyword. <code>__match_args__[i]</code> must be a string; if not <a class="reference internal" href="../library/exceptions#TypeError" title="TypeError"><code>TypeError</code></a> is raised.</li> <li>If there are duplicate keywords, <a class="reference internal" href="../library/exceptions#TypeError" title="TypeError"><code>TypeError</code></a> is raised.</li> </ul> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p><a class="reference internal" href="datamodel#class-pattern-matching"><span class="std std-ref">Customizing positional arguments in class pattern matching</span></a></p> </div> <dl class="simple"> <dt>II. Once all positional patterns have been converted to keyword patterns,</dt>
+<dd>
+<p>the match proceeds as if there were only keyword patterns.</p> </dd> </dl> <p>For the following built-in types the handling of positional subpatterns is different:</p> <ul class="simple"> <li><a class="reference internal" href="../library/functions#bool" title="bool"><code>bool</code></a></li> <li><a class="reference internal" href="../library/stdtypes#bytearray" title="bytearray"><code>bytearray</code></a></li> <li><a class="reference internal" href="../library/stdtypes#bytes" title="bytes"><code>bytes</code></a></li> <li><a class="reference internal" href="../library/stdtypes#dict" title="dict"><code>dict</code></a></li> <li><a class="reference internal" href="../library/functions#float" title="float"><code>float</code></a></li> <li><a class="reference internal" href="../library/stdtypes#frozenset" title="frozenset"><code>frozenset</code></a></li> <li><a class="reference internal" href="../library/functions#int" title="int"><code>int</code></a></li> <li><a class="reference internal" href="../library/stdtypes#list" title="list"><code>list</code></a></li> <li><a class="reference internal" href="../library/stdtypes#set" title="set"><code>set</code></a></li> <li><a class="reference internal" href="../library/stdtypes#str" title="str"><code>str</code></a></li> <li><a class="reference internal" href="../library/stdtypes#tuple" title="tuple"><code>tuple</code></a></li> </ul> <p>These classes accept a single positional argument, and the pattern there is matched against the whole object rather than an attribute. For example <code>int(0|1)</code> matches the value <code>0</code>, but not the value <code>0.0</code>.</p> </li> </ol> <p>In simple terms <code>CLS(P1, attr=P2)</code> matches only if the following happens:</p> <ul class="simple"> <li><code>isinstance(&lt;subject&gt;, CLS)</code></li> <li>convert <code>P1</code> to a keyword pattern using <code>CLS.__match_args__</code>
+</li> <li>
+<p>For each keyword argument <code>attr=P2</code>:</p> <ul> <li><code>hasattr(&lt;subject&gt;, "attr")</code></li> <li>
+<code>P2</code> matches <code>&lt;subject&gt;.attr</code>
+</li> </ul> </li> <li>… and so on for the corresponding keyword argument/pattern pair.</li> </ul> <div class="admonition seealso"> <p class="admonition-title">See also</p> <ul class="simple"> <li>
+<span class="target" id="index-25"></span><a class="pep reference external" href="https://peps.python.org/pep-0634/"><strong>PEP 634</strong></a> – Structural Pattern Matching: Specification</li> <li>
+<span class="target" id="index-26"></span><a class="pep reference external" href="https://peps.python.org/pep-0636/"><strong>PEP 636</strong></a> – Structural Pattern Matching: Tutorial</li> </ul> </div> </section> </section> </section> <section id="function-definitions"> <span id="def"></span><span id="function"></span><span id="index-27"></span><h2>
+<span class="section-number">8.7. </span>Function definitions</h2> <p id="index-28">A function definition defines a user-defined function object (see section <a class="reference internal" href="datamodel#types"><span class="std std-ref">The standard type hierarchy</span></a>):</p> <pre>
+<strong id="grammar-token-python-grammar-funcdef"><span id="grammar-token-funcdef"></span>funcdef </strong> ::= [<a class="reference internal" href="#grammar-token-python-grammar-decorators">decorators</a>] "def" <a class="reference internal" href="#grammar-token-python-grammar-funcname">funcname</a> [<a class="reference internal" href="#grammar-token-python-grammar-type_params">type_params</a>] "(" [<a class="reference internal" href="#grammar-token-python-grammar-parameter_list">parameter_list</a>] ")"
+ ["-&gt;" <a class="reference internal" href="expressions#grammar-token-python-grammar-expression">expression</a>] ":" <a class="reference internal" href="#grammar-token-python-grammar-suite">suite</a>
+<strong id="grammar-token-python-grammar-decorators"><span id="grammar-token-decorators"></span>decorators </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-decorator">decorator</a>+
+<strong id="grammar-token-python-grammar-decorator"><span id="grammar-token-decorator"></span>decorator </strong> ::= "@" <a class="reference internal" href="expressions#grammar-token-python-grammar-assignment_expression">assignment_expression</a> NEWLINE
+<strong id="grammar-token-python-grammar-parameter_list"><span id="grammar-token-parameter-list"></span>parameter_list </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-defparameter">defparameter</a> ("," <a class="reference internal" href="#grammar-token-python-grammar-defparameter">defparameter</a>)* "," "/" ["," [<a class="reference internal" href="#grammar-token-python-grammar-parameter_list_no_posonly">parameter_list_no_posonly</a>]]
+ | <a class="reference internal" href="#grammar-token-python-grammar-parameter_list_no_posonly">parameter_list_no_posonly</a>
+<strong id="grammar-token-python-grammar-parameter_list_no_posonly"><span id="grammar-token-parameter-list-no-posonly"></span>parameter_list_no_posonly</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-defparameter">defparameter</a> ("," <a class="reference internal" href="#grammar-token-python-grammar-defparameter">defparameter</a>)* ["," [<a class="reference internal" href="#grammar-token-python-grammar-parameter_list_starargs">parameter_list_starargs</a>]]
+ | <a class="reference internal" href="#grammar-token-python-grammar-parameter_list_starargs">parameter_list_starargs</a>
+<strong id="grammar-token-python-grammar-parameter_list_starargs"><span id="grammar-token-parameter-list-starargs"></span>parameter_list_starargs </strong> ::= "*" [<a class="reference internal" href="#grammar-token-python-grammar-parameter">parameter</a>] ("," <a class="reference internal" href="#grammar-token-python-grammar-defparameter">defparameter</a>)* ["," ["**" <a class="reference internal" href="#grammar-token-python-grammar-parameter">parameter</a> [","]]]
+ | "**" <a class="reference internal" href="#grammar-token-python-grammar-parameter">parameter</a> [","]
+<strong id="grammar-token-python-grammar-parameter"><span id="grammar-token-parameter"></span>parameter </strong> ::= <a class="reference internal" href="lexical_analysis#grammar-token-python-grammar-identifier">identifier</a> [":" <a class="reference internal" href="expressions#grammar-token-python-grammar-expression">expression</a>]
+<strong id="grammar-token-python-grammar-defparameter"><span id="grammar-token-defparameter"></span>defparameter </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-parameter">parameter</a> ["=" <a class="reference internal" href="expressions#grammar-token-python-grammar-expression">expression</a>]
+<strong id="grammar-token-python-grammar-funcname"><span id="grammar-token-funcname"></span>funcname </strong> ::= <a class="reference internal" href="lexical_analysis#grammar-token-python-grammar-identifier">identifier</a>
+</pre> <p>A function definition is an executable statement. Its execution binds the function name in the current local namespace to a function object (a wrapper around the executable code for the function). This function object contains a reference to the current global namespace as the global namespace to be used when the function is called.</p> <p>The function definition does not execute the function body; this gets executed only when the function is called. <a class="footnote-reference brackets" href="#id23" id="id15">4</a></p> <p id="index-29">A function definition may be wrapped by one or more <a class="reference internal" href="../glossary#term-decorator"><span class="xref std std-term">decorator</span></a> expressions. Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition. The result must be a callable, which is invoked with the function object as the only argument. The returned value is bound to the function name instead of the function object. Multiple decorators are applied in nested fashion. For example, the following code</p> <pre data-language="python">@f1(arg)
+@f2
+def func(): pass
+</pre> <p>is roughly equivalent to</p> <pre data-language="python">def func(): pass
+func = f1(arg)(f2(func))
+</pre> <p>except that the original function is not temporarily bound to the name <code>func</code>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>Functions may be decorated with any valid <a class="reference internal" href="expressions#grammar-token-python-grammar-assignment_expression"><code>assignment_expression</code></a>. Previously, the grammar was much more restrictive; see <span class="target" id="index-30"></span><a class="pep reference external" href="https://peps.python.org/pep-0614/"><strong>PEP 614</strong></a> for details.</p> </div> <p>A list of <a class="reference internal" href="#type-params"><span class="std std-ref">type parameters</span></a> may be given in square brackets between the function’s name and the opening parenthesis for its parameter list. This indicates to static type checkers that the function is generic. At runtime, the type parameters can be retrieved from the function’s <a class="reference internal" href="datamodel#function.__type_params__" title="function.__type_params__"><code>__type_params__</code></a> attribute. See <a class="reference internal" href="#generic-functions"><span class="std std-ref">Generic functions</span></a> for more.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Type parameter lists are new in Python 3.12.</p> </div> <p id="index-31">When one or more <a class="reference internal" href="../glossary#term-parameter"><span class="xref std std-term">parameters</span></a> have the form <em>parameter</em> <code>=</code> <em>expression</em>, the function is said to have “default parameter values.” For a parameter with a default value, the corresponding <a class="reference internal" href="../glossary#term-argument"><span class="xref std std-term">argument</span></a> may be omitted from a call, in which case the parameter’s default value is substituted. If a parameter has a default value, all following parameters up until the “<code>*</code>” must also have a default value — this is a syntactic restriction that is not expressed by the grammar.</p> <p><strong>Default parameter values are evaluated from left to right when the function definition is executed.</strong> This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call. This is especially important to understand when a default parameter value is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default parameter value is in effect modified. This is generally not what was intended. A way around this is to use <code>None</code> as the default, and explicitly test for it in the body of the function, e.g.:</p> <pre data-language="python">def whats_on_the_telly(penguin=None):
+ if penguin is None:
+ penguin = []
+ penguin.append("property of the zoo")
+ return penguin
+</pre> <p id="index-32">Function call semantics are described in more detail in section <a class="reference internal" href="expressions#calls"><span class="std std-ref">Calls</span></a>. A function call always assigns values to all parameters mentioned in the parameter list, either from positional arguments, from keyword arguments, or from default values. If the form “<code>*identifier</code>” is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form “<code>**identifier</code>” is present, it is initialized to a new ordered mapping receiving any excess keyword arguments, defaulting to a new empty mapping of the same type. Parameters after “<code>*</code>” or “<code>*identifier</code>” are keyword-only parameters and may only be passed by keyword arguments. Parameters before “<code>/</code>” are positional-only parameters and may only be passed by positional arguments.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>The <code>/</code> function parameter syntax may be used to indicate positional-only parameters. See <span class="target" id="index-33"></span><a class="pep reference external" href="https://peps.python.org/pep-0570/"><strong>PEP 570</strong></a> for details.</p> </div> <p id="index-34">Parameters may have an <a class="reference internal" href="../glossary#term-function-annotation"><span class="xref std std-term">annotation</span></a> of the form “<code>: expression</code>” following the parameter name. Any parameter may have an annotation, even those of the form <code>*identifier</code> or <code>**identifier</code>. Functions may have “return” annotation of the form “<code>-&gt; expression</code>” after the parameter list. These annotations can be any valid Python expression. The presence of annotations does not change the semantics of a function. The annotation values are available as values of a dictionary keyed by the parameters’ names in the <code>__annotations__</code> attribute of the function object. If the <code>annotations</code> import from <a class="reference internal" href="../library/__future__#module-__future__" title="__future__: Future statement definitions"><code>__future__</code></a> is used, annotations are preserved as strings at runtime which enables postponed evaluation. Otherwise, they are evaluated when the function definition is executed. In this case annotations may be evaluated in a different order than they appear in the source code.</p> <p id="index-35">It is also possible to create anonymous functions (functions not bound to a name), for immediate use in expressions. This uses lambda expressions, described in section <a class="reference internal" href="expressions#lambda"><span class="std std-ref">Lambdas</span></a>. Note that the lambda expression is merely a shorthand for a simplified function definition; a function defined in a “<a class="reference internal" href="#def"><code>def</code></a>” statement can be passed around or assigned to another name just like a function defined by a lambda expression. The “<code>def</code>” form is actually more powerful since it allows the execution of multiple statements and annotations.</p> <p><strong>Programmer’s note:</strong> Functions are first-class objects. A “<code>def</code>” statement executed inside a function definition defines a local function that can be returned or passed around. Free variables used in the nested function can access the local variables of the function containing the def. See section <a class="reference internal" href="executionmodel#naming"><span class="std std-ref">Naming and binding</span></a> for details.</p> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt>
+<span class="target" id="index-36"></span><a class="pep reference external" href="https://peps.python.org/pep-3107/"><strong>PEP 3107</strong></a> - Function Annotations</dt>
+<dd>
+<p>The original specification for function annotations.</p> </dd> <dt>
+<span class="target" id="index-37"></span><a class="pep reference external" href="https://peps.python.org/pep-0484/"><strong>PEP 484</strong></a> - Type Hints</dt>
+<dd>
+<p>Definition of a standard meaning for annotations: type hints.</p> </dd> <dt>
+<span class="target" id="index-38"></span><a class="pep reference external" href="https://peps.python.org/pep-0526/"><strong>PEP 526</strong></a> - Syntax for Variable Annotations</dt>
+<dd>
+<p>Ability to type hint variable declarations, including class variables and instance variables.</p> </dd> <dt>
+<span class="target" id="index-39"></span><a class="pep reference external" href="https://peps.python.org/pep-0563/"><strong>PEP 563</strong></a> - Postponed Evaluation of Annotations</dt>
+<dd>
+<p>Support for forward references within annotations by preserving annotations in a string form at runtime instead of eager evaluation.</p> </dd> <dt>
+<span class="target" id="index-40"></span><a class="pep reference external" href="https://peps.python.org/pep-0318/"><strong>PEP 318</strong></a> - Decorators for Functions and Methods</dt>
+<dd>
+<p>Function and method decorators were introduced. Class decorators were introduced in <span class="target" id="index-41"></span><a class="pep reference external" href="https://peps.python.org/pep-3129/"><strong>PEP 3129</strong></a>.</p> </dd> </dl> </div> </section> <section id="class-definitions"> <span id="class"></span><h2>
+<span class="section-number">8.8. </span>Class definitions</h2> <p id="index-42">A class definition defines a class object (see section <a class="reference internal" href="datamodel#types"><span class="std std-ref">The standard type hierarchy</span></a>):</p> <pre>
+<strong id="grammar-token-python-grammar-classdef"><span id="grammar-token-classdef"></span>classdef </strong> ::= [<a class="reference internal" href="#grammar-token-python-grammar-decorators">decorators</a>] "class" <a class="reference internal" href="#grammar-token-python-grammar-classname">classname</a> [<a class="reference internal" href="#grammar-token-python-grammar-type_params">type_params</a>] [<a class="reference internal" href="#grammar-token-python-grammar-inheritance">inheritance</a>] ":" <a class="reference internal" href="#grammar-token-python-grammar-suite">suite</a>
+<strong id="grammar-token-python-grammar-inheritance"><span id="grammar-token-inheritance"></span>inheritance</strong> ::= "(" [<a class="reference internal" href="expressions#grammar-token-python-grammar-argument_list">argument_list</a>] ")"
+<strong id="grammar-token-python-grammar-classname"><span id="grammar-token-classname"></span>classname </strong> ::= <a class="reference internal" href="lexical_analysis#grammar-token-python-grammar-identifier">identifier</a>
+</pre> <p>A class definition is an executable statement. The inheritance list usually gives a list of base classes (see <a class="reference internal" href="datamodel#metaclasses"><span class="std std-ref">Metaclasses</span></a> for more advanced uses), so each item in the list should evaluate to a class object which allows subclassing. Classes without an inheritance list inherit, by default, from the base class <a class="reference internal" href="../library/functions#object" title="object"><code>object</code></a>; hence,</p> <pre data-language="python">class Foo:
+ pass
+</pre> <p>is equivalent to</p> <pre data-language="python">class Foo(object):
+ pass
+</pre> <p>The class’s suite is then executed in a new execution frame (see <a class="reference internal" href="executionmodel#naming"><span class="std std-ref">Naming and binding</span></a>), using a newly created local namespace and the original global namespace. (Usually, the suite contains mostly function definitions.) When the class’s suite finishes execution, its execution frame is discarded but its local namespace is saved. <a class="footnote-reference brackets" href="#id24" id="id16">5</a> A class object is then created using the inheritance list for the base classes and the saved local namespace for the attribute dictionary. The class name is bound to this class object in the original local namespace.</p> <p>The order in which attributes are defined in the class body is preserved in the new class’s <code>__dict__</code>. Note that this is reliable only right after the class is created and only for classes that were defined using the definition syntax.</p> <p>Class creation can be customized heavily using <a class="reference internal" href="datamodel#metaclasses"><span class="std std-ref">metaclasses</span></a>.</p> <p id="index-43">Classes can also be decorated: just like when decorating functions,</p> <pre data-language="python">@f1(arg)
+@f2
+class Foo: pass
+</pre> <p>is roughly equivalent to</p> <pre data-language="python">class Foo: pass
+Foo = f1(arg)(f2(Foo))
+</pre> <p>The evaluation rules for the decorator expressions are the same as for function decorators. The result is then bound to the class name.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>Classes may be decorated with any valid <a class="reference internal" href="expressions#grammar-token-python-grammar-assignment_expression"><code>assignment_expression</code></a>. Previously, the grammar was much more restrictive; see <span class="target" id="index-44"></span><a class="pep reference external" href="https://peps.python.org/pep-0614/"><strong>PEP 614</strong></a> for details.</p> </div> <p>A list of <a class="reference internal" href="#type-params"><span class="std std-ref">type parameters</span></a> may be given in square brackets immediately after the class’s name. This indicates to static type checkers that the class is generic. At runtime, the type parameters can be retrieved from the class’s <code>__type_params__</code> attribute. See <a class="reference internal" href="#generic-classes"><span class="std std-ref">Generic classes</span></a> for more.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Type parameter lists are new in Python 3.12.</p> </div> <p><strong>Programmer’s note:</strong> Variables defined in the class definition are class attributes; they are shared by instances. Instance attributes can be set in a method with <code>self.name = value</code>. Both class and instance attributes are accessible through the notation “<code>self.name</code>”, and an instance attribute hides a class attribute with the same name when accessed in this way. Class attributes can be used as defaults for instance attributes, but using mutable values there can lead to unexpected results. <a class="reference internal" href="datamodel#descriptors"><span class="std std-ref">Descriptors</span></a> can be used to create instance variables with different implementation details.</p> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt>
+<span class="target" id="index-45"></span><a class="pep reference external" href="https://peps.python.org/pep-3115/"><strong>PEP 3115</strong></a> - Metaclasses in Python 3000</dt>
+<dd>
+<p>The proposal that changed the declaration of metaclasses to the current syntax, and the semantics for how classes with metaclasses are constructed.</p> </dd> <dt>
+<span class="target" id="index-46"></span><a class="pep reference external" href="https://peps.python.org/pep-3129/"><strong>PEP 3129</strong></a> - Class Decorators</dt>
+<dd>
+<p>The proposal that added class decorators. Function and method decorators were introduced in <span class="target" id="index-47"></span><a class="pep reference external" href="https://peps.python.org/pep-0318/"><strong>PEP 318</strong></a>.</p> </dd> </dl> </div> </section> <section id="coroutines"> <span id="async"></span><h2>
+<span class="section-number">8.9. </span>Coroutines</h2> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> <section id="coroutine-function-definition"> <span id="async-def"></span><span id="index-48"></span><h3>
+<span class="section-number">8.9.1. </span>Coroutine function definition</h3> <pre>
+<strong id="grammar-token-python-grammar-async_funcdef"><span id="grammar-token-async-funcdef"></span>async_funcdef</strong> ::= [<a class="reference internal" href="#grammar-token-python-grammar-decorators">decorators</a>] "async" "def" <a class="reference internal" href="#grammar-token-python-grammar-funcname">funcname</a> "(" [<a class="reference internal" href="#grammar-token-python-grammar-parameter_list">parameter_list</a>] ")"
+ ["-&gt;" <a class="reference internal" href="expressions#grammar-token-python-grammar-expression">expression</a>] ":" <a class="reference internal" href="#grammar-token-python-grammar-suite">suite</a>
+</pre> <p id="index-49">Execution of Python coroutines can be suspended and resumed at many points (see <a class="reference internal" href="../glossary#term-coroutine"><span class="xref std std-term">coroutine</span></a>). <a class="reference internal" href="expressions#await"><code>await</code></a> expressions, <a class="reference internal" href="#async-for"><code>async for</code></a> and <a class="reference internal" href="#async-with"><code>async with</code></a> can only be used in the body of a coroutine function.</p> <p>Functions defined with <code>async def</code> syntax are always coroutine functions, even if they do not contain <code>await</code> or <code>async</code> keywords.</p> <p>It is a <a class="reference internal" href="../library/exceptions#SyntaxError" title="SyntaxError"><code>SyntaxError</code></a> to use a <code>yield from</code> expression inside the body of a coroutine function.</p> <p>An example of a coroutine function:</p> <pre data-language="python">async def func(param1, param2):
+ do_stuff()
+ await some_coroutine()
+</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span><code>await</code> and <code>async</code> are now keywords; previously they were only treated as such inside the body of a coroutine function.</p> </div> </section> <section id="the-async-for-statement"> <span id="async-for"></span><span id="index-50"></span><h3>
+<span class="section-number">8.9.2. </span>The <code>async for</code> statement</h3> <pre>
+<strong id="grammar-token-python-grammar-async_for_stmt"><span id="grammar-token-async-for-stmt"></span>async_for_stmt</strong> ::= "async" <a class="reference internal" href="#grammar-token-python-grammar-for_stmt">for_stmt</a>
+</pre> <p>An <a class="reference internal" href="../glossary#term-asynchronous-iterable"><span class="xref std std-term">asynchronous iterable</span></a> provides an <code>__aiter__</code> method that directly returns an <a class="reference internal" href="../glossary#term-asynchronous-iterator"><span class="xref std std-term">asynchronous iterator</span></a>, which can call asynchronous code in its <code>__anext__</code> method.</p> <p>The <code>async for</code> statement allows convenient iteration over asynchronous iterables.</p> <p>The following code:</p> <pre data-language="python">async for TARGET in ITER:
+ SUITE
+else:
+ SUITE2
+</pre> <p>Is semantically equivalent to:</p> <pre data-language="python">iter = (ITER)
+iter = type(iter).__aiter__(iter)
+running = True
+
+while running:
+ try:
+ TARGET = await type(iter).__anext__(iter)
+ except StopAsyncIteration:
+ running = False
+ else:
+ SUITE
+else:
+ SUITE2
+</pre> <p>See also <a class="reference internal" href="datamodel#object.__aiter__" title="object.__aiter__"><code>__aiter__()</code></a> and <a class="reference internal" href="datamodel#object.__anext__" title="object.__anext__"><code>__anext__()</code></a> for details.</p> <p>It is a <a class="reference internal" href="../library/exceptions#SyntaxError" title="SyntaxError"><code>SyntaxError</code></a> to use an <code>async for</code> statement outside the body of a coroutine function.</p> </section> <section id="the-async-with-statement"> <span id="async-with"></span><span id="index-51"></span><h3>
+<span class="section-number">8.9.3. </span>The <code>async with</code> statement</h3> <pre>
+<strong id="grammar-token-python-grammar-async_with_stmt"><span id="grammar-token-async-with-stmt"></span>async_with_stmt</strong> ::= "async" <a class="reference internal" href="#grammar-token-python-grammar-with_stmt">with_stmt</a>
+</pre> <p>An <a class="reference internal" href="../glossary#term-asynchronous-context-manager"><span class="xref std std-term">asynchronous context manager</span></a> is a <a class="reference internal" href="../glossary#term-context-manager"><span class="xref std std-term">context manager</span></a> that is able to suspend execution in its <em>enter</em> and <em>exit</em> methods.</p> <p>The following code:</p> <pre data-language="python">async with EXPRESSION as TARGET:
+ SUITE
+</pre> <p>is semantically equivalent to:</p> <pre data-language="python">manager = (EXPRESSION)
+aenter = type(manager).__aenter__
+aexit = type(manager).__aexit__
+value = await aenter(manager)
+hit_except = False
+
+try:
+ TARGET = value
+ SUITE
+except:
+ hit_except = True
+ if not await aexit(manager, *sys.exc_info()):
+ raise
+finally:
+ if not hit_except:
+ await aexit(manager, None, None, None)
+</pre> <p>See also <a class="reference internal" href="datamodel#object.__aenter__" title="object.__aenter__"><code>__aenter__()</code></a> and <a class="reference internal" href="datamodel#object.__aexit__" title="object.__aexit__"><code>__aexit__()</code></a> for details.</p> <p>It is a <a class="reference internal" href="../library/exceptions#SyntaxError" title="SyntaxError"><code>SyntaxError</code></a> to use an <code>async with</code> statement outside the body of a coroutine function.</p> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt>
+<span class="target" id="index-52"></span><a class="pep reference external" href="https://peps.python.org/pep-0492/"><strong>PEP 492</strong></a> - Coroutines with async and await syntax</dt>
+<dd>
+<p>The proposal that made coroutines a proper standalone concept in Python, and added supporting syntax.</p> </dd> </dl> </div> </section> </section> <section id="type-parameter-lists"> <span id="type-params"></span><h2>
+<span class="section-number">8.10. </span>Type parameter lists</h2> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> <pre id="index-53">
+<strong id="grammar-token-python-grammar-type_params"><span id="grammar-token-type-params"></span>type_params </strong> ::= "[" <a class="reference internal" href="#grammar-token-python-grammar-type_param">type_param</a> ("," <a class="reference internal" href="#grammar-token-python-grammar-type_param">type_param</a>)* "]"
+<strong id="grammar-token-python-grammar-type_param"><span id="grammar-token-type-param"></span>type_param </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-typevar">typevar</a> | <a class="reference internal" href="#grammar-token-python-grammar-typevartuple">typevartuple</a> | <a class="reference internal" href="#grammar-token-python-grammar-paramspec">paramspec</a>
+<strong id="grammar-token-python-grammar-typevar"><span id="grammar-token-typevar"></span>typevar </strong> ::= <a class="reference internal" href="lexical_analysis#grammar-token-python-grammar-identifier">identifier</a> (":" <a class="reference internal" href="expressions#grammar-token-python-grammar-expression">expression</a>)?
+<strong id="grammar-token-python-grammar-typevartuple"><span id="grammar-token-typevartuple"></span>typevartuple</strong> ::= "*" <a class="reference internal" href="lexical_analysis#grammar-token-python-grammar-identifier">identifier</a>
+<strong id="grammar-token-python-grammar-paramspec"><span id="grammar-token-paramspec"></span>paramspec </strong> ::= "**" <a class="reference internal" href="lexical_analysis#grammar-token-python-grammar-identifier">identifier</a>
+</pre> <p><a class="reference internal" href="#def"><span class="std std-ref">Functions</span></a> (including <a class="reference internal" href="#async-def"><span class="std std-ref">coroutines</span></a>), <a class="reference internal" href="#class"><span class="std std-ref">classes</span></a> and <a class="reference internal" href="simple_stmts#type"><span class="std std-ref">type aliases</span></a> may contain a type parameter list:</p> <pre data-language="python">def max[T](args: list[T]) -&gt; T:
+ ...
+
+async def amax[T](args: list[T]) -&gt; T:
+ ...
+
+class Bag[T]:
+ def __iter__(self) -&gt; Iterator[T]:
+ ...
+
+ def add(self, arg: T) -&gt; None:
+ ...
+
+type ListOrSet[T] = list[T] | set[T]
+</pre> <p>Semantically, this indicates that the function, class, or type alias is generic over a type variable. This information is primarily used by static type checkers, and at runtime, generic objects behave much like their non-generic counterparts.</p> <p>Type parameters are declared in square brackets (<code>[]</code>) immediately after the name of the function, class, or type alias. The type parameters are accessible within the scope of the generic object, but not elsewhere. Thus, after a declaration <code>def func[T](): pass</code>, the name <code>T</code> is not available in the module scope. Below, the semantics of generic objects are described with more precision. The scope of type parameters is modeled with a special function (technically, an <a class="reference internal" href="executionmodel#annotation-scopes"><span class="std std-ref">annotation scope</span></a>) that wraps the creation of the generic object.</p> <p>Generic functions, classes, and type aliases have a <code>__type_params__</code> attribute listing their type parameters.</p> <p>Type parameters come in three kinds:</p> <ul class="simple"> <li>
+<a class="reference internal" href="../library/typing#typing.TypeVar" title="typing.TypeVar"><code>typing.TypeVar</code></a>, introduced by a plain name (e.g., <code>T</code>). Semantically, this represents a single type to a type checker.</li> <li>
+<a class="reference internal" href="../library/typing#typing.TypeVarTuple" title="typing.TypeVarTuple"><code>typing.TypeVarTuple</code></a>, introduced by a name prefixed with a single asterisk (e.g., <code>*Ts</code>). Semantically, this stands for a tuple of any number of types.</li> <li>
+<a class="reference internal" href="../library/typing#typing.ParamSpec" title="typing.ParamSpec"><code>typing.ParamSpec</code></a>, introduced by a name prefixed with two asterisks (e.g., <code>**P</code>). Semantically, this stands for the parameters of a callable.</li> </ul> <p><a class="reference internal" href="../library/typing#typing.TypeVar" title="typing.TypeVar"><code>typing.TypeVar</code></a> declarations can define <em>bounds</em> and <em>constraints</em> with a colon (<code>:</code>) followed by an expression. A single expression after the colon indicates a bound (e.g. <code>T: int</code>). Semantically, this means that the <code>typing.TypeVar</code> can only represent types that are a subtype of this bound. A parenthesized tuple of expressions after the colon indicates a set of constraints (e.g. <code>T: (str, bytes)</code>). Each member of the tuple should be a type (again, this is not enforced at runtime). Constrained type variables can only take on one of the types in the list of constraints.</p> <p>For <code>typing.TypeVar</code>s declared using the type parameter list syntax, the bound and constraints are not evaluated when the generic object is created, but only when the value is explicitly accessed through the attributes <code>__bound__</code> and <code>__constraints__</code>. To accomplish this, the bounds or constraints are evaluated in a separate <a class="reference internal" href="executionmodel#annotation-scopes"><span class="std std-ref">annotation scope</span></a>.</p> <p><a class="reference internal" href="../library/typing#typing.TypeVarTuple" title="typing.TypeVarTuple"><code>typing.TypeVarTuple</code></a>s and <a class="reference internal" href="../library/typing#typing.ParamSpec" title="typing.ParamSpec"><code>typing.ParamSpec</code></a>s cannot have bounds or constraints.</p> <p>The following example indicates the full set of allowed type parameter declarations:</p> <pre data-language="python">def overly_generic[
+ SimpleTypeVar,
+ TypeVarWithBound: int,
+ TypeVarWithConstraints: (str, bytes),
+ *SimpleTypeVarTuple,
+ **SimpleParamSpec,
+](
+ a: SimpleTypeVar,
+ b: TypeVarWithBound,
+ c: Callable[SimpleParamSpec, TypeVarWithConstraints],
+ *d: SimpleTypeVarTuple,
+): ...
+</pre> <section id="generic-functions"> <span id="id17"></span><h3>
+<span class="section-number">8.10.1. </span>Generic functions</h3> <p>Generic functions are declared as follows:</p> <pre data-language="python">def func[T](arg: T): ...
+</pre> <p>This syntax is equivalent to:</p> <pre data-language="python">annotation-def TYPE_PARAMS_OF_func():
+ T = typing.TypeVar("T")
+ def func(arg: T): ...
+ func.__type_params__ = (T,)
+ return func
+func = TYPE_PARAMS_OF_func()
+</pre> <p>Here <code>annotation-def</code> indicates an <a class="reference internal" href="executionmodel#annotation-scopes"><span class="std std-ref">annotation scope</span></a>, which is not actually bound to any name at runtime. (One other liberty is taken in the translation: the syntax does not go through attribute access on the <a class="reference internal" href="../library/typing#module-typing" title="typing: Support for type hints (see :pep:`484`)."><code>typing</code></a> module, but creates an instance of <a class="reference internal" href="../library/typing#typing.TypeVar" title="typing.TypeVar"><code>typing.TypeVar</code></a> directly.)</p> <p>The annotations of generic functions are evaluated within the annotation scope used for declaring the type parameters, but the function’s defaults and decorators are not.</p> <p>The following example illustrates the scoping rules for these cases, as well as for additional flavors of type parameters:</p> <pre data-language="python">@decorator
+def func[T: int, *Ts, **P](*args: *Ts, arg: Callable[P, T] = some_default):
+ ...
+</pre> <p>Except for the <a class="reference internal" href="executionmodel#lazy-evaluation"><span class="std std-ref">lazy evaluation</span></a> of the <a class="reference internal" href="../library/typing#typing.TypeVar" title="typing.TypeVar"><code>TypeVar</code></a> bound, this is equivalent to:</p> <pre data-language="python">DEFAULT_OF_arg = some_default
+
+annotation-def TYPE_PARAMS_OF_func():
+
+ annotation-def BOUND_OF_T():
+ return int
+ # In reality, BOUND_OF_T() is evaluated only on demand.
+ T = typing.TypeVar("T", bound=BOUND_OF_T())
+
+ Ts = typing.TypeVarTuple("Ts")
+ P = typing.ParamSpec("P")
+
+ def func(*args: *Ts, arg: Callable[P, T] = DEFAULT_OF_arg):
+ ...
+
+ func.__type_params__ = (T, Ts, P)
+ return func
+func = decorator(TYPE_PARAMS_OF_func())
+</pre> <p>The capitalized names like <code>DEFAULT_OF_arg</code> are not actually bound at runtime.</p> </section> <section id="generic-classes"> <span id="id18"></span><h3>
+<span class="section-number">8.10.2. </span>Generic classes</h3> <p>Generic classes are declared as follows:</p> <pre data-language="python">class Bag[T]: ...
+</pre> <p>This syntax is equivalent to:</p> <pre data-language="python">annotation-def TYPE_PARAMS_OF_Bag():
+ T = typing.TypeVar("T")
+ class Bag(typing.Generic[T]):
+ __type_params__ = (T,)
+ ...
+ return Bag
+Bag = TYPE_PARAMS_OF_Bag()
+</pre> <p>Here again <code>annotation-def</code> (not a real keyword) indicates an <a class="reference internal" href="executionmodel#annotation-scopes"><span class="std std-ref">annotation scope</span></a>, and the name <code>TYPE_PARAMS_OF_Bag</code> is not actually bound at runtime.</p> <p>Generic classes implicitly inherit from <a class="reference internal" href="../library/typing#typing.Generic" title="typing.Generic"><code>typing.Generic</code></a>. The base classes and keyword arguments of generic classes are evaluated within the type scope for the type parameters, and decorators are evaluated outside that scope. This is illustrated by this example:</p> <pre data-language="python">@decorator
+class Bag(Base[T], arg=T): ...
+</pre> <p>This is equivalent to:</p> <pre data-language="python">annotation-def TYPE_PARAMS_OF_Bag():
+ T = typing.TypeVar("T")
+ class Bag(Base[T], typing.Generic[T], arg=T):
+ __type_params__ = (T,)
+ ...
+ return Bag
+Bag = decorator(TYPE_PARAMS_OF_Bag())
+</pre> </section> <section id="generic-type-aliases"> <span id="id19"></span><h3>
+<span class="section-number">8.10.3. </span>Generic type aliases</h3> <p>The <a class="reference internal" href="simple_stmts#type"><code>type</code></a> statement can also be used to create a generic type alias:</p> <pre data-language="python">type ListOrSet[T] = list[T] | set[T]
+</pre> <p>Except for the <a class="reference internal" href="executionmodel#lazy-evaluation"><span class="std std-ref">lazy evaluation</span></a> of the value, this is equivalent to:</p> <pre data-language="python">annotation-def TYPE_PARAMS_OF_ListOrSet():
+ T = typing.TypeVar("T")
+
+ annotation-def VALUE_OF_ListOrSet():
+ return list[T] | set[T]
+ # In reality, the value is lazily evaluated
+ return typing.TypeAliasType("ListOrSet", VALUE_OF_ListOrSet(), type_params=(T,))
+ListOrSet = TYPE_PARAMS_OF_ListOrSet()
+</pre> <p>Here, <code>annotation-def</code> (not a real keyword) indicates an <a class="reference internal" href="executionmodel#annotation-scopes"><span class="std std-ref">annotation scope</span></a>. The capitalized names like <code>TYPE_PARAMS_OF_ListOrSet</code> are not actually bound at runtime.</p> <h4 class="rubric">Footnotes</h4> <dl class="footnote brackets"> <dt class="label" id="id20">
+<code>1</code> </dt> <dd>
+<p>The exception is propagated to the invocation stack unless there is a <a class="reference internal" href="#finally"><code>finally</code></a> clause which happens to raise another exception. That new exception causes the old one to be lost.</p> </dd> <dt class="label" id="id21">
+<code>2</code> </dt> <dd>
+<p>In pattern matching, a sequence is defined as one of the following:</p> <ul class="simple"> <li>a class that inherits from <a class="reference internal" href="../library/collections.abc#collections.abc.Sequence" title="collections.abc.Sequence"><code>collections.abc.Sequence</code></a>
+</li> <li>a Python class that has been registered as <a class="reference internal" href="../library/collections.abc#collections.abc.Sequence" title="collections.abc.Sequence"><code>collections.abc.Sequence</code></a>
+</li> <li>a builtin class that has its (CPython) <a class="reference internal" href="../c-api/typeobj#c.Py_TPFLAGS_SEQUENCE" title="Py_TPFLAGS_SEQUENCE"><code>Py_TPFLAGS_SEQUENCE</code></a> bit set</li> <li>a class that inherits from any of the above</li> </ul> <p>The following standard library classes are sequences:</p> <ul class="simple"> <li><a class="reference internal" href="../library/array#array.array" title="array.array"><code>array.array</code></a></li> <li><a class="reference internal" href="../library/collections#collections.deque" title="collections.deque"><code>collections.deque</code></a></li> <li><a class="reference internal" href="../library/stdtypes#list" title="list"><code>list</code></a></li> <li><a class="reference internal" href="../library/stdtypes#memoryview" title="memoryview"><code>memoryview</code></a></li> <li><a class="reference internal" href="../library/stdtypes#range" title="range"><code>range</code></a></li> <li><a class="reference internal" href="../library/stdtypes#tuple" title="tuple"><code>tuple</code></a></li> </ul> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Subject values of type <code>str</code>, <code>bytes</code>, and <code>bytearray</code> do not match sequence patterns.</p> </div> </dd> <dt class="label" id="id22">
+<code>3</code> </dt> <dd>
+<p>In pattern matching, a mapping is defined as one of the following:</p> <ul class="simple"> <li>a class that inherits from <a class="reference internal" href="../library/collections.abc#collections.abc.Mapping" title="collections.abc.Mapping"><code>collections.abc.Mapping</code></a>
+</li> <li>a Python class that has been registered as <a class="reference internal" href="../library/collections.abc#collections.abc.Mapping" title="collections.abc.Mapping"><code>collections.abc.Mapping</code></a>
+</li> <li>a builtin class that has its (CPython) <a class="reference internal" href="../c-api/typeobj#c.Py_TPFLAGS_MAPPING" title="Py_TPFLAGS_MAPPING"><code>Py_TPFLAGS_MAPPING</code></a> bit set</li> <li>a class that inherits from any of the above</li> </ul> <p>The standard library classes <a class="reference internal" href="../library/stdtypes#dict" title="dict"><code>dict</code></a> and <a class="reference internal" href="../library/types#types.MappingProxyType" title="types.MappingProxyType"><code>types.MappingProxyType</code></a> are mappings.</p> </dd> <dt class="label" id="id23">
+<code>4</code> </dt> <dd>
+<p>A string literal appearing as the first statement in the function body is transformed into the function’s <a class="reference internal" href="datamodel#function.__doc__" title="function.__doc__"><code>__doc__</code></a> attribute and therefore the function’s <a class="reference internal" href="../glossary#term-docstring"><span class="xref std std-term">docstring</span></a>.</p> </dd> <dt class="label" id="id24">
+<code>5</code> </dt> <dd>
+<p>A string literal appearing as the first statement in the class body is transformed into the namespace’s <code>__doc__</code> item and therefore the class’s <a class="reference internal" href="../glossary#term-docstring"><span class="xref std std-term">docstring</span></a>.</p> </dd> </dl> </section> </section> <div class="_attribution">
+ <p class="_attribution-p">
+ &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
+ <a href="https://docs.python.org/3.12/reference/compound_stmts.html" class="_attribution-link">https://docs.python.org/3.12/reference/compound_stmts.html</a>
+ </p>
+</div>