mirror of
				https://github.com/bunny-lab-io/Borealis.git
				synced 2025-10-30 00:01:57 -06:00 
			
		
		
		
	
		
			
				
	
	
		
			1959 lines
		
	
	
		
			210 KiB
		
	
	
	
		
			HTML
		
	
	
	
	
	
			
		
		
	
	
			1959 lines
		
	
	
		
			210 KiB
		
	
	
	
		
			HTML
		
	
	
	
	
	
| <!DOCTYPE html>
 | ||
| 
 | ||
| <html lang="en" data-content_root="../">
 | ||
|   <head>
 | ||
|     <meta charset="utf-8" />
 | ||
|     <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
 | ||
| <meta property="og:title" content="8. Compound statements" />
 | ||
| <meta property="og:type" content="website" />
 | ||
| <meta property="og:url" content="https://docs.python.org/3/reference/compound_stmts.html" />
 | ||
| <meta property="og:site_name" content="Python documentation" />
 | ||
| <meta property="og:description" content="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 i..." />
 | ||
| <meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
 | ||
| <meta property="og:image:alt" content="Python documentation" />
 | ||
| <meta name="description" content="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 i..." />
 | ||
| <meta property="og:image:width" content="200">
 | ||
| <meta property="og:image:height" content="200">
 | ||
| <meta name="theme-color" content="#3776ab">
 | ||
| 
 | ||
|     <title>8. Compound statements — Python 3.13.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
 | ||
|     
 | ||
|     <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />
 | ||
|     <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=23252803" />
 | ||
|     <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />
 | ||
|     
 | ||
|     <script src="../_static/documentation_options.js?v=5d57ca2d"></script>
 | ||
|     <script src="../_static/doctools.js?v=9bcbadda"></script>
 | ||
|     <script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
 | ||
|     
 | ||
|     <script src="../_static/sidebar.js"></script>
 | ||
|     
 | ||
|     <link rel="search" type="application/opensearchdescription+xml"
 | ||
|           title="Search within Python 3.13.3 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="https://docs.python.org/3/reference/compound_stmts.html">
 | ||
|     
 | ||
|       
 | ||
|     
 | ||
| 
 | ||
|     
 | ||
|     <style>
 | ||
|       @media only screen {
 | ||
|         table.full-width-table {
 | ||
|             width: 100%;
 | ||
|         }
 | ||
|       }
 | ||
|     </style>
 | ||
| <link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
 | ||
|     <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>
 | ||
|             <script type="text/javascript" src="../_static/search-focus.js"></script>
 | ||
|             <script type="text/javascript" src="../_static/themetoggle.js"></script> 
 | ||
|             <script type="text/javascript" src="../_static/rtd_switcher.js"></script>
 | ||
|             <meta name="readthedocs-addons-api-version" content="1">
 | ||
| 
 | ||
|   </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" />
 | ||
|     <nav class="nav-content" role="navigation">
 | ||
|         <label for="menuToggler" class="toggler__label">
 | ||
|             <span></span>
 | ||
|         </label>
 | ||
|         <span class="nav-items-wrapper">
 | ||
|             <a href="https://www.python.org/" class="nav-logo">
 | ||
|                 <img src="../_static/py.svg" alt="Python logo"/>
 | ||
|             </a>
 | ||
|             <span class="version_switcher_placeholder"></span>
 | ||
|             <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" fill="currentColor" 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"></path>
 | ||
|                 </svg>
 | ||
|                 <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
 | ||
|                 <input type="submit" value="Go"/>
 | ||
|             </form>
 | ||
|         </span>
 | ||
|     </nav>
 | ||
|     <div class="menu-wrapper">
 | ||
|         <nav class="menu" role="navigation" aria-label="main navigation">
 | ||
|             <div class="language_switcher_placeholder"></div>
 | ||
|             
 | ||
| <label class="theme-selector-label">
 | ||
|     Theme
 | ||
|     <select class="theme-selector" oninput="activateTheme(this.value)">
 | ||
|         <option value="auto" selected>Auto</option>
 | ||
|         <option value="light">Light</option>
 | ||
|         <option value="dark">Dark</option>
 | ||
|     </select>
 | ||
| </label>
 | ||
|   <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><ul>
 | ||
| <li><a class="reference internal" href="#except-clause">8.4.1. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause</a></li>
 | ||
| <li><a class="reference internal" href="#except-star">8.4.2. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code> clause</a></li>
 | ||
| <li><a class="reference internal" href="#else-clause">8.4.3. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause</a></li>
 | ||
| <li><a class="reference internal" href="#finally-clause">8.4.4. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause</a></li>
 | ||
| </ul>
 | ||
| </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>
 | ||
| <li><a class="reference internal" href="#type-parameter-lists">8.10. Type parameter lists</a><ul>
 | ||
| <li><a class="reference internal" href="#generic-functions">8.10.1. Generic functions</a></li>
 | ||
| <li><a class="reference internal" href="#generic-classes">8.10.2. Generic classes</a></li>
 | ||
| <li><a class="reference internal" href="#generic-type-aliases">8.10.3. Generic type aliases</a></li>
 | ||
| </ul>
 | ||
| </li>
 | ||
| </ul>
 | ||
| </li>
 | ||
| </ul>
 | ||
| 
 | ||
|   </div>
 | ||
|   <div>
 | ||
|     <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>
 | ||
|   </div>
 | ||
|   <div>
 | ||
|     <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>
 | ||
|   <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/main/Doc/reference/compound_stmts.rst"
 | ||
|             rel="nofollow">Show Source
 | ||
|         </a>
 | ||
|       </li>
 | ||
|     </ul>
 | ||
|   </div>
 | ||
|         </nav>
 | ||
|     </div>
 | ||
| </div>
 | ||
| 
 | ||
|   
 | ||
|     <div class="related" role="navigation" aria-label="Related">
 | ||
|       <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.13.3 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="search" name="q" id="search-box" />
 | ||
|           <input type="submit" value="Go" />
 | ||
|         </form>
 | ||
|     </div>
 | ||
|                      |
 | ||
|                 </li>
 | ||
|             <li class="right">
 | ||
| <label class="theme-selector-label">
 | ||
|     Theme
 | ||
|     <select class="theme-selector" oninput="activateTheme(this.value)">
 | ||
|         <option value="auto" selected>Auto</option>
 | ||
|         <option value="light">Light</option>
 | ||
|         <option value="dark">Dark</option>
 | ||
|     </select>
 | ||
| </label> |</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="Link to this heading">¶</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">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">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">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">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="Link to this heading">¶</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">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="Link to this heading">¶</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">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="Link to this heading">¶</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">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" <code class="xref docutils literal notranslate"><span class="pre">starred_list</span></code> ":" <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 <code class="docutils literal notranslate"><span class="pre">starred_list</span></code> expression is evaluated once; it should yield an
 | ||
| <a class="reference internal" href="../glossary.html#term-iterable"><span class="xref std std-term">iterable</span></a> object.  An <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a> is created for that iterable.
 | ||
| The first item provided
 | ||
| by the iterator is then assigned to the target list using the standard
 | ||
| rules for assignments (see <a class="reference internal" href="simple_stmts.html#assignment"><span class="std std-ref">Assignment statements</span></a>), and the suite is executed.  This
 | ||
| repeats for each item provided by the iterator.  When the iterator is exhausted,
 | ||
| the suite in the <code 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>
 | ||
| <div class="versionchanged">
 | ||
| <p><span class="versionmodified changed">Changed in version 3.11: </span>Starred elements are now allowed in the expression list.</p>
 | ||
| </div>
 | ||
| </section>
 | ||
| <section id="the-try-statement">
 | ||
| <span id="try"></span><h2><span class="section-number">8.4. </span>The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> statement<a class="headerlink" href="#the-try-statement" title="Link to this heading">¶</a></h2>
 | ||
| <p id="index-9">The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> statement specifies exception handlers and/or cleanup code
 | ||
| for a group of statements:</p>
 | ||
| <pre>
 | ||
| <strong id="grammar-token-python-grammar-try_stmt">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> | <a class="reference internal" href="#grammar-token-python-grammar-try3_stmt"><code class="xref docutils literal notranslate"><span class="pre">try3_stmt</span></code></a>
 | ||
| <strong id="grammar-token-python-grammar-try1_stmt">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">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>
 | ||
