gooderp18绿色标准版
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

1935 lines
204KB

  1. <!DOCTYPE html>
  2. <html lang="en" data-content_root="../">
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
  6. <meta property="og:title" content="8. Compound statements" />
  7. <meta property="og:type" content="website" />
  8. <meta property="og:url" content="https://docs.python.org/3/reference/compound_stmts.html" />
  9. <meta property="og:site_name" content="Python documentation" />
  10. <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..." />
  11. <meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
  12. <meta property="og:image:alt" content="Python documentation" />
  13. <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..." />
  14. <meta property="og:image:width" content="200" />
  15. <meta property="og:image:height" content="200" />
  16. <meta name="theme-color" content="#3776ab" />
  17. <title>8. Compound statements &#8212; Python 3.12.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
  18. <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=80d5e7a1" />
  19. <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=bb723527" />
  20. <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=b20cc3f5" />
  21. <script src="../_static/documentation_options.js?v=2c828074"></script>
  22. <script src="../_static/doctools.js?v=888ff710"></script>
  23. <script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
  24. <script src="../_static/sidebar.js"></script>
  25. <link rel="search" type="application/opensearchdescription+xml"
  26. title="Search within Python 3.12.3 documentation"
  27. href="../_static/opensearch.xml"/>
  28. <link rel="author" title="About these documents" href="../about.html" />
  29. <link rel="index" title="Index" href="../genindex.html" />
  30. <link rel="search" title="Search" href="../search.html" />
  31. <link rel="copyright" title="Copyright" href="../copyright.html" />
  32. <link rel="next" title="9. Top-level components" href="toplevel_components.html" />
  33. <link rel="prev" title="7. Simple statements" href="simple_stmts.html" />
  34. <link rel="canonical" href="https://docs.python.org/3/reference/compound_stmts.html" />
  35. <style>
  36. @media only screen {
  37. table.full-width-table {
  38. width: 100%;
  39. }
  40. }
  41. </style>
  42. <link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
  43. <link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
  44. <script type="text/javascript" src="../_static/copybutton.js"></script>
  45. <script type="text/javascript" src="../_static/menu.js"></script>
  46. <script type="text/javascript" src="../_static/search-focus.js"></script>
  47. <script type="text/javascript" src="../_static/themetoggle.js"></script>
  48. </head>
  49. <body>
  50. <div class="mobile-nav">
  51. <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
  52. aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
  53. <nav class="nav-content" role="navigation">
  54. <label for="menuToggler" class="toggler__label">
  55. <span></span>
  56. </label>
  57. <span class="nav-items-wrapper">
  58. <a href="https://www.python.org/" class="nav-logo">
  59. <img src="../_static/py.svg" alt="Python logo"/>
  60. </a>
  61. <span class="version_switcher_placeholder"></span>
  62. <form role="search" class="search" action="../search.html" method="get">
  63. <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
  64. <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>
  65. </svg>
  66. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  67. <input type="submit" value="Go"/>
  68. </form>
  69. </span>
  70. </nav>
  71. <div class="menu-wrapper">
  72. <nav class="menu" role="navigation" aria-label="main navigation">
  73. <div class="language_switcher_placeholder"></div>
  74. <label class="theme-selector-label">
  75. Theme
  76. <select class="theme-selector" oninput="activateTheme(this.value)">
  77. <option value="auto" selected>Auto</option>
  78. <option value="light">Light</option>
  79. <option value="dark">Dark</option>
  80. </select>
  81. </label>
  82. <div>
  83. <h3><a href="../contents.html">Table of Contents</a></h3>
  84. <ul>
  85. <li><a class="reference internal" href="#">8. Compound statements</a><ul>
  86. <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>
  87. <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>
  88. <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>
  89. <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>
  90. <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>
  91. <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>
  92. <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>
  93. <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>
  94. </ul>
  95. </li>
  96. <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>
  97. <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>
  98. <li><a class="reference internal" href="#overview">8.6.1. Overview</a></li>
  99. <li><a class="reference internal" href="#guards">8.6.2. Guards</a></li>
  100. <li><a class="reference internal" href="#irrefutable-case-blocks">8.6.3. Irrefutable Case Blocks</a></li>
  101. <li><a class="reference internal" href="#patterns">8.6.4. Patterns</a><ul>
  102. <li><a class="reference internal" href="#or-patterns">8.6.4.1. OR Patterns</a></li>
  103. <li><a class="reference internal" href="#as-patterns">8.6.4.2. AS Patterns</a></li>
  104. <li><a class="reference internal" href="#literal-patterns">8.6.4.3. Literal Patterns</a></li>
  105. <li><a class="reference internal" href="#capture-patterns">8.6.4.4. Capture Patterns</a></li>
  106. <li><a class="reference internal" href="#wildcard-patterns">8.6.4.5. Wildcard Patterns</a></li>
  107. <li><a class="reference internal" href="#value-patterns">8.6.4.6. Value Patterns</a></li>
  108. <li><a class="reference internal" href="#group-patterns">8.6.4.7. Group Patterns</a></li>
  109. <li><a class="reference internal" href="#sequence-patterns">8.6.4.8. Sequence Patterns</a></li>
  110. <li><a class="reference internal" href="#mapping-patterns">8.6.4.9. Mapping Patterns</a></li>
  111. <li><a class="reference internal" href="#class-patterns">8.6.4.10. Class Patterns</a></li>
  112. </ul>
  113. </li>
  114. </ul>
  115. </li>
  116. <li><a class="reference internal" href="#function-definitions">8.7. Function definitions</a></li>
  117. <li><a class="reference internal" href="#class-definitions">8.8. Class definitions</a></li>
  118. <li><a class="reference internal" href="#coroutines">8.9. Coroutines</a><ul>
  119. <li><a class="reference internal" href="#coroutine-function-definition">8.9.1. Coroutine function definition</a></li>
  120. <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>
  121. <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>
  122. </ul>
  123. </li>
  124. <li><a class="reference internal" href="#type-parameter-lists">8.10. Type parameter lists</a><ul>
  125. <li><a class="reference internal" href="#generic-functions">8.10.1. Generic functions</a></li>
  126. <li><a class="reference internal" href="#generic-classes">8.10.2. Generic classes</a></li>
  127. <li><a class="reference internal" href="#generic-type-aliases">8.10.3. Generic type aliases</a></li>
  128. </ul>
  129. </li>
  130. </ul>
  131. </li>
  132. </ul>
  133. </div>
  134. <div>
  135. <h4>Previous topic</h4>
  136. <p class="topless"><a href="simple_stmts.html"
  137. title="previous chapter"><span class="section-number">7. </span>Simple statements</a></p>
  138. </div>
  139. <div>
  140. <h4>Next topic</h4>
  141. <p class="topless"><a href="toplevel_components.html"
  142. title="next chapter"><span class="section-number">9. </span>Top-level components</a></p>
  143. </div>
  144. <div role="note" aria-label="source link">
  145. <h3>This Page</h3>
  146. <ul class="this-page-menu">
  147. <li><a href="../bugs.html">Report a Bug</a></li>
  148. <li>
  149. <a href="https://github.com/python/cpython/blob/main/Doc/reference/compound_stmts.rst"
  150. rel="nofollow">Show Source
  151. </a>
  152. </li>
  153. </ul>
  154. </div>
  155. </nav>
  156. </div>
  157. </div>
  158. <div class="related" role="navigation" aria-label="related navigation">
  159. <h3>Navigation</h3>
  160. <ul>
  161. <li class="right" style="margin-right: 10px">
  162. <a href="../genindex.html" title="General Index"
  163. accesskey="I">index</a></li>
  164. <li class="right" >
  165. <a href="../py-modindex.html" title="Python Module Index"
  166. >modules</a> |</li>
  167. <li class="right" >
  168. <a href="toplevel_components.html" title="9. Top-level components"
  169. accesskey="N">next</a> |</li>
  170. <li class="right" >
  171. <a href="simple_stmts.html" title="7. Simple statements"
  172. accesskey="P">previous</a> |</li>
  173. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  174. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  175. <li class="switchers">
  176. <div class="language_switcher_placeholder"></div>
  177. <div class="version_switcher_placeholder"></div>
  178. </li>
  179. <li>
  180. </li>
  181. <li id="cpython-language-and-version">
  182. <a href="../index.html">3.12.3 Documentation</a> &#187;
  183. </li>
  184. <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> &#187;</li>
  185. <li class="nav-item nav-item-this"><a href=""><span class="section-number">8. </span>Compound statements</a></li>
  186. <li class="right">
  187. <div class="inline-search" role="search">
  188. <form class="inline-search" action="../search.html" method="get">
  189. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  190. <input type="submit" value="Go" />
  191. </form>
  192. </div>
  193. |
  194. </li>
  195. <li class="right">
  196. <label class="theme-selector-label">
  197. Theme
  198. <select class="theme-selector" oninput="activateTheme(this.value)">
  199. <option value="auto" selected>Auto</option>
  200. <option value="light">Light</option>
  201. <option value="dark">Dark</option>
  202. </select>
  203. </label> |</li>
  204. </ul>
  205. </div>
  206. <div class="document">
  207. <div class="documentwrapper">
  208. <div class="bodywrapper">
  209. <div class="body" role="main">
  210. <section id="compound-statements">
  211. <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>
  212. <p id="index-0">Compound statements contain (groups of) other statements; they affect or control
  213. the execution of those other statements in some way. In general, compound
  214. statements span multiple lines, although in simple incarnations a whole compound
  215. statement may be contained in one line.</p>
  216. <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
  217. 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
  218. handlers and/or cleanup code for a group of statements, while the
  219. <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
  220. finalization code around a block of code. Function and class definitions are
  221. also syntactically compound statements.</p>
  222. <p id="index-1">A compound statement consists of one or more ‘clauses.’ A clause consists of a
  223. header and a ‘suite.’ The clause headers of a particular compound statement are
  224. all at the same indentation level. Each clause header begins with a uniquely
  225. identifying keyword and ends with a colon. A suite is a group of statements
  226. controlled by a clause. A suite can be one or more semicolon-separated simple
  227. statements on the same line as the header, following the header’s colon, or it
  228. can be one or more indented statements on subsequent lines. Only the latter
  229. form of a suite can contain nested compound statements; the following is illegal,
  230. 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
  231. <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>
  232. <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>
  233. </pre></div>
  234. </div>
  235. <p>Also note that the semicolon binds tighter than the colon in this context, so
  236. 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
  237. executed:</p>
  238. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">x</span> <span class="o">&lt;</span> <span class="n">y</span> <span class="o">&lt;</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>
  239. </pre></div>
  240. </div>
  241. <p>Summarizing:</p>
  242. <pre>
  243. <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>
  244. | <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>
  245. | <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>
  246. | <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>
  247. | <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>
  248. | <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>
  249. | <a class="reference internal" href="#grammar-token-python-grammar-funcdef"><code class="xref docutils literal notranslate"><span class="pre">funcdef</span></code></a>
  250. | <a class="reference internal" href="#grammar-token-python-grammar-classdef"><code class="xref docutils literal notranslate"><span class="pre">classdef</span></code></a>
  251. | <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>
  252. | <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>
  253. | <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>
  254. <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
  255. <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>
  256. <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> (&quot;;&quot; <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>)* [&quot;;&quot;]
  257. </pre>
  258. <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
  259. <code class="docutils literal notranslate"><span class="pre">DEDENT</span></code>. Also note that optional continuation clauses always begin with a
  260. keyword that cannot start a statement, thus there are no ambiguities (the
  261. ‘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
  262. <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>
  263. <p>The formatting of the grammar rules in the following sections places each clause
  264. on a separate line for clarity.</p>
  265. <section id="the-if-statement">
  266. <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>
  267. <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>
  268. <pre>
  269. <strong id="grammar-token-python-grammar-if_stmt">if_stmt</strong> ::= &quot;if&quot; <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> &quot;:&quot; <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
  270. (&quot;elif&quot; <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> &quot;:&quot; <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>)*
  271. [&quot;else&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
  272. </pre>
  273. <p>It selects exactly one of the suites by evaluating the expressions one by one
  274. 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
  275. true and false); then that suite is executed (and no other part of the
  276. <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
  277. 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>
  278. </section>
  279. <section id="the-while-statement">
  280. <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>
  281. <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
  282. expression is true:</p>
  283. <pre>
  284. <strong id="grammar-token-python-grammar-while_stmt">while_stmt</strong> ::= &quot;while&quot; <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> &quot;:&quot; <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
  285. [&quot;else&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
  286. </pre>
  287. <p>This repeatedly tests the expression and, if it is true, executes the first
  288. suite; if the expression is false (which may be the first time it is tested) the
  289. 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
  290. terminates.</p>
  291. <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
  292. 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>
  293. statement executed in the first suite skips the rest of the suite and goes back
  294. to testing the expression.</p>
  295. </section>
  296. <section id="the-for-statement">
  297. <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>
  298. <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
  299. (such as a string, tuple or list) or other iterable object:</p>
  300. <pre>
  301. <strong id="grammar-token-python-grammar-for_stmt">for_stmt</strong> ::= &quot;for&quot; <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> &quot;in&quot; <a class="reference internal" href="expressions.html#grammar-token-python-grammar-starred_list"><code class="xref docutils literal notranslate"><span class="pre">starred_list</span></code></a> &quot;:&quot; <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
  302. [&quot;else&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
  303. </pre>
  304. <p>The <code class="docutils literal notranslate"><span class="pre">starred_list</span></code> expression is evaluated once; it should yield an
  305. <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.
  306. The first item provided
  307. by the iterator is then assigned to the target list using the standard
  308. 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
  309. repeats for each item provided by the iterator. When the iterator is exhausted,
  310. the suite in the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause,
  311. if present, is executed, and the loop terminates.</p>
  312. <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
  313. 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>
  314. statement executed in the first suite skips the rest of the suite and continues
  315. 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
  316. item.</p>
  317. <p>The for-loop makes assignments to the variables in the target list.
  318. This overwrites all previous assignments to those variables including
  319. those made in the suite of the for-loop:</p>
  320. <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>
  321. <span class="nb">print</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
  322. <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>
  323. <span class="c1"># because i will be overwritten with the next</span>
  324. <span class="c1"># index in the range</span>
  325. </pre></div>
  326. </div>
  327. <p id="index-8">Names in the target list are not deleted when the loop is finished, but if the
  328. sequence is empty, they will not have been assigned to at all by the loop. Hint:
  329. 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.
  330. For instance, iterating <code class="docutils literal notranslate"><span class="pre">range(3)</span></code> successively yields 0, 1, and then 2.</p>
  331. <div class="versionchanged">
  332. <p><span class="versionmodified changed">Changed in version 3.11: </span>Starred elements are now allowed in the expression list.</p>
  333. </div>
  334. </section>
  335. <section id="the-try-statement">
  336. <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>
  337. <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
  338. for a group of statements:</p>
  339. <pre>
  340. <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>
  341. <strong id="grammar-token-python-grammar-try1_stmt">try1_stmt</strong> ::= &quot;try&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
  342. (&quot;except&quot; [<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> [&quot;as&quot; <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>]] &quot;:&quot; <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>)+
  343. [&quot;else&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
  344. [&quot;finally&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
  345. <strong id="grammar-token-python-grammar-try2_stmt">try2_stmt</strong> ::= &quot;try&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
  346. (&quot;except&quot; &quot;*&quot; <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> [&quot;as&quot; <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>] &quot;:&quot; <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>)+
  347. [&quot;else&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
  348. [&quot;finally&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
  349. <strong id="grammar-token-python-grammar-try3_stmt">try3_stmt</strong> ::= &quot;try&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
  350. &quot;finally&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
  351. </pre>
  352. <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>,
  353. 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
  354. 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>
  355. <section id="except-clause">
  356. <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>
  357. <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
  358. 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.
  359. 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
  360. 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
  361. until one is found that matches the exception.
  362. An expression-less <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause, if present, must be last;
  363. it matches any exception.
  364. For an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause with an expression,
  365. that expression is evaluated, and the clause matches the exception
  366. if the resulting object is “compatible” with the exception. An object is
  367. compatible with an exception if the object is the class or a
  368. <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,
  369. or a tuple containing an item that is the class or a non-virtual base class
  370. of the exception object.</p>
  371. <p>If no <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause matches the exception,
  372. the search for an exception handler
  373. 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>
  374. <p>If the evaluation of an expression
  375. in the header of an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause raises an exception,
  376. the original search for a handler is canceled and a search starts for
  377. the new exception in the surrounding code and on the call stack (it is treated
  378. 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>
  379. <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,
  380. the exception is assigned to the target
  381. 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,
  382. if present, and the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause’s suite is executed.
  383. All <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clauses must have an executable block.
  384. When the end of this block is reached, execution continues
  385. 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.
  386. (This means that if two nested handlers exist for the same exception,
  387. 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,
  388. the outer handler will not handle the exception.)</p>
  389. <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
  390. end of the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause. This is as if</p>
  391. <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>
  392. <span class="n">foo</span>
  393. </pre></div>
  394. </div>
  395. <p>was translated to</p>
  396. <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>
  397. <span class="k">try</span><span class="p">:</span>
  398. <span class="n">foo</span>
  399. <span class="k">finally</span><span class="p">:</span>
  400. <span class="k">del</span> <span class="n">N</span>
  401. </pre></div>
  402. </div>
  403. <p>This means the exception must be assigned to a different name to be able to
  404. refer to it after the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause.
  405. Exceptions are cleared because with the
  406. traceback attached to them, they form a reference cycle with the stack frame,
  407. keeping all locals in that frame alive until the next garbage collection occurs.</p>
  408. <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,
  409. 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
  410. from within the body of the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause by calling
  411. <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
  412. 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>
  413. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </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>
  414. <span class="go">None</span>
  415. <span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
  416. <span class="gp">... </span> <span class="k">raise</span> <span class="ne">TypeError</span>
  417. <span class="gp">... </span><span class="k">except</span><span class="p">:</span>
  418. <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>
  419. <span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
  420. <span class="gp">... </span> <span class="k">raise</span> <span class="ne">ValueError</span>
  421. <span class="gp">... </span> <span class="k">except</span><span class="p">:</span>
  422. <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>
  423. <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>
  424. <span class="gp">...</span>
  425. <span class="go">TypeError()</span>
  426. <span class="go">ValueError()</span>
  427. <span class="go">TypeError()</span>
  428. <span class="gp">&gt;&gt;&gt; </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>
  429. <span class="go">None</span>
  430. </pre></div>
  431. </div>
  432. </section>
  433. <section id="except-star">
  434. <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>
  435. <p>The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code> clause(s) are used for handling
  436. <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
  437. 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
  438. partial matches when the type matches some of the exceptions in the group.
  439. This means that multiple <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code> clauses can execute,
  440. each handling part of the exception group.
  441. Each clause executes at most once and handles an exception group
  442. of all matching exceptions. Each exception in the group is handled by at most
  443. one <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code> clause, the first that matches it.</p>
  444. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
  445. <span class="gp">... </span> <span class="k">raise</span> <span class="n">ExceptionGroup</span><span class="p">(</span><span class="s2">&quot;eg&quot;</span><span class="p">,</span>
  446. <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>
  447. <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>
  448. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;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">&#39;</span><span class="p">)</span>
  449. <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>
  450. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;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">&#39;</span><span class="p">)</span>
  451. <span class="gp">...</span>
  452. <span class="go">caught &lt;class &#39;ExceptionGroup&#39;&gt; with nested (TypeError(2),)</span>
  453. <span class="go">caught &lt;class &#39;ExceptionGroup&#39;&gt; with nested (OSError(3), OSError(4))</span>
  454. <span class="go"> + Exception Group Traceback (most recent call last):</span>
  455. <span class="go"> | File &quot;&lt;stdin&gt;&quot;, line 2, in &lt;module&gt;</span>
  456. <span class="go"> | ExceptionGroup: eg</span>
  457. <span class="go"> +-+---------------- 1 ----------------</span>
  458. <span class="go"> | ValueError: 1</span>
  459. <span class="go"> +------------------------------------</span>
  460. </pre></div>
  461. </div>
  462. <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>
  463. clause are re-raised at the end, along with all exceptions that were
  464. raised from within the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code> clauses. If this list contains
  465. more than one exception to reraise, they are combined into an exception
  466. group.</p>
  467. <p>If the raised exception is not an exception group and its type matches
  468. 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
  469. exception group with an empty message string.</p>
  470. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
  471. <span class="gp">... </span> <span class="k">raise</span> <span class="ne">BlockingIOError</span>
  472. <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>
  473. <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>
  474. <span class="gp">...</span>
  475. <span class="go">ExceptionGroup(&#39;&#39;, (BlockingIOError()))</span>
  476. </pre></div>
  477. </div>
  478. <p>An <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code> clause must have a matching type,
  479. and this type cannot be a subclass of <a class="reference internal" href="../library/exceptions.html#BaseExceptionGroup" title="BaseExceptionGroup"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BaseExceptionGroup</span></code></a>.
  480. 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>
  481. 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>.
  482. <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>
  483. cannot appear in an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code> clause.</p>
  484. </section>
  485. <section id="else-clause">
  486. <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>
  487. <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
  488. <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>,
  489. <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
  490. 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>
  491. clauses.</p>
  492. </section>
  493. <section id="finally-clause">
  494. <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>
  495. <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
  496. <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
  497. <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
  498. not handled, the exception is temporarily saved. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause
  499. is executed. If there is a saved exception it is re-raised at the end of the
  500. <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
  501. exception, the saved exception is set as the context of the new exception.
  502. 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>
  503. 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>
  504. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">f</span><span class="p">():</span>
  505. <span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
  506. <span class="gp">... </span> <span class="mi">1</span><span class="o">/</span><span class="mi">0</span>
  507. <span class="gp">... </span> <span class="k">finally</span><span class="p">:</span>
  508. <span class="gp">... </span> <span class="k">return</span> <span class="mi">42</span>
  509. <span class="gp">...</span>
  510. <span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">()</span>
  511. <span class="go">42</span>
  512. </pre></div>
  513. </div>
  514. <p>The exception information is not available to the program during execution of
  515. the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause.</p>
  516. <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
  517. 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>
  518. 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>
  519. <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>
  520. statement executed. Since the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause always executes, a
  521. <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
  522. always be the last one executed:</p>
  523. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">foo</span><span class="p">():</span>
  524. <span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
  525. <span class="gp">... </span> <span class="k">return</span> <span class="s1">&#39;try&#39;</span>
  526. <span class="gp">... </span> <span class="k">finally</span><span class="p">:</span>
  527. <span class="gp">... </span> <span class="k">return</span> <span class="s1">&#39;finally&#39;</span>
  528. <span class="gp">...</span>
  529. <span class="gp">&gt;&gt;&gt; </span><span class="n">foo</span><span class="p">()</span>
  530. <span class="go">&#39;finally&#39;</span>
  531. </pre></div>
  532. </div>
  533. <div class="versionchanged">
  534. <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
  535. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause due to a problem with the implementation.</p>
  536. </div>
  537. </section>
  538. </section>
  539. <section id="the-with-statement">
  540. <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>
  541. <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
  542. 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>).
  543. 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>
  544. usage patterns to be encapsulated for convenient reuse.</p>
  545. <pre>
  546. <strong id="grammar-token-python-grammar-with_stmt">with_stmt </strong> ::= &quot;with&quot; ( &quot;(&quot; <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> &quot;,&quot;? &quot;)&quot; | <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> ) &quot;:&quot; <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
  547. <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> (&quot;,&quot; <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>)*
  548. <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> [&quot;as&quot; <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>]
  549. </pre>
  550. <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>
  551. <ol class="arabic">
  552. <li><p>The context expression (the expression given in the
  553. <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>
  554. <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>
  555. <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>
  556. <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>
  557. <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
  558. 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>
  559. <div class="admonition note">
  560. <p class="admonition-title">Note</p>
  561. <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>
  562. 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
  563. called. Thus, if an error occurs during the assignment to the target list,
  564. it will be treated the same as an error occurring within the suite would
  565. be. See step 7 below.</p>
  566. </div>
  567. </li>
  568. <li><p>The suite is executed.</p></li>
  569. <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
  570. caused the suite to be exited, its type, value, and traceback are passed as
  571. 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
  572. supplied.</p>
  573. <p>If the suite was exited due to an exception, and the return value from the
  574. <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
  575. value was true, the exception is suppressed, and execution continues with the
  576. 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>
  577. <p>If the suite was exited for any reason other than an exception, the return
  578. 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
  579. location for the kind of exit that was taken.</p>
  580. </li>
  581. </ol>
  582. <p>The following code:</p>
  583. <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>
  584. <span class="n">SUITE</span>
  585. </pre></div>
  586. </div>
  587. <p>is semantically equivalent to:</p>
  588. <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>
  589. <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>
  590. <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>
  591. <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>
  592. <span class="n">hit_except</span> <span class="o">=</span> <span class="kc">False</span>
  593. <span class="k">try</span><span class="p">:</span>
  594. <span class="n">TARGET</span> <span class="o">=</span> <span class="n">value</span>
  595. <span class="n">SUITE</span>
  596. <span class="k">except</span><span class="p">:</span>
  597. <span class="n">hit_except</span> <span class="o">=</span> <span class="kc">True</span>
  598. <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>
  599. <span class="k">raise</span>
  600. <span class="k">finally</span><span class="p">:</span>
  601. <span class="k">if</span> <span class="ow">not</span> <span class="n">hit_except</span><span class="p">:</span>
  602. <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>
  603. </pre></div>
  604. </div>
  605. <p>With more than one item, the context managers are processed as if multiple
  606. <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>
  607. <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>
  608. <span class="n">SUITE</span>
  609. </pre></div>
  610. </div>
  611. <p>is semantically equivalent to:</p>
  612. <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>
  613. <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>
  614. <span class="n">SUITE</span>
  615. </pre></div>
  616. </div>
  617. <p>You can also write multi-item context managers in multiple lines if
  618. the items are surrounded by parentheses. For example:</p>
  619. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="p">(</span>
  620. <span class="n">A</span><span class="p">()</span> <span class="k">as</span> <span class="n">a</span><span class="p">,</span>
  621. <span class="n">B</span><span class="p">()</span> <span class="k">as</span> <span class="n">b</span><span class="p">,</span>
  622. <span class="p">):</span>
  623. <span class="n">SUITE</span>
  624. </pre></div>
  625. </div>
  626. <div class="versionchanged">
  627. <p><span class="versionmodified changed">Changed in version 3.1: </span>Support for multiple context expressions.</p>
  628. </div>
  629. <div class="versionchanged">
  630. <p><span class="versionmodified changed">Changed in version 3.10: </span>Support for using grouping parentheses to break the statement in multiple lines.</p>
  631. </div>
  632. <div class="admonition seealso">
  633. <p class="admonition-title">See also</p>
  634. <dl class="simple">
  635. <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>
  636. statement.</p>
  637. </dd>
  638. </dl>
  639. </div>
  640. </section>
  641. <section id="the-match-statement">
  642. <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>
  643. <div class="versionadded" id="index-18">
  644. <p><span class="versionmodified added">New in version 3.10.</span></p>
  645. </div>
  646. <p>The match statement is used for pattern matching. Syntax:</p>
  647. <pre>
  648. <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> &quot;:&quot; 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
  649. <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> &quot;,&quot; <code class="xref docutils literal notranslate"><span class="pre">star_named_expressions</span></code>?
  650. | <code class="xref docutils literal notranslate"><span class="pre">named_expression</span></code>
  651. <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>] &quot;:&quot; <code class="xref docutils literal notranslate"><span class="pre">block</span></code>
  652. </pre>
  653. <div class="admonition note">
  654. <p class="admonition-title">Note</p>
  655. <p>This section uses single quotes to denote
  656. <a class="reference internal" href="lexical_analysis.html#soft-keywords"><span class="std std-ref">soft keywords</span></a>.</p>
  657. </div>
  658. <p>Pattern matching takes a pattern as input (following <code class="docutils literal notranslate"><span class="pre">case</span></code>) and a subject
  659. value (following <code class="docutils literal notranslate"><span class="pre">match</span></code>). The pattern (which may contain subpatterns) is
  660. matched against the subject value. The outcomes are:</p>
  661. <ul class="simple">
  662. <li><p>A match success or failure (also termed a pattern success or failure).</p></li>
  663. <li><p>Possible binding of matched values to a name. The prerequisites for this are
  664. further discussed below.</p></li>
  665. </ul>
  666. <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>
  667. <div class="admonition seealso">
  668. <p class="admonition-title">See also</p>
  669. <ul class="simple">
  670. <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>
  671. <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>
  672. </ul>
  673. </div>
  674. <section id="overview">
  675. <h3><span class="section-number">8.6.1. </span>Overview<a class="headerlink" href="#overview" title="Link to this heading">¶</a></h3>
  676. <p>Here’s an overview of the logical flow of a match statement:</p>
  677. <ol class="arabic">
  678. <li><p>The subject expression <code class="docutils literal notranslate"><span class="pre">subject_expr</span></code> is evaluated and a resulting subject
  679. value obtained. If the subject expression contains a comma, a tuple is
  680. constructed using <a class="reference internal" href="../library/stdtypes.html#typesseq-tuple"><span class="std std-ref">the standard rules</span></a>.</p></li>
  681. <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
  682. specific rules for success or failure are described below. The match attempt can also
  683. bind some or all of the standalone names within the pattern. The precise
  684. pattern binding rules vary per pattern type and are
  685. specified below. <strong>Name bindings made during a successful pattern match
  686. outlive the executed block and can be used after the match statement</strong>.</p>
  687. <div class="admonition note">
  688. <p class="admonition-title">Note</p>
  689. <p>During failed pattern matches, some subpatterns may succeed. Do not
  690. rely on bindings being made for a failed match. Conversely, do not
  691. rely on variables remaining unchanged after a failed match. The exact
  692. behavior is dependent on implementation and may vary. This is an
  693. intentional decision made to allow different implementations to add
  694. optimizations.</p>
  695. </div>
  696. </li>
  697. <li><p>If the pattern succeeds, the corresponding guard (if present) is evaluated. In
  698. this case all name bindings are guaranteed to have happened.</p>
  699. <ul class="simple">
  700. <li><p>If the guard evaluates as true or is missing, the <code class="docutils literal notranslate"><span class="pre">block</span></code> inside
  701. <code class="docutils literal notranslate"><span class="pre">case_block</span></code> is executed.</p></li>
  702. <li><p>Otherwise, the next <code class="docutils literal notranslate"><span class="pre">case_block</span></code> is attempted as described above.</p></li>
  703. <li><p>If there are no further case blocks, the match statement is completed.</p></li>
  704. </ul>
  705. </li>
  706. </ol>
  707. <div class="admonition note">
  708. <p class="admonition-title">Note</p>
  709. <p>Users should generally never rely on a pattern being evaluated. Depending on
  710. implementation, the interpreter may cache values or use other optimizations
  711. which skip repeated evaluations.</p>
  712. </div>
  713. <p>A sample match statement:</p>
  714. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">flag</span> <span class="o">=</span> <span class="kc">False</span>
  715. <span class="gp">&gt;&gt;&gt; </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>
  716. <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>
  717. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Case 1&#39;</span><span class="p">)</span>
  718. <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>
  719. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Case 2&#39;</span><span class="p">)</span>
  720. <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>
  721. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;Case 3, y: </span><span class="si">{</span><span class="n">y</span><span class="si">}</span><span class="s1">&#39;</span><span class="p">)</span>
  722. <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>
  723. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Case 4, I match anything!&#39;</span><span class="p">)</span>
  724. <span class="gp">...</span>
  725. <span class="go">Case 3, y: 200</span>
  726. </pre></div>
  727. </div>
  728. <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>
  729. </section>
  730. <section id="guards">
  731. <h3><span class="section-number">8.6.2. </span>Guards<a class="headerlink" href="#guards" title="Link to this heading">¶</a></h3>
  732. <pre id="index-21">
  733. <strong id="grammar-token-python-grammar-guard">guard</strong> ::= &quot;if&quot; <code class="xref docutils literal notranslate"><span class="pre">named_expression</span></code>
  734. </pre>
  735. <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
  736. 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
  737. expression.</p>
  738. <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>
  739. <ol class="arabic simple">
  740. <li><p>Check that the pattern in the <code class="docutils literal notranslate"><span class="pre">case</span></code> block succeeded. If the pattern
  741. 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
  742. checked.</p></li>
  743. <li><p>If the pattern succeeded, evaluate the <code class="docutils literal notranslate"><span class="pre">guard</span></code>.</p>
  744. <ul class="simple">
  745. <li><p>If the <code class="docutils literal notranslate"><span class="pre">guard</span></code> condition evaluates as true, the case block is
  746. selected.</p></li>
  747. <li><p>If the <code class="docutils literal notranslate"><span class="pre">guard</span></code> condition evaluates as false, the case block is not
  748. selected.</p></li>
  749. <li><p>If the <code class="docutils literal notranslate"><span class="pre">guard</span></code> raises an exception during evaluation, the exception
  750. bubbles up.</p></li>
  751. </ul>
  752. </li>
  753. </ol>
  754. <p>Guards are allowed to have side effects as they are expressions. Guard
  755. evaluation must proceed from the first to the last case block, one at a time,
  756. skipping case blocks whose pattern(s) don’t all succeed. (I.e.,
  757. guard evaluation must happen in order.) Guard evaluation must stop once a case
  758. block is selected.</p>
  759. </section>
  760. <section id="irrefutable-case-blocks">
  761. <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>
  762. <p id="index-22">An irrefutable case block is a match-all case block. A match statement may have
  763. at most one irrefutable case block, and it must be last.</p>
  764. <p>A case block is considered irrefutable if it has no guard and its pattern is
  765. irrefutable. A pattern is considered irrefutable if we can prove from its
  766. syntax alone that it will always succeed. Only the following patterns are
  767. irrefutable:</p>
  768. <ul class="simple">
  769. <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>
  770. <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>
  771. <li><p><a class="reference internal" href="#capture-patterns"><span class="std std-ref">Capture Patterns</span></a></p></li>
  772. <li><p><a class="reference internal" href="#wildcard-patterns"><span class="std std-ref">Wildcard Patterns</span></a></p></li>
  773. <li><p>parenthesized irrefutable patterns</p></li>
  774. </ul>
  775. </section>
  776. <section id="patterns">
  777. <h3><span class="section-number">8.6.4. </span>Patterns<a class="headerlink" href="#patterns" title="Link to this heading">¶</a></h3>
  778. <div class="admonition note" id="index-23">
  779. <p class="admonition-title">Note</p>
  780. <p>This section uses grammar notations beyond standard EBNF:</p>
  781. <ul class="simple">
  782. <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>
  783. <li><p>the notation <code class="docutils literal notranslate"><span class="pre">!RULE</span></code> is shorthand for a negative lookahead assertion</p></li>
  784. </ul>
  785. </div>
  786. <p>The top-level syntax for <code class="docutils literal notranslate"><span class="pre">patterns</span></code> is:</p>
  787. <pre>
  788. <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>
  789. <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>
  790. <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>
  791. | <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>
  792. | <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>
  793. | <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>
  794. | <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>
  795. | <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>
  796. | <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>
  797. | <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>
  798. </pre>
  799. <p>The descriptions below will include a description “in simple terms” of what a pattern
  800. does for illustration purposes (credits to Raymond Hettinger for a document that
  801. inspired most of the descriptions). Note that these descriptions are purely for
  802. illustration purposes and <strong>may not</strong> reflect
  803. the underlying implementation. Furthermore, they do not cover all valid forms.</p>
  804. <section id="or-patterns">
  805. <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>
  806. <p>An OR pattern is two or more patterns separated by vertical
  807. bars <code class="docutils literal notranslate"><span class="pre">|</span></code>. Syntax:</p>
  808. <pre>
  809. <strong id="grammar-token-python-grammar-or_pattern">or_pattern</strong> ::= &quot;|&quot;.<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>+
  810. </pre>
  811. <p>Only the final subpattern may be <a class="reference internal" href="#irrefutable-case"><span class="std std-ref">irrefutable</span></a>, and each
  812. subpattern must bind the same set of names to avoid ambiguity.</p>
  813. <p>An OR pattern matches each of its subpatterns in turn to the subject value,
  814. until one succeeds. The OR pattern is then considered successful. Otherwise,
  815. if none of the subpatterns succeed, the OR pattern fails.</p>
  816. <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
  817. match <code class="docutils literal notranslate"><span class="pre">P2</span></code>, succeeding immediately if any succeeds, failing otherwise.</p>
  818. </section>
  819. <section id="as-patterns">
  820. <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>
  821. <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>
  822. keyword against a subject. Syntax:</p>
  823. <pre>
  824. <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> &quot;as&quot; <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>
  825. </pre>
  826. <p>If the OR pattern fails, the AS pattern fails. Otherwise, the AS pattern binds
  827. the subject to the name on the right of the as keyword and succeeds.
  828. <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>
  829. <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
  830. set <code class="docutils literal notranslate"><span class="pre">NAME</span> <span class="pre">=</span> <span class="pre">&lt;subject&gt;</span></code>.</p>
  831. </section>
  832. <section id="literal-patterns">
  833. <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>
  834. <p>A literal pattern corresponds to most
  835. <a class="reference internal" href="lexical_analysis.html#literals"><span class="std std-ref">literals</span></a> in Python. Syntax:</p>
  836. <pre>
  837. <strong id="grammar-token-python-grammar-literal_pattern">literal_pattern</strong> ::= <code class="xref docutils literal notranslate"><span class="pre">signed_number</span></code>
  838. | <code class="xref docutils literal notranslate"><span class="pre">signed_number</span></code> &quot;+&quot; NUMBER
  839. | <code class="xref docutils literal notranslate"><span class="pre">signed_number</span></code> &quot;-&quot; NUMBER
  840. | <code class="xref docutils literal notranslate"><span class="pre">strings</span></code>
  841. | &quot;None&quot;
  842. | &quot;True&quot;
  843. | &quot;False&quot;
  844. | <code class="xref docutils literal notranslate"><span class="pre">signed_number</span></code>: NUMBER | &quot;-&quot; NUMBER
  845. </pre>
  846. <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
  847. <a class="reference internal" href="grammar.html"><span class="doc">standard Python grammar</span></a>. Triple-quoted strings are
  848. 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
  849. not supported.</p>
  850. <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
  851. 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
  852. 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>
  853. <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">&lt;subject&gt;</span> <span class="pre">==</span> <span class="pre">LITERAL</span></code>. For
  854. 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>
  855. </section>
  856. <section id="capture-patterns">
  857. <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>
  858. <p>A capture pattern binds the subject value to a name.
  859. Syntax:</p>
  860. <pre>
  861. <strong id="grammar-token-python-grammar-capture_pattern">capture_pattern</strong> ::= !'_' NAME
  862. </pre>
  863. <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>
  864. expresses). It is instead treated as a
  865. <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>
  866. <p>In a given pattern, a given name can only be bound once. E.g.
  867. <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>
  868. <p>Capture patterns always succeed. The binding follows scoping rules
  869. 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
  870. name becomes a local variable in the closest containing function scope unless
  871. 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>
  872. <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">&lt;subject&gt;</span></code>.</p>
  873. </section>
  874. <section id="wildcard-patterns">
  875. <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>
  876. <p>A wildcard pattern always succeeds (matches anything)
  877. and binds no name. Syntax:</p>
  878. <pre>
  879. <strong id="grammar-token-python-grammar-wildcard_pattern">wildcard_pattern</strong> ::= '_'
  880. </pre>
  881. <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,
  882. but only within patterns. It is an identifier, as usual, even within
  883. <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>
  884. <p>In simple terms, <code class="docutils literal notranslate"><span class="pre">_</span></code> will always succeed.</p>
  885. </section>
  886. <section id="value-patterns">
  887. <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>
  888. <p>A value pattern represents a named value in Python.
  889. Syntax:</p>
  890. <pre>
  891. <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>
  892. <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> &quot;.&quot; NAME
  893. <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
  894. </pre>
  895. <p>The dotted name in the pattern is looked up using standard Python
  896. <a class="reference internal" href="executionmodel.html#resolve-names"><span class="std std-ref">name resolution rules</span></a>. The pattern succeeds if the
  897. value found compares equal to the subject value (using the <code class="docutils literal notranslate"><span class="pre">==</span></code> equality
  898. operator).</p>
  899. <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">&lt;subject&gt;</span> <span class="pre">==</span> <span class="pre">NAME1.NAME2</span></code></p>
  900. <div class="admonition note">
  901. <p class="admonition-title">Note</p>
  902. <p>If the same value occurs multiple times in the same match statement, the
  903. interpreter may cache the first value found and reuse it rather than repeat
  904. the same lookup. This cache is strictly tied to a given execution of a
  905. given match statement.</p>
  906. </div>
  907. </section>
  908. <section id="group-patterns">
  909. <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>
  910. <p>A group pattern allows users to add parentheses around patterns to
  911. emphasize the intended grouping. Otherwise, it has no additional syntax.
  912. Syntax:</p>
  913. <pre>
  914. <strong id="grammar-token-python-grammar-group_pattern">group_pattern</strong> ::= &quot;(&quot; <a class="reference internal" href="#grammar-token-python-grammar-pattern"><code class="xref docutils literal notranslate"><span class="pre">pattern</span></code></a> &quot;)&quot;
  915. </pre>
  916. <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>
  917. </section>
  918. <section id="sequence-patterns">
  919. <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>
  920. <p>A sequence pattern contains several subpatterns to be matched against sequence elements.
  921. The syntax is similar to the unpacking of a list or tuple.</p>
  922. <pre>
  923. <strong id="grammar-token-python-grammar-sequence_pattern">sequence_pattern </strong> ::= &quot;[&quot; [<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>] &quot;]&quot;
  924. | &quot;(&quot; [<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>] &quot;)&quot;
  925. <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> &quot;,&quot; [<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>]
  926. <strong id="grammar-token-python-grammar-maybe_sequence_pattern">maybe_sequence_pattern</strong> ::= &quot;,&quot;.<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>+ &quot;,&quot;?
  927. <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>
  928. <strong id="grammar-token-python-grammar-star_pattern">star_pattern </strong> ::= &quot;*&quot; (<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>)
  929. </pre>
  930. <p>There is no difference if parentheses or square brackets
  931. 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>
  932. <div class="admonition note">
  933. <p class="admonition-title">Note</p>
  934. <p>A single pattern enclosed in parentheses without a trailing comma
  935. (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>.
  936. 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
  937. still a sequence pattern.</p>
  938. </div>
  939. <p>At most one star subpattern may be in a sequence pattern. The star subpattern
  940. may occur in any position. If no star subpattern is present, the sequence
  941. pattern is a fixed-length sequence pattern; otherwise it is a variable-length
  942. sequence pattern.</p>
  943. <p>The following is the logical flow for matching a sequence pattern against a
  944. subject value:</p>
  945. <ol class="arabic">
  946. <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
  947. fails.</p></li>
  948. <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>
  949. the sequence pattern fails.</p></li>
  950. <li><p>The subsequent steps depend on whether the sequence pattern is fixed or
  951. variable-length.</p>
  952. <p>If the sequence pattern is fixed-length:</p>
  953. <ol class="arabic simple">
  954. <li><p>If the length of the subject sequence is not equal to the number of
  955. subpatterns, the sequence pattern fails</p></li>
  956. <li><p>Subpatterns in the sequence pattern are matched to their corresponding
  957. items in the subject sequence from left to right. Matching stops as soon
  958. as a subpattern fails. If all subpatterns succeed in matching their
  959. corresponding item, the sequence pattern succeeds.</p></li>
  960. </ol>
  961. <p>Otherwise, if the sequence pattern is variable-length:</p>
  962. <ol class="arabic simple">
  963. <li><p>If the length of the subject sequence is less than the number of non-star
  964. subpatterns, the sequence pattern fails.</p></li>
  965. <li><p>The leading non-star subpatterns are matched to their corresponding items
  966. as for fixed-length sequences.</p></li>
  967. <li><p>If the previous step succeeds, the star subpattern matches a list formed
  968. of the remaining subject items, excluding the remaining items
  969. corresponding to non-star subpatterns following the star subpattern.</p></li>
  970. <li><p>Remaining non-star subpatterns are matched to their corresponding subject
  971. items, as for a fixed-length sequence.</p></li>
  972. </ol>
  973. <div class="admonition note">
  974. <p class="admonition-title">Note</p>
  975. <p>The length of the subject sequence is obtained via
  976. <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
  977. cached by the interpreter in a similar manner as
  978. <a class="reference internal" href="#value-patterns"><span class="std std-ref">value patterns</span></a>.</p>
  979. </div>
  980. </li>
  981. </ol>
  982. <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&lt;N&gt;]</span></code> matches only if all the following
  983. happens:</p>
  984. <ul class="simple">
  985. <li><p>check <code class="docutils literal notranslate"><span class="pre">&lt;subject&gt;</span></code> is a sequence</p></li>
  986. <li><p><code class="docutils literal notranslate"><span class="pre">len(subject)</span> <span class="pre">==</span> <span class="pre">&lt;N&gt;</span></code></p></li>
  987. <li><p><code class="docutils literal notranslate"><span class="pre">P1</span></code> matches <code class="docutils literal notranslate"><span class="pre">&lt;subject&gt;[0]</span></code> (note that this match can also bind names)</p></li>
  988. <li><p><code class="docutils literal notranslate"><span class="pre">P2</span></code> matches <code class="docutils literal notranslate"><span class="pre">&lt;subject&gt;[1]</span></code> (note that this match can also bind names)</p></li>
  989. <li><p>… and so on for the corresponding pattern/element.</p></li>
  990. </ul>
  991. </section>
  992. <section id="mapping-patterns">
  993. <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>
  994. <p>A mapping pattern contains one or more key-value patterns. The syntax is
  995. similar to the construction of a dictionary.
  996. Syntax:</p>
  997. <pre>
  998. <strong id="grammar-token-python-grammar-mapping_pattern">mapping_pattern </strong> ::= &quot;{&quot; [<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>] &quot;}&quot;
  999. <strong id="grammar-token-python-grammar-items_pattern">items_pattern </strong> ::= &quot;,&quot;.<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>+ &quot;,&quot;?
  1000. <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>) &quot;:&quot; <a class="reference internal" href="#grammar-token-python-grammar-pattern"><code class="xref docutils literal notranslate"><span class="pre">pattern</span></code></a>
  1001. | <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>
  1002. <strong id="grammar-token-python-grammar-double_star_pattern">double_star_pattern</strong> ::= &quot;**&quot; <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>
  1003. </pre>
  1004. <p>At most one double star pattern may be in a mapping pattern. The double star
  1005. pattern must be the last subpattern in the mapping pattern.</p>
  1006. <p>Duplicate keys in mapping patterns are disallowed. Duplicate literal keys will
  1007. 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
  1008. 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>
  1009. <p>The following is the logical flow for matching a mapping pattern against a
  1010. subject value:</p>
  1011. <ol class="arabic simple">
  1012. <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>
  1013. <li><p>If every key given in the mapping pattern is present in the subject mapping,
  1014. and the pattern for each key matches the corresponding item of the subject
  1015. mapping, the mapping pattern succeeds.</p></li>
  1016. <li><p>If duplicate keys are detected in the mapping pattern, the pattern is
  1017. 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
  1018. 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>
  1019. </ol>
  1020. <div class="admonition note">
  1021. <p class="admonition-title">Note</p>
  1022. <p>Key-value pairs are matched using the two-argument form of the mapping
  1023. subject’s <code class="docutils literal notranslate"><span class="pre">get()</span></code> method. Matched key-value pairs must already be present
  1024. 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
  1025. <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>
  1026. </div>
  1027. <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
  1028. happens:</p>
  1029. <ul class="simple">
  1030. <li><p>check <code class="docutils literal notranslate"><span class="pre">&lt;subject&gt;</span></code> is a mapping</p></li>
  1031. <li><p><code class="docutils literal notranslate"><span class="pre">KEY1</span> <span class="pre">in</span> <span class="pre">&lt;subject&gt;</span></code></p></li>
  1032. <li><p><code class="docutils literal notranslate"><span class="pre">P1</span></code> matches <code class="docutils literal notranslate"><span class="pre">&lt;subject&gt;[KEY1]</span></code></p></li>
  1033. <li><p>… and so on for the corresponding KEY/pattern pair.</p></li>
  1034. </ul>
  1035. </section>
  1036. <section id="class-patterns">
  1037. <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>
  1038. <p>A class pattern represents a class and its positional and keyword arguments
  1039. (if any). Syntax:</p>
  1040. <pre>
  1041. <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> &quot;(&quot; [<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> &quot;,&quot;?] &quot;)&quot;
  1042. <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> [&quot;,&quot; <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>]
  1043. | <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>
  1044. <strong id="grammar-token-python-grammar-positional_patterns">positional_patterns</strong> ::= &quot;,&quot;.<a class="reference internal" href="#grammar-token-python-grammar-pattern"><code class="xref docutils literal notranslate"><span class="pre">pattern</span></code></a>+
  1045. <strong id="grammar-token-python-grammar-keyword_patterns">keyword_patterns </strong> ::= &quot;,&quot;.<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>+
  1046. <strong id="grammar-token-python-grammar-keyword_pattern">keyword_pattern </strong> ::= NAME &quot;=&quot; <a class="reference internal" href="#grammar-token-python-grammar-pattern"><code class="xref docutils literal notranslate"><span class="pre">pattern</span></code></a>
  1047. </pre>
  1048. <p>The same keyword should not be repeated in class patterns.</p>
  1049. <p>The following is the logical flow for matching a class pattern against a
  1050. subject value:</p>
  1051. <ol class="arabic">
  1052. <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
  1053. <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>
  1054. <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
  1055. <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>
  1056. <li><p>If no pattern arguments are present, the pattern succeeds. Otherwise,
  1057. the subsequent steps depend on whether keyword or positional argument patterns
  1058. are present.</p>
  1059. <p>For a number of built-in types (specified below), a single positional
  1060. subpattern is accepted which will match the entire subject; for these types
  1061. keyword patterns also work as for other types.</p>
  1062. <p>If only keyword patterns are present, they are processed as follows,
  1063. one by one:</p>
  1064. <p>I. The keyword is looked up as an attribute on the subject.</p>
  1065. <blockquote>
  1066. <div><ul class="simple">
  1067. <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
  1068. exception bubbles up.</p></li>
  1069. <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>
  1070. <li><p>Else, the subpattern associated with the keyword pattern is matched
  1071. against the subject’s attribute value. If this fails, the class
  1072. pattern fails; if this succeeds, the match proceeds to the next keyword.</p></li>
  1073. </ul>
  1074. </div></blockquote>
  1075. <p>II. If all keyword patterns succeed, the class pattern succeeds.</p>
  1076. <p>If any positional patterns are present, they are converted to keyword
  1077. 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
  1078. <code class="docutils literal notranslate"><span class="pre">name_or_attr</span></code> before matching:</p>
  1079. <p>I. The equivalent of <code class="docutils literal notranslate"><span class="pre">getattr(cls,</span> <span class="pre">&quot;__match_args__&quot;,</span> <span class="pre">())</span></code> is called.</p>
  1080. <blockquote>
  1081. <div><ul class="simple">
  1082. <li><p>If this raises an exception, the exception bubbles up.</p></li>
  1083. <li><p>If the returned value is not a tuple, the conversion fails and
  1084. <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>
  1085. <li><p>If there are more positional patterns than <code class="docutils literal notranslate"><span class="pre">len(cls.__match_args__)</span></code>,
  1086. <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>
  1087. <li><p>Otherwise, positional pattern <code class="docutils literal notranslate"><span class="pre">i</span></code> is converted to a keyword pattern
  1088. 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
  1089. 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>
  1090. <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>
  1091. </ul>
  1092. <div class="admonition seealso">
  1093. <p class="admonition-title">See also</p>
  1094. <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>
  1095. </div>
  1096. </div></blockquote>
  1097. <dl class="simple">
  1098. <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>
  1099. </dd>
  1100. </dl>
  1101. <p>For the following built-in types the handling of positional subpatterns is
  1102. different:</p>
  1103. <ul class="simple">
  1104. <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>
  1105. <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>
  1106. <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>
  1107. <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>
  1108. <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>
  1109. <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>
  1110. <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>
  1111. <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>
  1112. <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>
  1113. <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>
  1114. <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>
  1115. </ul>
  1116. <p>These classes accept a single positional argument, and the pattern there is matched
  1117. against the whole object rather than an attribute. For example <code class="docutils literal notranslate"><span class="pre">int(0|1)</span></code> matches
  1118. 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>
  1119. </li>
  1120. </ol>
  1121. <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>
  1122. <ul class="simple">
  1123. <li><p><code class="docutils literal notranslate"><span class="pre">isinstance(&lt;subject&gt;,</span> <span class="pre">CLS)</span></code></p></li>
  1124. <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>
  1125. <li><p>For each keyword argument <code class="docutils literal notranslate"><span class="pre">attr=P2</span></code>:</p>
  1126. <ul>
  1127. <li><p><code class="docutils literal notranslate"><span class="pre">hasattr(&lt;subject&gt;,</span> <span class="pre">&quot;attr&quot;)</span></code></p></li>
  1128. <li><p><code class="docutils literal notranslate"><span class="pre">P2</span></code> matches <code class="docutils literal notranslate"><span class="pre">&lt;subject&gt;.attr</span></code></p></li>
  1129. </ul>
  1130. </li>
  1131. <li><p>… and so on for the corresponding keyword argument/pattern pair.</p></li>
  1132. </ul>
  1133. <div class="admonition seealso">
  1134. <p class="admonition-title">See also</p>
  1135. <ul class="simple">
  1136. <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>
  1137. <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>
  1138. </ul>
  1139. </div>
  1140. </section>
  1141. </section>
  1142. </section>
  1143. <section id="function-definitions">
  1144. <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>
  1145. <p id="index-28">A function definition defines a user-defined function object (see section
  1146. <a class="reference internal" href="datamodel.html#types"><span class="std std-ref">The standard type hierarchy</span></a>):</p>
  1147. <pre>
  1148. <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>] &quot;def&quot; <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>] &quot;(&quot; [<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>] &quot;)&quot;
  1149. [&quot;-&gt;&quot; <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>] &quot;:&quot; <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
  1150. <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>+
  1151. <strong id="grammar-token-python-grammar-decorator">decorator </strong> ::= &quot;&#64;&quot; <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
  1152. <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> (&quot;,&quot; <a class="reference internal" href="#grammar-token-python-grammar-defparameter"><code class="xref docutils literal notranslate"><span class="pre">defparameter</span></code></a>)* &quot;,&quot; &quot;/&quot; [&quot;,&quot; [<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>]]
  1153. | <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>
  1154. <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> (&quot;,&quot; <a class="reference internal" href="#grammar-token-python-grammar-defparameter"><code class="xref docutils literal notranslate"><span class="pre">defparameter</span></code></a>)* [&quot;,&quot; [<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>]]
  1155. | <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>
  1156. <strong id="grammar-token-python-grammar-parameter_list_starargs">parameter_list_starargs </strong> ::= &quot;*&quot; [<a class="reference internal" href="#grammar-token-python-grammar-parameter"><code class="xref docutils literal notranslate"><span class="pre">parameter</span></code></a>] (&quot;,&quot; <a class="reference internal" href="#grammar-token-python-grammar-defparameter"><code class="xref docutils literal notranslate"><span class="pre">defparameter</span></code></a>)* [&quot;,&quot; [&quot;**&quot; <a class="reference internal" href="#grammar-token-python-grammar-parameter"><code class="xref docutils literal notranslate"><span class="pre">parameter</span></code></a> [&quot;,&quot;]]]
  1157. | &quot;**&quot; <a class="reference internal" href="#grammar-token-python-grammar-parameter"><code class="xref docutils literal notranslate"><span class="pre">parameter</span></code></a> [&quot;,&quot;]
  1158. <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> [&quot;:&quot; <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>]
  1159. <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> [&quot;=&quot; <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>]
  1160. <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>
  1161. </pre>
  1162. <p>A function definition is an executable statement. Its execution binds the
  1163. function name in the current local namespace to a function object (a wrapper
  1164. around the executable code for the function). This function object contains a
  1165. reference to the current global namespace as the global namespace to be used
  1166. when the function is called.</p>
  1167. <p>The function definition does not execute the function body; this gets executed
  1168. 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>
  1169. <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.
  1170. Decorator expressions are evaluated when the function is defined, in the scope
  1171. that contains the function definition. The result must be a callable, which is
  1172. invoked with the function object as the only argument. The returned value is
  1173. bound to the function name instead of the function object. Multiple decorators
  1174. are applied in nested fashion. For example, the following code</p>
  1175. <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>
  1176. <span class="nd">@f2</span>
  1177. <span class="k">def</span> <span class="nf">func</span><span class="p">():</span> <span class="k">pass</span>
  1178. </pre></div>
  1179. </div>
  1180. <p>is roughly equivalent to</p>
  1181. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">func</span><span class="p">():</span> <span class="k">pass</span>
  1182. <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>
  1183. </pre></div>
  1184. </div>
  1185. <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>
  1186. <div class="versionchanged">
  1187. <p><span class="versionmodified changed">Changed in version 3.9: </span>Functions may be decorated with any valid
  1188. <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
  1189. 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>
  1190. </div>
  1191. <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
  1192. between the function’s name and the opening parenthesis for its parameter list.
  1193. This indicates to static type checkers that the function is generic. At runtime,
  1194. the type parameters can be retrieved from the function’s
  1195. <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>
  1196. attribute. See <a class="reference internal" href="#generic-functions"><span class="std std-ref">Generic functions</span></a> for more.</p>
  1197. <div class="versionchanged">
  1198. <p><span class="versionmodified changed">Changed in version 3.12: </span>Type parameter lists are new in Python 3.12.</p>
  1199. </div>
  1200. <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>
  1201. <em>expression</em>, the function is said to have “default parameter values.” For a
  1202. 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
  1203. omitted from a call, in which
  1204. case the parameter’s default value is substituted. If a parameter has a default
  1205. value, all following parameters up until the “<code class="docutils literal notranslate"><span class="pre">*</span></code>” must also have a default
  1206. value — this is a syntactic restriction that is not expressed by the grammar.</p>
  1207. <p><strong>Default parameter values are evaluated from left to right when the function
  1208. definition is executed.</strong> This means that the expression is evaluated once, when
  1209. the function is defined, and that the same “pre-computed” value is used for each
  1210. call. This is especially important to understand when a default parameter value is a
  1211. mutable object, such as a list or a dictionary: if the function modifies the
  1212. object (e.g. by appending an item to a list), the default parameter value is in effect
  1213. modified. This is generally not what was intended. A way around this is to use
  1214. <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,
  1215. e.g.:</p>
  1216. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">whats_on_the_telly</span><span class="p">(</span><span class="n">penguin</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
  1217. <span class="k">if</span> <span class="n">penguin</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
  1218. <span class="n">penguin</span> <span class="o">=</span> <span class="p">[]</span>
  1219. <span class="n">penguin</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s2">&quot;property of the zoo&quot;</span><span class="p">)</span>
  1220. <span class="k">return</span> <span class="n">penguin</span>
  1221. </pre></div>
  1222. </div>
  1223. <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
  1224. function call always assigns values to all parameters mentioned in the parameter
  1225. list, either from positional arguments, from keyword arguments, or from default
  1226. values. If the form “<code class="docutils literal notranslate"><span class="pre">*identifier</span></code>” is present, it is initialized to a tuple
  1227. receiving any excess positional parameters, defaulting to the empty tuple.
  1228. If the form “<code class="docutils literal notranslate"><span class="pre">**identifier</span></code>” is present, it is initialized to a new
  1229. ordered mapping receiving any excess keyword arguments, defaulting to a
  1230. new empty mapping of the same type. Parameters after “<code class="docutils literal notranslate"><span class="pre">*</span></code>” or
  1231. “<code class="docutils literal notranslate"><span class="pre">*identifier</span></code>” are keyword-only parameters and may only be passed
  1232. by keyword arguments. Parameters before “<code class="docutils literal notranslate"><span class="pre">/</span></code>” are positional-only parameters
  1233. and may only be passed by positional arguments.</p>
  1234. <div class="versionchanged">
  1235. <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
  1236. 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>
  1237. </div>
  1238. <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>”
  1239. following the parameter name. Any parameter may have an annotation, even those of the form
  1240. <code class="docutils literal notranslate"><span class="pre">*identifier</span></code> or <code class="docutils literal notranslate"><span class="pre">**identifier</span></code>. Functions may have “return” annotation of
  1241. the form “<code class="docutils literal notranslate"><span class="pre">-&gt;</span> <span class="pre">expression</span></code>” after the parameter list. These annotations can be
  1242. any valid Python expression. The presence of annotations does not change the
  1243. semantics of a function. The annotation values are available as values of
  1244. a dictionary keyed by the parameters’ names in the <code class="xref py py-attr docutils literal notranslate"><span class="pre">__annotations__</span></code>
  1245. attribute of the function object. If the <code class="docutils literal notranslate"><span class="pre">annotations</span></code> import from
  1246. <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
  1247. enables postponed evaluation. Otherwise, they are evaluated when the function
  1248. definition is executed. In this case annotations may be evaluated in
  1249. a different order than they appear in the source code.</p>
  1250. <p id="index-35">It is also possible to create anonymous functions (functions not bound to a
  1251. name), for immediate use in expressions. This uses lambda expressions, described in
  1252. 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
  1253. 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>”
  1254. statement can be passed around or assigned to another name just like a function
  1255. 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
  1256. since it allows the execution of multiple statements and annotations.</p>
  1257. <p><strong>Programmer’s note:</strong> Functions are first-class objects. A “<code class="docutils literal notranslate"><span class="pre">def</span></code>” statement
  1258. executed inside a function definition defines a local function that can be
  1259. returned or passed around. Free variables used in the nested function can
  1260. access the local variables of the function containing the def. See section
  1261. <a class="reference internal" href="executionmodel.html#naming"><span class="std std-ref">Naming and binding</span></a> for details.</p>
  1262. <div class="admonition seealso">
  1263. <p class="admonition-title">See also</p>
  1264. <dl class="simple">
  1265. <dt><span class="target" id="index-36"></span><a class="pep reference external" href="https://peps.python.org/pep-3107/"><strong>PEP 3107</strong></a> - Function Annotations</dt><dd><p>The original specification for function annotations.</p>
  1266. </dd>
  1267. <dt><span class="target" id="index-37"></span><a class="pep reference external" href="https://peps.python.org/pep-0484/"><strong>PEP 484</strong></a> - Type Hints</dt><dd><p>Definition of a standard meaning for annotations: type hints.</p>
  1268. </dd>
  1269. <dt><span class="target" id="index-38"></span><a class="pep reference external" href="https://peps.python.org/pep-0526/"><strong>PEP 526</strong></a> - Syntax for Variable Annotations</dt><dd><p>Ability to type hint variable declarations, including class
  1270. variables and instance variables.</p>
  1271. </dd>
  1272. <dt><span class="target" id="index-39"></span><a class="pep reference external" href="https://peps.python.org/pep-0563/"><strong>PEP 563</strong></a> - Postponed Evaluation of Annotations</dt><dd><p>Support for forward references within annotations by preserving
  1273. annotations in a string form at runtime instead of eager evaluation.</p>
  1274. </dd>
  1275. <dt><span class="target" id="index-40"></span><a class="pep reference external" href="https://peps.python.org/pep-0318/"><strong>PEP 318</strong></a> - Decorators for Functions and Methods</dt><dd><p>Function and method decorators were introduced.
  1276. Class decorators were introduced in <span class="target" id="index-41"></span><a class="pep reference external" href="https://peps.python.org/pep-3129/"><strong>PEP 3129</strong></a>.</p>
  1277. </dd>
  1278. </dl>
  1279. </div>
  1280. </section>
  1281. <section id="class-definitions">
  1282. <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>
  1283. <p id="index-42">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>
  1284. <pre>
  1285. <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>] &quot;class&quot; <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>] &quot;:&quot; <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
  1286. <strong id="grammar-token-python-grammar-inheritance">inheritance</strong> ::= &quot;(&quot; [<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>] &quot;)&quot;
  1287. <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>
  1288. </pre>
  1289. <p>A class definition is an executable statement. The inheritance list usually
  1290. 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
  1291. each item in the list should evaluate to a class object which allows
  1292. subclassing. Classes without an inheritance list inherit, by default, from the
  1293. 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>
  1294. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Foo</span><span class="p">:</span>
  1295. <span class="k">pass</span>
  1296. </pre></div>
  1297. </div>
  1298. <p>is equivalent to</p>
  1299. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Foo</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
  1300. <span class="k">pass</span>
  1301. </pre></div>
  1302. </div>
  1303. <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>),
  1304. using a newly created local namespace and the original global namespace.
  1305. (Usually, the suite contains mostly function definitions.) When the class’s
  1306. suite finishes execution, its execution frame is discarded but its local
  1307. 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
  1308. list for the base classes and the saved local namespace for the attribute
  1309. dictionary. The class name is bound to this class object in the original local
  1310. namespace.</p>
  1311. <p>The order in which attributes are defined in the class body is preserved
  1312. in the new class’s <code class="docutils literal notranslate"><span class="pre">__dict__</span></code>. Note that this is reliable only right
  1313. after the class is created and only for classes that were defined using
  1314. the definition syntax.</p>
  1315. <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>
  1316. <p id="index-43">Classes can also be decorated: just like when decorating functions,</p>
  1317. <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>
  1318. <span class="nd">@f2</span>
  1319. <span class="k">class</span> <span class="nc">Foo</span><span class="p">:</span> <span class="k">pass</span>
  1320. </pre></div>
  1321. </div>
  1322. <p>is roughly equivalent to</p>
  1323. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Foo</span><span class="p">:</span> <span class="k">pass</span>
  1324. <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>
  1325. </pre></div>
  1326. </div>
  1327. <p>The evaluation rules for the decorator expressions are the same as for function
  1328. decorators. The result is then bound to the class name.</p>
  1329. <div class="versionchanged">
  1330. <p><span class="versionmodified changed">Changed in version 3.9: </span>Classes may be decorated with any valid
  1331. <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
  1332. much more restrictive; see <span class="target" id="index-44"></span><a class="pep reference external" href="https://peps.python.org/pep-0614/"><strong>PEP 614</strong></a> for details.</p>
  1333. </div>
  1334. <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
  1335. immediately after the class’s name.
  1336. This indicates to static type checkers that the class is generic. At runtime,
  1337. the type parameters can be retrieved from the class’s <code class="docutils literal notranslate"><span class="pre">__type_params__</span></code>
  1338. attribute. See <a class="reference internal" href="#generic-classes"><span class="std std-ref">Generic classes</span></a> for more.</p>
  1339. <div class="versionchanged">
  1340. <p><span class="versionmodified changed">Changed in version 3.12: </span>Type parameter lists are new in Python 3.12.</p>
  1341. </div>
  1342. <p><strong>Programmer’s note:</strong> Variables defined in the class definition are class
  1343. attributes; they are shared by instances. Instance attributes can be set in a
  1344. 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
  1345. accessible through the notation “<code class="docutils literal notranslate"><span class="pre">self.name</span></code>”, and an instance attribute hides
  1346. a class attribute with the same name when accessed in this way. Class
  1347. attributes can be used as defaults for instance attributes, but using mutable
  1348. values there can lead to unexpected results. <a class="reference internal" href="datamodel.html#descriptors"><span class="std std-ref">Descriptors</span></a>
  1349. can be used to create instance variables with different implementation details.</p>
  1350. <div class="admonition seealso">
  1351. <p class="admonition-title">See also</p>
  1352. <dl class="simple">
  1353. <dt><span class="target" id="index-45"></span><a class="pep reference external" href="https://peps.python.org/pep-3115/"><strong>PEP 3115</strong></a> - Metaclasses in Python 3000</dt><dd><p>The proposal that changed the declaration of metaclasses to the current
  1354. syntax, and the semantics for how classes with metaclasses are
  1355. constructed.</p>
  1356. </dd>
  1357. <dt><span class="target" id="index-46"></span><a class="pep reference external" href="https://peps.python.org/pep-3129/"><strong>PEP 3129</strong></a> - Class Decorators</dt><dd><p>The proposal that added class decorators. Function and method decorators
  1358. were introduced in <span class="target" id="index-47"></span><a class="pep reference external" href="https://peps.python.org/pep-0318/"><strong>PEP 318</strong></a>.</p>
  1359. </dd>
  1360. </dl>
  1361. </div>
  1362. </section>
  1363. <section id="coroutines">
  1364. <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>
  1365. <div class="versionadded">
  1366. <p><span class="versionmodified added">New in version 3.5.</span></p>
  1367. </div>
  1368. <section id="coroutine-function-definition">
  1369. <span id="async-def"></span><span id="index-48"></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>
  1370. <pre>
  1371. <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>] &quot;async&quot; &quot;def&quot; <a class="reference internal" href="#grammar-token-python-grammar-funcname"><code class="xref docutils literal notranslate"><span class="pre">funcname</span></code></a> &quot;(&quot; [<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>] &quot;)&quot;
  1372. [&quot;-&gt;&quot; <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>] &quot;:&quot; <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
  1373. </pre>
  1374. <p id="index-49">Execution of Python coroutines can be suspended and resumed at many points
  1375. (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
  1376. <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>
  1377. <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,
  1378. 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>
  1379. <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
  1380. of a coroutine function.</p>
  1381. <p>An example of a coroutine function:</p>
  1382. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span> <span class="nf">func</span><span class="p">(</span><span class="n">param1</span><span class="p">,</span> <span class="n">param2</span><span class="p">):</span>
  1383. <span class="n">do_stuff</span><span class="p">()</span>
  1384. <span class="k">await</span> <span class="n">some_coroutine</span><span class="p">()</span>
  1385. </pre></div>
  1386. </div>
  1387. <div class="versionchanged">
  1388. <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
  1389. treated as such inside the body of a coroutine function.</p>
  1390. </div>
  1391. </section>
  1392. <section id="the-async-for-statement">
  1393. <span id="async-for"></span><span id="index-50"></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>
  1394. <pre>
  1395. <strong id="grammar-token-python-grammar-async_for_stmt">async_for_stmt</strong> ::= &quot;async&quot; <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>
  1396. </pre>
  1397. <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
  1398. 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
  1399. its <code class="docutils literal notranslate"><span class="pre">__anext__</span></code> method.</p>
  1400. <p>The <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code> statement allows convenient iteration over asynchronous
  1401. iterables.</p>
  1402. <p>The following code:</p>
  1403. <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>
  1404. <span class="n">SUITE</span>
  1405. <span class="k">else</span><span class="p">:</span>
  1406. <span class="n">SUITE2</span>
  1407. </pre></div>
  1408. </div>
  1409. <p>Is semantically equivalent to:</p>
  1410. <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>
  1411. <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>
  1412. <span class="n">running</span> <span class="o">=</span> <span class="kc">True</span>
  1413. <span class="k">while</span> <span class="n">running</span><span class="p">:</span>
  1414. <span class="k">try</span><span class="p">:</span>
  1415. <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>
  1416. <span class="k">except</span> <span class="ne">StopAsyncIteration</span><span class="p">:</span>
  1417. <span class="n">running</span> <span class="o">=</span> <span class="kc">False</span>
  1418. <span class="k">else</span><span class="p">:</span>
  1419. <span class="n">SUITE</span>
  1420. <span class="k">else</span><span class="p">:</span>
  1421. <span class="n">SUITE2</span>
  1422. </pre></div>
  1423. </div>
  1424. <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>
  1425. <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
  1426. body of a coroutine function.</p>
  1427. </section>
  1428. <section id="the-async-with-statement">
  1429. <span id="async-with"></span><span id="index-51"></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>
  1430. <pre>
  1431. <strong id="grammar-token-python-grammar-async_with_stmt">async_with_stmt</strong> ::= &quot;async&quot; <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>
  1432. </pre>
  1433. <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
  1434. able to suspend execution in its <em>enter</em> and <em>exit</em> methods.</p>
  1435. <p>The following code:</p>
  1436. <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>
  1437. <span class="n">SUITE</span>
  1438. </pre></div>
  1439. </div>
  1440. <p>is semantically equivalent to:</p>
  1441. <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>
  1442. <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>
  1443. <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>
  1444. <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>
  1445. <span class="n">hit_except</span> <span class="o">=</span> <span class="kc">False</span>
  1446. <span class="k">try</span><span class="p">:</span>
  1447. <span class="n">TARGET</span> <span class="o">=</span> <span class="n">value</span>
  1448. <span class="n">SUITE</span>
  1449. <span class="k">except</span><span class="p">:</span>
  1450. <span class="n">hit_except</span> <span class="o">=</span> <span class="kc">True</span>
  1451. <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>
  1452. <span class="k">raise</span>
  1453. <span class="k">finally</span><span class="p">:</span>
  1454. <span class="k">if</span> <span class="ow">not</span> <span class="n">hit_except</span><span class="p">:</span>
  1455. <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>
  1456. </pre></div>
  1457. </div>
  1458. <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>
  1459. <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
  1460. body of a coroutine function.</p>
  1461. <div class="admonition seealso">
  1462. <p class="admonition-title">See also</p>
  1463. <dl class="simple">
  1464. <dt><span class="target" id="index-52"></span><a class="pep reference external" href="https://peps.python.org/pep-0492/"><strong>PEP 492</strong></a> - Coroutines with async and await syntax</dt><dd><p>The proposal that made coroutines a proper standalone concept in Python,
  1465. and added supporting syntax.</p>
  1466. </dd>
  1467. </dl>
  1468. </div>
  1469. </section>
  1470. </section>
  1471. <section id="type-parameter-lists">
  1472. <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>
  1473. <div class="versionadded">
  1474. <p><span class="versionmodified added">New in version 3.12.</span></p>
  1475. </div>
  1476. <pre id="index-53">
  1477. <strong id="grammar-token-python-grammar-type_params">type_params </strong> ::= &quot;[&quot; <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> (&quot;,&quot; <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>)* &quot;]&quot;
  1478. <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>
  1479. <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> (&quot;:&quot; <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>)?
  1480. <strong id="grammar-token-python-grammar-typevartuple">typevartuple</strong> ::= &quot;*&quot; <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>
  1481. <strong id="grammar-token-python-grammar-paramspec">paramspec </strong> ::= &quot;**&quot; <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>
  1482. </pre>
  1483. <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>),
  1484. <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
  1485. contain a type parameter list:</p>
  1486. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</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">-&gt;</span> <span class="n">T</span><span class="p">:</span>
  1487. <span class="o">...</span>
  1488. <span class="k">async</span> <span class="k">def</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">-&gt;</span> <span class="n">T</span><span class="p">:</span>
  1489. <span class="o">...</span>
  1490. <span class="k">class</span> <span class="nc">Bag</span><span class="p">[</span><span class="n">T</span><span class="p">]:</span>
  1491. <span class="k">def</span> <span class="fm">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">Iterator</span><span class="p">[</span><span class="n">T</span><span class="p">]:</span>
  1492. <span class="o">...</span>
  1493. <span class="k">def</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">-&gt;</span> <span class="kc">None</span><span class="p">:</span>
  1494. <span class="o">...</span>
  1495. <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>
  1496. </pre></div>
  1497. </div>
  1498. <p>Semantically, this indicates that the function, class, or type alias is
  1499. generic over a type variable. This information is primarily used by static
  1500. type checkers, and at runtime, generic objects behave much like their
  1501. non-generic counterparts.</p>
  1502. <p>Type parameters are declared in square brackets (<code class="docutils literal notranslate"><span class="pre">[]</span></code>) immediately
  1503. after the name of the function, class, or type alias. The type parameters
  1504. are accessible within the scope of the generic object, but not elsewhere.
  1505. 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
  1506. the module scope. Below, the semantics of generic objects are described
  1507. with more precision. The scope of type parameters is modeled with a special
  1508. function (technically, an <a class="reference internal" href="executionmodel.html#annotation-scopes"><span class="std std-ref">annotation scope</span></a>) that
  1509. wraps the creation of the generic object.</p>
  1510. <p>Generic functions, classes, and type aliases have a <code class="xref py py-attr docutils literal notranslate"><span class="pre">__type_params__</span></code>
  1511. attribute listing their type parameters.</p>
  1512. <p>Type parameters come in three kinds:</p>
  1513. <ul class="simple">
  1514. <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
  1515. represents a single type to a type checker.</p></li>
  1516. <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
  1517. asterisk (e.g., <code class="docutils literal notranslate"><span class="pre">*Ts</span></code>). Semantically, this stands for a tuple of any
  1518. number of types.</p></li>
  1519. <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
  1520. (e.g., <code class="docutils literal notranslate"><span class="pre">**P</span></code>). Semantically, this stands for the parameters of a callable.</p></li>
  1521. </ul>
  1522. <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
  1523. a colon (<code class="docutils literal notranslate"><span class="pre">:</span></code>) followed by an expression. A single expression after the colon
  1524. indicates a bound (e.g. <code class="docutils literal notranslate"><span class="pre">T:</span> <span class="pre">int</span></code>). Semantically, this means
  1525. 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
  1526. this bound. A parenthesized tuple of expressions after the colon indicates a
  1527. 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
  1528. type (again, this is not enforced at runtime). Constrained type variables can only
  1529. take on one of the types in the list of constraints.</p>
  1530. <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,
  1531. the bound and constraints are not evaluated when the generic object is created,
  1532. but only when the value is explicitly accessed through the attributes <code class="docutils literal notranslate"><span class="pre">__bound__</span></code>
  1533. and <code class="docutils literal notranslate"><span class="pre">__constraints__</span></code>. To accomplish this, the bounds or constraints are
  1534. evaluated in a separate <a class="reference internal" href="executionmodel.html#annotation-scopes"><span class="std std-ref">annotation scope</span></a>.</p>
  1535. <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
  1536. or constraints.</p>
  1537. <p>The following example indicates the full set of allowed type parameter declarations:</p>
  1538. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">overly_generic</span><span class="p">[</span>
  1539. <span class="n">SimpleTypeVar</span><span class="p">,</span>
  1540. <span class="n">TypeVarWithBound</span><span class="p">:</span> <span class="nb">int</span><span class="p">,</span>
  1541. <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>
  1542. <span class="o">*</span><span class="n">SimpleTypeVarTuple</span><span class="p">,</span>
  1543. <span class="o">**</span><span class="n">SimpleParamSpec</span><span class="p">,</span>
  1544. <span class="p">](</span>
  1545. <span class="n">a</span><span class="p">:</span> <span class="n">SimpleTypeVar</span><span class="p">,</span>
  1546. <span class="n">b</span><span class="p">:</span> <span class="n">TypeVarWithBound</span><span class="p">,</span>
  1547. <span class="n">c</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>
  1548. <span class="o">*</span><span class="n">d</span><span class="p">:</span> <span class="n">SimpleTypeVarTuple</span><span class="p">,</span>
  1549. <span class="p">):</span> <span class="o">...</span>
  1550. </pre></div>
  1551. </div>
  1552. <section id="generic-functions">
  1553. <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>
  1554. <p>Generic functions are declared as follows:</p>
  1555. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">func</span><span class="p">[</span><span class="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>
  1556. </pre></div>
  1557. </div>
  1558. <p>This syntax is equivalent to:</p>
  1559. <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="nf">TYPE_PARAMS_OF_func</span><span class="p">():</span>
  1560. <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">&quot;T&quot;</span><span class="p">)</span>
  1561. <span class="k">def</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>
  1562. <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>
  1563. <span class="k">return</span> <span class="n">func</span>
  1564. <span class="n">func</span> <span class="o">=</span> <span class="n">TYPE_PARAMS_OF_func</span><span class="p">()</span>
  1565. </pre></div>
  1566. </div>
  1567. <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>,
  1568. which is not actually bound to any name at runtime. (One
  1569. other liberty is taken in the translation: the syntax does not go through
  1570. 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
  1571. <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>
  1572. <p>The annotations of generic functions are evaluated within the annotation scope
  1573. used for declaring the type parameters, but the function’s defaults and
  1574. decorators are not.</p>
  1575. <p>The following example illustrates the scoping rules for these cases,
  1576. as well as for additional flavors of type parameters:</p>
  1577. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nd">@decorator</span>
  1578. <span class="k">def</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>
  1579. <span class="o">...</span>
  1580. </pre></div>
  1581. </div>
  1582. <p>Except for the <a class="reference internal" href="executionmodel.html#lazy-evaluation"><span class="std std-ref">lazy evaluation</span></a> of the
  1583. <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>
  1584. <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>
  1585. <span class="n">annotation</span><span class="o">-</span><span class="k">def</span> <span class="nf">TYPE_PARAMS_OF_func</span><span class="p">():</span>
  1586. <span class="n">annotation</span><span class="o">-</span><span class="k">def</span> <span class="nf">BOUND_OF_T</span><span class="p">():</span>
  1587. <span class="k">return</span> <span class="nb">int</span>
  1588. <span class="c1"># In reality, BOUND_OF_T() is evaluated only on demand.</span>
  1589. <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">&quot;T&quot;</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>
  1590. <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">&quot;Ts&quot;</span><span class="p">)</span>
  1591. <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">&quot;P&quot;</span><span class="p">)</span>
  1592. <span class="k">def</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>
  1593. <span class="o">...</span>
  1594. <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>
  1595. <span class="k">return</span> <span class="n">func</span>
  1596. <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>
  1597. </pre></div>
  1598. </div>
  1599. <p>The capitalized names like <code class="docutils literal notranslate"><span class="pre">DEFAULT_OF_arg</span></code> are not actually
  1600. bound at runtime.</p>
  1601. </section>
  1602. <section id="generic-classes">
  1603. <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>
  1604. <p>Generic classes are declared as follows:</p>
  1605. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Bag</span><span class="p">[</span><span class="n">T</span><span class="p">]:</span> <span class="o">...</span>
  1606. </pre></div>
  1607. </div>
  1608. <p>This syntax is equivalent to:</p>
  1609. <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="nf">TYPE_PARAMS_OF_Bag</span><span class="p">():</span>
  1610. <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">&quot;T&quot;</span><span class="p">)</span>
  1611. <span class="k">class</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>
  1612. <span class="n">__type_params__</span> <span class="o">=</span> <span class="p">(</span><span class="n">T</span><span class="p">,)</span>
  1613. <span class="o">...</span>
  1614. <span class="k">return</span> <span class="n">Bag</span>
  1615. <span class="n">Bag</span> <span class="o">=</span> <span class="n">TYPE_PARAMS_OF_Bag</span><span class="p">()</span>
  1616. </pre></div>
  1617. </div>
  1618. <p>Here again <code class="docutils literal notranslate"><span class="pre">annotation-def</span></code> (not a real keyword) indicates an
  1619. <a class="reference internal" href="executionmodel.html#annotation-scopes"><span class="std std-ref">annotation scope</span></a>, and the name
  1620. <code class="docutils literal notranslate"><span class="pre">TYPE_PARAMS_OF_Bag</span></code> is not actually bound at runtime.</p>
  1621. <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>.
  1622. The base classes and keyword arguments of generic classes are
  1623. evaluated within the type scope for the type parameters,
  1624. and decorators are evaluated outside that scope. This is illustrated
  1625. by this example:</p>
  1626. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nd">@decorator</span>
  1627. <span class="k">class</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>
  1628. </pre></div>
  1629. </div>
  1630. <p>This is equivalent to:</p>
  1631. <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="nf">TYPE_PARAMS_OF_Bag</span><span class="p">():</span>
  1632. <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">&quot;T&quot;</span><span class="p">)</span>
  1633. <span class="k">class</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>
  1634. <span class="n">__type_params__</span> <span class="o">=</span> <span class="p">(</span><span class="n">T</span><span class="p">,)</span>
  1635. <span class="o">...</span>
  1636. <span class="k">return</span> <span class="n">Bag</span>
  1637. <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>
  1638. </pre></div>
  1639. </div>
  1640. </section>
  1641. <section id="generic-type-aliases">
  1642. <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>
  1643. <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>
  1644. <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>
  1645. </pre></div>
  1646. </div>
  1647. <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,
  1648. this is equivalent to:</p>
  1649. <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="nf">TYPE_PARAMS_OF_ListOrSet</span><span class="p">():</span>
  1650. <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">&quot;T&quot;</span><span class="p">)</span>
  1651. <span class="n">annotation</span><span class="o">-</span><span class="k">def</span> <span class="nf">VALUE_OF_ListOrSet</span><span class="p">():</span>
  1652. <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>
  1653. <span class="c1"># In reality, the value is lazily evaluated</span>
  1654. <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">&quot;ListOrSet&quot;</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>
  1655. <span class="n">ListOrSet</span> <span class="o">=</span> <span class="n">TYPE_PARAMS_OF_ListOrSet</span><span class="p">()</span>
  1656. </pre></div>
  1657. </div>
  1658. <p>Here, <code class="docutils literal notranslate"><span class="pre">annotation-def</span></code> (not a real keyword) indicates an
  1659. <a class="reference internal" href="executionmodel.html#annotation-scopes"><span class="std std-ref">annotation scope</span></a>. The capitalized names
  1660. like <code class="docutils literal notranslate"><span class="pre">TYPE_PARAMS_OF_ListOrSet</span></code> are not actually bound at runtime.</p>
  1661. <p class="rubric">Footnotes</p>
  1662. <aside class="footnote-list brackets">
  1663. <aside class="footnote brackets" id="id20" role="doc-footnote">
  1664. <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id1">1</a><span class="fn-bracket">]</span></span>
  1665. <p>The exception is propagated to the invocation stack unless
  1666. 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
  1667. exception. That new exception causes the old one to be lost.</p>
  1668. </aside>
  1669. <aside class="footnote brackets" id="id21" role="doc-footnote">
  1670. <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id11">2</a><span class="fn-bracket">]</span></span>
  1671. <p>In pattern matching, a sequence is defined as one of the following:</p>
  1672. <ul class="simple">
  1673. <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>
  1674. <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>
  1675. <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>
  1676. <li><p>a class that inherits from any of the above</p></li>
  1677. </ul>
  1678. <p>The following standard library classes are sequences:</p>
  1679. <ul class="simple">
  1680. <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>
  1681. <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>
  1682. <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>
  1683. <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>
  1684. <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>
  1685. <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>
  1686. </ul>
  1687. <div class="admonition note">
  1688. <p class="admonition-title">Note</p>
  1689. <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>
  1690. do not match sequence patterns.</p>
  1691. </div>
  1692. </aside>
  1693. <aside class="footnote brackets" id="id22" role="doc-footnote">
  1694. <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id13">3</a><span class="fn-bracket">]</span></span>
  1695. <p>In pattern matching, a mapping is defined as one of the following:</p>
  1696. <ul class="simple">
  1697. <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>
  1698. <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>
  1699. <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>
  1700. <li><p>a class that inherits from any of the above</p></li>
  1701. </ul>
  1702. <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>
  1703. are mappings.</p>
  1704. </aside>
  1705. <aside class="footnote brackets" id="id23" role="doc-footnote">
  1706. <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id15">4</a><span class="fn-bracket">]</span></span>
  1707. <p>A string literal appearing as the first statement in the function body is
  1708. 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
  1709. therefore the function’s <a class="reference internal" href="../glossary.html#term-docstring"><span class="xref std std-term">docstring</span></a>.</p>
  1710. </aside>
  1711. <aside class="footnote brackets" id="id24" role="doc-footnote">
  1712. <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id16">5</a><span class="fn-bracket">]</span></span>
  1713. <p>A string literal appearing as the first statement in the class body is
  1714. transformed into the namespace’s <code class="docutils literal notranslate"><span class="pre">__doc__</span></code> item and therefore the class’s
  1715. <a class="reference internal" href="../glossary.html#term-docstring"><span class="xref std std-term">docstring</span></a>.</p>
  1716. </aside>
  1717. </aside>
  1718. </section>
  1719. </section>
  1720. </section>
  1721. <div class="clearer"></div>
  1722. </div>
  1723. </div>
  1724. </div>
  1725. <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
  1726. <div class="sphinxsidebarwrapper">
  1727. <div>
  1728. <h3><a href="../contents.html">Table of Contents</a></h3>
  1729. <ul>
  1730. <li><a class="reference internal" href="#">8. Compound statements</a><ul>
  1731. <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>
  1732. <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>
  1733. <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>
  1734. <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>
  1735. <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>
  1736. <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>
  1737. <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>
  1738. <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>
  1739. </ul>
  1740. </li>
  1741. <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>
  1742. <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>
  1743. <li><a class="reference internal" href="#overview">8.6.1. Overview</a></li>
  1744. <li><a class="reference internal" href="#guards">8.6.2. Guards</a></li>
  1745. <li><a class="reference internal" href="#irrefutable-case-blocks">8.6.3. Irrefutable Case Blocks</a></li>
  1746. <li><a class="reference internal" href="#patterns">8.6.4. Patterns</a><ul>
  1747. <li><a class="reference internal" href="#or-patterns">8.6.4.1. OR Patterns</a></li>
  1748. <li><a class="reference internal" href="#as-patterns">8.6.4.2. AS Patterns</a></li>
  1749. <li><a class="reference internal" href="#literal-patterns">8.6.4.3. Literal Patterns</a></li>
  1750. <li><a class="reference internal" href="#capture-patterns">8.6.4.4. Capture Patterns</a></li>
  1751. <li><a class="reference internal" href="#wildcard-patterns">8.6.4.5. Wildcard Patterns</a></li>
  1752. <li><a class="reference internal" href="#value-patterns">8.6.4.6. Value Patterns</a></li>
  1753. <li><a class="reference internal" href="#group-patterns">8.6.4.7. Group Patterns</a></li>
  1754. <li><a class="reference internal" href="#sequence-patterns">8.6.4.8. Sequence Patterns</a></li>
  1755. <li><a class="reference internal" href="#mapping-patterns">8.6.4.9. Mapping Patterns</a></li>
  1756. <li><a class="reference internal" href="#class-patterns">8.6.4.10. Class Patterns</a></li>
  1757. </ul>
  1758. </li>
  1759. </ul>
  1760. </li>
  1761. <li><a class="reference internal" href="#function-definitions">8.7. Function definitions</a></li>
  1762. <li><a class="reference internal" href="#class-definitions">8.8. Class definitions</a></li>
  1763. <li><a class="reference internal" href="#coroutines">8.9. Coroutines</a><ul>
  1764. <li><a class="reference internal" href="#coroutine-function-definition">8.9.1. Coroutine function definition</a></li>
  1765. <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>
  1766. <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>
  1767. </ul>
  1768. </li>
  1769. <li><a class="reference internal" href="#type-parameter-lists">8.10. Type parameter lists</a><ul>
  1770. <li><a class="reference internal" href="#generic-functions">8.10.1. Generic functions</a></li>
  1771. <li><a class="reference internal" href="#generic-classes">8.10.2. Generic classes</a></li>
  1772. <li><a class="reference internal" href="#generic-type-aliases">8.10.3. Generic type aliases</a></li>
  1773. </ul>
  1774. </li>
  1775. </ul>
  1776. </li>
  1777. </ul>
  1778. </div>
  1779. <div>
  1780. <h4>Previous topic</h4>
  1781. <p class="topless"><a href="simple_stmts.html"
  1782. title="previous chapter"><span class="section-number">7. </span>Simple statements</a></p>
  1783. </div>
  1784. <div>
  1785. <h4>Next topic</h4>
  1786. <p class="topless"><a href="toplevel_components.html"
  1787. title="next chapter"><span class="section-number">9. </span>Top-level components</a></p>
  1788. </div>
  1789. <div role="note" aria-label="source link">
  1790. <h3>This Page</h3>
  1791. <ul class="this-page-menu">
  1792. <li><a href="../bugs.html">Report a Bug</a></li>
  1793. <li>
  1794. <a href="https://github.com/python/cpython/blob/main/Doc/reference/compound_stmts.rst"
  1795. rel="nofollow">Show Source
  1796. </a>
  1797. </li>
  1798. </ul>
  1799. </div>
  1800. </div>
  1801. <div id="sidebarbutton" title="Collapse sidebar">
  1802. <span>«</span>
  1803. </div>
  1804. </div>
  1805. <div class="clearer"></div>
  1806. </div>
  1807. <div class="related" role="navigation" aria-label="related navigation">
  1808. <h3>Navigation</h3>
  1809. <ul>
  1810. <li class="right" style="margin-right: 10px">
  1811. <a href="../genindex.html" title="General Index"
  1812. >index</a></li>
  1813. <li class="right" >
  1814. <a href="../py-modindex.html" title="Python Module Index"
  1815. >modules</a> |</li>
  1816. <li class="right" >
  1817. <a href="toplevel_components.html" title="9. Top-level components"
  1818. >next</a> |</li>
  1819. <li class="right" >
  1820. <a href="simple_stmts.html" title="7. Simple statements"
  1821. >previous</a> |</li>
  1822. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  1823. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  1824. <li class="switchers">
  1825. <div class="language_switcher_placeholder"></div>
  1826. <div class="version_switcher_placeholder"></div>
  1827. </li>
  1828. <li>
  1829. </li>
  1830. <li id="cpython-language-and-version">
  1831. <a href="../index.html">3.12.3 Documentation</a> &#187;
  1832. </li>
  1833. <li class="nav-item nav-item-1"><a href="index.html" >The Python Language Reference</a> &#187;</li>
  1834. <li class="nav-item nav-item-this"><a href=""><span class="section-number">8. </span>Compound statements</a></li>
  1835. <li class="right">
  1836. <div class="inline-search" role="search">
  1837. <form class="inline-search" action="../search.html" method="get">
  1838. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  1839. <input type="submit" value="Go" />
  1840. </form>
  1841. </div>
  1842. |
  1843. </li>
  1844. <li class="right">
  1845. <label class="theme-selector-label">
  1846. Theme
  1847. <select class="theme-selector" oninput="activateTheme(this.value)">
  1848. <option value="auto" selected>Auto</option>
  1849. <option value="light">Light</option>
  1850. <option value="dark">Dark</option>
  1851. </select>
  1852. </label> |</li>
  1853. </ul>
  1854. </div>
  1855. <div class="footer">
  1856. &copy;
  1857. <a href="../copyright.html">
  1858. Copyright
  1859. </a>
  1860. 2001-2024, Python Software Foundation.
  1861. <br />
  1862. This page is licensed under the Python Software Foundation License Version 2.
  1863. <br />
  1864. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  1865. <br />
  1866. See <a href="/license.html">History and License</a> for more information.<br />
  1867. <br />
  1868. The Python Software Foundation is a non-profit corporation.
  1869. <a href="https://www.python.org/psf/donations/">Please donate.</a>
  1870. <br />
  1871. <br />
  1872. Last updated on Apr 09, 2024 (13:47 UTC).
  1873. <a href="/bugs.html">Found a bug</a>?
  1874. <br />
  1875. Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 7.2.6.
  1876. </div>
  1877. </body>
  1878. </html>
上海开阖软件有限公司 沪ICP备12045867号-1