View file File name : compound_stmts.html Content : <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" /> <title>8. Compound statements — Python 3.10.12 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?2022.1" /> <script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/doctools.js"></script> <script src="../_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 3.10.12 documentation" href="../_static/opensearch.xml"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="next" title="9. Top-level components" href="toplevel_components.html" /> <link rel="prev" title="7. Simple statements" href="simple_stmts.html" /> <link rel="canonical" href="file:///usr/share/doc/python3.10/html/reference/compound_stmts.html" /> <style> @media only screen { table.full-width-table { width: 100%; } } </style> <link rel="shortcut icon" type="image/png" href="../_static/py.svg" /> <script type="text/javascript" src="../_static/copybutton.js"></script> <script type="text/javascript" src="../_static/menu.js"></script> </head> <body> <div class="mobile-nav"> <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation" aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" /> <label for="menuToggler" class="toggler__label"> <span></span> </label> <nav class="nav-content" role="navigation"> <a href="https://www.python.org/" class="nav-logo"> <img src="../_static/py.svg" alt="Logo"/> </a> <div class="version_switcher_placeholder"></div> <form role="search" class="search" action="../search.html" method="get"> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon"> <path fill-rule="nonzero" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z" fill="#444"></path> </svg> <input type="text" name="q" aria-label="Quick search"/> <input type="submit" value="Go"/> </form> </nav> <div class="menu-wrapper"> <nav class="menu" role="navigation" aria-label="main navigation"> <div class="language_switcher_placeholder"></div> <h3><a href="../contents.html">Table of Contents</a></h3> <ul> <li><a class="reference internal" href="#">8. Compound statements</a><ul> <li><a class="reference internal" href="#the-if-statement">8.1. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code> statement</a></li> <li><a class="reference internal" href="#the-while-statement">8.2. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code> statement</a></li> <li><a class="reference internal" href="#the-for-statement">8.3. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> statement</a></li> <li><a class="reference internal" href="#the-try-statement">8.4. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> statement</a></li> <li><a class="reference internal" href="#the-with-statement">8.5. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> statement</a></li> <li><a class="reference internal" href="#the-match-statement">8.6. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">match</span></code> statement</a><ul> <li><a class="reference internal" href="#overview">8.6.1. Overview</a></li> <li><a class="reference internal" href="#guards">8.6.2. Guards</a></li> <li><a class="reference internal" href="#irrefutable-case-blocks">8.6.3. Irrefutable Case Blocks</a></li> <li><a class="reference internal" href="#patterns">8.6.4. Patterns</a><ul> <li><a class="reference internal" href="#or-patterns">8.6.4.1. OR Patterns</a></li> <li><a class="reference internal" href="#as-patterns">8.6.4.2. AS Patterns</a></li> <li><a class="reference internal" href="#literal-patterns">8.6.4.3. Literal Patterns</a></li> <li><a class="reference internal" href="#capture-patterns">8.6.4.4. Capture Patterns</a></li> <li><a class="reference internal" href="#wildcard-patterns">8.6.4.5. Wildcard Patterns</a></li> <li><a class="reference internal" href="#value-patterns">8.6.4.6. Value Patterns</a></li> <li><a class="reference internal" href="#group-patterns">8.6.4.7. Group Patterns</a></li> <li><a class="reference internal" href="#sequence-patterns">8.6.4.8. Sequence Patterns</a></li> <li><a class="reference internal" href="#mapping-patterns">8.6.4.9. Mapping Patterns</a></li> <li><a class="reference internal" href="#class-patterns">8.6.4.10. Class Patterns</a></li> </ul> </li> </ul> </li> <li><a class="reference internal" href="#function-definitions">8.7. Function definitions</a></li> <li><a class="reference internal" href="#class-definitions">8.8. Class definitions</a></li> <li><a class="reference internal" href="#coroutines">8.9. Coroutines</a><ul> <li><a class="reference internal" href="#coroutine-function-definition">8.9.1. Coroutine function definition</a></li> <li><a class="reference internal" href="#the-async-for-statement">8.9.2. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code> statement</a></li> <li><a class="reference internal" href="#the-async-with-statement">8.9.3. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code> statement</a></li> </ul> </li> </ul> </li> </ul> <h4>Previous topic</h4> <p class="topless"><a href="simple_stmts.html" title="previous chapter"><span class="section-number">7. </span>Simple statements</a></p> <h4>Next topic</h4> <p class="topless"><a href="toplevel_components.html" title="next chapter"><span class="section-number">9. </span>Top-level components</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a Bug</a></li> <li> <a href="https://github.com/python/cpython/blob/3.10/Doc/reference/compound_stmts.rst" rel="nofollow">Show Source </a> </li> </ul> </div> </nav> </div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="toplevel_components.html" title="9. Top-level components" accesskey="N">next</a> |</li> <li class="right" > <a href="simple_stmts.html" title="7. Simple statements" accesskey="P">previous</a> |</li> <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.10.12 Documentation</a> » </li> <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> »</li> <li class="nav-item nav-item-this"><a href=""><span class="section-number">8. </span>Compound statements</a></li> <li class="right"> <div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> | </li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <section id="compound-statements"> <span id="compound"></span><h1><span class="section-number">8. </span>Compound statements<a class="headerlink" href="#compound-statements" title="Permalink to this headline">¶</a></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 class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a>, <a class="reference internal" href="#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a> and <a class="reference internal" href="#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> statements implement traditional control flow constructs. <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> specifies exception handlers and/or cleanup code for a group of statements, while the <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></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 class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> clause a following <a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> clause would belong:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">test1</span><span class="p">:</span> <span class="k">if</span> <span class="n">test2</span><span class="p">:</span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> </pre></div> </div> <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.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> calls are executed:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">x</span> <span class="o"><</span> <span class="n">y</span> <span class="o"><</span> <span class="n">z</span><span class="p">:</span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">);</span> <span class="nb">print</span><span class="p">(</span><span class="n">y</span><span class="p">);</span> <span class="nb">print</span><span class="p">(</span><span class="n">z</span><span class="p">)</span> </pre></div> </div> <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"><code class="xref docutils literal notranslate"><span class="pre">if_stmt</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-while_stmt"><code class="xref docutils literal notranslate"><span class="pre">while_stmt</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-for_stmt"><code class="xref docutils literal notranslate"><span class="pre">for_stmt</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-try_stmt"><code class="xref docutils literal notranslate"><span class="pre">try_stmt</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-with_stmt"><code class="xref docutils literal notranslate"><span class="pre">with_stmt</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-match_stmt"><code class="xref docutils literal notranslate"><span class="pre">match_stmt</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-funcdef"><code class="xref docutils literal notranslate"><span class="pre">funcdef</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-classdef"><code class="xref docutils literal notranslate"><span class="pre">classdef</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-async_with_stmt"><code class="xref docutils literal notranslate"><span class="pre">async_with_stmt</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-async_for_stmt"><code class="xref docutils literal notranslate"><span class="pre">async_for_stmt</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-async_funcdef"><code class="xref docutils literal notranslate"><span class="pre">async_funcdef</span></code></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"><code class="xref docutils literal notranslate"><span class="pre">stmt_list</span></code></a> NEWLINE | NEWLINE INDENT <a class="reference internal" href="#grammar-token-python-grammar-statement"><code class="xref docutils literal notranslate"><span class="pre">statement</span></code></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"><code class="xref docutils literal notranslate"><span class="pre">stmt_list</span></code></a> NEWLINE | <a class="reference internal" href="#grammar-token-python-grammar-compound_stmt"><code class="xref docutils literal notranslate"><span class="pre">compound_stmt</span></code></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.html#grammar-token-python-grammar-simple_stmt"><code class="xref docutils literal notranslate"><span class="pre">simple_stmt</span></code></a> (";" <a class="reference internal" href="simple_stmts.html#grammar-token-python-grammar-simple_stmt"><code class="xref docutils literal notranslate"><span class="pre">simple_stmt</span></code></a>)* [";"] </pre> <p id="index-2">Note that statements always end in a <code class="docutils literal notranslate"><span class="pre">NEWLINE</span></code> possibly followed by a <code class="docutils literal notranslate"><span class="pre">DEDENT</span></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 class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a>’ problem is solved in Python by requiring nested <a class="reference internal" href="#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></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 class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code> statement<a class="headerlink" href="#the-if-statement" title="Permalink to this headline">¶</a></h2> <p id="index-3">The <a class="reference internal" href="#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></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.html#grammar-token-python-grammar-assignment_expression"><code class="xref docutils literal notranslate"><span class="pre">assignment_expression</span></code></a> ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a> ("elif" <a class="reference internal" href="expressions.html#grammar-token-python-grammar-assignment_expression"><code class="xref docutils literal notranslate"><span class="pre">assignment_expression</span></code></a> ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>)* ["else" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></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.html#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 class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement is executed or evaluated). If all expressions are false, the suite of the <a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></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 class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code> statement<a class="headerlink" href="#the-while-statement" title="Permalink to this headline">¶</a></h2> <p id="index-4">The <a class="reference internal" href="#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></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.html#grammar-token-python-grammar-assignment_expression"><code class="xref docutils literal notranslate"><span class="pre">assignment_expression</span></code></a> ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a> ["else" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></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 class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause, if present, is executed and the loop terminates.</p> <p id="index-5">A <a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> statement executed in the first suite terminates the loop without executing the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause’s suite. A <a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></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 class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> statement<a class="headerlink" href="#the-for-statement" title="Permalink to this headline">¶</a></h2> <p id="index-6">The <a class="reference internal" href="#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></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.html#grammar-token-python-grammar-target_list"><code class="xref docutils literal notranslate"><span class="pre">target_list</span></code></a> "in" <a class="reference internal" href="expressions.html#grammar-token-python-grammar-expression_list"><code class="xref docutils literal notranslate"><span class="pre">expression_list</span></code></a> ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a> ["else" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>] </pre> <p>The expression list is evaluated once; it should yield an iterable object. An iterator is created for the result of the <code class="docutils literal notranslate"><span class="pre">expression_list</span></code>. The suite is then executed once for each item provided by the iterator, in the order returned by the iterator. Each item in turn is assigned to the target list using the standard rules for assignments (see <a class="reference internal" href="simple_stmts.html#assignment"><span class="std std-ref">Assignment statements</span></a>), and then the suite is executed. When the items are exhausted (which is immediately when the sequence is empty or an iterator raises a <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> exception), the suite in the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause, if present, is executed, and the loop terminates.</p> <p id="index-7">A <a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> statement executed in the first suite terminates the loop without executing the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause’s suite. A <a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> statement executed in the first suite skips the rest of the suite and continues with the next item, or with the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></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> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span> <span class="nb">print</span><span class="p">(</span><span class="n">i</span><span class="p">)</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">5</span> <span class="c1"># this will not affect the for-loop</span> <span class="c1"># because i will be overwritten with the next</span> <span class="c1"># index in the range</span> </pre></div> </div> <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.html#range" title="range"><code class="xref py py-func docutils literal notranslate"><span class="pre">range()</span></code></a> represents immutable arithmetic sequences of integers. For instance, iterating <code class="docutils literal notranslate"><span class="pre">range(3)</span></code> successively yields 0, 1, and then 2.</p> </section> <section id="the-try-statement"> <span id="finally"></span><span id="except"></span><span id="try"></span><h2><span class="section-number">8.4. </span>The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> statement<a class="headerlink" href="#the-try-statement" title="Permalink to this headline">¶</a></h2> <p id="index-9">The <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> 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"><code class="xref docutils literal notranslate"><span class="pre">try1_stmt</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-try2_stmt"><code class="xref docutils literal notranslate"><span class="pre">try2_stmt</span></code></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"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a> ("except" [<a class="reference internal" href="expressions.html#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> ["as" <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>]] ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>)+ ["else" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>] ["finally" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></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"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a> "finally" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a> </pre> <p>The <a class="reference internal" href="#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> clause(s) specify one or more exception handlers. When no exception occurs in the <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> clause, no exception handler is executed. When an exception occurs in the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> suite, a search for an exception handler is started. This search inspects the except clauses in turn until one is found that matches the exception. An expression-less except clause, if present, must be last; it matches any exception. For an except 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.html#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 except 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="#id16" id="id1">1</a></p> <p>If the evaluation of an expression in the header of an except 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 class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement raised the exception).</p> <p id="index-10">When a matching except clause is found, the exception is assigned to the target specified after the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code> keyword in that except clause, if present, and the except clause’s suite is executed. All except clauses must have an executable block. When the end of this block is reached, execution continues normally after the entire try statement. (This means that if two nested handlers exist for the same exception, and the exception occurs in the try clause of the inner handler, the outer handler will not handle the exception.)</p> <p>When an exception has been assigned using <code class="docutils literal notranslate"><span class="pre">as</span> <span class="pre">target</span></code>, it is cleared at the end of the except clause. This is as if</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">except</span> <span class="n">E</span> <span class="k">as</span> <span class="n">N</span><span class="p">:</span> <span class="n">foo</span> </pre></div> </div> <p>was translated to</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">except</span> <span class="n">E</span> <span class="k">as</span> <span class="n">N</span><span class="p">:</span> <span class="k">try</span><span class="p">:</span> <span class="n">foo</span> <span class="k">finally</span><span class="p">:</span> <span class="k">del</span> <span class="n">N</span> </pre></div> </div> <p>This means the exception must be assigned to a different name to be able to refer to it after the except 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 except clause’s suite is executed, details about the exception are stored in the <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> module and can be accessed via <a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>. <a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a> returns a 3-tuple consisting of the exception class, the exception instance and a traceback object (see section <a class="reference internal" href="datamodel.html#types"><span class="std std-ref">The standard type hierarchy</span></a>) identifying the point in the program where the exception occurred. The details about the exception accessed via <a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a> are restored to their previous values when leaving an exception handler:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">exc_info</span><span class="p">())</span> <span class="go">(None, None, None)</span> <span class="gp">>>> </span><span class="k">try</span><span class="p">:</span> <span class="gp">... </span> <span class="k">raise</span> <span class="ne">TypeError</span> <span class="gp">... </span><span class="k">except</span><span class="p">:</span> <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">exc_info</span><span class="p">())</span> <span class="gp">... </span> <span class="k">try</span><span class="p">:</span> <span class="gp">... </span> <span class="k">raise</span> <span class="ne">ValueError</span> <span class="gp">... </span> <span class="k">except</span><span class="p">:</span> <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">exc_info</span><span class="p">())</span> <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">exc_info</span><span class="p">())</span> <span class="gp">...</span> <span class="go">(<class 'TypeError'>, TypeError(), <traceback object at 0x10efad080>)</span> <span class="go">(<class 'ValueError'>, ValueError(), <traceback object at 0x10efad040>)</span> <span class="go">(<class 'TypeError'>, TypeError(), <traceback object at 0x10efad080>)</span> <span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">exc_info</span><span class="p">())</span> <span class="go">(None, None, None)</span> </pre></div> </div> <p id="index-12">The optional <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause is executed if the control flow leaves the <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> suite, no exception was raised, and no <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a>, <a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a>, or <a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> statement was executed. Exceptions in the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause are not handled by the preceding <a class="reference internal" href="#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> clauses.</p> <p id="index-13">If <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> is present, it specifies a ‘cleanup’ handler. The <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> clause is executed, including any <a class="reference internal" href="#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> and <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause is executed. If there is a saved exception it is re-raised at the end of the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause. If the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause raises another exception, the saved exception is set as the context of the new exception. If the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause executes a <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a>, <a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> or <a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> statement, the saved exception is discarded:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span> <span class="nf">f</span><span class="p">():</span> <span class="gp">... </span> <span class="k">try</span><span class="p">:</span> <span class="gp">... </span> <span class="mi">1</span><span class="o">/</span><span class="mi">0</span> <span class="gp">... </span> <span class="k">finally</span><span class="p">:</span> <span class="gp">... </span> <span class="k">return</span> <span class="mi">42</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">f</span><span class="p">()</span> <span class="go">42</span> </pre></div> </div> <p>The exception information is not available to the program during execution of the <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause.</p> <p id="index-14">When a <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a>, <a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> or <a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> statement is executed in the <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> suite of a <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code>…<code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> statement, the <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> 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.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement executed. Since the <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause always executes, a <code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code> statement executed in the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause will always be the last one executed:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span> <span class="nf">foo</span><span class="p">():</span> <span class="gp">... </span> <span class="k">try</span><span class="p">:</span> <span class="gp">... </span> <span class="k">return</span> <span class="s1">'try'</span> <span class="gp">... </span> <span class="k">finally</span><span class="p">:</span> <span class="gp">... </span> <span class="k">return</span> <span class="s1">'finally'</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">foo</span><span class="p">()</span> <span class="go">'finally'</span> </pre></div> </div> <p>Additional information on exceptions can be found in section <a class="reference internal" href="executionmodel.html#exceptions"><span class="std std-ref">Exceptions</span></a>, and information on using the <a class="reference internal" href="simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> statement to generate exceptions may be found in section <a class="reference internal" href="simple_stmts.html#raise"><span class="std std-ref">The raise statement</span></a>.</p> <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.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> statement was illegal in the <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause due to a problem with the implementation.</p> </div> </section> <section id="the-with-statement"> <span id="as"></span><span id="with"></span><h2><span class="section-number">8.5. </span>The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> statement<a class="headerlink" href="#the-with-statement" title="Permalink to this headline">¶</a></h2> <p id="index-15">The <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></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.html#context-managers"><span class="std std-ref">With Statement Context Managers</span></a>). This allows common <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>…<a class="reference internal" href="#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a>…<a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></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"><code class="xref docutils literal notranslate"><span class="pre">with_stmt_contents</span></code></a> ","? ")" | <a class="reference internal" href="#grammar-token-python-grammar-with_stmt_contents"><code class="xref docutils literal notranslate"><span class="pre">with_stmt_contents</span></code></a> ) ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></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"><code class="xref docutils literal notranslate"><span class="pre">with_item</span></code></a> ("," <a class="reference internal" href="#grammar-token-python-grammar-with_item"><code class="xref docutils literal notranslate"><span class="pre">with_item</span></code></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.html#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> ["as" <a class="reference internal" href="simple_stmts.html#grammar-token-python-grammar-target"><code class="xref docutils literal notranslate"><span class="pre">target</span></code></a>] </pre> <p>The execution of the <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement with one “item” proceeds as follows:</p> <ol class="arabic"> <li><p>The context expression (the expression given in the <a class="reference internal" href="#grammar-token-python-grammar-with_item"><code class="xref std std-token docutils literal notranslate"><span class="pre">with_item</span></code></a>) is evaluated to obtain a context manager.</p></li> <li><p>The context manager’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code> is loaded for later use.</p></li> <li><p>The context manager’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code> is loaded for later use.</p></li> <li><p>The context manager’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code> method is invoked.</p></li> <li><p>If a target was included in the <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement, the return value from <code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code> is assigned to it.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement guarantees that if the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code> method returns without an error, then <code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code> 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><p>The suite is executed.</p></li> <li><p>The context manager’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code> method is invoked. If an exception caused the suite to be exited, its type, value, and traceback are passed as arguments to <code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code>. Otherwise, three <a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> arguments are supplied.</p> <p>If the suite was exited due to an exception, and the return value from the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code> 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 class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement.</p> <p>If the suite was exited for any reason other than an exception, the return value from <code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code> 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> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">EXPRESSION</span> <span class="k">as</span> <span class="n">TARGET</span><span class="p">:</span> <span class="n">SUITE</span> </pre></div> </div> <p>is semantically equivalent to:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">manager</span> <span class="o">=</span> <span class="p">(</span><span class="n">EXPRESSION</span><span class="p">)</span> <span class="n">enter</span> <span class="o">=</span> <span class="nb">type</span><span class="p">(</span><span class="n">manager</span><span class="p">)</span><span class="o">.</span><span class="fm">__enter__</span> <span class="n">exit</span> <span class="o">=</span> <span class="nb">type</span><span class="p">(</span><span class="n">manager</span><span class="p">)</span><span class="o">.</span><span class="fm">__exit__</span> <span class="n">value</span> <span class="o">=</span> <span class="n">enter</span><span class="p">(</span><span class="n">manager</span><span class="p">)</span> <span class="n">hit_except</span> <span class="o">=</span> <span class="kc">False</span> <span class="k">try</span><span class="p">:</span> <span class="n">TARGET</span> <span class="o">=</span> <span class="n">value</span> <span class="n">SUITE</span> <span class="k">except</span><span class="p">:</span> <span class="n">hit_except</span> <span class="o">=</span> <span class="kc">True</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">exit</span><span class="p">(</span><span class="n">manager</span><span class="p">,</span> <span class="o">*</span><span class="n">sys</span><span class="o">.</span><span class="n">exc_info</span><span class="p">()):</span> <span class="k">raise</span> <span class="k">finally</span><span class="p">:</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">hit_except</span><span class="p">:</span> <span class="n">exit</span><span class="p">(</span><span class="n">manager</span><span class="p">,</span> <span class="kc">None</span><span class="p">,</span> <span class="kc">None</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span> </pre></div> </div> <p>With more than one item, the context managers are processed as if multiple <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statements were nested:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">A</span><span class="p">()</span> <span class="k">as</span> <span class="n">a</span><span class="p">,</span> <span class="n">B</span><span class="p">()</span> <span class="k">as</span> <span class="n">b</span><span class="p">:</span> <span class="n">SUITE</span> </pre></div> </div> <p>is semantically equivalent to:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">A</span><span class="p">()</span> <span class="k">as</span> <span class="n">a</span><span class="p">:</span> <span class="k">with</span> <span class="n">B</span><span class="p">()</span> <span class="k">as</span> <span class="n">b</span><span class="p">:</span> <span class="n">SUITE</span> </pre></div> </div> <p>You can also write multi-item context managers in multiple lines if the items are surrounded by parentheses. For example:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="p">(</span> <span class="n">A</span><span class="p">()</span> <span class="k">as</span> <span class="n">a</span><span class="p">,</span> <span class="n">B</span><span class="p">()</span> <span class="k">as</span> <span class="n">b</span><span class="p">,</span> <span class="p">):</span> <span class="n">SUITE</span> </pre></div> </div> <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-16"></span><a class="pep reference external" href="https://www.python.org/dev/peps/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 class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></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 class="xref std std-keyword docutils literal notranslate"><span class="pre">match</span></code> statement<a class="headerlink" href="#the-match-statement" title="Permalink to this headline">¶</a></h2> <div class="versionadded" id="index-17"> <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"><code class="xref docutils literal notranslate"><span class="pre">subject_expr</span></code></a> ":" NEWLINE INDENT <a class="reference internal" href="#grammar-token-python-grammar-case_block"><code class="xref docutils literal notranslate"><span class="pre">case_block</span></code></a>+ DEDENT <strong id="grammar-token-python-grammar-subject_expr"><span id="grammar-token-subject-expr"></span>subject_expr</strong> ::= <code class="xref docutils literal notranslate"><span class="pre">star_named_expression</span></code> "," <code class="xref docutils literal notranslate"><span class="pre">star_named_expressions</span></code>? | <code class="xref docutils literal notranslate"><span class="pre">named_expression</span></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"><code class="xref docutils literal notranslate"><span class="pre">patterns</span></code></a> [<a class="reference internal" href="#grammar-token-python-grammar-guard"><code class="xref docutils literal notranslate"><span class="pre">guard</span></code></a>] ":" <code class="xref docutils literal notranslate"><span class="pre">block</span></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.html#soft-keywords"><span class="std std-ref">soft keywords</span></a>.</p> </div> <p>Pattern matching takes a pattern as input (following <code class="docutils literal notranslate"><span class="pre">case</span></code>) and a subject value (following <code class="docutils literal notranslate"><span class="pre">match</span></code>). The pattern (which may contain subpatterns) is matched against the subject value. The outcomes are:</p> <ul class="simple"> <li><p>A match success or failure (also termed a pattern success or failure).</p></li> <li><p>Possible binding of matched values to a name. The prerequisites for this are further discussed below.</p></li> </ul> <p>The <code class="docutils literal notranslate"><span class="pre">match</span></code> and <code class="docutils literal notranslate"><span class="pre">case</span></code> keywords are <a class="reference internal" href="lexical_analysis.html#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><p><span class="target" id="index-18"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0634"><strong>PEP 634</strong></a> – Structural Pattern Matching: Specification</p></li> <li><p><span class="target" id="index-19"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0636"><strong>PEP 636</strong></a> – Structural Pattern Matching: Tutorial</p></li> </ul> </div> <section id="overview"> <h3><span class="section-number">8.6.1. </span>Overview<a class="headerlink" href="#overview" title="Permalink to this headline">¶</a></h3> <p>Here’s an overview of the logical flow of a match statement:</p> <ol class="arabic"> <li><p>The subject expression <code class="docutils literal notranslate"><span class="pre">subject_expr</span></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.html#typesseq-tuple"><span class="std std-ref">the standard rules</span></a>.</p></li> <li><p>Each pattern in a <code class="docutils literal notranslate"><span class="pre">case_block</span></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> <blockquote> <div><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> </div></blockquote> </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><p>If the guard evaluates as true or is missing, the <code class="docutils literal notranslate"><span class="pre">block</span></code> inside <code class="docutils literal notranslate"><span class="pre">case_block</span></code> is executed.</p></li> <li><p>Otherwise, the next <code class="docutils literal notranslate"><span class="pre">case_block</span></code> is attempted as described above.</p></li> <li><p>If there are no further case blocks, the match statement is completed.</p></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> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">flag</span> <span class="o">=</span> <span class="kc">False</span> <span class="gp">>>> </span><span class="k">match</span> <span class="p">(</span><span class="mi">100</span><span class="p">,</span> <span class="mi">200</span><span class="p">):</span> <span class="gp">... </span> <span class="k">case</span> <span class="p">(</span><span class="mi">100</span><span class="p">,</span> <span class="mi">300</span><span class="p">):</span> <span class="c1"># Mismatch: 200 != 300</span> <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">'Case 1'</span><span class="p">)</span> <span class="gp">... </span> <span class="k">case</span> <span class="p">(</span><span class="mi">100</span><span class="p">,</span> <span class="mi">200</span><span class="p">)</span> <span class="k">if</span> <span class="n">flag</span><span class="p">:</span> <span class="c1"># Successful match, but guard fails</span> <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">'Case 2'</span><span class="p">)</span> <span class="gp">... </span> <span class="k">case</span> <span class="p">(</span><span class="mi">100</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span> <span class="c1"># Matches and binds y to 200</span> <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'Case 3, y: </span><span class="si">{</span><span class="n">y</span><span class="si">}</span><span class="s1">'</span><span class="p">)</span> <span class="gp">... </span> <span class="k">case</span> <span class="k">_</span><span class="p">:</span> <span class="c1"># Pattern not attempted</span> <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">'Case 4, I match anything!'</span><span class="p">)</span> <span class="gp">...</span> <span class="go">Case 3, y: 200</span> </pre></div> </div> <p>In this case, <code class="docutils literal notranslate"><span class="pre">if</span> <span class="pre">flag</span></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<a class="headerlink" href="#guards" title="Permalink to this headline">¶</a></h3> <pre id="index-20"> <strong id="grammar-token-python-grammar-guard"><span id="grammar-token-guard"></span>guard</strong> ::= "if" <code class="xref docutils literal notranslate"><span class="pre">named_expression</span></code> </pre> <p>A <code class="docutils literal notranslate"><span class="pre">guard</span></code> (which is part of the <code class="docutils literal notranslate"><span class="pre">case</span></code>) must succeed for code inside the <code class="docutils literal notranslate"><span class="pre">case</span></code> block to execute. It takes the form: <a class="reference internal" href="#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> followed by an expression.</p> <p>The logical flow of a <code class="docutils literal notranslate"><span class="pre">case</span></code> block with a <code class="docutils literal notranslate"><span class="pre">guard</span></code> follows:</p> <ol class="arabic simple"> <li><p>Check that the pattern in the <code class="docutils literal notranslate"><span class="pre">case</span></code> block succeeded. If the pattern failed, the <code class="docutils literal notranslate"><span class="pre">guard</span></code> is not evaluated and the next <code class="docutils literal notranslate"><span class="pre">case</span></code> block is checked.</p></li> <li><p>If the pattern succeeded, evaluate the <code class="docutils literal notranslate"><span class="pre">guard</span></code>.</p> <ul class="simple"> <li><p>If the <code class="docutils literal notranslate"><span class="pre">guard</span></code> condition evaluates as true, the case block is selected.</p></li> <li><p>If the <code class="docutils literal notranslate"><span class="pre">guard</span></code> condition evaluates as false, the case block is not selected.</p></li> <li><p>If the <code class="docutils literal notranslate"><span class="pre">guard</span></code> raises an exception during evaluation, the exception bubbles up.</p></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<a class="headerlink" href="#irrefutable-case-blocks" title="Permalink to this headline">¶</a></h3> <p id="index-21">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><p><a class="reference internal" href="#as-patterns"><span class="std std-ref">AS Patterns</span></a> whose left-hand side is irrefutable</p></li> <li><p><a class="reference internal" href="#or-patterns"><span class="std std-ref">OR Patterns</span></a> containing at least one irrefutable pattern</p></li> <li><p><a class="reference internal" href="#capture-patterns"><span class="std std-ref">Capture Patterns</span></a></p></li> <li><p><a class="reference internal" href="#wildcard-patterns"><span class="std std-ref">Wildcard Patterns</span></a></p></li> <li><p>parenthesized irrefutable patterns</p></li> </ul> </section> <section id="patterns"> <h3><span class="section-number">8.6.4. </span>Patterns<a class="headerlink" href="#patterns" title="Permalink to this headline">¶</a></h3> <div class="admonition note" id="index-22"> <p class="admonition-title">Note</p> <p>This section uses grammar notations beyond standard EBNF:</p> <ul class="simple"> <li><p>the notation <code class="docutils literal notranslate"><span class="pre">SEP.RULE+</span></code> is shorthand for <code class="docutils literal notranslate"><span class="pre">RULE</span> <span class="pre">(SEP</span> <span class="pre">RULE)*</span></code></p></li> <li><p>the notation <code class="docutils literal notranslate"><span class="pre">!RULE</span></code> is shorthand for a negative lookahead assertion</p></li> </ul> </div> <p>The top-level syntax for <code class="docutils literal notranslate"><span class="pre">patterns</span></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"><code class="xref docutils literal notranslate"><span class="pre">open_sequence_pattern</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-pattern"><code class="xref docutils literal notranslate"><span class="pre">pattern</span></code></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"><code class="xref docutils literal notranslate"><span class="pre">as_pattern</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-or_pattern"><code class="xref docutils literal notranslate"><span class="pre">or_pattern</span></code></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"><code class="xref docutils literal notranslate"><span class="pre">literal_pattern</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-capture_pattern"><code class="xref docutils literal notranslate"><span class="pre">capture_pattern</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-wildcard_pattern"><code class="xref docutils literal notranslate"><span class="pre">wildcard_pattern</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-value_pattern"><code class="xref docutils literal notranslate"><span class="pre">value_pattern</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-group_pattern"><code class="xref docutils literal notranslate"><span class="pre">group_pattern</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-sequence_pattern"><code class="xref docutils literal notranslate"><span class="pre">sequence_pattern</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-mapping_pattern"><code class="xref docutils literal notranslate"><span class="pre">mapping_pattern</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-class_pattern"><code class="xref docutils literal notranslate"><span class="pre">class_pattern</span></code></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="id2"></span><h4><span class="section-number">8.6.4.1. </span>OR Patterns<a class="headerlink" href="#or-patterns" title="Permalink to this headline">¶</a></h4> <p>An OR pattern is two or more patterns separated by vertical bars <code class="docutils literal notranslate"><span class="pre">|</span></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"><code class="xref docutils literal notranslate"><span class="pre">closed_pattern</span></code></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 class="docutils literal notranslate"><span class="pre">P1</span> <span class="pre">|</span> <span class="pre">P2</span> <span class="pre">|</span> <span class="pre">...</span></code> will try to match <code class="docutils literal notranslate"><span class="pre">P1</span></code>, if it fails it will try to match <code class="docutils literal notranslate"><span class="pre">P2</span></code>, succeeding immediately if any succeeds, failing otherwise.</p> </section> <section id="as-patterns"> <span id="id3"></span><h4><span class="section-number">8.6.4.2. </span>AS Patterns<a class="headerlink" href="#as-patterns" title="Permalink to this headline">¶</a></h4> <p>An AS pattern matches an OR pattern on the left of the <a class="reference internal" href="#as"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></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"><code class="xref docutils literal notranslate"><span class="pre">or_pattern</span></code></a> "as" <a class="reference internal" href="#grammar-token-python-grammar-capture_pattern"><code class="xref docutils literal notranslate"><span class="pre">capture_pattern</span></code></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 class="docutils literal notranslate"><span class="pre">capture_pattern</span></code> cannot be a <code class="docutils literal notranslate"><span class="pre">_</span></code>.</p> <p>In simple terms <code class="docutils literal notranslate"><span class="pre">P</span> <span class="pre">as</span> <span class="pre">NAME</span></code> will match with <code class="docutils literal notranslate"><span class="pre">P</span></code>, and on success it will set <code class="docutils literal notranslate"><span class="pre">NAME</span> <span class="pre">=</span> <span class="pre"><subject></span></code>.</p> </section> <section id="literal-patterns"> <span id="id4"></span><h4><span class="section-number">8.6.4.3. </span>Literal Patterns<a class="headerlink" href="#literal-patterns" title="Permalink to this headline">¶</a></h4> <p>A literal pattern corresponds to most <a class="reference internal" href="lexical_analysis.html#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 class="xref docutils literal notranslate"><span class="pre">signed_number</span></code> | <code class="xref docutils literal notranslate"><span class="pre">signed_number</span></code> "+" NUMBER | <code class="xref docutils literal notranslate"><span class="pre">signed_number</span></code> "-" NUMBER | <code class="xref docutils literal notranslate"><span class="pre">strings</span></code> | "None" | "True" | "False" | <code class="xref docutils literal notranslate"><span class="pre">signed_number</span></code>: NUMBER | "-" NUMBER </pre> <p>The rule <code class="docutils literal notranslate"><span class="pre">strings</span></code> and the token <code class="docutils literal notranslate"><span class="pre">NUMBER</span></code> are defined in the <a class="reference internal" href="grammar.html"><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.html#f-strings"><span class="std std-ref">Formatted string literals</span></a> are not supported.</p> <p>The forms <code class="docutils literal notranslate"><span class="pre">signed_number</span> <span class="pre">'+'</span> <span class="pre">NUMBER</span></code> and <code class="docutils literal notranslate"><span class="pre">signed_number</span> <span class="pre">'-'</span> <span class="pre">NUMBER</span></code> are for expressing <a class="reference internal" href="lexical_analysis.html#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 class="docutils literal notranslate"><span class="pre">3</span> <span class="pre">+</span> <span class="pre">4j</span></code>.</p> <p>In simple terms, <code class="docutils literal notranslate"><span class="pre">LITERAL</span></code> will succeed only if <code class="docutils literal notranslate"><span class="pre"><subject></span> <span class="pre">==</span> <span class="pre">LITERAL</span></code>. For the singletons <code class="docutils literal notranslate"><span class="pre">None</span></code>, <code class="docutils literal notranslate"><span class="pre">True</span></code> and <code class="docutils literal notranslate"><span class="pre">False</span></code>, the <a class="reference internal" href="expressions.html#is"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">is</span></code></a> operator is used.</p> </section> <section id="capture-patterns"> <span id="id5"></span><h4><span class="section-number">8.6.4.4. </span>Capture Patterns<a class="headerlink" href="#capture-patterns" title="Permalink to this headline">¶</a></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 class="docutils literal notranslate"><span class="pre">_</span></code> is not a capture pattern (this is what <code class="docutils literal notranslate"><span class="pre">!'_'</span></code> expresses). It is instead treated as a <a class="reference internal" href="#grammar-token-python-grammar-wildcard_pattern"><code class="xref std std-token docutils literal notranslate"><span class="pre">wildcard_pattern</span></code></a>.</p> <p>In a given pattern, a given name can only be bound once. E.g. <code class="docutils literal notranslate"><span class="pre">case</span> <span class="pre">x,</span> <span class="pre">x:</span> <span class="pre">...</span></code> is invalid while <code class="docutils literal notranslate"><span class="pre">case</span> <span class="pre">[x]</span> <span class="pre">|</span> <span class="pre">x:</span> <span class="pre">...</span></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-23"></span><a class="pep reference external" href="https://www.python.org/dev/peps/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.html#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> or <a class="reference internal" href="simple_stmts.html#nonlocal"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">nonlocal</span></code></a> statement.</p> <p>In simple terms <code class="docutils literal notranslate"><span class="pre">NAME</span></code> will always succeed and it will set <code class="docutils literal notranslate"><span class="pre">NAME</span> <span class="pre">=</span> <span class="pre"><subject></span></code>.</p> </section> <section id="wildcard-patterns"> <span id="id6"></span><h4><span class="section-number">8.6.4.5. </span>Wildcard Patterns<a class="headerlink" href="#wildcard-patterns" title="Permalink to this headline">¶</a></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 class="docutils literal notranslate"><span class="pre">_</span></code> is a <a class="reference internal" href="lexical_analysis.html#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 class="docutils literal notranslate"><span class="pre">match</span></code> subject expressions, <code class="docutils literal notranslate"><span class="pre">guard</span></code>s, and <code class="docutils literal notranslate"><span class="pre">case</span></code> blocks.</p> <p>In simple terms, <code class="docutils literal notranslate"><span class="pre">_</span></code> will always succeed.</p> </section> <section id="value-patterns"> <span id="id7"></span><h4><span class="section-number">8.6.4.6. </span>Value Patterns<a class="headerlink" href="#value-patterns" title="Permalink to this headline">¶</a></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"><code class="xref docutils literal notranslate"><span class="pre">attr</span></code></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"><code class="xref docutils literal notranslate"><span class="pre">name_or_attr</span></code></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"><code class="xref docutils literal notranslate"><span class="pre">attr</span></code></a> | NAME </pre> <p>The dotted name in the pattern is looked up using standard Python <a class="reference internal" href="executionmodel.html#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 class="docutils literal notranslate"><span class="pre">==</span></code> equality operator).</p> <p>In simple terms <code class="docutils literal notranslate"><span class="pre">NAME1.NAME2</span></code> will succeed only if <code class="docutils literal notranslate"><span class="pre"><subject></span> <span class="pre">==</span> <span class="pre">NAME1.NAME2</span></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="id8"></span><h4><span class="section-number">8.6.4.7. </span>Group Patterns<a class="headerlink" href="#group-patterns" title="Permalink to this headline">¶</a></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"><code class="xref docutils literal notranslate"><span class="pre">pattern</span></code></a> ")" </pre> <p>In simple terms <code class="docutils literal notranslate"><span class="pre">(P)</span></code> has the same effect as <code class="docutils literal notranslate"><span class="pre">P</span></code>.</p> </section> <section id="sequence-patterns"> <span id="id9"></span><h4><span class="section-number">8.6.4.8. </span>Sequence Patterns<a class="headerlink" href="#sequence-patterns" title="Permalink to this headline">¶</a></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"><code class="xref docutils literal notranslate"><span class="pre">maybe_sequence_pattern</span></code></a>] "]" | "(" [<a class="reference internal" href="#grammar-token-python-grammar-open_sequence_pattern"><code class="xref docutils literal notranslate"><span class="pre">open_sequence_pattern</span></code></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"><code class="xref docutils literal notranslate"><span class="pre">maybe_star_pattern</span></code></a> "," [<a class="reference internal" href="#grammar-token-python-grammar-maybe_sequence_pattern"><code class="xref docutils literal notranslate"><span class="pre">maybe_sequence_pattern</span></code></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"><code class="xref docutils literal notranslate"><span class="pre">maybe_star_pattern</span></code></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"><code class="xref docutils literal notranslate"><span class="pre">star_pattern</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-pattern"><code class="xref docutils literal notranslate"><span class="pre">pattern</span></code></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"><code class="xref docutils literal notranslate"><span class="pre">capture_pattern</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-wildcard_pattern"><code class="xref docutils literal notranslate"><span class="pre">wildcard_pattern</span></code></a>) </pre> <p>There is no difference if parentheses or square brackets are used for sequence patterns (i.e. <code class="docutils literal notranslate"><span class="pre">(...)</span></code> vs <code class="docutils literal notranslate"><span class="pre">[...]</span></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 class="docutils literal notranslate"><span class="pre">(3</span> <span class="pre">|</span> <span class="pre">4)</span></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 class="docutils literal notranslate"><span class="pre">[3</span> <span class="pre">|</span> <span class="pre">4]</span></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><p>If the subject value is not a sequence <a class="footnote-reference brackets" href="#id17" id="id10">2</a>, the sequence pattern fails.</p></li> <li><p>If the subject value is an instance of <code class="docutils literal notranslate"><span class="pre">str</span></code>, <code class="docutils literal notranslate"><span class="pre">bytes</span></code> or <code class="docutils literal notranslate"><span class="pre">bytearray</span></code> the sequence pattern fails.</p></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><p>If the length of the subject sequence is not equal to the number of subpatterns, the sequence pattern fails</p></li> <li><p>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.</p></li> </ol> <p>Otherwise, if the sequence pattern is variable-length:</p> <ol class="arabic simple"> <li><p>If the length of the subject sequence is less than the number of non-star subpatterns, the sequence pattern fails.</p></li> <li><p>The leading non-star subpatterns are matched to their corresponding items as for fixed-length sequences.</p></li> <li><p>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.</p></li> <li><p>Remaining non-star subpatterns are matched to their corresponding subject items, as for a fixed-length sequence.</p></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.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a> (i.e. via the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></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 class="docutils literal notranslate"><span class="pre">[P1,</span> <span class="pre">P2,</span> <span class="pre">P3,</span></code> … <code class="docutils literal notranslate"><span class="pre">,</span> <span class="pre">P<N>]</span></code> matches only if all the following happens:</p> <ul class="simple"> <li><p>check <code class="docutils literal notranslate"><span class="pre"><subject></span></code> is a sequence</p></li> <li><p><code class="docutils literal notranslate"><span class="pre">len(subject)</span> <span class="pre">==</span> <span class="pre"><N></span></code></p></li> <li><p><code class="docutils literal notranslate"><span class="pre">P1</span></code> matches <code class="docutils literal notranslate"><span class="pre"><subject>[0]</span></code> (note that this match can also bind names)</p></li> <li><p><code class="docutils literal notranslate"><span class="pre">P2</span></code> matches <code class="docutils literal notranslate"><span class="pre"><subject>[1]</span></code> (note that this match can also bind names)</p></li> <li><p>… and so on for the corresponding pattern/element.</p></li> </ul> </section> <section id="mapping-patterns"> <span id="id11"></span><h4><span class="section-number">8.6.4.9. </span>Mapping Patterns<a class="headerlink" href="#mapping-patterns" title="Permalink to this headline">¶</a></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"><code class="xref docutils literal notranslate"><span class="pre">items_pattern</span></code></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"><code class="xref docutils literal notranslate"><span class="pre">key_value_pattern</span></code></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"><code class="xref docutils literal notranslate"><span class="pre">literal_pattern</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-value_pattern"><code class="xref docutils literal notranslate"><span class="pre">value_pattern</span></code></a>) ":" <a class="reference internal" href="#grammar-token-python-grammar-pattern"><code class="xref docutils literal notranslate"><span class="pre">pattern</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-double_star_pattern"><code class="xref docutils literal notranslate"><span class="pre">double_star_pattern</span></code></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"><code class="xref docutils literal notranslate"><span class="pre">capture_pattern</span></code></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.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a>. Two keys that otherwise have the same value will raise a <a class="reference internal" href="../library/exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></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><p>If the subject value is not a mapping <a class="footnote-reference brackets" href="#id18" id="id12">3</a>,the mapping pattern fails.</p></li> <li><p>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.</p></li> <li><p>If duplicate keys are detected in the mapping pattern, the pattern is considered invalid. A <a class="reference internal" href="../library/exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> is raised for duplicate literal values; or a <a class="reference internal" href="../library/exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> for named keys of the same value.</p></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 class="docutils literal notranslate"><span class="pre">get()</span></code> method. Matched key-value pairs must already be present in the mapping, and not created on-the-fly via <code class="xref py py-meth docutils literal notranslate"><span class="pre">__missing__()</span></code> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code>.</p> </div> <p>In simple terms <code class="docutils literal notranslate"><span class="pre">{KEY1:</span> <span class="pre">P1,</span> <span class="pre">KEY2:</span> <span class="pre">P2,</span> <span class="pre">...</span> <span class="pre">}</span></code> matches only if all the following happens:</p> <ul class="simple"> <li><p>check <code class="docutils literal notranslate"><span class="pre"><subject></span></code> is a mapping</p></li> <li><p><code class="docutils literal notranslate"><span class="pre">KEY1</span> <span class="pre">in</span> <span class="pre"><subject></span></code></p></li> <li><p><code class="docutils literal notranslate"><span class="pre">P1</span></code> matches <code class="docutils literal notranslate"><span class="pre"><subject>[KEY1]</span></code></p></li> <li><p>… and so on for the corresponding KEY/pattern pair.</p></li> </ul> </section> <section id="class-patterns"> <span id="id13"></span><h4><span class="section-number">8.6.4.10. </span>Class Patterns<a class="headerlink" href="#class-patterns" title="Permalink to this headline">¶</a></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"><code class="xref docutils literal notranslate"><span class="pre">name_or_attr</span></code></a> "(" [<a class="reference internal" href="#grammar-token-python-grammar-pattern_arguments"><code class="xref docutils literal notranslate"><span class="pre">pattern_arguments</span></code></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"><code class="xref docutils literal notranslate"><span class="pre">positional_patterns</span></code></a> ["," <a class="reference internal" href="#grammar-token-python-grammar-keyword_patterns"><code class="xref docutils literal notranslate"><span class="pre">keyword_patterns</span></code></a>] | <a class="reference internal" href="#grammar-token-python-grammar-keyword_patterns"><code class="xref docutils literal notranslate"><span class="pre">keyword_patterns</span></code></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"><code class="xref docutils literal notranslate"><span class="pre">pattern</span></code></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"><code class="xref docutils literal notranslate"><span class="pre">keyword_pattern</span></code></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"><code class="xref docutils literal notranslate"><span class="pre">pattern</span></code></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><p>If <code class="docutils literal notranslate"><span class="pre">name_or_attr</span></code> is not an instance of the builtin <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-class docutils literal notranslate"><span class="pre">type</span></code></a> , raise <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.</p></li> <li><p>If the subject value is not an instance of <code class="docutils literal notranslate"><span class="pre">name_or_attr</span></code> (tested via <a class="reference internal" href="../library/functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a>), the class pattern fails.</p></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> <blockquote> <div><ul class="simple"> <li><p>If this raises an exception other than <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>, the exception bubbles up.</p></li> <li><p>If this raises <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>, the class pattern has failed.</p></li> <li><p>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.</p></li> </ul> </div></blockquote> <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.html#object.__match_args__" title="object.__match_args__"><code class="xref py py-data docutils literal notranslate"><span class="pre">__match_args__</span></code></a> attribute on the class <code class="docutils literal notranslate"><span class="pre">name_or_attr</span></code> before matching:</p> <p>I. The equivalent of <code class="docutils literal notranslate"><span class="pre">getattr(cls,</span> <span class="pre">"__match_args__",</span> <span class="pre">())</span></code> is called.</p> <blockquote> <div><ul class="simple"> <li><p>If this raises an exception, the exception bubbles up.</p></li> <li><p>If the returned value is not a tuple, the conversion fails and <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.</p></li> <li><p>If there are more positional patterns than <code class="docutils literal notranslate"><span class="pre">len(cls.__match_args__)</span></code>, <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.</p></li> <li><p>Otherwise, positional pattern <code class="docutils literal notranslate"><span class="pre">i</span></code> is converted to a keyword pattern using <code class="docutils literal notranslate"><span class="pre">__match_args__[i]</span></code> as the keyword. <code class="docutils literal notranslate"><span class="pre">__match_args__[i]</span></code> must be a string; if not <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.</p></li> <li><p>If there are duplicate keywords, <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.</p></li> </ul> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p><a class="reference internal" href="datamodel.html#class-pattern-matching"><span class="std std-ref">Customizing positional arguments in class pattern matching</span></a></p> </div> </div></blockquote> <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><p><a class="reference internal" href="../library/functions.html#bool" title="bool"><code class="xref py py-class docutils literal notranslate"><span class="pre">bool</span></code></a></p></li> <li><p><a class="reference internal" href="../library/stdtypes.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a></p></li> <li><p><a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a></p></li> <li><p><a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a></p></li> <li><p><a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a></p></li> <li><p><a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a></p></li> <li><p><a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a></p></li> <li><p><a class="reference internal" href="../library/stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a></p></li> <li><p><a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a></p></li> <li><p><a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a></p></li> <li><p><a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a></p></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 class="docutils literal notranslate"><span class="pre">int(0|1)</span></code> matches the value <code class="docutils literal notranslate"><span class="pre">0</span></code>, but not the value <code class="docutils literal notranslate"><span class="pre">0.0</span></code>.</p> </li> </ol> <p>In simple terms <code class="docutils literal notranslate"><span class="pre">CLS(P1,</span> <span class="pre">attr=P2)</span></code> matches only if the following happens:</p> <ul class="simple"> <li><p><code class="docutils literal notranslate"><span class="pre">isinstance(<subject>,</span> <span class="pre">CLS)</span></code></p></li> <li><p>convert <code class="docutils literal notranslate"><span class="pre">P1</span></code> to a keyword pattern using <code class="docutils literal notranslate"><span class="pre">CLS.__match_args__</span></code></p></li> <li><dl class="simple"> <dt>For each keyword argument <code class="docutils literal notranslate"><span class="pre">attr=P2</span></code>:</dt><dd><ul> <li><p><code class="docutils literal notranslate"><span class="pre">hasattr(<subject>,</span> <span class="pre">"attr")</span></code></p></li> <li><p><code class="docutils literal notranslate"><span class="pre">P2</span></code> matches <code class="docutils literal notranslate"><span class="pre"><subject>.attr</span></code></p></li> </ul> </dd> </dl> </li> <li><p>… and so on for the corresponding keyword argument/pattern pair.</p></li> </ul> <div class="admonition seealso"> <p class="admonition-title">See also</p> <ul class="simple"> <li><p><span class="target" id="index-24"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0634"><strong>PEP 634</strong></a> – Structural Pattern Matching: Specification</p></li> <li><p><span class="target" id="index-25"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0636"><strong>PEP 636</strong></a> – Structural Pattern Matching: Tutorial</p></li> </ul> </div> </section> </section> </section> <section id="function-definitions"> <span id="def"></span><span id="function"></span><span id="index-26"></span><h2><span class="section-number">8.7. </span>Function definitions<a class="headerlink" href="#function-definitions" title="Permalink to this headline">¶</a></h2> <p id="index-27">A function definition defines a user-defined function object (see section <a class="reference internal" href="datamodel.html#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"><code class="xref docutils literal notranslate"><span class="pre">decorators</span></code></a>] "def" <a class="reference internal" href="#grammar-token-python-grammar-funcname"><code class="xref docutils literal notranslate"><span class="pre">funcname</span></code></a> "(" [<a class="reference internal" href="#grammar-token-python-grammar-parameter_list"><code class="xref docutils literal notranslate"><span class="pre">parameter_list</span></code></a>] ")" ["->" <a class="reference internal" href="expressions.html#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>] ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></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"><code class="xref docutils literal notranslate"><span class="pre">decorator</span></code></a>+ <strong id="grammar-token-python-grammar-decorator"><span id="grammar-token-decorator"></span>decorator </strong> ::= "@" <a class="reference internal" href="expressions.html#grammar-token-python-grammar-assignment_expression"><code class="xref docutils literal notranslate"><span class="pre">assignment_expression</span></code></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"><code class="xref docutils literal notranslate"><span class="pre">defparameter</span></code></a> ("," <a class="reference internal" href="#grammar-token-python-grammar-defparameter"><code class="xref docutils literal notranslate"><span class="pre">defparameter</span></code></a>)* "," "/" ["," [<a class="reference internal" href="#grammar-token-python-grammar-parameter_list_no_posonly"><code class="xref docutils literal notranslate"><span class="pre">parameter_list_no_posonly</span></code></a>]] | <a class="reference internal" href="#grammar-token-python-grammar-parameter_list_no_posonly"><code class="xref docutils literal notranslate"><span class="pre">parameter_list_no_posonly</span></code></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"><code class="xref docutils literal notranslate"><span class="pre">defparameter</span></code></a> ("," <a class="reference internal" href="#grammar-token-python-grammar-defparameter"><code class="xref docutils literal notranslate"><span class="pre">defparameter</span></code></a>)* ["," [<a class="reference internal" href="#grammar-token-python-grammar-parameter_list_starargs"><code class="xref docutils literal notranslate"><span class="pre">parameter_list_starargs</span></code></a>]] | <a class="reference internal" href="#grammar-token-python-grammar-parameter_list_starargs"><code class="xref docutils literal notranslate"><span class="pre">parameter_list_starargs</span></code></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"><code class="xref docutils literal notranslate"><span class="pre">parameter</span></code></a>] ("," <a class="reference internal" href="#grammar-token-python-grammar-defparameter"><code class="xref docutils literal notranslate"><span class="pre">defparameter</span></code></a>)* ["," ["**" <a class="reference internal" href="#grammar-token-python-grammar-parameter"><code class="xref docutils literal notranslate"><span class="pre">parameter</span></code></a> [","]]] | "**" <a class="reference internal" href="#grammar-token-python-grammar-parameter"><code class="xref docutils literal notranslate"><span class="pre">parameter</span></code></a> [","] <strong id="grammar-token-python-grammar-parameter"><span id="grammar-token-parameter"></span>parameter </strong> ::= <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> [":" <a class="reference internal" href="expressions.html#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></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"><code class="xref docutils literal notranslate"><span class="pre">parameter</span></code></a> ["=" <a class="reference internal" href="expressions.html#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>] <strong id="grammar-token-python-grammar-funcname"><span id="grammar-token-funcname"></span>funcname </strong> ::= <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></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="#id19" id="id14">4</a></p> <p id="index-28">A function definition may be wrapped by one or more <a class="reference internal" href="../glossary.html#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> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nd">@f1</span><span class="p">(</span><span class="n">arg</span><span class="p">)</span> <span class="nd">@f2</span> <span class="k">def</span> <span class="nf">func</span><span class="p">():</span> <span class="k">pass</span> </pre></div> </div> <p>is roughly equivalent to</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">func</span><span class="p">():</span> <span class="k">pass</span> <span class="n">func</span> <span class="o">=</span> <span class="n">f1</span><span class="p">(</span><span class="n">arg</span><span class="p">)(</span><span class="n">f2</span><span class="p">(</span><span class="n">func</span><span class="p">))</span> </pre></div> </div> <p>except that the original function is not temporarily bound to the name <code class="docutils literal notranslate"><span class="pre">func</span></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.html#grammar-token-python-grammar-assignment_expression"><code class="xref std std-token docutils literal notranslate"><span class="pre">assignment_expression</span></code></a>. Previously, the grammar was much more restrictive; see <span class="target" id="index-29"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0614"><strong>PEP 614</strong></a> for details.</p> </div> <p id="index-30">When one or more <a class="reference internal" href="../glossary.html#term-parameter"><span class="xref std std-term">parameters</span></a> have the form <em>parameter</em> <code class="docutils literal notranslate"><span class="pre">=</span></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.html#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 class="docutils literal notranslate"><span class="pre">*</span></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 class="docutils literal notranslate"><span class="pre">None</span></code> as the default, and explicitly test for it in the body of the function, e.g.:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">whats_on_the_telly</span><span class="p">(</span><span class="n">penguin</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span> <span class="k">if</span> <span class="n">penguin</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span> <span class="n">penguin</span> <span class="o">=</span> <span class="p">[]</span> <span class="n">penguin</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s2">"property of the zoo"</span><span class="p">)</span> <span class="k">return</span> <span class="n">penguin</span> </pre></div> </div> <p id="index-31">Function call semantics are described in more detail in section <a class="reference internal" href="expressions.html#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 class="docutils literal notranslate"><span class="pre">*identifier</span></code>” is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form “<code class="docutils literal notranslate"><span class="pre">**identifier</span></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 class="docutils literal notranslate"><span class="pre">*</span></code>” or “<code class="docutils literal notranslate"><span class="pre">*identifier</span></code>” are keyword-only parameters and may only be passed by keyword arguments. Parameters before “<code class="docutils literal notranslate"><span class="pre">/</span></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 class="docutils literal notranslate"><span class="pre">/</span></code> function parameter syntax may be used to indicate positional-only parameters. See <span class="target" id="index-32"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0570"><strong>PEP 570</strong></a> for details.</p> </div> <p id="index-33">Parameters may have an <a class="reference internal" href="../glossary.html#term-function-annotation"><span class="xref std std-term">annotation</span></a> of the form “<code class="docutils literal notranslate"><span class="pre">:</span> <span class="pre">expression</span></code>” following the parameter name. Any parameter may have an annotation, even those of the form <code class="docutils literal notranslate"><span class="pre">*identifier</span></code> or <code class="docutils literal notranslate"><span class="pre">**identifier</span></code>. Functions may have “return” annotation of the form “<code class="docutils literal notranslate"><span class="pre">-></span> <span class="pre">expression</span></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 class="xref py py-attr docutils literal notranslate"><span class="pre">__annotations__</span></code> attribute of the function object. If the <code class="docutils literal notranslate"><span class="pre">annotations</span></code> import from <a class="reference internal" href="../library/__future__.html#module-__future__" title="__future__: Future statement definitions"><code class="xref py py-mod docutils literal notranslate"><span class="pre">__future__</span></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-34">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.html#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 class="xref std std-keyword docutils literal notranslate"><span class="pre">def</span></code></a>” statement can be passed around or assigned to another name just like a function defined by a lambda expression. The “<code class="xref std std-keyword docutils literal notranslate"><span class="pre">def</span></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 class="docutils literal notranslate"><span class="pre">def</span></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.html#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-35"></span><a class="pep reference external" href="https://www.python.org/dev/peps/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-36"></span><a class="pep reference external" href="https://www.python.org/dev/peps/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-37"></span><a class="pep reference external" href="https://www.python.org/dev/peps/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-38"></span><a class="pep reference external" href="https://www.python.org/dev/peps/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> </dl> </div> </section> <section id="class-definitions"> <span id="class"></span><h2><span class="section-number">8.8. </span>Class definitions<a class="headerlink" href="#class-definitions" title="Permalink to this headline">¶</a></h2> <p id="index-39">A class definition defines a class object (see section <a class="reference internal" href="datamodel.html#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"><code class="xref docutils literal notranslate"><span class="pre">decorators</span></code></a>] "class" <a class="reference internal" href="#grammar-token-python-grammar-classname"><code class="xref docutils literal notranslate"><span class="pre">classname</span></code></a> [<a class="reference internal" href="#grammar-token-python-grammar-inheritance"><code class="xref docutils literal notranslate"><span class="pre">inheritance</span></code></a>] ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a> <strong id="grammar-token-python-grammar-inheritance"><span id="grammar-token-inheritance"></span>inheritance</strong> ::= "(" [<a class="reference internal" href="expressions.html#grammar-token-python-grammar-argument_list"><code class="xref docutils literal notranslate"><span class="pre">argument_list</span></code></a>] ")" <strong id="grammar-token-python-grammar-classname"><span id="grammar-token-classname"></span>classname </strong> ::= <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></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.html#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.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>; hence,</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Foo</span><span class="p">:</span> <span class="k">pass</span> </pre></div> </div> <p>is equivalent to</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Foo</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="k">pass</span> </pre></div> </div> <p>The class’s suite is then executed in a new execution frame (see <a class="reference internal" href="executionmodel.html#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="#id20" id="id15">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 class="docutils literal notranslate"><span class="pre">__dict__</span></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.html#metaclasses"><span class="std std-ref">metaclasses</span></a>.</p> <p id="index-40">Classes can also be decorated: just like when decorating functions,</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nd">@f1</span><span class="p">(</span><span class="n">arg</span><span class="p">)</span> <span class="nd">@f2</span> <span class="k">class</span> <span class="nc">Foo</span><span class="p">:</span> <span class="k">pass</span> </pre></div> </div> <p>is roughly equivalent to</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Foo</span><span class="p">:</span> <span class="k">pass</span> <span class="n">Foo</span> <span class="o">=</span> <span class="n">f1</span><span class="p">(</span><span class="n">arg</span><span class="p">)(</span><span class="n">f2</span><span class="p">(</span><span class="n">Foo</span><span class="p">))</span> </pre></div> </div> <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.html#grammar-token-python-grammar-assignment_expression"><code class="xref std std-token docutils literal notranslate"><span class="pre">assignment_expression</span></code></a>. Previously, the grammar was much more restrictive; see <span class="target" id="index-41"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0614"><strong>PEP 614</strong></a> for details.</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 class="docutils literal notranslate"><span class="pre">self.name</span> <span class="pre">=</span> <span class="pre">value</span></code>. Both class and instance attributes are accessible through the notation “<code class="docutils literal notranslate"><span class="pre">self.name</span></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.html#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-42"></span><a class="pep reference external" href="https://www.python.org/dev/peps/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-43"></span><a class="pep reference external" href="https://www.python.org/dev/peps/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-44"></span><a class="pep reference external" href="https://www.python.org/dev/peps/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<a class="headerlink" href="#coroutines" title="Permalink to this headline">¶</a></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-45"></span><h3><span class="section-number">8.9.1. </span>Coroutine function definition<a class="headerlink" href="#coroutine-function-definition" title="Permalink to this headline">¶</a></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"><code class="xref docutils literal notranslate"><span class="pre">decorators</span></code></a>] "async" "def" <a class="reference internal" href="#grammar-token-python-grammar-funcname"><code class="xref docutils literal notranslate"><span class="pre">funcname</span></code></a> "(" [<a class="reference internal" href="#grammar-token-python-grammar-parameter_list"><code class="xref docutils literal notranslate"><span class="pre">parameter_list</span></code></a>] ")" ["->" <a class="reference internal" href="expressions.html#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>] ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a> </pre> <p id="index-46">Execution of Python coroutines can be suspended and resumed at many points (see <a class="reference internal" href="../glossary.html#term-coroutine"><span class="xref std std-term">coroutine</span></a>). <a class="reference internal" href="expressions.html#await"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">await</span></code></a> expressions, <a class="reference internal" href="#async-for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code></a> and <a class="reference internal" href="#async-with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code></a> can only be used in the body of a coroutine function.</p> <p>Functions defined with <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code> syntax are always coroutine functions, even if they do not contain <code class="docutils literal notranslate"><span class="pre">await</span></code> or <code class="docutils literal notranslate"><span class="pre">async</span></code> keywords.</p> <p>It is a <a class="reference internal" href="../library/exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> to use a <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code> expression inside the body of a coroutine function.</p> <p>An example of a coroutine function:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span> <span class="nf">func</span><span class="p">(</span><span class="n">param1</span><span class="p">,</span> <span class="n">param2</span><span class="p">):</span> <span class="n">do_stuff</span><span class="p">()</span> <span class="k">await</span> <span class="n">some_coroutine</span><span class="p">()</span> </pre></div> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span><code class="docutils literal notranslate"><span class="pre">await</span></code> and <code class="docutils literal notranslate"><span class="pre">async</span></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-47"></span><h3><span class="section-number">8.9.2. </span>The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code> statement<a class="headerlink" href="#the-async-for-statement" title="Permalink to this headline">¶</a></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"><code class="xref docutils literal notranslate"><span class="pre">for_stmt</span></code></a> </pre> <p>An <a class="reference internal" href="../glossary.html#term-asynchronous-iterable"><span class="xref std std-term">asynchronous iterable</span></a> provides an <code class="docutils literal notranslate"><span class="pre">__aiter__</span></code> method that directly returns an <a class="reference internal" href="../glossary.html#term-asynchronous-iterator"><span class="xref std std-term">asynchronous iterator</span></a>, which can call asynchronous code in its <code class="docutils literal notranslate"><span class="pre">__anext__</span></code> method.</p> <p>The <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code> statement allows convenient iteration over asynchronous iterables.</p> <p>The following code:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">for</span> <span class="n">TARGET</span> <span class="ow">in</span> <span class="n">ITER</span><span class="p">:</span> <span class="n">SUITE</span> <span class="k">else</span><span class="p">:</span> <span class="n">SUITE2</span> </pre></div> </div> <p>Is semantically equivalent to:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nb">iter</span> <span class="o">=</span> <span class="p">(</span><span class="n">ITER</span><span class="p">)</span> <span class="nb">iter</span> <span class="o">=</span> <span class="nb">type</span><span class="p">(</span><span class="nb">iter</span><span class="p">)</span><span class="o">.</span><span class="fm">__aiter__</span><span class="p">(</span><span class="nb">iter</span><span class="p">)</span> <span class="n">running</span> <span class="o">=</span> <span class="kc">True</span> <span class="k">while</span> <span class="n">running</span><span class="p">:</span> <span class="k">try</span><span class="p">:</span> <span class="n">TARGET</span> <span class="o">=</span> <span class="k">await</span> <span class="nb">type</span><span class="p">(</span><span class="nb">iter</span><span class="p">)</span><span class="o">.</span><span class="fm">__anext__</span><span class="p">(</span><span class="nb">iter</span><span class="p">)</span> <span class="k">except</span> <span class="ne">StopAsyncIteration</span><span class="p">:</span> <span class="n">running</span> <span class="o">=</span> <span class="kc">False</span> <span class="k">else</span><span class="p">:</span> <span class="n">SUITE</span> <span class="k">else</span><span class="p">:</span> <span class="n">SUITE2</span> </pre></div> </div> <p>See also <a class="reference internal" href="datamodel.html#object.__aiter__" title="object.__aiter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__aiter__()</span></code></a> and <a class="reference internal" href="datamodel.html#object.__anext__" title="object.__anext__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__anext__()</span></code></a> for details.</p> <p>It is a <a class="reference internal" href="../library/exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> to use an <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></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-48"></span><h3><span class="section-number">8.9.3. </span>The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code> statement<a class="headerlink" href="#the-async-with-statement" title="Permalink to this headline">¶</a></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"><code class="xref docutils literal notranslate"><span class="pre">with_stmt</span></code></a> </pre> <p>An <a class="reference internal" href="../glossary.html#term-asynchronous-context-manager"><span class="xref std std-term">asynchronous context manager</span></a> is a <a class="reference internal" href="../glossary.html#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> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">with</span> <span class="n">EXPRESSION</span> <span class="k">as</span> <span class="n">TARGET</span><span class="p">:</span> <span class="n">SUITE</span> </pre></div> </div> <p>is semantically equivalent to:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">manager</span> <span class="o">=</span> <span class="p">(</span><span class="n">EXPRESSION</span><span class="p">)</span> <span class="n">aenter</span> <span class="o">=</span> <span class="nb">type</span><span class="p">(</span><span class="n">manager</span><span class="p">)</span><span class="o">.</span><span class="fm">__aenter__</span> <span class="n">aexit</span> <span class="o">=</span> <span class="nb">type</span><span class="p">(</span><span class="n">manager</span><span class="p">)</span><span class="o">.</span><span class="fm">__aexit__</span> <span class="n">value</span> <span class="o">=</span> <span class="k">await</span> <span class="n">aenter</span><span class="p">(</span><span class="n">manager</span><span class="p">)</span> <span class="n">hit_except</span> <span class="o">=</span> <span class="kc">False</span> <span class="k">try</span><span class="p">:</span> <span class="n">TARGET</span> <span class="o">=</span> <span class="n">value</span> <span class="n">SUITE</span> <span class="k">except</span><span class="p">:</span> <span class="n">hit_except</span> <span class="o">=</span> <span class="kc">True</span> <span class="k">if</span> <span class="ow">not</span> <span class="k">await</span> <span class="n">aexit</span><span class="p">(</span><span class="n">manager</span><span class="p">,</span> <span class="o">*</span><span class="n">sys</span><span class="o">.</span><span class="n">exc_info</span><span class="p">()):</span> <span class="k">raise</span> <span class="k">finally</span><span class="p">:</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">hit_except</span><span class="p">:</span> <span class="k">await</span> <span class="n">aexit</span><span class="p">(</span><span class="n">manager</span><span class="p">,</span> <span class="kc">None</span><span class="p">,</span> <span class="kc">None</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span> </pre></div> </div> <p>See also <a class="reference internal" href="datamodel.html#object.__aenter__" title="object.__aenter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__aenter__()</span></code></a> and <a class="reference internal" href="datamodel.html#object.__aexit__" title="object.__aexit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__aexit__()</span></code></a> for details.</p> <p>It is a <a class="reference internal" href="../library/exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> to use an <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></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-49"></span><a class="pep reference external" href="https://www.python.org/dev/peps/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> <p class="rubric">Footnotes</p> <dl class="footnote brackets"> <dt class="label" id="id16"><span class="brackets"><a class="fn-backref" href="#id1">1</a></span></dt> <dd><p>The exception is propagated to the invocation stack unless there is a <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></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="id17"><span class="brackets"><a class="fn-backref" href="#id10">2</a></span></dt> <dd><p>In pattern matching, a sequence is defined as one of the following:</p> <blockquote> <div><ul class="simple"> <li><p>a class that inherits from <a class="reference internal" href="../library/collections.abc.html#collections.abc.Sequence" title="collections.abc.Sequence"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.Sequence</span></code></a></p></li> <li><p>a Python class that has been registered as <a class="reference internal" href="../library/collections.abc.html#collections.abc.Sequence" title="collections.abc.Sequence"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.Sequence</span></code></a></p></li> <li><p>a builtin class that has its (CPython) <a class="reference internal" href="../c-api/typeobj.html#Py_TPFLAGS_SEQUENCE" title="Py_TPFLAGS_SEQUENCE"><code class="xref py py-data docutils literal notranslate"><span class="pre">Py_TPFLAGS_SEQUENCE</span></code></a> bit set</p></li> <li><p>a class that inherits from any of the above</p></li> </ul> </div></blockquote> <p>The following standard library classes are sequences:</p> <blockquote> <div><ul class="simple"> <li><p><a class="reference internal" href="../library/array.html#array.array" title="array.array"><code class="xref py py-class docutils literal notranslate"><span class="pre">array.array</span></code></a></p></li> <li><p><a class="reference internal" href="../library/collections.html#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.deque</span></code></a></p></li> <li><p><a class="reference internal" href="../library/stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a></p></li> <li><p><a class="reference internal" href="../library/stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a></p></li> <li><p><a class="reference internal" href="../library/stdtypes.html#range" title="range"><code class="xref py py-class docutils literal notranslate"><span class="pre">range</span></code></a></p></li> <li><p><a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a></p></li> </ul> </div></blockquote> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Subject values of type <code class="docutils literal notranslate"><span class="pre">str</span></code>, <code class="docutils literal notranslate"><span class="pre">bytes</span></code>, and <code class="docutils literal notranslate"><span class="pre">bytearray</span></code> do not match sequence patterns.</p> </div> </dd> <dt class="label" id="id18"><span class="brackets"><a class="fn-backref" href="#id12">3</a></span></dt> <dd><p>In pattern matching, a mapping is defined as one of the following:</p> <blockquote> <div><ul class="simple"> <li><p>a class that inherits from <a class="reference internal" href="../library/collections.abc.html#collections.abc.Mapping" title="collections.abc.Mapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.Mapping</span></code></a></p></li> <li><p>a Python class that has been registered as <a class="reference internal" href="../library/collections.abc.html#collections.abc.Mapping" title="collections.abc.Mapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.Mapping</span></code></a></p></li> <li><p>a builtin class that has its (CPython) <a class="reference internal" href="../c-api/typeobj.html#Py_TPFLAGS_MAPPING" title="Py_TPFLAGS_MAPPING"><code class="xref py py-data docutils literal notranslate"><span class="pre">Py_TPFLAGS_MAPPING</span></code></a> bit set</p></li> <li><p>a class that inherits from any of the above</p></li> </ul> </div></blockquote> <p>The standard library classes <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> and <a class="reference internal" href="../library/types.html#types.MappingProxyType" title="types.MappingProxyType"><code class="xref py py-class docutils literal notranslate"><span class="pre">types.MappingProxyType</span></code></a> are mappings.</p> </dd> <dt class="label" id="id19"><span class="brackets"><a class="fn-backref" href="#id14">4</a></span></dt> <dd><p>A string literal appearing as the first statement in the function body is transformed into the function’s <code class="docutils literal notranslate"><span class="pre">__doc__</span></code> attribute and therefore the function’s <a class="reference internal" href="../glossary.html#term-docstring"><span class="xref std std-term">docstring</span></a>.</p> </dd> <dt class="label" id="id20"><span class="brackets"><a class="fn-backref" href="#id15">5</a></span></dt> <dd><p>A string literal appearing as the first statement in the class body is transformed into the namespace’s <code class="docutils literal notranslate"><span class="pre">__doc__</span></code> item and therefore the class’s <a class="reference internal" href="../glossary.html#term-docstring"><span class="xref std std-term">docstring</span></a>.</p> </dd> </dl> </section> </section> </section> <div class="clearer"></div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h3><a href="../contents.html">Table of Contents</a></h3> <ul> <li><a class="reference internal" href="#">8. Compound statements</a><ul> <li><a class="reference internal" href="#the-if-statement">8.1. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code> statement</a></li> <li><a class="reference internal" href="#the-while-statement">8.2. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code> statement</a></li> <li><a class="reference internal" href="#the-for-statement">8.3. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> statement</a></li> <li><a class="reference internal" href="#the-try-statement">8.4. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> statement</a></li> <li><a class="reference internal" href="#the-with-statement">8.5. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> statement</a></li> <li><a class="reference internal" href="#the-match-statement">8.6. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">match</span></code> statement</a><ul> <li><a class="reference internal" href="#overview">8.6.1. Overview</a></li> <li><a class="reference internal" href="#guards">8.6.2. Guards</a></li> <li><a class="reference internal" href="#irrefutable-case-blocks">8.6.3. Irrefutable Case Blocks</a></li> <li><a class="reference internal" href="#patterns">8.6.4. Patterns</a><ul> <li><a class="reference internal" href="#or-patterns">8.6.4.1. OR Patterns</a></li> <li><a class="reference internal" href="#as-patterns">8.6.4.2. AS Patterns</a></li> <li><a class="reference internal" href="#literal-patterns">8.6.4.3. Literal Patterns</a></li> <li><a class="reference internal" href="#capture-patterns">8.6.4.4. Capture Patterns</a></li> <li><a class="reference internal" href="#wildcard-patterns">8.6.4.5. Wildcard Patterns</a></li> <li><a class="reference internal" href="#value-patterns">8.6.4.6. Value Patterns</a></li> <li><a class="reference internal" href="#group-patterns">8.6.4.7. Group Patterns</a></li> <li><a class="reference internal" href="#sequence-patterns">8.6.4.8. Sequence Patterns</a></li> <li><a class="reference internal" href="#mapping-patterns">8.6.4.9. Mapping Patterns</a></li> <li><a class="reference internal" href="#class-patterns">8.6.4.10. Class Patterns</a></li> </ul> </li> </ul> </li> <li><a class="reference internal" href="#function-definitions">8.7. Function definitions</a></li> <li><a class="reference internal" href="#class-definitions">8.8. Class definitions</a></li> <li><a class="reference internal" href="#coroutines">8.9. Coroutines</a><ul> <li><a class="reference internal" href="#coroutine-function-definition">8.9.1. Coroutine function definition</a></li> <li><a class="reference internal" href="#the-async-for-statement">8.9.2. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code> statement</a></li> <li><a class="reference internal" href="#the-async-with-statement">8.9.3. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code> statement</a></li> </ul> </li> </ul> </li> </ul> <h4>Previous topic</h4> <p class="topless"><a href="simple_stmts.html" title="previous chapter"><span class="section-number">7. </span>Simple statements</a></p> <h4>Next topic</h4> <p class="topless"><a href="toplevel_components.html" title="next chapter"><span class="section-number">9. </span>Top-level components</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../bugs.html">Report a Bug</a></li> <li> <a href="https://github.com/python/cpython/blob/3.10/Doc/reference/compound_stmts.rst" rel="nofollow">Show Source </a> </li> </ul> </div> </div> </div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="toplevel_components.html" title="9. Top-level components" >next</a> |</li> <li class="right" > <a href="simple_stmts.html" title="7. Simple statements" >previous</a> |</li> <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="https://www.python.org/">Python</a> »</li> <li class="switchers"> <div class="language_switcher_placeholder"></div> <div class="version_switcher_placeholder"></div> </li> <li> </li> <li id="cpython-language-and-version"> <a href="../index.html">3.10.12 Documentation</a> » </li> <li class="nav-item nav-item-1"><a href="index.html" >The Python Language Reference</a> »</li> <li class="nav-item nav-item-this"><a href=""><span class="section-number">8. </span>Compound statements</a></li> <li class="right"> <div class="inline-search" role="search"> <form class="inline-search" action="../search.html" method="get"> <input placeholder="Quick search" aria-label="Quick search" type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> | </li> </ul> </div> <div class="footer"> © <a href="../copyright.html">Copyright</a> 2001-2025, Python Software Foundation. <br /> This page is licensed under the Python Software Foundation License Version 2. <br /> Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. <br /> See <a href="/license.html">History and License</a> for more information.<br /> <br /> The Python Software Foundation is a non-profit corporation. <a href="https://www.python.org/psf/donations/">Please donate.</a> <br /> <br /> Last updated on February 04, 2025. <a href="/bugs.html">Found a bug</a>? <br /> Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 4.3.2. </div> </body> </html>