|               ("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-try3_stmt">try3_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>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>
 | ||
| <section id="except-clause">
 | ||
| <span id="except"></span><h3><span class="section-number">8.4.1. </span><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause<a class="headerlink" href="#except-clause" title="Link to this heading">¶</a></h3>
 | ||
| <p>The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> 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 <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clauses in turn
 | ||
| until one is found that matches the exception.
 | ||
| An expression-less <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause, if present, must be last;
 | ||
| it matches any exception.</p>
 | ||
| <p>For an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause with an expression, the
 | ||
| expression must evaluate to an exception type or a tuple of exception types.
 | ||
| The raised exception matches an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause whose expression evaluates
 | ||
| to 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 to a tuple that contains such a class.</p>
 | ||
| <p>If no <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause matches the exception,
 | ||
| the search for an exception handler
 | ||
| continues in the surrounding code and on the invocation stack.  <a class="footnote-reference brackets" href="#id20" id="id1" role="doc-noteref"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></a></p>
 | ||
| <p>If the evaluation of an expression
 | ||
| in the header of an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause raises an exception,
 | ||
| the original search for a handler is canceled and a search starts for
 | ||
| the new exception in the surrounding code and on the call stack (it is treated
 | ||
| as if the entire <a class="reference internal" href="#try"><code 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 <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> 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 <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause,
 | ||
| if present, and the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause’s suite is executed.
 | ||
| All <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clauses must have an executable block.
 | ||
| When the end of this block is reached, execution continues
 | ||
| normally after the entire <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement.
 | ||
| (This means that if two nested handlers exist for the same exception,
 | ||
| and the exception occurs in the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> 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 <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> 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 <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause.
 | ||
| Exceptions are cleared because with the
 | ||
| traceback attached to them, they form a reference cycle with the stack frame,
 | ||
| keeping all locals in that frame alive until the next garbage collection occurs.</p>
 | ||
| <p id="index-11">Before an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause’s suite is executed,
 | ||
| the exception is 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, where it can be accessed
 | ||
| from within the body of the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause by calling
 | ||
| <a class="reference internal" href="../library/sys.html#sys.exception" title="sys.exception"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exception()</span></code></a>. When leaving an exception handler, the exception
 | ||
| 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 is reset to its previous value:</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">exception</span><span class="p">())</span>
 | ||
| <span class="go">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="nb">repr</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">exception</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="nb">repr</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">exception</span><span class="p">()))</span>
 | ||
| <span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="nb">repr</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">exception</span><span class="p">()))</span>
 | ||
| <span class="gp">...</span>
 | ||
| <span class="go">TypeError()</span>
 | ||
| <span class="go">ValueError()</span>
 | ||
| <span class="go">TypeError()</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">exception</span><span class="p">())</span>
 | ||
| <span class="go">None</span>
 | ||
| </pre></div>
 | ||
| </div>
 | ||
| </section>
 | ||
| <section id="except-star">
 | ||
| <span id="index-12"></span><span id="id2"></span><h3><span class="section-number">8.4.2. </span><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code> clause<a class="headerlink" href="#except-star" title="Link to this heading">¶</a></h3>
 | ||
| <p>The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code> clause(s) are used for handling
 | ||
| <a class="reference internal" href="../library/exceptions.html#ExceptionGroup" title="ExceptionGroup"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ExceptionGroup</span></code></a>s. The exception type for matching is interpreted as in
 | ||
| the case of <a class="reference internal" href="#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a>, but in the case of exception groups we can have
 | ||
| partial matches when the type matches some of the exceptions in the group.
 | ||
| This means that multiple <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code> clauses can execute,
 | ||
| each handling part of the exception group.
 | ||
| Each clause executes at most once and handles an exception group
 | ||
| of all matching exceptions.  Each exception in the group is handled by at most
 | ||
| one <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code> clause, the first that matches it.</p>
 | ||
| <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></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="n">ExceptionGroup</span><span class="p">(</span><span class="s2">"eg"</span><span class="p">,</span>
 | ||
| <span class="gp">... </span>        <span class="p">[</span><span class="ne">ValueError</span><span class="p">(</span><span class="mi">1</span><span class="p">),</span> <span class="ne">TypeError</span><span class="p">(</span><span class="mi">2</span><span class="p">),</span> <span class="ne">OSError</span><span class="p">(</span><span class="mi">3</span><span class="p">),</span> <span class="ne">OSError</span><span class="p">(</span><span class="mi">4</span><span class="p">)])</span>
 | ||
| <span class="gp">... </span><span class="k">except</span><span class="o">*</span> <span class="ne">TypeError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
 | ||
| <span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'caught </span><span class="si">{</span><span class="nb">type</span><span class="p">(</span><span class="n">e</span><span class="p">)</span><span class="si">}</span><span class="s1"> with nested </span><span class="si">{</span><span class="n">e</span><span class="o">.</span><span class="n">exceptions</span><span class="si">}</span><span class="s1">'</span><span class="p">)</span>
 | ||
| <span class="gp">... </span><span class="k">except</span><span class="o">*</span> <span class="ne">OSError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
 | ||
| <span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'caught </span><span class="si">{</span><span class="nb">type</span><span class="p">(</span><span class="n">e</span><span class="p">)</span><span class="si">}</span><span class="s1"> with nested </span><span class="si">{</span><span class="n">e</span><span class="o">.</span><span class="n">exceptions</span><span class="si">}</span><span class="s1">'</span><span class="p">)</span>
 | ||
| <span class="gp">...</span>
 | ||
| <span class="go">caught <class 'ExceptionGroup'> with nested (TypeError(2),)</span>
 | ||
| <span class="go">caught <class 'ExceptionGroup'> with nested (OSError(3), OSError(4))</span>
 | ||
| <span class="go">  + Exception Group Traceback (most recent call last):</span>
 | ||
| <span class="go">  |   File "<stdin>", line 2, in <module></span>
 | ||
| <span class="go">  | ExceptionGroup: eg</span>
 | ||
| <span class="go">  +-+---------------- 1 ----------------</span>
 | ||
| <span class="go">    | ValueError: 1</span>
 | ||
| <span class="go">    +------------------------------------</span>
 | ||
| </pre></div>
 | ||
| </div>
 | ||
| <p>Any remaining exceptions that were not handled by any <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code>
 | ||
| clause are re-raised at the end, along with all exceptions that were
 | ||
| raised from within the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code> clauses. If this list contains
 | ||
| more than one exception to reraise, they are combined into an exception
 | ||
| group.</p>
 | ||
| <p>If the raised exception is not an exception group and its type matches
 | ||
| one of the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code> clauses, it is caught and wrapped by an
 | ||
| exception group with an empty message string.</p>
 | ||
| <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></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">BlockingIOError</span>
 | ||
| <span class="gp">... </span><span class="k">except</span><span class="o">*</span> <span class="ne">BlockingIOError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
 | ||
| <span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="nb">repr</span><span class="p">(</span><span class="n">e</span><span class="p">))</span>
 | ||
| <span class="gp">...</span>
 | ||
| <span class="go">ExceptionGroup('', (BlockingIOError()))</span>
 | ||
| </pre></div>
 | ||
| </div>
 | ||
| <p>An <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code> clause must have a matching expression; it cannot be <code class="docutils literal notranslate"><span class="pre">except*:</span></code>.
 | ||
| Furthermore, this expression cannot contain exception group types, because that would
 | ||
| have ambiguous semantics.</p>
 | ||
| <p>It is not possible to mix <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">except*</span></code>
 | ||
| in the same <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="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</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> and <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>
 | ||
| cannot appear in an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code> clause.</p>
 | ||
| </section>
 | ||
| <section id="else-clause">
 | ||
| <span id="except-else"></span><span id="index-13"></span><h3><span class="section-number">8.4.3. </span><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause<a class="headerlink" href="#else-clause" title="Link to this heading">¶</a></h3>
 | ||
| <p>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>
 | ||
| </section>
 | ||
| <section id="finally-clause">
 | ||
| <span id="finally"></span><span id="index-14"></span><h3><span class="section-number">8.4.4. </span><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause<a class="headerlink" href="#finally-clause" title="Link to this heading">¶</a></h3>
 | ||
| <p>If <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> 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
 | ||
| <a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> 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="w"> </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 <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause.</p>
 | ||
| <p id="index-15">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 <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause is also executed ‘on the way out.’</p>
 | ||
| <p>The return value of a function is determined by the last <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a>
 | ||
| statement executed.  Since the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> 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="w"> </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>
 | ||
| <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
 | ||
| <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause due to a problem with the implementation.</p>
 | ||
| </div>
 | ||
| </section>
 | ||
| </section>
 | ||
| <section id="the-with-statement">
 | ||
| <span id="as"></span><span id="with"></span><h2><span class="section-number">8.5. </span>The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> statement<a class="headerlink" href="#the-with-statement" title="Link to this heading">¶</a></h2>
 | ||
| <p id="index-16">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">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">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">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 <a class="reference internal" href="datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> is loaded for later use.</p></li>
 | ||
| <li><p>The context manager’s <a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> is loaded for later use.</p></li>
 | ||
| <li><p>The context manager’s <a class="reference internal" href="datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> 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 <a class="reference internal" href="datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> is assigned to it.</p>
 | ||
| <div class="admonition note">
 | ||
| <p class="admonition-title">Note</p>
 | ||
| <p>The <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement guarantees that if the <a class="reference internal" href="datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a>
 | ||
| method returns without an error, then <a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> will always be
 | ||
| called. Thus, if an error occurs during the assignment to the target list,
 | ||
| it will be treated the same as an error occurring within the suite would
 | ||
| be. See step 7 below.</p>
 | ||
| </div>
 | ||
| </li>
 | ||
| <li><p>The suite is executed.</p></li>
 | ||
| <li><p>The context manager’s <a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method is invoked.  If an exception
 | ||
| caused the suite to be exited, its type, value, and traceback are passed as
 | ||
| arguments to <a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a>. 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
 | ||
| <a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method was false, the exception is reraised.  If the return
 | ||
| value was true, the exception is suppressed, and execution continues with the
 | ||
| statement following the <a class="reference internal" href="#with"><code 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 <a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> is ignored, and execution proceeds at the normal
 | ||
| location for the kind of exit that was taken.</p>
 | ||
| </li>
 | ||
| </ol>
 | ||
| <p>The following code:</p>
 | ||
| <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-17"></span><a class="pep reference external" href="https://peps.python.org/pep-0343/"><strong>PEP 343</strong></a> - The “with” statement</dt><dd><p>The specification, background, and examples for the Python <a class="reference internal" href="#with"><code 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="Link to this heading">¶</a></h2>
 | ||
| <div class="versionadded" id="index-18">
 | ||
| <p><span class="versionmodified added">Added 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">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">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">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-19"></span><a class="pep reference external" href="https://peps.python.org/pep-0634/"><strong>PEP 634</strong></a> – Structural Pattern Matching: Specification</p></li>
 | ||
| <li><p><span class="target" id="index-20"></span><a class="pep reference external" href="https://peps.python.org/pep-0636/"><strong>PEP 636</strong></a> – Structural Pattern Matching: Tutorial</p></li>
 | ||
| </ul>
 | ||
| </div>
 | ||
| <section id="overview">
 | ||
| <h3><span class="section-number">8.6.1. </span>Overview<a class="headerlink" href="#overview" title="Link to this heading">¶</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>
 | ||
| <div class="admonition note">
 | ||
| <p class="admonition-title">Note</p>
 | ||
| <p>During failed pattern matches, some subpatterns may succeed.  Do not
 | ||
| rely on bindings being made for a failed match.  Conversely, do not
 | ||
| rely on variables remaining unchanged after a failed match.  The exact
 | ||
| behavior is dependent on implementation and may vary.  This is an
 | ||
| intentional decision made to allow different implementations to add
 | ||
| optimizations.</p>
 | ||
| </div>
 | ||
| </li>
 | ||
| <li><p>If the pattern succeeds, the corresponding guard (if present) is evaluated. In
 | ||
| this case all name bindings are guaranteed to have happened.</p>
 | ||
| <ul class="simple">
 | ||
| <li><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="w"> </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="Link to this heading">¶</a></h3>
 | ||
| <pre id="index-21">
 | ||
| <strong id="grammar-token-python-grammar-guard">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="Link to this heading">¶</a></h3>
 | ||
| <p id="index-22">An irrefutable case block is a match-all case block.  A match statement may have
 | ||
| at most one irrefutable case block, and it must be last.</p>
 | ||
| <p>A case block is considered irrefutable if it has no guard and its pattern is
 | ||
| irrefutable.  A pattern is considered irrefutable if we can prove from its
 | ||
| syntax alone that it will always succeed.  Only the following patterns are
 | ||
| irrefutable:</p>
 | ||
| <ul class="simple">
 | ||
| <li><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="Link to this heading">¶</a></h3>
 | ||
| <div class="admonition note" id="index-23">
 | ||
| <p class="admonition-title">Note</p>
 | ||
| <p>This section uses grammar notations beyond standard EBNF:</p>
 | ||
| <ul class="simple">
 | ||
| <li><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">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">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">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="id3"></span><h4><span class="section-number">8.6.4.1. </span>OR Patterns<a class="headerlink" href="#or-patterns" title="Link to this heading">¶</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">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="id4"></span><h4><span class="section-number">8.6.4.2. </span>AS Patterns<a class="headerlink" href="#as-patterns" title="Link to this heading">¶</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">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="id5"></span><h4><span class="section-number">8.6.4.3. </span>Literal Patterns<a class="headerlink" href="#literal-patterns" title="Link to this heading">¶</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">literal_pattern</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-signed_number"><code class="xref docutils literal notranslate"><span class="pre">signed_number</span></code></a>
 | ||
|                     | <a class="reference internal" href="#grammar-token-python-grammar-signed_number"><code class="xref docutils literal notranslate"><span class="pre">signed_number</span></code></a> "+" NUMBER
 | ||
|                     | <a class="reference internal" href="#grammar-token-python-grammar-signed_number"><code class="xref docutils literal notranslate"><span class="pre">signed_number</span></code></a> "-" NUMBER
 | ||
|                     | <code class="xref docutils literal notranslate"><span class="pre">strings</span></code>
 | ||
|                     | "None"
 | ||
|                     | "True"
 | ||
|                     | "False"
 | ||
| <strong id="grammar-token-python-grammar-signed_number">signed_number</strong>   ::= ["-"] 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">f-strings</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="id6"></span><h4><span class="section-number">8.6.4.4. </span>Capture Patterns<a class="headerlink" href="#capture-patterns" title="Link to this heading">¶</a></h4>
 | ||
| <p>A capture pattern binds the subject value to a name.
 | ||
| Syntax:</p>
 | ||
| <pre>
 | ||
| <strong id="grammar-token-python-grammar-capture_pattern">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-24"></span><a class="pep reference external" href="https://peps.python.org/pep-0572/"><strong>PEP 572</strong></a>; the
 | ||
| name becomes a local variable in the closest containing function scope unless
 | ||
| there’s an applicable <a class="reference internal" href="simple_stmts.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="id7"></span><h4><span class="section-number">8.6.4.5. </span>Wildcard Patterns<a class="headerlink" href="#wildcard-patterns" title="Link to this heading">¶</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">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="id8"></span><h4><span class="section-number">8.6.4.6. </span>Value Patterns<a class="headerlink" href="#value-patterns" title="Link to this heading">¶</a></h4>
 | ||
| <p>A value pattern represents a named value in Python.
 | ||
| Syntax:</p>
 | ||
| <pre>
 | ||
| <strong id="grammar-token-python-grammar-value_pattern">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">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">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="id9"></span><h4><span class="section-number">8.6.4.7. </span>Group Patterns<a class="headerlink" href="#group-patterns" title="Link to this heading">¶</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">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="id10"></span><h4><span class="section-number">8.6.4.8. </span>Sequence Patterns<a class="headerlink" href="#sequence-patterns" title="Link to this heading">¶</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">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">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">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">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">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="#id21" id="id11" role="doc-noteref"><span class="fn-bracket">[</span>2<span class="fn-bracket">]</span></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="id12"></span><h4><span class="section-number">8.6.4.9. </span>Mapping Patterns<a class="headerlink" href="#mapping-patterns" title="Link to this heading">¶</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">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">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">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">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="#id22" id="id13" role="doc-noteref"><span class="fn-bracket">[</span>3<span class="fn-bracket">]</span></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
 | ||
| <a class="reference internal" href="datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>.</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="id14"></span><h4><span class="section-number">8.6.4.10. </span>Class Patterns<a class="headerlink" href="#class-patterns" title="Link to this heading">¶</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">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">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">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">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">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><p>For each keyword argument <code class="docutils literal notranslate"><span class="pre">attr=P2</span></code>:</p>
 | ||
| <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>
 | ||
| </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-25"></span><a class="pep reference external" href="https://peps.python.org/pep-0634/"><strong>PEP 634</strong></a> – Structural Pattern Matching: Specification</p></li>
 | ||
| <li><p><span class="target" id="index-26"></span><a class="pep reference external" href="https://peps.python.org/pep-0636/"><strong>PEP 636</strong></a> – Structural Pattern Matching: Tutorial</p></li>
 | ||
| </ul>
 | ||
| </div>
 | ||
| </section>
 | ||
| </section>
 | ||
| </section>
 | ||
| <section id="function-definitions">
 | ||
| <span id="def"></span><span id="function"></span><span id="index-27"></span><h2><span class="section-number">8.7. </span>Function definitions<a class="headerlink" href="#function-definitions" title="Link to this heading">¶</a></h2>
 | ||
| <p id="index-28">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">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-type_params"><code class="xref docutils literal notranslate"><span class="pre">type_params</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">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">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">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">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">parameter_list_starargs</strong>   ::= "*" [<a class="reference internal" href="#grammar-token-python-grammar-star_parameter"><code class="xref docutils literal notranslate"><span class="pre">star_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_star_kwargs"><code class="xref docutils literal notranslate"><span class="pre">parameter_star_kwargs</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_star_kwargs"><code class="xref docutils literal notranslate"><span class="pre">parameter_star_kwargs</span></code></a>]]
 | ||
|                               | <a class="reference internal" href="#grammar-token-python-grammar-parameter_star_kwargs"><code class="xref docutils literal notranslate"><span class="pre">parameter_star_kwargs</span></code></a>
 | ||
| <strong id="grammar-token-python-grammar-parameter_star_kwargs">parameter_star_kwargs</strong>     ::= "**" <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">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-star_parameter">star_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">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">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="#id23" id="id15" role="doc-noteref"><span class="fn-bracket">[</span>4<span class="fn-bracket">]</span></a></p>
 | ||
| <p id="index-29">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="w"> </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="w"> </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-30"></span><a class="pep reference external" href="https://peps.python.org/pep-0614/"><strong>PEP 614</strong></a> for details.</p>
 | ||
| </div>
 | ||
| <p>A list of <a class="reference internal" href="#type-params"><span class="std std-ref">type parameters</span></a> may be given in square brackets
 | ||
| between the function’s name and the opening parenthesis for its parameter list.
 | ||
| This indicates to static type checkers that the function is generic. At runtime,
 | ||
| the type parameters can be retrieved from the function’s
 | ||
| <a class="reference internal" href="datamodel.html#function.__type_params__" title="function.__type_params__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__type_params__</span></code></a>
 | ||
| attribute. See <a class="reference internal" href="#generic-functions"><span class="std std-ref">Generic functions</span></a> for more.</p>
 | ||
| <div class="versionchanged">
 | ||
| <p><span class="versionmodified changed">Changed in version 3.12: </span>Type parameter lists are new in Python 3.12.</p>
 | ||
| </div>
 | ||
| <p id="index-31">When one or more <a class="reference internal" href="../glossary.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="w"> </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-32">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-33"></span><a class="pep reference external" href="https://peps.python.org/pep-0570/"><strong>PEP 570</strong></a> for details.</p>
 | ||
| </div>
 | ||
| <p id="index-34">Parameters may have an <a class="reference internal" href="../glossary.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>. (As a special case, parameters of the form
 | ||
| <code class="docutils literal notranslate"><span class="pre">*identifier</span></code> may have an annotation “<code class="docutils literal notranslate"><span class="pre">:</span> <span class="pre">*expression</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>
 | ||
| <div class="versionchanged">
 | ||
| <p><span class="versionmodified changed">Changed in version 3.11: </span>Parameters of the form “<code class="docutils literal notranslate"><span class="pre">*identifier</span></code>” may have an annotation
 | ||
| “<code class="docutils literal notranslate"><span class="pre">:</span> <span class="pre">*expression</span></code>”. See <span class="target" id="index-35"></span><a class="pep reference external" href="https://peps.python.org/pep-0646/"><strong>PEP 646</strong></a>.</p>
 | ||
| </div>
 | ||
| <p id="index-36">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-37"></span><a class="pep reference external" href="https://peps.python.org/pep-3107/"><strong>PEP 3107</strong></a> - Function Annotations</dt><dd><p>The original specification for function annotations.</p>
 | ||
| </dd>
 | ||
| <dt><span class="target" id="index-38"></span><a class="pep reference external" href="https://peps.python.org/pep-0484/"><strong>PEP 484</strong></a> - Type Hints</dt><dd><p>Definition of a standard meaning for annotations: type hints.</p>
 | ||
| </dd>
 | ||
| <dt><span class="target" id="index-39"></span><a class="pep reference external" href="https://peps.python.org/pep-0526/"><strong>PEP 526</strong></a> - Syntax for Variable Annotations</dt><dd><p>Ability to type hint variable declarations, including class
 | ||
| variables and instance variables.</p>
 | ||
| </dd>
 | ||
| <dt><span class="target" id="index-40"></span><a class="pep reference external" href="https://peps.python.org/pep-0563/"><strong>PEP 563</strong></a> - Postponed Evaluation of Annotations</dt><dd><p>Support for forward references within annotations by preserving
 | ||
| annotations in a string form at runtime instead of eager evaluation.</p>
 | ||
| </dd>
 | ||
| <dt><span class="target" id="index-41"></span><a class="pep reference external" href="https://peps.python.org/pep-0318/"><strong>PEP 318</strong></a> - Decorators for Functions and Methods</dt><dd><p>Function and method decorators were introduced.
 | ||
| Class decorators were introduced in <span class="target" id="index-42"></span><a class="pep reference external" href="https://peps.python.org/pep-3129/"><strong>PEP 3129</strong></a>.</p>
 | ||
| </dd>
 | ||
| </dl>
 | ||
| </div>
 | ||
| </section>
 | ||
| <section id="class-definitions">
 | ||
| <span id="class"></span><h2><span class="section-number">8.8. </span>Class definitions<a class="headerlink" href="#class-definitions" title="Link to this heading">¶</a></h2>
 | ||
| <p id="index-43">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">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-type_params"><code class="xref docutils literal notranslate"><span class="pre">type_params</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">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">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="w"> </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="w"> </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="#id24" id="id16" role="doc-noteref"><span class="fn-bracket">[</span>5<span class="fn-bracket">]</span></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 <a class="reference internal" href="datamodel.html#type.__dict__" title="type.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a>.  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-44">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="w"> </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="w"> </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-45"></span><a class="pep reference external" href="https://peps.python.org/pep-0614/"><strong>PEP 614</strong></a> for details.</p>
 | ||
| </div>
 | ||
| <p>A list of <a class="reference internal" href="#type-params"><span class="std std-ref">type parameters</span></a> may be given in square brackets
 | ||
| immediately after the class’s name.
 | ||
| This indicates to static type checkers that the class is generic. At runtime,
 | ||
| the type parameters can be retrieved from the class’s
 | ||
| <a class="reference internal" href="datamodel.html#type.__type_params__" title="type.__type_params__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__type_params__</span></code></a> attribute. See <a class="reference internal" href="#generic-classes"><span class="std std-ref">Generic classes</span></a> for more.</p>
 | ||
| <div class="versionchanged">
 | ||
| <p><span class="versionmodified changed">Changed in version 3.12: </span>Type parameter lists are new in Python 3.12.</p>
 | ||
| </div>
 | ||
| <p><strong>Programmer’s note:</strong> Variables defined in the class definition are class
 | ||
| attributes; they are shared by instances.  Instance attributes can be set in a
 | ||
| method with <code 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-46"></span><a class="pep reference external" href="https://peps.python.org/pep-3115/"><strong>PEP 3115</strong></a> - Metaclasses in Python 3000</dt><dd><p>The proposal that changed the declaration of metaclasses to the current
 | ||
| syntax, and the semantics for how classes with metaclasses are
 | ||
| constructed.</p>
 | ||
| </dd>
 | ||
| <dt><span class="target" id="index-47"></span><a class="pep reference external" href="https://peps.python.org/pep-3129/"><strong>PEP 3129</strong></a> - Class Decorators</dt><dd><p>The proposal that added class decorators.  Function and method decorators
 | ||
| were introduced in <span class="target" id="index-48"></span><a class="pep reference external" href="https://peps.python.org/pep-0318/"><strong>PEP 318</strong></a>.</p>
 | ||
| </dd>
 | ||
| </dl>
 | ||
| </div>
 | ||
| </section>
 | ||
| <section id="coroutines">
 | ||
| <span id="async"></span><h2><span class="section-number">8.9. </span>Coroutines<a class="headerlink" href="#coroutines" title="Link to this heading">¶</a></h2>
 | ||
| <div class="versionadded">
 | ||
| <p><span class="versionmodified added">Added in version 3.5.</span></p>
 | ||
| </div>
 | ||
| <section id="coroutine-function-definition">
 | ||
| <span id="async-def"></span><span id="index-49"></span><h3><span class="section-number">8.9.1. </span>Coroutine function definition<a class="headerlink" href="#coroutine-function-definition" title="Link to this heading">¶</a></h3>
 | ||
| <pre>
 | ||
| <strong id="grammar-token-python-grammar-async_funcdef">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-50">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="w"> </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-51"></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="Link to this heading">¶</a></h3>
 | ||
| <pre>
 | ||
| <strong id="grammar-token-python-grammar-async_for_stmt">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-52"></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="Link to this heading">¶</a></h3>
 | ||
| <pre>
 | ||
| <strong id="grammar-token-python-grammar-async_with_stmt">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-53"></span><a class="pep reference external" href="https://peps.python.org/pep-0492/"><strong>PEP 492</strong></a> - Coroutines with async and await syntax</dt><dd><p>The proposal that made coroutines a proper standalone concept in Python,
 | ||
| and added supporting syntax.</p>
 | ||
| </dd>
 | ||
| </dl>
 | ||
| </div>
 | ||
| </section>
 | ||
| </section>
 | ||
| <section id="type-parameter-lists">
 | ||
| <span id="type-params"></span><h2><span class="section-number">8.10. </span>Type parameter lists<a class="headerlink" href="#type-parameter-lists" title="Link to this heading">¶</a></h2>
 | ||
| <div class="versionadded">
 | ||
| <p><span class="versionmodified added">Added in version 3.12.</span></p>
 | ||
| </div>
 | ||
| <div class="versionchanged">
 | ||
| <p><span class="versionmodified changed">Changed in version 3.13: </span>Support for default values was added (see <span class="target" id="index-54"></span><a class="pep reference external" href="https://peps.python.org/pep-0696/"><strong>PEP 696</strong></a>).</p>
 | ||
| </div>
 | ||
| <pre id="index-55">
 | ||
| <strong id="grammar-token-python-grammar-type_params">type_params</strong>  ::= "[" <a class="reference internal" href="#grammar-token-python-grammar-type_param"><code class="xref docutils literal notranslate"><span class="pre">type_param</span></code></a> ("," <a class="reference internal" href="#grammar-token-python-grammar-type_param"><code class="xref docutils literal notranslate"><span class="pre">type_param</span></code></a>)* "]"
 | ||
| <strong id="grammar-token-python-grammar-type_param">type_param</strong>   ::= <a class="reference internal" href="#grammar-token-python-grammar-typevar"><code class="xref docutils literal notranslate"><span class="pre">typevar</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-typevartuple"><code class="xref docutils literal notranslate"><span class="pre">typevartuple</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-paramspec"><code class="xref docutils literal notranslate"><span class="pre">paramspec</span></code></a>
 | ||
| <strong id="grammar-token-python-grammar-typevar">typevar</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>)? ("=" <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-typevartuple">typevartuple</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-paramspec">paramspec</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>)?
 | ||
| </pre>
 | ||
| <p><a class="reference internal" href="#def"><span class="std std-ref">Functions</span></a> (including <a class="reference internal" href="#async-def"><span class="std std-ref">coroutines</span></a>),
 | ||
| <a class="reference internal" href="#class"><span class="std std-ref">classes</span></a> and <a class="reference internal" href="simple_stmts.html#type"><span class="std std-ref">type aliases</span></a> may
 | ||
| contain a type parameter list:</p>
 | ||
| <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">max</span><span class="p">[</span><span class="n">T</span><span class="p">](</span><span class="n">args</span><span class="p">:</span> <span class="nb">list</span><span class="p">[</span><span class="n">T</span><span class="p">])</span> <span class="o">-></span> <span class="n">T</span><span class="p">:</span>
 | ||
|     <span class="o">...</span>
 | ||
| 
 | ||
| <span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">amax</span><span class="p">[</span><span class="n">T</span><span class="p">](</span><span class="n">args</span><span class="p">:</span> <span class="nb">list</span><span class="p">[</span><span class="n">T</span><span class="p">])</span> <span class="o">-></span> <span class="n">T</span><span class="p">:</span>
 | ||
|     <span class="o">...</span>
 | ||
| 
 | ||
| <span class="k">class</span><span class="w"> </span><span class="nc">Bag</span><span class="p">[</span><span class="n">T</span><span class="p">]:</span>
 | ||
|     <span class="k">def</span><span class="w"> </span><span class="fm">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span> <span class="o">-></span> <span class="n">Iterator</span><span class="p">[</span><span class="n">T</span><span class="p">]:</span>
 | ||
|         <span class="o">...</span>
 | ||
| 
 | ||
|     <span class="k">def</span><span class="w"> </span><span class="nf">add</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">arg</span><span class="p">:</span> <span class="n">T</span><span class="p">)</span> <span class="o">-></span> <span class="kc">None</span><span class="p">:</span>
 | ||
|         <span class="o">...</span>
 | ||
| 
 | ||
| <span class="nb">type</span> <span class="n">ListOrSet</span><span class="p">[</span><span class="n">T</span><span class="p">]</span> <span class="o">=</span> <span class="nb">list</span><span class="p">[</span><span class="n">T</span><span class="p">]</span> <span class="o">|</span> <span class="nb">set</span><span class="p">[</span><span class="n">T</span><span class="p">]</span>
 | ||
| </pre></div>
 | ||
| </div>
 | ||
| <p>Semantically, this indicates that the function, class, or type alias is
 | ||
| generic over a type variable. This information is primarily used by static
 | ||
| type checkers, and at runtime, generic objects behave much like their
 | ||
| non-generic counterparts.</p>
 | ||
| <p>Type parameters are declared in square brackets (<code class="docutils literal notranslate"><span class="pre">[]</span></code>) immediately
 | ||
| after the name of the function, class, or type alias. The type parameters
 | ||
| are accessible within the scope of the generic object, but not elsewhere.
 | ||
| Thus, after a declaration <code class="docutils literal notranslate"><span class="pre">def</span> <span class="pre">func[T]():</span> <span class="pre">pass</span></code>, the name <code class="docutils literal notranslate"><span class="pre">T</span></code> is not available in
 | ||
| the module scope. Below, the semantics of generic objects are described
 | ||
| with more precision. The scope of type parameters is modeled with a special
 | ||
| function (technically, an <a class="reference internal" href="executionmodel.html#annotation-scopes"><span class="std std-ref">annotation scope</span></a>) that
 | ||
| wraps the creation of the generic object.</p>
 | ||
| <p>Generic functions, classes, and type aliases have a
 | ||
| <a class="reference internal" href="../library/stdtypes.html#definition.__type_params__" title="definition.__type_params__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__type_params__</span></code></a> attribute listing their type parameters.</p>
 | ||
| <p>Type parameters come in three kinds:</p>
 | ||
| <ul class="simple">
 | ||
| <li><p><a class="reference internal" href="../library/typing.html#typing.TypeVar" title="typing.TypeVar"><code class="xref py py-data docutils literal notranslate"><span class="pre">typing.TypeVar</span></code></a>, introduced by a plain name (e.g., <code class="docutils literal notranslate"><span class="pre">T</span></code>). Semantically, this
 | ||
| represents a single type to a type checker.</p></li>
 | ||
| <li><p><a class="reference internal" href="../library/typing.html#typing.TypeVarTuple" title="typing.TypeVarTuple"><code class="xref py py-data docutils literal notranslate"><span class="pre">typing.TypeVarTuple</span></code></a>, introduced by a name prefixed with a single
 | ||
| asterisk (e.g., <code class="docutils literal notranslate"><span class="pre">*Ts</span></code>). Semantically, this stands for a tuple of any
 | ||
| number of types.</p></li>
 | ||
| <li><p><a class="reference internal" href="../library/typing.html#typing.ParamSpec" title="typing.ParamSpec"><code class="xref py py-data docutils literal notranslate"><span class="pre">typing.ParamSpec</span></code></a>, introduced by a name prefixed with two asterisks
 | ||
| (e.g., <code class="docutils literal notranslate"><span class="pre">**P</span></code>). Semantically, this stands for the parameters of a callable.</p></li>
 | ||
| </ul>
 | ||
| <p><a class="reference internal" href="../library/typing.html#typing.TypeVar" title="typing.TypeVar"><code class="xref py py-data docutils literal notranslate"><span class="pre">typing.TypeVar</span></code></a> declarations can define <em>bounds</em> and <em>constraints</em> with
 | ||
| a colon (<code class="docutils literal notranslate"><span class="pre">:</span></code>) followed by an expression. A single expression after the colon
 | ||
| indicates a bound (e.g. <code class="docutils literal notranslate"><span class="pre">T:</span> <span class="pre">int</span></code>). Semantically, this means
 | ||
| that the <code class="xref py py-data docutils literal notranslate"><span class="pre">typing.TypeVar</span></code> can only represent types that are a subtype of
 | ||
| this bound. A parenthesized tuple of expressions after the colon indicates a
 | ||
| set of constraints (e.g. <code class="docutils literal notranslate"><span class="pre">T:</span> <span class="pre">(str,</span> <span class="pre">bytes)</span></code>). Each member of the tuple should be a
 | ||
| type (again, this is not enforced at runtime). Constrained type variables can only
 | ||
| take on one of the types in the list of constraints.</p>
 | ||
| <p>For <code class="xref py py-data docutils literal notranslate"><span class="pre">typing.TypeVar</span></code>s declared using the type parameter list syntax,
 | ||
| the bound and constraints are not evaluated when the generic object is created,
 | ||
| but only when the value is explicitly accessed through the attributes <code class="docutils literal notranslate"><span class="pre">__bound__</span></code>
 | ||
| and <code class="docutils literal notranslate"><span class="pre">__constraints__</span></code>. To accomplish this, the bounds or constraints are
 | ||
| evaluated in a separate <a class="reference internal" href="executionmodel.html#annotation-scopes"><span class="std std-ref">annotation scope</span></a>.</p>
 | ||
| <p><a class="reference internal" href="../library/typing.html#typing.TypeVarTuple" title="typing.TypeVarTuple"><code class="xref py py-data docutils literal notranslate"><span class="pre">typing.TypeVarTuple</span></code></a>s and <a class="reference internal" href="../library/typing.html#typing.ParamSpec" title="typing.ParamSpec"><code class="xref py py-data docutils literal notranslate"><span class="pre">typing.ParamSpec</span></code></a>s cannot have bounds
 | ||
| or constraints.</p>
 | ||
| <p>All three flavors of type parameters can also have a <em>default value</em>, which is used
 | ||
| when the type parameter is not explicitly provided. This is added by appending
 | ||
| a single equals sign (<code class="docutils literal notranslate"><span class="pre">=</span></code>) followed by an expression. Like the bounds and
 | ||
| constraints of type variables, the default value is not evaluated when the
 | ||
| object is created, but only when the type parameter’s <code class="docutils literal notranslate"><span class="pre">__default__</span></code> attribute
 | ||
| is accessed. To this end, the default value is evaluated in a separate
 | ||
| <a class="reference internal" href="executionmodel.html#annotation-scopes"><span class="std std-ref">annotation scope</span></a>. If no default value is specified
 | ||
| for a type parameter, the <code class="docutils literal notranslate"><span class="pre">__default__</span></code> attribute is set to the special
 | ||
| sentinel object <a class="reference internal" href="../library/typing.html#typing.NoDefault" title="typing.NoDefault"><code class="xref py py-data docutils literal notranslate"><span class="pre">typing.NoDefault</span></code></a>.</p>
 | ||
| <p>The following example indicates the full set of allowed type parameter declarations:</p>
 | ||
| <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">overly_generic</span><span class="p">[</span>
 | ||
|    <span class="n">SimpleTypeVar</span><span class="p">,</span>
 | ||
|    <span class="n">TypeVarWithDefault</span> <span class="o">=</span> <span class="nb">int</span><span class="p">,</span>
 | ||
|    <span class="n">TypeVarWithBound</span><span class="p">:</span> <span class="nb">int</span><span class="p">,</span>
 | ||
|    <span class="n">TypeVarWithConstraints</span><span class="p">:</span> <span class="p">(</span><span class="nb">str</span><span class="p">,</span> <span class="nb">bytes</span><span class="p">),</span>
 | ||
|    <span class="o">*</span><span class="n">SimpleTypeVarTuple</span> <span class="o">=</span> <span class="p">(</span><span class="nb">int</span><span class="p">,</span> <span class="nb">float</span><span class="p">),</span>
 | ||
|    <span class="o">**</span><span class="n">SimpleParamSpec</span> <span class="o">=</span> <span class="p">(</span><span class="nb">str</span><span class="p">,</span> <span class="nb">bytearray</span><span class="p">),</span>
 | ||
| <span class="p">](</span>
 | ||
|    <span class="n">a</span><span class="p">:</span> <span class="n">SimpleTypeVar</span><span class="p">,</span>
 | ||
|    <span class="n">b</span><span class="p">:</span> <span class="n">TypeVarWithDefault</span><span class="p">,</span>
 | ||
|    <span class="n">c</span><span class="p">:</span> <span class="n">TypeVarWithBound</span><span class="p">,</span>
 | ||
|    <span class="n">d</span><span class="p">:</span> <span class="n">Callable</span><span class="p">[</span><span class="n">SimpleParamSpec</span><span class="p">,</span> <span class="n">TypeVarWithConstraints</span><span class="p">],</span>
 | ||
|    <span class="o">*</span><span class="n">e</span><span class="p">:</span> <span class="n">SimpleTypeVarTuple</span><span class="p">,</span>
 | ||
| <span class="p">):</span> <span class="o">...</span>
 | ||
| </pre></div>
 | ||
| </div>
 | ||
| <section id="generic-functions">
 | ||
| <span id="id17"></span><h3><span class="section-number">8.10.1. </span>Generic functions<a class="headerlink" href="#generic-functions" title="Link to this heading">¶</a></h3>
 | ||
| <p>Generic functions are declared as follows:</p>
 | ||
| <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">func</span><span class="p">[</span><span class="n">T</span><span class="p">](</span><span class="n">arg</span><span class="p">:</span> <span class="n">T</span><span class="p">):</span> <span class="o">...</span>
 | ||
| </pre></div>
 | ||
| </div>
 | ||
| <p>This syntax is equivalent to:</p>
 | ||
| <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">annotation</span><span class="o">-</span><span class="k">def</span><span class="w"> </span><span class="nf">TYPE_PARAMS_OF_func</span><span class="p">():</span>
 | ||
|     <span class="n">T</span> <span class="o">=</span> <span class="n">typing</span><span class="o">.</span><span class="n">TypeVar</span><span class="p">(</span><span class="s2">"T"</span><span class="p">)</span>
 | ||
|     <span class="k">def</span><span class="w"> </span><span class="nf">func</span><span class="p">(</span><span class="n">arg</span><span class="p">:</span> <span class="n">T</span><span class="p">):</span> <span class="o">...</span>
 | ||
|     <span class="n">func</span><span class="o">.</span><span class="n">__type_params__</span> <span class="o">=</span> <span class="p">(</span><span class="n">T</span><span class="p">,)</span>
 | ||
|     <span class="k">return</span> <span class="n">func</span>
 | ||
| <span class="n">func</span> <span class="o">=</span> <span class="n">TYPE_PARAMS_OF_func</span><span class="p">()</span>
 | ||
| </pre></div>
 | ||
| </div>
 | ||
| <p>Here <code class="docutils literal notranslate"><span class="pre">annotation-def</span></code> indicates an <a class="reference internal" href="executionmodel.html#annotation-scopes"><span class="std std-ref">annotation scope</span></a>,
 | ||
| which is not actually bound to any name at runtime. (One
 | ||
| other liberty is taken in the translation: the syntax does not go through
 | ||
| attribute access on the <a class="reference internal" href="../library/typing.html#module-typing" title="typing: Support for type hints (see :pep:`484`)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">typing</span></code></a> module, but creates an instance of
 | ||
| <a class="reference internal" href="../library/typing.html#typing.TypeVar" title="typing.TypeVar"><code class="xref py py-data docutils literal notranslate"><span class="pre">typing.TypeVar</span></code></a> directly.)</p>
 | ||
| <p>The annotations of generic functions are evaluated within the annotation scope
 | ||
| used for declaring the type parameters, but the function’s defaults and
 | ||
| decorators are not.</p>
 | ||
| <p>The following example illustrates the scoping rules for these cases,
 | ||
| as well as for additional flavors of type parameters:</p>
 | ||
| <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nd">@decorator</span>
 | ||
| <span class="k">def</span><span class="w"> </span><span class="nf">func</span><span class="p">[</span><span class="n">T</span><span class="p">:</span> <span class="nb">int</span><span class="p">,</span> <span class="o">*</span><span class="n">Ts</span><span class="p">,</span> <span class="o">**</span><span class="n">P</span><span class="p">](</span><span class="o">*</span><span class="n">args</span><span class="p">:</span> <span class="o">*</span><span class="n">Ts</span><span class="p">,</span> <span class="n">arg</span><span class="p">:</span> <span class="n">Callable</span><span class="p">[</span><span class="n">P</span><span class="p">,</span> <span class="n">T</span><span class="p">]</span> <span class="o">=</span> <span class="n">some_default</span><span class="p">):</span>
 | ||
|     <span class="o">...</span>
 | ||
| </pre></div>
 | ||
| </div>
 | ||
| <p>Except for the <a class="reference internal" href="executionmodel.html#lazy-evaluation"><span class="std std-ref">lazy evaluation</span></a> of the
 | ||
| <a class="reference internal" href="../library/typing.html#typing.TypeVar" title="typing.TypeVar"><code class="xref py py-class docutils literal notranslate"><span class="pre">TypeVar</span></code></a> bound, this is equivalent to:</p>
 | ||
| <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">DEFAULT_OF_arg</span> <span class="o">=</span> <span class="n">some_default</span>
 | ||
| 
 | ||
| <span class="n">annotation</span><span class="o">-</span><span class="k">def</span><span class="w"> </span><span class="nf">TYPE_PARAMS_OF_func</span><span class="p">():</span>
 | ||
| 
 | ||
|     <span class="n">annotation</span><span class="o">-</span><span class="k">def</span><span class="w"> </span><span class="nf">BOUND_OF_T</span><span class="p">():</span>
 | ||
|         <span class="k">return</span> <span class="nb">int</span>
 | ||
|     <span class="c1"># In reality, BOUND_OF_T() is evaluated only on demand.</span>
 | ||
|     <span class="n">T</span> <span class="o">=</span> <span class="n">typing</span><span class="o">.</span><span class="n">TypeVar</span><span class="p">(</span><span class="s2">"T"</span><span class="p">,</span> <span class="n">bound</span><span class="o">=</span><span class="n">BOUND_OF_T</span><span class="p">())</span>
 | ||
| 
 | ||
|     <span class="n">Ts</span> <span class="o">=</span> <span class="n">typing</span><span class="o">.</span><span class="n">TypeVarTuple</span><span class="p">(</span><span class="s2">"Ts"</span><span class="p">)</span>
 | ||
|     <span class="n">P</span> <span class="o">=</span> <span class="n">typing</span><span class="o">.</span><span class="n">ParamSpec</span><span class="p">(</span><span class="s2">"P"</span><span class="p">)</span>
 | ||
| 
 | ||
|     <span class="k">def</span><span class="w"> </span><span class="nf">func</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">:</span> <span class="o">*</span><span class="n">Ts</span><span class="p">,</span> <span class="n">arg</span><span class="p">:</span> <span class="n">Callable</span><span class="p">[</span><span class="n">P</span><span class="p">,</span> <span class="n">T</span><span class="p">]</span> <span class="o">=</span> <span class="n">DEFAULT_OF_arg</span><span class="p">):</span>
 | ||
|         <span class="o">...</span>
 | ||
| 
 | ||
|     <span class="n">func</span><span class="o">.</span><span class="n">__type_params__</span> <span class="o">=</span> <span class="p">(</span><span class="n">T</span><span class="p">,</span> <span class="n">Ts</span><span class="p">,</span> <span class="n">P</span><span class="p">)</span>
 | ||
|     <span class="k">return</span> <span class="n">func</span>
 | ||
| <span class="n">func</span> <span class="o">=</span> <span class="n">decorator</span><span class="p">(</span><span class="n">TYPE_PARAMS_OF_func</span><span class="p">())</span>
 | ||
| </pre></div>
 | ||
| </div>
 | ||
| <p>The capitalized names like <code class="docutils literal notranslate"><span class="pre">DEFAULT_OF_arg</span></code> are not actually
 | ||
| bound at runtime.</p>
 | ||
| </section>
 | ||
| <section id="generic-classes">
 | ||
| <span id="id18"></span><h3><span class="section-number">8.10.2. </span>Generic classes<a class="headerlink" href="#generic-classes" title="Link to this heading">¶</a></h3>
 | ||
| <p>Generic classes are declared as follows:</p>
 | ||
| <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">Bag</span><span class="p">[</span><span class="n">T</span><span class="p">]:</span> <span class="o">...</span>
 | ||
| </pre></div>
 | ||
| </div>
 | ||
| <p>This syntax is equivalent to:</p>
 | ||
| <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">annotation</span><span class="o">-</span><span class="k">def</span><span class="w"> </span><span class="nf">TYPE_PARAMS_OF_Bag</span><span class="p">():</span>
 | ||
|     <span class="n">T</span> <span class="o">=</span> <span class="n">typing</span><span class="o">.</span><span class="n">TypeVar</span><span class="p">(</span><span class="s2">"T"</span><span class="p">)</span>
 | ||
|     <span class="k">class</span><span class="w"> </span><span class="nc">Bag</span><span class="p">(</span><span class="n">typing</span><span class="o">.</span><span class="n">Generic</span><span class="p">[</span><span class="n">T</span><span class="p">]):</span>
 | ||
|         <span class="n">__type_params__</span> <span class="o">=</span> <span class="p">(</span><span class="n">T</span><span class="p">,)</span>
 | ||
|         <span class="o">...</span>
 | ||
|     <span class="k">return</span> <span class="n">Bag</span>
 | ||
| <span class="n">Bag</span> <span class="o">=</span> <span class="n">TYPE_PARAMS_OF_Bag</span><span class="p">()</span>
 | ||
| </pre></div>
 | ||
| </div>
 | ||
| <p>Here again <code class="docutils literal notranslate"><span class="pre">annotation-def</span></code> (not a real keyword) indicates an
 | ||
| <a class="reference internal" href="executionmodel.html#annotation-scopes"><span class="std std-ref">annotation scope</span></a>, and the name
 | ||
| <code class="docutils literal notranslate"><span class="pre">TYPE_PARAMS_OF_Bag</span></code> is not actually bound at runtime.</p>
 | ||
| <p>Generic classes implicitly inherit from <a class="reference internal" href="../library/typing.html#typing.Generic" title="typing.Generic"><code class="xref py py-data docutils literal notranslate"><span class="pre">typing.Generic</span></code></a>.
 | ||
| The base classes and keyword arguments of generic classes are
 | ||
| evaluated within the type scope for the type parameters,
 | ||
| and decorators are evaluated outside that scope. This is illustrated
 | ||
| by this example:</p>
 | ||
| <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nd">@decorator</span>
 | ||
| <span class="k">class</span><span class="w"> </span><span class="nc">Bag</span><span class="p">(</span><span class="n">Base</span><span class="p">[</span><span class="n">T</span><span class="p">],</span> <span class="n">arg</span><span class="o">=</span><span class="n">T</span><span class="p">):</span> <span class="o">...</span>
 | ||
| </pre></div>
 | ||
| </div>
 | ||
| <p>This is equivalent to:</p>
 | ||
| <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">annotation</span><span class="o">-</span><span class="k">def</span><span class="w"> </span><span class="nf">TYPE_PARAMS_OF_Bag</span><span class="p">():</span>
 | ||
|     <span class="n">T</span> <span class="o">=</span> <span class="n">typing</span><span class="o">.</span><span class="n">TypeVar</span><span class="p">(</span><span class="s2">"T"</span><span class="p">)</span>
 | ||
|     <span class="k">class</span><span class="w"> </span><span class="nc">Bag</span><span class="p">(</span><span class="n">Base</span><span class="p">[</span><span class="n">T</span><span class="p">],</span> <span class="n">typing</span><span class="o">.</span><span class="n">Generic</span><span class="p">[</span><span class="n">T</span><span class="p">],</span> <span class="n">arg</span><span class="o">=</span><span class="n">T</span><span class="p">):</span>
 | ||
|         <span class="n">__type_params__</span> <span class="o">=</span> <span class="p">(</span><span class="n">T</span><span class="p">,)</span>
 | ||
|         <span class="o">...</span>
 | ||
|     <span class="k">return</span> <span class="n">Bag</span>
 | ||
| <span class="n">Bag</span> <span class="o">=</span> <span class="n">decorator</span><span class="p">(</span><span class="n">TYPE_PARAMS_OF_Bag</span><span class="p">())</span>
 | ||
| </pre></div>
 | ||
| </div>
 | ||
| </section>
 | ||
| <section id="generic-type-aliases">
 | ||
| <span id="id19"></span><h3><span class="section-number">8.10.3. </span>Generic type aliases<a class="headerlink" href="#generic-type-aliases" title="Link to this heading">¶</a></h3>
 | ||
| <p>The <a class="reference internal" href="simple_stmts.html#type"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">type</span></code></a> statement can also be used to create a generic type alias:</p>
 | ||
| <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nb">type</span> <span class="n">ListOrSet</span><span class="p">[</span><span class="n">T</span><span class="p">]</span> <span class="o">=</span> <span class="nb">list</span><span class="p">[</span><span class="n">T</span><span class="p">]</span> <span class="o">|</span> <span class="nb">set</span><span class="p">[</span><span class="n">T</span><span class="p">]</span>
 | ||
| </pre></div>
 | ||
| </div>
 | ||
| <p>Except for the <a class="reference internal" href="executionmodel.html#lazy-evaluation"><span class="std std-ref">lazy evaluation</span></a> of the value,
 | ||
| this is equivalent to:</p>
 | ||
| <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">annotation</span><span class="o">-</span><span class="k">def</span><span class="w"> </span><span class="nf">TYPE_PARAMS_OF_ListOrSet</span><span class="p">():</span>
 | ||
|     <span class="n">T</span> <span class="o">=</span> <span class="n">typing</span><span class="o">.</span><span class="n">TypeVar</span><span class="p">(</span><span class="s2">"T"</span><span class="p">)</span>
 | ||
| 
 | ||
|     <span class="n">annotation</span><span class="o">-</span><span class="k">def</span><span class="w"> </span><span class="nf">VALUE_OF_ListOrSet</span><span class="p">():</span>
 | ||
|         <span class="k">return</span> <span class="nb">list</span><span class="p">[</span><span class="n">T</span><span class="p">]</span> <span class="o">|</span> <span class="nb">set</span><span class="p">[</span><span class="n">T</span><span class="p">]</span>
 | ||
|     <span class="c1"># In reality, the value is lazily evaluated</span>
 | ||
|     <span class="k">return</span> <span class="n">typing</span><span class="o">.</span><span class="n">TypeAliasType</span><span class="p">(</span><span class="s2">"ListOrSet"</span><span class="p">,</span> <span class="n">VALUE_OF_ListOrSet</span><span class="p">(),</span> <span class="n">type_params</span><span class="o">=</span><span class="p">(</span><span class="n">T</span><span class="p">,))</span>
 | ||
| <span class="n">ListOrSet</span> <span class="o">=</span> <span class="n">TYPE_PARAMS_OF_ListOrSet</span><span class="p">()</span>
 | ||
| </pre></div>
 | ||
| </div>
 | ||
| <p>Here, <code class="docutils literal notranslate"><span class="pre">annotation-def</span></code> (not a real keyword) indicates an
 | ||
| <a class="reference internal" href="executionmodel.html#annotation-scopes"><span class="std std-ref">annotation scope</span></a>. The capitalized names
 | ||
| like <code class="docutils literal notranslate"><span class="pre">TYPE_PARAMS_OF_ListOrSet</span></code> are not actually bound at runtime.</p>
 | ||
| <p class="rubric">Footnotes</p>
 | ||
| <aside class="footnote-list brackets">
 | ||
| <aside class="footnote brackets" id="id20" role="doc-footnote">
 | ||
| <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id1">1</a><span class="fn-bracket">]</span></span>
 | ||
| <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>
 | ||
| </aside>
 | ||
| <aside class="footnote brackets" id="id21" role="doc-footnote">
 | ||
| <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id11">2</a><span class="fn-bracket">]</span></span>
 | ||
| <p>In pattern matching, a sequence is defined as one of the following:</p>
 | ||
| <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#c.Py_TPFLAGS_SEQUENCE" title="Py_TPFLAGS_SEQUENCE"><code class="xref c c-macro 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>
 | ||
| <p>The following standard library classes are sequences:</p>
 | ||
| <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 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>
 | ||
| </aside>
 | ||
| <aside class="footnote brackets" id="id22" role="doc-footnote">
 | ||
| <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id13">3</a><span class="fn-bracket">]</span></span>
 | ||
| <p>In pattern matching, a mapping is defined as one of the following:</p>
 | ||
| <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#c.Py_TPFLAGS_MAPPING" title="Py_TPFLAGS_MAPPING"><code class="xref c c-macro 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>
 | ||
| <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>
 | ||
| </aside>
 | ||
| <aside class="footnote brackets" id="id23" role="doc-footnote">
 | ||
| <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id15">4</a><span class="fn-bracket">]</span></span>
 | ||
| <p>A string literal appearing as the first statement in the function body is
 | ||
| transformed into the function’s <a class="reference internal" href="datamodel.html#function.__doc__" title="function.__doc__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code></a> 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>
 | ||
| </aside>
 | ||
| <aside class="footnote brackets" id="id24" role="doc-footnote">
 | ||
| <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id16">5</a><span class="fn-bracket">]</span></span>
 | ||
| <p>A string literal appearing as the first statement in the class body is
 | ||
| transformed into the namespace’s <a class="reference internal" href="datamodel.html#type.__doc__" title="type.__doc__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code></a> 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>
 | ||
| </aside>
 | ||
| </aside>
 | ||
| </section>
 | ||
| </section>
 | ||
| </section>
 | ||
| 
 | ||
| 
 | ||
|             <div class="clearer"></div>
 | ||
|           </div>
 | ||
|         </div>
 | ||
|       </div>
 | ||
|       <div class="sphinxsidebar" role="navigation" aria-label="Main">
 | ||
|         <div class="sphinxsidebarwrapper">
 | ||
|   <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><ul>
 | ||
| <li><a class="reference internal" href="#except-clause">8.4.1. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause</a></li>
 | ||
| <li><a class="reference internal" href="#except-star">8.4.2. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code> clause</a></li>
 | ||
| <li><a class="reference internal" href="#else-clause">8.4.3. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause</a></li>
 | ||
| <li><a class="reference internal" href="#finally-clause">8.4.4. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause</a></li>
 | ||
| </ul>
 | ||
| </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>
 | ||
| <li><a class="reference internal" href="#type-parameter-lists">8.10. Type parameter lists</a><ul>
 | ||
| <li><a class="reference internal" href="#generic-functions">8.10.1. Generic functions</a></li>
 | ||
| <li><a class="reference internal" href="#generic-classes">8.10.2. Generic classes</a></li>
 | ||
| <li><a class="reference internal" href="#generic-type-aliases">8.10.3. Generic type aliases</a></li>
 | ||
| </ul>
 | ||
| </li>
 | ||
| </ul>
 | ||
| </li>
 | ||
| </ul>
 | ||
| 
 | ||
|   </div>
 | ||
|   <div>
 | ||
|     <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>
 | ||
|   </div>
 | ||
|   <div>
 | ||
|     <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>
 | ||
|   <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/main/Doc/reference/compound_stmts.rst"
 | ||
|             rel="nofollow">Show Source
 | ||
|         </a>
 | ||
|       </li>
 | ||
|     </ul>
 | ||
|   </div>
 | ||
|         </div>
 | ||
| <div id="sidebarbutton" title="Collapse sidebar">
 | ||
| <span>«</span>
 | ||
| </div>
 | ||
| 
 | ||
|       </div>
 | ||
|       <div class="clearer"></div>
 | ||
|     </div>  
 | ||
|     <div class="related" role="navigation" aria-label="Related">
 | ||
|       <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.13.3 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="search" name="q" id="search-box" />
 | ||
|           <input type="submit" value="Go" />
 | ||
|         </form>
 | ||
|     </div>
 | ||
|                      |
 | ||
|                 </li>
 | ||
|             <li class="right">
 | ||
| <label class="theme-selector-label">
 | ||
|     Theme
 | ||
|     <select class="theme-selector" oninput="activateTheme(this.value)">
 | ||
|         <option value="auto" selected>Auto</option>
 | ||
|         <option value="light">Light</option>
 | ||
|         <option value="dark">Dark</option>
 | ||
|     </select>
 | ||
| </label> |</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 Apr 08, 2025 (14:33 UTC).
 | ||
|     
 | ||
|       <a href="/bugs.html">Found a bug</a>?
 | ||
|     
 | ||
|     <br />
 | ||
| 
 | ||
|     Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.
 | ||
|     </div>
 | ||
| 
 | ||
|   </body>
 | ||
| </html> |