gooderp18绿色标准版
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1851 line
208KB

  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="6. Expressions" />
  7. <meta property="og:type" content="website" />
  8. <meta property="og:url" content="https://docs.python.org/3/reference/expressions.html" />
  9. <meta property="og:site_name" content="Python documentation" />
  10. <meta property="og:description" content="This chapter explains the meaning of the elements of expressions in Python. Syntax Notes: In this and the following chapters, extended BNF notation will be used to describe syntax, not lexical anal..." />
  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="This chapter explains the meaning of the elements of expressions in Python. Syntax Notes: In this and the following chapters, extended BNF notation will be used to describe syntax, not lexical anal..." />
  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>6. Expressions &#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="7. Simple statements" href="simple_stmts.html" />
  33. <link rel="prev" title="5. The import system" href="import.html" />
  34. <link rel="canonical" href="https://docs.python.org/3/reference/expressions.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="#">6. Expressions</a><ul>
  86. <li><a class="reference internal" href="#arithmetic-conversions">6.1. Arithmetic conversions</a></li>
  87. <li><a class="reference internal" href="#atoms">6.2. Atoms</a><ul>
  88. <li><a class="reference internal" href="#atom-identifiers">6.2.1. Identifiers (Names)</a></li>
  89. <li><a class="reference internal" href="#literals">6.2.2. Literals</a></li>
  90. <li><a class="reference internal" href="#parenthesized-forms">6.2.3. Parenthesized forms</a></li>
  91. <li><a class="reference internal" href="#displays-for-lists-sets-and-dictionaries">6.2.4. Displays for lists, sets and dictionaries</a></li>
  92. <li><a class="reference internal" href="#list-displays">6.2.5. List displays</a></li>
  93. <li><a class="reference internal" href="#set-displays">6.2.6. Set displays</a></li>
  94. <li><a class="reference internal" href="#dictionary-displays">6.2.7. Dictionary displays</a></li>
  95. <li><a class="reference internal" href="#generator-expressions">6.2.8. Generator expressions</a></li>
  96. <li><a class="reference internal" href="#yield-expressions">6.2.9. Yield expressions</a><ul>
  97. <li><a class="reference internal" href="#generator-iterator-methods">6.2.9.1. Generator-iterator methods</a></li>
  98. <li><a class="reference internal" href="#examples">6.2.9.2. Examples</a></li>
  99. <li><a class="reference internal" href="#asynchronous-generator-functions">6.2.9.3. Asynchronous generator functions</a></li>
  100. <li><a class="reference internal" href="#asynchronous-generator-iterator-methods">6.2.9.4. Asynchronous generator-iterator methods</a></li>
  101. </ul>
  102. </li>
  103. </ul>
  104. </li>
  105. <li><a class="reference internal" href="#primaries">6.3. Primaries</a><ul>
  106. <li><a class="reference internal" href="#attribute-references">6.3.1. Attribute references</a></li>
  107. <li><a class="reference internal" href="#subscriptions">6.3.2. Subscriptions</a></li>
  108. <li><a class="reference internal" href="#slicings">6.3.3. Slicings</a></li>
  109. <li><a class="reference internal" href="#calls">6.3.4. Calls</a></li>
  110. </ul>
  111. </li>
  112. <li><a class="reference internal" href="#await-expression">6.4. Await expression</a></li>
  113. <li><a class="reference internal" href="#the-power-operator">6.5. The power operator</a></li>
  114. <li><a class="reference internal" href="#unary-arithmetic-and-bitwise-operations">6.6. Unary arithmetic and bitwise operations</a></li>
  115. <li><a class="reference internal" href="#binary-arithmetic-operations">6.7. Binary arithmetic operations</a></li>
  116. <li><a class="reference internal" href="#shifting-operations">6.8. Shifting operations</a></li>
  117. <li><a class="reference internal" href="#binary-bitwise-operations">6.9. Binary bitwise operations</a></li>
  118. <li><a class="reference internal" href="#comparisons">6.10. Comparisons</a><ul>
  119. <li><a class="reference internal" href="#value-comparisons">6.10.1. Value comparisons</a></li>
  120. <li><a class="reference internal" href="#membership-test-operations">6.10.2. Membership test operations</a></li>
  121. <li><a class="reference internal" href="#is-not">6.10.3. Identity comparisons</a></li>
  122. </ul>
  123. </li>
  124. <li><a class="reference internal" href="#boolean-operations">6.11. Boolean operations</a></li>
  125. <li><a class="reference internal" href="#assignment-expressions">6.12. Assignment expressions</a></li>
  126. <li><a class="reference internal" href="#conditional-expressions">6.13. Conditional expressions</a></li>
  127. <li><a class="reference internal" href="#lambda">6.14. Lambdas</a></li>
  128. <li><a class="reference internal" href="#expression-lists">6.15. Expression lists</a></li>
  129. <li><a class="reference internal" href="#evaluation-order">6.16. Evaluation order</a></li>
  130. <li><a class="reference internal" href="#operator-precedence">6.17. Operator precedence</a></li>
  131. </ul>
  132. </li>
  133. </ul>
  134. </div>
  135. <div>
  136. <h4>Previous topic</h4>
  137. <p class="topless"><a href="import.html"
  138. title="previous chapter"><span class="section-number">5. </span>The import system</a></p>
  139. </div>
  140. <div>
  141. <h4>Next topic</h4>
  142. <p class="topless"><a href="simple_stmts.html"
  143. title="next chapter"><span class="section-number">7. </span>Simple statements</a></p>
  144. </div>
  145. <div role="note" aria-label="source link">
  146. <h3>This Page</h3>
  147. <ul class="this-page-menu">
  148. <li><a href="../bugs.html">Report a Bug</a></li>
  149. <li>
  150. <a href="https://github.com/python/cpython/blob/main/Doc/reference/expressions.rst"
  151. rel="nofollow">Show Source
  152. </a>
  153. </li>
  154. </ul>
  155. </div>
  156. </nav>
  157. </div>
  158. </div>
  159. <div class="related" role="navigation" aria-label="related navigation">
  160. <h3>Navigation</h3>
  161. <ul>
  162. <li class="right" style="margin-right: 10px">
  163. <a href="../genindex.html" title="General Index"
  164. accesskey="I">index</a></li>
  165. <li class="right" >
  166. <a href="../py-modindex.html" title="Python Module Index"
  167. >modules</a> |</li>
  168. <li class="right" >
  169. <a href="simple_stmts.html" title="7. Simple statements"
  170. accesskey="N">next</a> |</li>
  171. <li class="right" >
  172. <a href="import.html" title="5. The import system"
  173. accesskey="P">previous</a> |</li>
  174. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  175. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  176. <li class="switchers">
  177. <div class="language_switcher_placeholder"></div>
  178. <div class="version_switcher_placeholder"></div>
  179. </li>
  180. <li>
  181. </li>
  182. <li id="cpython-language-and-version">
  183. <a href="../index.html">3.12.3 Documentation</a> &#187;
  184. </li>
  185. <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> &#187;</li>
  186. <li class="nav-item nav-item-this"><a href=""><span class="section-number">6. </span>Expressions</a></li>
  187. <li class="right">
  188. <div class="inline-search" role="search">
  189. <form class="inline-search" action="../search.html" method="get">
  190. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  191. <input type="submit" value="Go" />
  192. </form>
  193. </div>
  194. |
  195. </li>
  196. <li class="right">
  197. <label class="theme-selector-label">
  198. Theme
  199. <select class="theme-selector" oninput="activateTheme(this.value)">
  200. <option value="auto" selected>Auto</option>
  201. <option value="light">Light</option>
  202. <option value="dark">Dark</option>
  203. </select>
  204. </label> |</li>
  205. </ul>
  206. </div>
  207. <div class="document">
  208. <div class="documentwrapper">
  209. <div class="bodywrapper">
  210. <div class="body" role="main">
  211. <section id="expressions">
  212. <span id="id1"></span><h1><span class="section-number">6. </span>Expressions<a class="headerlink" href="#expressions" title="Link to this heading">¶</a></h1>
  213. <p id="index-0">This chapter explains the meaning of the elements of expressions in Python.</p>
  214. <p><strong>Syntax Notes:</strong> In this and the following chapters, extended BNF notation will
  215. be used to describe syntax, not lexical analysis. When (one alternative of) a
  216. syntax rule has the form</p>
  217. <pre>
  218. <strong id="grammar-token-python-grammar-name">name</strong> ::= othername
  219. </pre>
  220. <p>and no semantics are given, the semantics of this form of <code class="docutils literal notranslate"><span class="pre">name</span></code> are the same
  221. as for <code class="docutils literal notranslate"><span class="pre">othername</span></code>.</p>
  222. <section id="arithmetic-conversions">
  223. <span id="conversions"></span><h2><span class="section-number">6.1. </span>Arithmetic conversions<a class="headerlink" href="#arithmetic-conversions" title="Link to this heading">¶</a></h2>
  224. <p id="index-1">When a description of an arithmetic operator below uses the phrase “the numeric
  225. arguments are converted to a common type”, this means that the operator
  226. implementation for built-in types works as follows:</p>
  227. <ul class="simple">
  228. <li><p>If either argument is a complex number, the other is converted to complex;</p></li>
  229. <li><p>otherwise, if either argument is a floating point number, the other is
  230. converted to floating point;</p></li>
  231. <li><p>otherwise, both must be integers and no conversion is necessary.</p></li>
  232. </ul>
  233. <p>Some additional rules apply for certain operators (e.g., a string as a left
  234. argument to the ‘%’ operator). Extensions must define their own conversion
  235. behavior.</p>
  236. </section>
  237. <section id="atoms">
  238. <span id="id2"></span><h2><span class="section-number">6.2. </span>Atoms<a class="headerlink" href="#atoms" title="Link to this heading">¶</a></h2>
  239. <p id="index-2">Atoms are the most basic elements of expressions. The simplest atoms are
  240. identifiers or literals. Forms enclosed in parentheses, brackets or braces are
  241. also categorized syntactically as atoms. The syntax for atoms is:</p>
  242. <pre>
  243. <strong id="grammar-token-python-grammar-atom">atom </strong> ::= <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-literal"><code class="xref docutils literal notranslate"><span class="pre">literal</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-enclosure"><code class="xref docutils literal notranslate"><span class="pre">enclosure</span></code></a>
  244. <strong id="grammar-token-python-grammar-enclosure">enclosure</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-parenth_form"><code class="xref docutils literal notranslate"><span class="pre">parenth_form</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-list_display"><code class="xref docutils literal notranslate"><span class="pre">list_display</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-dict_display"><code class="xref docutils literal notranslate"><span class="pre">dict_display</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-set_display"><code class="xref docutils literal notranslate"><span class="pre">set_display</span></code></a>
  245. | <a class="reference internal" href="#grammar-token-python-grammar-generator_expression"><code class="xref docutils literal notranslate"><span class="pre">generator_expression</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-yield_atom"><code class="xref docutils literal notranslate"><span class="pre">yield_atom</span></code></a>
  246. </pre>
  247. <section id="atom-identifiers">
  248. <span id="identifiers-names"></span><h3><span class="section-number">6.2.1. </span>Identifiers (Names)<a class="headerlink" href="#atom-identifiers" title="Link to this heading">¶</a></h3>
  249. <p id="index-3">An identifier occurring as an atom is a name. See section <a class="reference internal" href="lexical_analysis.html#identifiers"><span class="std std-ref">Identifiers and keywords</span></a>
  250. for lexical definition and section <a class="reference internal" href="executionmodel.html#naming"><span class="std std-ref">Naming and binding</span></a> for documentation of naming and
  251. binding.</p>
  252. <p id="index-4">When the name is bound to an object, evaluation of the atom yields that object.
  253. When a name is not bound, an attempt to evaluate it raises a <a class="reference internal" href="../library/exceptions.html#NameError" title="NameError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NameError</span></code></a>
  254. exception.</p>
  255. <p id="index-5"><span id="private-name-mangling"></span><strong>Private name mangling:</strong> When an identifier that textually occurs in a class
  256. definition begins with two or more underscore characters and does not end in two
  257. or more underscores, it is considered a <em class="dfn">private name</em> of that class.
  258. Private names are transformed to a longer form before code is generated for
  259. them. The transformation inserts the class name, with leading underscores
  260. removed and a single underscore inserted, in front of the name. For example,
  261. the identifier <code class="docutils literal notranslate"><span class="pre">__spam</span></code> occurring in a class named <code class="docutils literal notranslate"><span class="pre">Ham</span></code> will be transformed
  262. to <code class="docutils literal notranslate"><span class="pre">_Ham__spam</span></code>. This transformation is independent of the syntactical
  263. context in which the identifier is used. If the transformed name is extremely
  264. long (longer than 255 characters), implementation defined truncation may happen.
  265. If the class name consists only of underscores, no transformation is done.</p>
  266. </section>
  267. <section id="literals">
  268. <span id="atom-literals"></span><h3><span class="section-number">6.2.2. </span>Literals<a class="headerlink" href="#literals" title="Link to this heading">¶</a></h3>
  269. <p id="index-6">Python supports string and bytes literals and various numeric literals:</p>
  270. <pre>
  271. <strong id="grammar-token-python-grammar-literal">literal</strong> ::= <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-stringliteral"><code class="xref docutils literal notranslate"><span class="pre">stringliteral</span></code></a> | <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-bytesliteral"><code class="xref docutils literal notranslate"><span class="pre">bytesliteral</span></code></a>
  272. | <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-integer"><code class="xref docutils literal notranslate"><span class="pre">integer</span></code></a> | <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-floatnumber"><code class="xref docutils literal notranslate"><span class="pre">floatnumber</span></code></a> | <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-imagnumber"><code class="xref docutils literal notranslate"><span class="pre">imagnumber</span></code></a>
  273. </pre>
  274. <p>Evaluation of a literal yields an object of the given type (string, bytes,
  275. integer, floating point number, complex number) with the given value. The value
  276. may be approximated in the case of floating point and imaginary (complex)
  277. literals. See section <a class="reference internal" href="lexical_analysis.html#literals"><span class="std std-ref">Literals</span></a> for details.</p>
  278. <p id="index-7">All literals correspond to immutable data types, and hence the object’s identity
  279. is less important than its value. Multiple evaluations of literals with the
  280. same value (either the same occurrence in the program text or a different
  281. occurrence) may obtain the same object or a different object with the same
  282. value.</p>
  283. </section>
  284. <section id="parenthesized-forms">
  285. <span id="parenthesized"></span><h3><span class="section-number">6.2.3. </span>Parenthesized forms<a class="headerlink" href="#parenthesized-forms" title="Link to this heading">¶</a></h3>
  286. <p id="index-8">A parenthesized form is an optional expression list enclosed in parentheses:</p>
  287. <pre>
  288. <strong id="grammar-token-python-grammar-parenth_form">parenth_form</strong> ::= &quot;(&quot; [<a class="reference internal" href="#grammar-token-python-grammar-starred_expression"><code class="xref docutils literal notranslate"><span class="pre">starred_expression</span></code></a>] &quot;)&quot;
  289. </pre>
  290. <p>A parenthesized expression list yields whatever that expression list yields: if
  291. the list contains at least one comma, it yields a tuple; otherwise, it yields
  292. the single expression that makes up the expression list.</p>
  293. <p id="index-9">An empty pair of parentheses yields an empty tuple object. Since tuples are
  294. immutable, the same rules as for literals apply (i.e., two occurrences of the empty
  295. tuple may or may not yield the same object).</p>
  296. <p id="index-10">Note that tuples are not formed by the parentheses, but rather by use of the
  297. comma. The exception is the empty tuple, for which parentheses <em>are</em>
  298. required — allowing unparenthesized “nothing” in expressions would cause
  299. ambiguities and allow common typos to pass uncaught.</p>
  300. </section>
  301. <section id="displays-for-lists-sets-and-dictionaries">
  302. <span id="comprehensions"></span><h3><span class="section-number">6.2.4. </span>Displays for lists, sets and dictionaries<a class="headerlink" href="#displays-for-lists-sets-and-dictionaries" title="Link to this heading">¶</a></h3>
  303. <p id="index-11">For constructing a list, a set or a dictionary Python provides special syntax
  304. called “displays”, each of them in two flavors:</p>
  305. <ul class="simple">
  306. <li><p>either the container contents are listed explicitly, or</p></li>
  307. <li><p>they are computed via a set of looping and filtering instructions, called a
  308. <em class="dfn">comprehension</em>.</p></li>
  309. </ul>
  310. <p id="index-12">Common syntax elements for comprehensions are:</p>
  311. <pre>
  312. <strong id="grammar-token-python-grammar-comprehension">comprehension</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-assignment_expression"><code class="xref docutils literal notranslate"><span class="pre">assignment_expression</span></code></a> <a class="reference internal" href="#grammar-token-python-grammar-comp_for"><code class="xref docutils literal notranslate"><span class="pre">comp_for</span></code></a>
  313. <strong id="grammar-token-python-grammar-comp_for">comp_for </strong> ::= [&quot;async&quot;] &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="#grammar-token-python-grammar-or_test"><code class="xref docutils literal notranslate"><span class="pre">or_test</span></code></a> [<a class="reference internal" href="#grammar-token-python-grammar-comp_iter"><code class="xref docutils literal notranslate"><span class="pre">comp_iter</span></code></a>]
  314. <strong id="grammar-token-python-grammar-comp_iter">comp_iter </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-comp_for"><code class="xref docutils literal notranslate"><span class="pre">comp_for</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-comp_if"><code class="xref docutils literal notranslate"><span class="pre">comp_if</span></code></a>
  315. <strong id="grammar-token-python-grammar-comp_if">comp_if </strong> ::= &quot;if&quot; <a class="reference internal" href="#grammar-token-python-grammar-or_test"><code class="xref docutils literal notranslate"><span class="pre">or_test</span></code></a> [<a class="reference internal" href="#grammar-token-python-grammar-comp_iter"><code class="xref docutils literal notranslate"><span class="pre">comp_iter</span></code></a>]
  316. </pre>
  317. <p>The comprehension consists of a single expression followed by at least one
  318. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clause and zero or more <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> or <code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code> clauses.
  319. In this case, the elements of the new container are those that would be produced
  320. by considering each of the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> or <code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code> clauses a block,
  321. nesting from left to right, and evaluating the expression to produce an element
  322. each time the innermost block is reached.</p>
  323. <p>However, aside from the iterable expression in the leftmost <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clause,
  324. the comprehension is executed in a separate implicitly nested scope. This ensures
  325. that names assigned to in the target list don’t “leak” into the enclosing scope.</p>
  326. <p>The iterable expression in the leftmost <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clause is evaluated
  327. directly in the enclosing scope and then passed as an argument to the implicitly
  328. nested scope. Subsequent <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clauses and any filter condition in the
  329. leftmost <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clause cannot be evaluated in the enclosing scope as
  330. they may depend on the values obtained from the leftmost iterable. For example:
  331. <code class="docutils literal notranslate"><span class="pre">[x*y</span> <span class="pre">for</span> <span class="pre">x</span> <span class="pre">in</span> <span class="pre">range(10)</span> <span class="pre">for</span> <span class="pre">y</span> <span class="pre">in</span> <span class="pre">range(x,</span> <span class="pre">x+10)]</span></code>.</p>
  332. <p>To ensure the comprehension always results in a container of the appropriate
  333. type, <code class="docutils literal notranslate"><span class="pre">yield</span></code> and <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code> expressions are prohibited in the implicitly
  334. nested scope.</p>
  335. <p id="index-13">Since Python 3.6, in an <a class="reference internal" href="compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> function, an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code>
  336. clause may be used to iterate over a <a class="reference internal" href="../glossary.html#term-asynchronous-iterator"><span class="xref std std-term">asynchronous iterator</span></a>.
  337. A comprehension in an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code> function may consist of either a
  338. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> or <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code> clause following the leading
  339. expression, may contain additional <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> or <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code>
  340. clauses, and may also use <a class="reference internal" href="#await"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">await</span></code></a> expressions.
  341. If a comprehension contains either <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code> clauses or
  342. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">await</span></code> expressions or other asynchronous comprehensions it is called
  343. an <em class="dfn">asynchronous comprehension</em>. An asynchronous comprehension may
  344. suspend the execution of the coroutine function in which it appears.
  345. See also <span class="target" id="index-14"></span><a class="pep reference external" href="https://peps.python.org/pep-0530/"><strong>PEP 530</strong></a>.</p>
  346. <div class="versionadded">
  347. <p><span class="versionmodified added">New in version 3.6: </span>Asynchronous comprehensions were introduced.</p>
  348. </div>
  349. <div class="versionchanged">
  350. <p><span class="versionmodified changed">Changed in version 3.8: </span><code class="docutils literal notranslate"><span class="pre">yield</span></code> and <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code> prohibited in the implicitly nested scope.</p>
  351. </div>
  352. <div class="versionchanged">
  353. <p><span class="versionmodified changed">Changed in version 3.11: </span>Asynchronous comprehensions are now allowed inside comprehensions in
  354. asynchronous functions. Outer comprehensions implicitly become
  355. asynchronous.</p>
  356. </div>
  357. </section>
  358. <section id="list-displays">
  359. <span id="lists"></span><h3><span class="section-number">6.2.5. </span>List displays<a class="headerlink" href="#list-displays" title="Link to this heading">¶</a></h3>
  360. <p id="index-15">A list display is a possibly empty series of expressions enclosed in square
  361. brackets:</p>
  362. <pre>
  363. <strong id="grammar-token-python-grammar-list_display">list_display</strong> ::= &quot;[&quot; [<a class="reference internal" href="#grammar-token-python-grammar-starred_list"><code class="xref docutils literal notranslate"><span class="pre">starred_list</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-comprehension"><code class="xref docutils literal notranslate"><span class="pre">comprehension</span></code></a>] &quot;]&quot;
  364. </pre>
  365. <p>A list display yields a new list object, the contents being specified by either
  366. a list of expressions or a comprehension. When a comma-separated list of
  367. expressions is supplied, its elements are evaluated from left to right and
  368. placed into the list object in that order. When a comprehension is supplied,
  369. the list is constructed from the elements resulting from the comprehension.</p>
  370. </section>
  371. <section id="set-displays">
  372. <span id="set"></span><h3><span class="section-number">6.2.6. </span>Set displays<a class="headerlink" href="#set-displays" title="Link to this heading">¶</a></h3>
  373. <p id="index-16">A set display is denoted by curly braces and distinguishable from dictionary
  374. displays by the lack of colons separating keys and values:</p>
  375. <pre>
  376. <strong id="grammar-token-python-grammar-set_display">set_display</strong> ::= &quot;{&quot; (<a class="reference internal" href="#grammar-token-python-grammar-starred_list"><code class="xref docutils literal notranslate"><span class="pre">starred_list</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-comprehension"><code class="xref docutils literal notranslate"><span class="pre">comprehension</span></code></a>) &quot;}&quot;
  377. </pre>
  378. <p>A set display yields a new mutable set object, the contents being specified by
  379. either a sequence of expressions or a comprehension. When a comma-separated
  380. list of expressions is supplied, its elements are evaluated from left to right
  381. and added to the set object. When a comprehension is supplied, the set is
  382. constructed from the elements resulting from the comprehension.</p>
  383. <p>An empty set cannot be constructed with <code class="docutils literal notranslate"><span class="pre">{}</span></code>; this literal constructs an empty
  384. dictionary.</p>
  385. </section>
  386. <section id="dictionary-displays">
  387. <span id="dict"></span><h3><span class="section-number">6.2.7. </span>Dictionary displays<a class="headerlink" href="#dictionary-displays" title="Link to this heading">¶</a></h3>
  388. <p id="index-17">A dictionary display is a possibly empty series of dict items (key/value pairs)
  389. enclosed in curly braces:</p>
  390. <pre>
  391. <strong id="grammar-token-python-grammar-dict_display">dict_display </strong> ::= &quot;{&quot; [<a class="reference internal" href="#grammar-token-python-grammar-dict_item_list"><code class="xref docutils literal notranslate"><span class="pre">dict_item_list</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-dict_comprehension"><code class="xref docutils literal notranslate"><span class="pre">dict_comprehension</span></code></a>] &quot;}&quot;
  392. <strong id="grammar-token-python-grammar-dict_item_list">dict_item_list </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-dict_item"><code class="xref docutils literal notranslate"><span class="pre">dict_item</span></code></a> (&quot;,&quot; <a class="reference internal" href="#grammar-token-python-grammar-dict_item"><code class="xref docutils literal notranslate"><span class="pre">dict_item</span></code></a>)* [&quot;,&quot;]
  393. <strong id="grammar-token-python-grammar-dict_item">dict_item </strong> ::= <a class="reference internal" href="#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-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-or_expr"><code class="xref docutils literal notranslate"><span class="pre">or_expr</span></code></a>
  394. <strong id="grammar-token-python-grammar-dict_comprehension">dict_comprehension</strong> ::= <a class="reference internal" href="#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-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> <a class="reference internal" href="#grammar-token-python-grammar-comp_for"><code class="xref docutils literal notranslate"><span class="pre">comp_for</span></code></a>
  395. </pre>
  396. <p>A dictionary display yields a new dictionary object.</p>
  397. <p>If a comma-separated sequence of dict items is given, they are evaluated
  398. from left to right to define the entries of the dictionary: each key object is
  399. used as a key into the dictionary to store the corresponding value. This means
  400. that you can specify the same key multiple times in the dict item list, and the
  401. final dictionary’s value for that key will be the last one given.</p>
  402. <p id="index-18">A double asterisk <code class="docutils literal notranslate"><span class="pre">**</span></code> denotes <em class="dfn">dictionary unpacking</em>.
  403. Its operand must be a <a class="reference internal" href="../glossary.html#term-mapping"><span class="xref std std-term">mapping</span></a>. Each mapping item is added
  404. to the new dictionary. Later values replace values already set by
  405. earlier dict items and earlier dictionary unpackings.</p>
  406. <div class="versionadded">
  407. <p><span class="versionmodified added">New in version 3.5: </span>Unpacking into dictionary displays, originally proposed by <span class="target" id="index-19"></span><a class="pep reference external" href="https://peps.python.org/pep-0448/"><strong>PEP 448</strong></a>.</p>
  408. </div>
  409. <p>A dict comprehension, in contrast to list and set comprehensions, needs two
  410. expressions separated with a colon followed by the usual “for” and “if” clauses.
  411. When the comprehension is run, the resulting key and value elements are inserted
  412. in the new dictionary in the order they are produced.</p>
  413. <p id="index-20">Restrictions on the types of the key values are listed earlier in section
  414. <a class="reference internal" href="datamodel.html#types"><span class="std std-ref">The standard type hierarchy</span></a>. (To summarize, the key type should be <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a>, which excludes
  415. all mutable objects.) Clashes between duplicate keys are not detected; the last
  416. value (textually rightmost in the display) stored for a given key value
  417. prevails.</p>
  418. <div class="versionchanged">
  419. <p><span class="versionmodified changed">Changed in version 3.8: </span>Prior to Python 3.8, in dict comprehensions, the evaluation order of key
  420. and value was not well-defined. In CPython, the value was evaluated before
  421. the key. Starting with 3.8, the key is evaluated before the value, as
  422. proposed by <span class="target" id="index-21"></span><a class="pep reference external" href="https://peps.python.org/pep-0572/"><strong>PEP 572</strong></a>.</p>
  423. </div>
  424. </section>
  425. <section id="generator-expressions">
  426. <span id="genexpr"></span><h3><span class="section-number">6.2.8. </span>Generator expressions<a class="headerlink" href="#generator-expressions" title="Link to this heading">¶</a></h3>
  427. <p id="index-22">A generator expression is a compact generator notation in parentheses:</p>
  428. <pre>
  429. <strong id="grammar-token-python-grammar-generator_expression">generator_expression</strong> ::= &quot;(&quot; <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> <a class="reference internal" href="#grammar-token-python-grammar-comp_for"><code class="xref docutils literal notranslate"><span class="pre">comp_for</span></code></a> &quot;)&quot;
  430. </pre>
  431. <p>A generator expression yields a new generator object. Its syntax is the same as
  432. for comprehensions, except that it is enclosed in parentheses instead of
  433. brackets or curly braces.</p>
  434. <p>Variables used in the generator expression are evaluated lazily when the
  435. <a class="reference internal" href="#generator.__next__" title="generator.__next__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code></a> method is called for the generator object (in the same
  436. fashion as normal generators). However, the iterable expression in the
  437. leftmost <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clause is immediately evaluated, so that an error
  438. produced by it will be emitted at the point where the generator expression
  439. is defined, rather than at the point where the first value is retrieved.
  440. Subsequent <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clauses and any filter condition in the leftmost
  441. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> clause cannot be evaluated in the enclosing scope as they may
  442. depend on the values obtained from the leftmost iterable. For example:
  443. <code class="docutils literal notranslate"><span class="pre">(x*y</span> <span class="pre">for</span> <span class="pre">x</span> <span class="pre">in</span> <span class="pre">range(10)</span> <span class="pre">for</span> <span class="pre">y</span> <span class="pre">in</span> <span class="pre">range(x,</span> <span class="pre">x+10))</span></code>.</p>
  444. <p>The parentheses can be omitted on calls with only one argument. See section
  445. <a class="reference internal" href="#calls"><span class="std std-ref">Calls</span></a> for details.</p>
  446. <p>To avoid interfering with the expected operation of the generator expression
  447. itself, <code class="docutils literal notranslate"><span class="pre">yield</span></code> and <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code> expressions are prohibited in the
  448. implicitly defined generator.</p>
  449. <p>If a generator expression contains either <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code>
  450. clauses or <a class="reference internal" href="#await"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">await</span></code></a> expressions it is called an
  451. <em class="dfn">asynchronous generator expression</em>. An asynchronous generator
  452. expression returns a new asynchronous generator object,
  453. which is an asynchronous iterator (see <a class="reference internal" href="datamodel.html#async-iterators"><span class="std std-ref">Asynchronous Iterators</span></a>).</p>
  454. <div class="versionadded">
  455. <p><span class="versionmodified added">New in version 3.6: </span>Asynchronous generator expressions were introduced.</p>
  456. </div>
  457. <div class="versionchanged">
  458. <p><span class="versionmodified changed">Changed in version 3.7: </span>Prior to Python 3.7, asynchronous generator expressions could
  459. only appear in <a class="reference internal" href="compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> coroutines. Starting
  460. with 3.7, any function can use asynchronous generator expressions.</p>
  461. </div>
  462. <div class="versionchanged">
  463. <p><span class="versionmodified changed">Changed in version 3.8: </span><code class="docutils literal notranslate"><span class="pre">yield</span></code> and <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code> prohibited in the implicitly nested scope.</p>
  464. </div>
  465. </section>
  466. <section id="yield-expressions">
  467. <span id="yieldexpr"></span><h3><span class="section-number">6.2.9. </span>Yield expressions<a class="headerlink" href="#yield-expressions" title="Link to this heading">¶</a></h3>
  468. <pre id="index-23">
  469. <strong id="grammar-token-python-grammar-yield_atom">yield_atom </strong> ::= &quot;(&quot; <a class="reference internal" href="#grammar-token-python-grammar-yield_expression"><code class="xref docutils literal notranslate"><span class="pre">yield_expression</span></code></a> &quot;)&quot;
  470. <strong id="grammar-token-python-grammar-yield_from">yield_from </strong> ::= &quot;yield&quot; &quot;from&quot; <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
  471. <strong id="grammar-token-python-grammar-yield_expression">yield_expression</strong> ::= &quot;yield&quot; <a class="reference internal" href="#grammar-token-python-grammar-expression_list"><code class="xref docutils literal notranslate"><span class="pre">expression_list</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-yield_from"><code class="xref docutils literal notranslate"><span class="pre">yield_from</span></code></a>
  472. </pre>
  473. <p>The yield expression is used when defining a <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a> function
  474. or an <a class="reference internal" href="../glossary.html#term-asynchronous-generator"><span class="xref std std-term">asynchronous generator</span></a> function and
  475. thus can only be used in the body of a function definition. Using a yield
  476. expression in a function’s body causes that function to be a generator function,
  477. and using it in an <a class="reference internal" href="compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> function’s body causes that
  478. coroutine function to be an asynchronous generator function. For example:</p>
  479. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">gen</span><span class="p">():</span> <span class="c1"># defines a generator function</span>
  480. <span class="k">yield</span> <span class="mi">123</span>
  481. <span class="k">async</span> <span class="k">def</span> <span class="nf">agen</span><span class="p">():</span> <span class="c1"># defines an asynchronous generator function</span>
  482. <span class="k">yield</span> <span class="mi">123</span>
  483. </pre></div>
  484. </div>
  485. <p>Due to their side effects on the containing scope, <code class="docutils literal notranslate"><span class="pre">yield</span></code> expressions
  486. are not permitted as part of the implicitly defined scopes used to
  487. implement comprehensions and generator expressions.</p>
  488. <div class="versionchanged">
  489. <p><span class="versionmodified changed">Changed in version 3.8: </span>Yield expressions prohibited in the implicitly nested scopes used to
  490. implement comprehensions and generator expressions.</p>
  491. </div>
  492. <p>Generator functions are described below, while asynchronous generator
  493. functions are described separately in section
  494. <a class="reference internal" href="#asynchronous-generator-functions"><span class="std std-ref">Asynchronous generator functions</span></a>.</p>
  495. <p>When a generator function is called, it returns an iterator known as a
  496. generator. That generator then controls the execution of the generator
  497. function. The execution starts when one of the generator’s methods is called.
  498. At that time, the execution proceeds to the first yield expression, where it is
  499. suspended again, returning the value of <a class="reference internal" href="#grammar-token-python-grammar-expression_list"><code class="xref std std-token docutils literal notranslate"><span class="pre">expression_list</span></code></a>
  500. to the generator’s caller,
  501. or <code class="docutils literal notranslate"><span class="pre">None</span></code> if <a class="reference internal" href="#grammar-token-python-grammar-expression_list"><code class="xref std std-token docutils literal notranslate"><span class="pre">expression_list</span></code></a> is omitted.
  502. By suspended, we mean that all local state is
  503. retained, including the current bindings of local variables, the instruction
  504. pointer, the internal evaluation stack, and the state of any exception handling.
  505. When the execution is resumed by calling one of the generator’s methods, the
  506. function can proceed exactly as if the yield expression were just another
  507. external call. The value of the yield expression after resuming depends on the
  508. method which resumed the execution. If <a class="reference internal" href="#generator.__next__" title="generator.__next__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code></a> is used
  509. (typically via either a <a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> or the <a class="reference internal" href="../library/functions.html#next" title="next"><code class="xref py py-func docutils literal notranslate"><span class="pre">next()</span></code></a> builtin) then the
  510. result is <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>. Otherwise, if <a class="reference internal" href="#generator.send" title="generator.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a> is used, then
  511. the result will be the value passed in to that method.</p>
  512. <p id="index-24">All of this makes generator functions quite similar to coroutines; they yield
  513. multiple times, they have more than one entry point and their execution can be
  514. suspended. The only difference is that a generator function cannot control
  515. where the execution should continue after it yields; the control is always
  516. transferred to the generator’s caller.</p>
  517. <p>Yield expressions are allowed anywhere in a <a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> construct. If the
  518. generator is not resumed before it is
  519. finalized (by reaching a zero reference count or by being garbage collected),
  520. the generator-iterator’s <a class="reference internal" href="#generator.close" title="generator.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> method will be called,
  521. allowing any pending <a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clauses to execute.</p>
  522. <p id="index-25">When <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span> <span class="pre">&lt;expr&gt;</span></code> is used, the supplied expression must be an
  523. iterable. The values produced by iterating that iterable are passed directly
  524. to the caller of the current generator’s methods. Any values passed in with
  525. <a class="reference internal" href="#generator.send" title="generator.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a> and any exceptions passed in with
  526. <a class="reference internal" href="#generator.throw" title="generator.throw"><code class="xref py py-meth docutils literal notranslate"><span class="pre">throw()</span></code></a> are passed to the underlying iterator if it has the
  527. appropriate methods. If this is not the case, then <a class="reference internal" href="#generator.send" title="generator.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a>
  528. will raise <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> or <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>, while
  529. <a class="reference internal" href="#generator.throw" title="generator.throw"><code class="xref py py-meth docutils literal notranslate"><span class="pre">throw()</span></code></a> will just raise the passed in exception immediately.</p>
  530. <p>When the underlying iterator is complete, the <a class="reference internal" href="../library/exceptions.html#StopIteration.value" title="StopIteration.value"><code class="xref py py-attr docutils literal notranslate"><span class="pre">value</span></code></a>
  531. attribute of the raised <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> instance becomes the value of
  532. the yield expression. It can be either set explicitly when raising
  533. <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a>, or automatically when the subiterator is a generator
  534. (by returning a value from the subgenerator).</p>
  535. <div class="versionchanged">
  536. <p><span class="versionmodified changed">Changed in version 3.3: </span>Added <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span> <span class="pre">&lt;expr&gt;</span></code> to delegate control flow to a subiterator.</p>
  537. </div>
  538. <p>The parentheses may be omitted when the yield expression is the sole expression
  539. on the right hand side of an assignment statement.</p>
  540. <div class="admonition seealso">
  541. <p class="admonition-title">See also</p>
  542. <dl class="simple">
  543. <dt><span class="target" id="index-26"></span><a class="pep reference external" href="https://peps.python.org/pep-0255/"><strong>PEP 255</strong></a> - Simple Generators</dt><dd><p>The proposal for adding generators and the <a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement to Python.</p>
  544. </dd>
  545. <dt><span class="target" id="index-27"></span><a class="pep reference external" href="https://peps.python.org/pep-0342/"><strong>PEP 342</strong></a> - Coroutines via Enhanced Generators</dt><dd><p>The proposal to enhance the API and syntax of generators, making them
  546. usable as simple coroutines.</p>
  547. </dd>
  548. <dt><span class="target" id="index-28"></span><a class="pep reference external" href="https://peps.python.org/pep-0380/"><strong>PEP 380</strong></a> - Syntax for Delegating to a Subgenerator</dt><dd><p>The proposal to introduce the <a class="reference internal" href="#grammar-token-python-grammar-yield_from"><code class="xref std std-token docutils literal notranslate"><span class="pre">yield_from</span></code></a> syntax,
  549. making delegation to subgenerators easy.</p>
  550. </dd>
  551. <dt><span class="target" id="index-29"></span><a class="pep reference external" href="https://peps.python.org/pep-0525/"><strong>PEP 525</strong></a> - Asynchronous Generators</dt><dd><p>The proposal that expanded on <span class="target" id="index-30"></span><a class="pep reference external" href="https://peps.python.org/pep-0492/"><strong>PEP 492</strong></a> by adding generator capabilities to
  552. coroutine functions.</p>
  553. </dd>
  554. </dl>
  555. </div>
  556. <section id="generator-iterator-methods">
  557. <span id="generator-methods"></span><span id="index-31"></span><h4><span class="section-number">6.2.9.1. </span>Generator-iterator methods<a class="headerlink" href="#generator-iterator-methods" title="Link to this heading">¶</a></h4>
  558. <p>This subsection describes the methods of a generator iterator. They can
  559. be used to control the execution of a generator function.</p>
  560. <p>Note that calling any of the generator methods below when the generator
  561. is already executing raises 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> exception.</p>
  562. <dl class="py method" id="index-32">
  563. <dt class="sig sig-object py" id="generator.__next__">
  564. <span class="sig-prename descclassname"><span class="pre">generator.</span></span><span class="sig-name descname"><span class="pre">__next__</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#generator.__next__" title="Link to this definition">¶</a></dt>
  565. <dd><p>Starts the execution of a generator function or resumes it at the last
  566. executed yield expression. When a generator function is resumed with a
  567. <a class="reference internal" href="#generator.__next__" title="generator.__next__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code></a> method, the current yield expression always
  568. evaluates to <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>. The execution then continues to the next yield
  569. expression, where the generator is suspended again, and the value of the
  570. <a class="reference internal" href="#grammar-token-python-grammar-expression_list"><code class="xref std std-token docutils literal notranslate"><span class="pre">expression_list</span></code></a> is returned to <a class="reference internal" href="#generator.__next__" title="generator.__next__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code></a>’s
  571. caller. If the generator exits without yielding another value, a
  572. <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> exception is raised.</p>
  573. <p>This method is normally called implicitly, e.g. by a <a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loop, or
  574. by the built-in <a class="reference internal" href="../library/functions.html#next" title="next"><code class="xref py py-func docutils literal notranslate"><span class="pre">next()</span></code></a> function.</p>
  575. </dd></dl>
  576. <dl class="py method">
  577. <dt class="sig sig-object py" id="generator.send">
  578. <span class="sig-prename descclassname"><span class="pre">generator.</span></span><span class="sig-name descname"><span class="pre">send</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">value</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#generator.send" title="Link to this definition">¶</a></dt>
  579. <dd><p>Resumes the execution and “sends” a value into the generator function. The
  580. <em>value</em> argument becomes the result of the current yield expression. The
  581. <a class="reference internal" href="#generator.send" title="generator.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a> method returns the next value yielded by the generator, or
  582. raises <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> if the generator exits without yielding another
  583. value. When <a class="reference internal" href="#generator.send" title="generator.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a> is called to start the generator, it must be called
  584. with <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> as the argument, because there is no yield expression that
  585. could receive the value.</p>
  586. </dd></dl>
  587. <dl class="py method">
  588. <dt class="sig sig-object py" id="generator.throw">
  589. <span class="sig-prename descclassname"><span class="pre">generator.</span></span><span class="sig-name descname"><span class="pre">throw</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">value</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#generator.throw" title="Link to this definition">¶</a></dt>
  590. <dt class="sig sig-object py">
  591. <span class="sig-prename descclassname"><span class="pre">generator.</span></span><span class="sig-name descname"><span class="pre">throw</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">type</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">value</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">traceback</span></span></em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span></dt>
  592. <dd><p>Raises an exception at the point where the generator was paused,
  593. and returns the next value yielded by the generator function. If the generator
  594. exits without yielding another value, a <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> exception is
  595. raised. If the generator function does not catch the passed-in exception, or
  596. raises a different exception, then that exception propagates to the caller.</p>
  597. <p>In typical use, this is called with a single exception instance similar to the
  598. way 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> keyword is used.</p>
  599. <p>For backwards compatibility, however, the second signature is
  600. supported, following a convention from older versions of Python.
  601. The <em>type</em> argument should be an exception class, and <em>value</em>
  602. should be an exception instance. If the <em>value</em> is not provided, the
  603. <em>type</em> constructor is called to get an instance. If <em>traceback</em>
  604. is provided, it is set on the exception, otherwise any existing
  605. <a class="reference internal" href="../library/exceptions.html#BaseException.__traceback__" title="BaseException.__traceback__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__traceback__</span></code></a> attribute stored in <em>value</em> may
  606. be cleared.</p>
  607. <div class="versionchanged">
  608. <p><span class="versionmodified changed">Changed in version 3.12: </span>The second signature (type[, value[, traceback]]) is deprecated and
  609. may be removed in a future version of Python.</p>
  610. </div>
  611. </dd></dl>
  612. <dl class="py method" id="index-33">
  613. <dt class="sig sig-object py" id="generator.close">
  614. <span class="sig-prename descclassname"><span class="pre">generator.</span></span><span class="sig-name descname"><span class="pre">close</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#generator.close" title="Link to this definition">¶</a></dt>
  615. <dd><p>Raises a <a class="reference internal" href="../library/exceptions.html#GeneratorExit" title="GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> at the point where the generator function was
  616. paused. If the generator function then exits gracefully, is already closed,
  617. or raises <a class="reference internal" href="../library/exceptions.html#GeneratorExit" title="GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> (by not catching the exception), close
  618. returns to its caller. If the generator yields a value, a
  619. <a class="reference internal" href="../library/exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is raised. If the generator raises any other exception,
  620. it is propagated to the caller. <a class="reference internal" href="#generator.close" title="generator.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> does nothing if the generator
  621. has already exited due to an exception or normal exit.</p>
  622. </dd></dl>
  623. </section>
  624. <section id="examples">
  625. <span id="index-34"></span><h4><span class="section-number">6.2.9.2. </span>Examples<a class="headerlink" href="#examples" title="Link to this heading">¶</a></h4>
  626. <p>Here is a simple example that demonstrates the behavior of generators and
  627. generator functions:</p>
  628. <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">echo</span><span class="p">(</span><span class="n">value</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
  629. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Execution starts when &#39;next()&#39; is called for the first time.&quot;</span><span class="p">)</span>
  630. <span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
  631. <span class="gp">... </span> <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
  632. <span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
  633. <span class="gp">... </span> <span class="n">value</span> <span class="o">=</span> <span class="p">(</span><span class="k">yield</span> <span class="n">value</span><span class="p">)</span>
  634. <span class="gp">... </span> <span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
  635. <span class="gp">... </span> <span class="n">value</span> <span class="o">=</span> <span class="n">e</span>
  636. <span class="gp">... </span> <span class="k">finally</span><span class="p">:</span>
  637. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Don&#39;t forget to clean up when &#39;close()&#39; is called.&quot;</span><span class="p">)</span>
  638. <span class="gp">...</span>
  639. <span class="gp">&gt;&gt;&gt; </span><span class="n">generator</span> <span class="o">=</span> <span class="n">echo</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
  640. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="nb">next</span><span class="p">(</span><span class="n">generator</span><span class="p">))</span>
  641. <span class="go">Execution starts when &#39;next()&#39; is called for the first time.</span>
  642. <span class="go">1</span>
  643. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="nb">next</span><span class="p">(</span><span class="n">generator</span><span class="p">))</span>
  644. <span class="go">None</span>
  645. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">generator</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="mi">2</span><span class="p">))</span>
  646. <span class="go">2</span>
  647. <span class="gp">&gt;&gt;&gt; </span><span class="n">generator</span><span class="o">.</span><span class="n">throw</span><span class="p">(</span><span class="ne">TypeError</span><span class="p">,</span> <span class="s2">&quot;spam&quot;</span><span class="p">)</span>
  648. <span class="go">TypeError(&#39;spam&#39;,)</span>
  649. <span class="gp">&gt;&gt;&gt; </span><span class="n">generator</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
  650. <span class="go">Don&#39;t forget to clean up when &#39;close()&#39; is called.</span>
  651. </pre></div>
  652. </div>
  653. <p>For examples using <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code>, see <a class="reference internal" href="../whatsnew/3.3.html#pep-380"><span class="std std-ref">PEP 380: Syntax for Delegating to a Subgenerator</span></a> in “What’s New in
  654. Python.”</p>
  655. </section>
  656. <section id="asynchronous-generator-functions">
  657. <span id="id3"></span><h4><span class="section-number">6.2.9.3. </span>Asynchronous generator functions<a class="headerlink" href="#asynchronous-generator-functions" title="Link to this heading">¶</a></h4>
  658. <p>The presence of a yield expression in a function or method defined using
  659. <a class="reference internal" href="compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> further defines the function as an
  660. <a class="reference internal" href="../glossary.html#term-asynchronous-generator"><span class="xref std std-term">asynchronous generator</span></a> function.</p>
  661. <p>When an asynchronous generator function is called, it returns an
  662. asynchronous iterator known as an asynchronous generator object.
  663. That object then controls the execution of the generator function.
  664. An asynchronous generator object is typically used in an
  665. <a class="reference internal" href="compound_stmts.html#async-for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code></a> statement in a coroutine function analogously to
  666. how a generator object would be used in a <a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> statement.</p>
  667. <p>Calling one of the asynchronous generator’s methods returns an <a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a>
  668. object, and the execution starts when this object is awaited on. At that time,
  669. the execution proceeds to the first yield expression, where it is suspended
  670. again, returning the value of <a class="reference internal" href="#grammar-token-python-grammar-expression_list"><code class="xref std std-token docutils literal notranslate"><span class="pre">expression_list</span></code></a> to the
  671. awaiting coroutine. As with a generator, suspension means that all local state
  672. is retained, including the current bindings of local variables, the instruction
  673. pointer, the internal evaluation stack, and the state of any exception handling.
  674. When the execution is resumed by awaiting on the next object returned by the
  675. asynchronous generator’s methods, the function can proceed exactly as if the
  676. yield expression were just another external call. The value of the yield
  677. expression after resuming depends on the method which resumed the execution. If
  678. <a class="reference internal" href="#agen.__anext__" title="agen.__anext__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__anext__()</span></code></a> is used then the result is <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>. Otherwise, if
  679. <a class="reference internal" href="#agen.asend" title="agen.asend"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asend()</span></code></a> is used, then the result will be the value passed in to that
  680. method.</p>
  681. <p>If an asynchronous generator happens to exit early by <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>, the caller
  682. task being cancelled, or other exceptions, the generator’s async cleanup code
  683. will run and possibly raise exceptions or access context variables in an
  684. unexpected context–perhaps after the lifetime of tasks it depends, or
  685. during the event loop shutdown when the async-generator garbage collection hook
  686. is called.
  687. To prevent this, the caller must explicitly close the async generator by calling
  688. <a class="reference internal" href="#agen.aclose" title="agen.aclose"><code class="xref py py-meth docutils literal notranslate"><span class="pre">aclose()</span></code></a> method to finalize the generator and ultimately detach it
  689. from the event loop.</p>
  690. <p>In an asynchronous generator function, yield expressions are allowed anywhere
  691. in a <a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> construct. However, if an asynchronous generator is not
  692. resumed before it is finalized (by reaching a zero reference count or by
  693. being garbage collected), then a yield expression within a <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code>
  694. construct could result in a failure to execute pending <a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a>
  695. clauses. In this case, it is the responsibility of the event loop or
  696. scheduler running the asynchronous generator to call the asynchronous
  697. generator-iterator’s <a class="reference internal" href="#agen.aclose" title="agen.aclose"><code class="xref py py-meth docutils literal notranslate"><span class="pre">aclose()</span></code></a> method and run the resulting
  698. coroutine object, thus allowing any pending <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clauses
  699. to execute.</p>
  700. <p>To take care of finalization upon event loop termination, an event loop should
  701. define a <em>finalizer</em> function which takes an asynchronous generator-iterator and
  702. presumably calls <a class="reference internal" href="#agen.aclose" title="agen.aclose"><code class="xref py py-meth docutils literal notranslate"><span class="pre">aclose()</span></code></a> and executes the coroutine.
  703. This <em>finalizer</em> may be registered by calling <a class="reference internal" href="../library/sys.html#sys.set_asyncgen_hooks" title="sys.set_asyncgen_hooks"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.set_asyncgen_hooks()</span></code></a>.
  704. When first iterated over, an asynchronous generator-iterator will store the
  705. registered <em>finalizer</em> to be called upon finalization. For a reference example
  706. of a <em>finalizer</em> method see the implementation of
  707. <code class="docutils literal notranslate"><span class="pre">asyncio.Loop.shutdown_asyncgens</span></code> in <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/asyncio/base_events.py">Lib/asyncio/base_events.py</a>.</p>
  708. <p>The expression <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span> <span class="pre">&lt;expr&gt;</span></code> is a syntax error when used in an
  709. asynchronous generator function.</p>
  710. </section>
  711. <section id="asynchronous-generator-iterator-methods">
  712. <span id="asynchronous-generator-methods"></span><span id="index-35"></span><h4><span class="section-number">6.2.9.4. </span>Asynchronous generator-iterator methods<a class="headerlink" href="#asynchronous-generator-iterator-methods" title="Link to this heading">¶</a></h4>
  713. <p>This subsection describes the methods of an asynchronous generator iterator,
  714. which are used to control the execution of a generator function.</p>
  715. <dl class="py method" id="index-36">
  716. <dt class="sig sig-object py" id="agen.__anext__">
  717. <em class="property"><span class="pre">coroutine</span> </em><span class="sig-prename descclassname"><span class="pre">agen.</span></span><span class="sig-name descname"><span class="pre">__anext__</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#agen.__anext__" title="Link to this definition">¶</a></dt>
  718. <dd><p>Returns an awaitable which when run starts to execute the asynchronous
  719. generator or resumes it at the last executed yield expression. When an
  720. asynchronous generator function is resumed with an <a class="reference internal" href="#agen.__anext__" title="agen.__anext__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__anext__()</span></code></a>
  721. method, the current yield expression always evaluates to <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> in the
  722. returned awaitable, which when run will continue to the next yield
  723. expression. The value of the <a class="reference internal" href="#grammar-token-python-grammar-expression_list"><code class="xref std std-token docutils literal notranslate"><span class="pre">expression_list</span></code></a> of the
  724. yield expression is the value of the <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> exception raised by
  725. the completing coroutine. If the asynchronous generator exits without
  726. yielding another value, the awaitable instead raises a
  727. <a class="reference internal" href="../library/exceptions.html#StopAsyncIteration" title="StopAsyncIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopAsyncIteration</span></code></a> exception, signalling that the asynchronous
  728. iteration has completed.</p>
  729. <p>This method is normally called implicitly by a <a class="reference internal" href="compound_stmts.html#async-for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code></a> loop.</p>
  730. </dd></dl>
  731. <dl class="py method">
  732. <dt class="sig sig-object py" id="agen.asend">
  733. <em class="property"><span class="pre">coroutine</span> </em><span class="sig-prename descclassname"><span class="pre">agen.</span></span><span class="sig-name descname"><span class="pre">asend</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">value</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#agen.asend" title="Link to this definition">¶</a></dt>
  734. <dd><p>Returns an awaitable which when run resumes the execution of the
  735. asynchronous generator. As with the <a class="reference internal" href="#generator.send" title="generator.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a> method for a
  736. generator, this “sends” a value into the asynchronous generator function,
  737. and the <em>value</em> argument becomes the result of the current yield expression.
  738. The awaitable returned by the <a class="reference internal" href="#agen.asend" title="agen.asend"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asend()</span></code></a> method will return the next
  739. value yielded by the generator as the value of the raised
  740. <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a>, or raises <a class="reference internal" href="../library/exceptions.html#StopAsyncIteration" title="StopAsyncIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopAsyncIteration</span></code></a> if the
  741. asynchronous generator exits without yielding another value. When
  742. <a class="reference internal" href="#agen.asend" title="agen.asend"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asend()</span></code></a> is called to start the asynchronous
  743. generator, it must be called with <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> as the argument,
  744. because there is no yield expression that could receive the value.</p>
  745. </dd></dl>
  746. <dl class="py method">
  747. <dt class="sig sig-object py" id="agen.athrow">
  748. <em class="property"><span class="pre">coroutine</span> </em><span class="sig-prename descclassname"><span class="pre">agen.</span></span><span class="sig-name descname"><span class="pre">athrow</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">value</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#agen.athrow" title="Link to this definition">¶</a></dt>
  749. <dt class="sig sig-object py">
  750. <em class="property"><span class="pre">coroutine</span> </em><span class="sig-prename descclassname"><span class="pre">agen.</span></span><span class="sig-name descname"><span class="pre">athrow</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">type</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">value</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">traceback</span></span></em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span></dt>
  751. <dd><p>Returns an awaitable that raises an exception of type <code class="docutils literal notranslate"><span class="pre">type</span></code> at the point
  752. where the asynchronous generator was paused, and returns the next value
  753. yielded by the generator function as the value of the raised
  754. <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> exception. If the asynchronous generator exits
  755. without yielding another value, a <a class="reference internal" href="../library/exceptions.html#StopAsyncIteration" title="StopAsyncIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopAsyncIteration</span></code></a> exception is
  756. raised by the awaitable.
  757. If the generator function does not catch the passed-in exception, or
  758. raises a different exception, then when the awaitable is run that exception
  759. propagates to the caller of the awaitable.</p>
  760. <div class="versionchanged">
  761. <p><span class="versionmodified changed">Changed in version 3.12: </span>The second signature (type[, value[, traceback]]) is deprecated and
  762. may be removed in a future version of Python.</p>
  763. </div>
  764. </dd></dl>
  765. <dl class="py method" id="index-37">
  766. <dt class="sig sig-object py" id="agen.aclose">
  767. <em class="property"><span class="pre">coroutine</span> </em><span class="sig-prename descclassname"><span class="pre">agen.</span></span><span class="sig-name descname"><span class="pre">aclose</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#agen.aclose" title="Link to this definition">¶</a></dt>
  768. <dd><p>Returns an awaitable that when run will throw a <a class="reference internal" href="../library/exceptions.html#GeneratorExit" title="GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> into
  769. the asynchronous generator function at the point where it was paused.
  770. If the asynchronous generator function then exits gracefully, is already
  771. closed, or raises <a class="reference internal" href="../library/exceptions.html#GeneratorExit" title="GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> (by not catching the exception),
  772. then the returned awaitable will raise a <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> exception.
  773. Any further awaitables returned by subsequent calls to the asynchronous
  774. generator will raise a <a class="reference internal" href="../library/exceptions.html#StopAsyncIteration" title="StopAsyncIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopAsyncIteration</span></code></a> exception. If the
  775. asynchronous generator yields a value, a <a class="reference internal" href="../library/exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is raised
  776. by the awaitable. If the asynchronous generator raises any other exception,
  777. it is propagated to the caller of the awaitable. If the asynchronous
  778. generator has already exited due to an exception or normal exit, then
  779. further calls to <a class="reference internal" href="#agen.aclose" title="agen.aclose"><code class="xref py py-meth docutils literal notranslate"><span class="pre">aclose()</span></code></a> will return an awaitable that does nothing.</p>
  780. </dd></dl>
  781. </section>
  782. </section>
  783. </section>
  784. <section id="primaries">
  785. <span id="id4"></span><h2><span class="section-number">6.3. </span>Primaries<a class="headerlink" href="#primaries" title="Link to this heading">¶</a></h2>
  786. <p id="index-38">Primaries represent the most tightly bound operations of the language. Their
  787. syntax is:</p>
  788. <pre>
  789. <strong id="grammar-token-python-grammar-primary">primary</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-atom"><code class="xref docutils literal notranslate"><span class="pre">atom</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-attributeref"><code class="xref docutils literal notranslate"><span class="pre">attributeref</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-subscription"><code class="xref docutils literal notranslate"><span class="pre">subscription</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-slicing"><code class="xref docutils literal notranslate"><span class="pre">slicing</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-call"><code class="xref docutils literal notranslate"><span class="pre">call</span></code></a>
  790. </pre>
  791. <section id="attribute-references">
  792. <span id="id5"></span><h3><span class="section-number">6.3.1. </span>Attribute references<a class="headerlink" href="#attribute-references" title="Link to this heading">¶</a></h3>
  793. <p id="index-39">An attribute reference is a primary followed by a period and a name:</p>
  794. <pre>
  795. <strong id="grammar-token-python-grammar-attributeref">attributeref</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-primary"><code class="xref docutils literal notranslate"><span class="pre">primary</span></code></a> &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>
  796. </pre>
  797. <p id="index-40">The primary must evaluate to an object of a type that supports attribute
  798. references, which most objects do. This object is then asked to produce the
  799. attribute whose name is the identifier. The type and value produced is
  800. determined by the object. Multiple evaluations of the same attribute
  801. reference may yield different objects.</p>
  802. <p>This production can be customized by overriding the
  803. <a class="reference internal" href="datamodel.html#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a> method or the <a class="reference internal" href="datamodel.html#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a>
  804. method. The <code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code> method is called first and either
  805. returns a value or 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> if the attribute is not
  806. available.</p>
  807. <p>If an <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> is raised and the object has a <code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code>
  808. method, that method is called as a fallback.</p>
  809. </section>
  810. <section id="subscriptions">
  811. <span id="id6"></span><h3><span class="section-number">6.3.2. </span>Subscriptions<a class="headerlink" href="#subscriptions" title="Link to this heading">¶</a></h3>
  812. <p id="index-42"><span id="index-41"></span>The subscription of an instance of a <a class="reference internal" href="datamodel.html#sequence-types"><span class="std std-ref">container class</span></a>
  813. will generally select an element from the container. The subscription of a
  814. <a class="reference internal" href="../glossary.html#term-generic-type"><span class="xref std std-term">generic class</span></a> will generally return a
  815. <a class="reference internal" href="../library/stdtypes.html#types-genericalias"><span class="std std-ref">GenericAlias</span></a> object.</p>
  816. <pre>
  817. <strong id="grammar-token-python-grammar-subscription">subscription</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-primary"><code class="xref docutils literal notranslate"><span class="pre">primary</span></code></a> &quot;[&quot; <a class="reference internal" href="#grammar-token-python-grammar-expression_list"><code class="xref docutils literal notranslate"><span class="pre">expression_list</span></code></a> &quot;]&quot;
  818. </pre>
  819. <p>When an object is subscripted, the interpreter will evaluate the primary and
  820. the expression list.</p>
  821. <p>The primary must evaluate to an object that supports subscription. An object
  822. may support subscription through defining one or both of
  823. <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> and <a class="reference internal" href="datamodel.html#object.__class_getitem__" title="object.__class_getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__class_getitem__()</span></code></a>. When the
  824. primary is subscripted, the evaluated result of the expression list will be
  825. passed to one of these methods. For more details on when <code class="docutils literal notranslate"><span class="pre">__class_getitem__</span></code>
  826. is called instead of <code class="docutils literal notranslate"><span class="pre">__getitem__</span></code>, see <a class="reference internal" href="datamodel.html#classgetitem-versus-getitem"><span class="std std-ref">__class_getitem__ versus __getitem__</span></a>.</p>
  827. <p>If the expression list contains at least one comma, it will evaluate to a
  828. <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> containing the items of the expression list. Otherwise, the
  829. expression list will evaluate to the value of the list’s sole member.</p>
  830. <p>For built-in objects, there are two types of objects that support subscription
  831. via <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>
  832. <ol class="arabic simple">
  833. <li><p>Mappings. If the primary is a <a class="reference internal" href="../glossary.html#term-mapping"><span class="xref std std-term">mapping</span></a>, the expression list must
  834. evaluate to an object whose value is one of the keys of the mapping, and the
  835. subscription selects the value in the mapping that corresponds to that key.
  836. An example of a builtin mapping class is the <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> class.</p></li>
  837. <li><p>Sequences. If the primary is a <a class="reference internal" href="../glossary.html#term-sequence"><span class="xref std std-term">sequence</span></a>, the expression list must
  838. evaluate to an <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> or a <a class="reference internal" href="../library/functions.html#slice" title="slice"><code class="xref py py-class docutils literal notranslate"><span class="pre">slice</span></code></a> (as discussed in the
  839. following section). Examples of builtin sequence classes include the
  840. <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>, <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> and <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> classes.</p></li>
  841. </ol>
  842. <p>The formal syntax makes no special provision for negative indices in
  843. <a class="reference internal" href="../glossary.html#term-sequence"><span class="xref std std-term">sequences</span></a>. However, built-in sequences all provide a <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>
  844. method that interprets negative indices by adding the length of the sequence
  845. to the index so that, for example, <code class="docutils literal notranslate"><span class="pre">x[-1]</span></code> selects the last item of <code class="docutils literal notranslate"><span class="pre">x</span></code>. The
  846. resulting value must be a nonnegative integer less than the number of items in
  847. the sequence, and the subscription selects the item whose index is that value
  848. (counting from zero). Since the support for negative indices and slicing
  849. occurs in the object’s <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> method, subclasses overriding
  850. this method will need to explicitly add that support.</p>
  851. <p id="index-43">A <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">string</span></code></a> is a special kind of sequence whose items are
  852. <em>characters</em>. A character is not a separate data type but a
  853. string of exactly one character.</p>
  854. </section>
  855. <section id="slicings">
  856. <span id="id7"></span><h3><span class="section-number">6.3.3. </span>Slicings<a class="headerlink" href="#slicings" title="Link to this heading">¶</a></h3>
  857. <p id="index-45"><span id="index-44"></span>A slicing selects a range of items in a sequence object (e.g., a string, tuple
  858. or list). Slicings may be used as expressions or as targets in assignment or
  859. <a class="reference internal" href="simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> statements. The syntax for a slicing:</p>
  860. <pre>
  861. <strong id="grammar-token-python-grammar-slicing">slicing </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-primary"><code class="xref docutils literal notranslate"><span class="pre">primary</span></code></a> &quot;[&quot; <a class="reference internal" href="#grammar-token-python-grammar-slice_list"><code class="xref docutils literal notranslate"><span class="pre">slice_list</span></code></a> &quot;]&quot;
  862. <strong id="grammar-token-python-grammar-slice_list">slice_list </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-slice_item"><code class="xref docutils literal notranslate"><span class="pre">slice_item</span></code></a> (&quot;,&quot; <a class="reference internal" href="#grammar-token-python-grammar-slice_item"><code class="xref docutils literal notranslate"><span class="pre">slice_item</span></code></a>)* [&quot;,&quot;]
  863. <strong id="grammar-token-python-grammar-slice_item">slice_item </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-proper_slice"><code class="xref docutils literal notranslate"><span class="pre">proper_slice</span></code></a>
  864. <strong id="grammar-token-python-grammar-proper_slice">proper_slice</strong> ::= [<a class="reference internal" href="#grammar-token-python-grammar-lower_bound"><code class="xref docutils literal notranslate"><span class="pre">lower_bound</span></code></a>] &quot;:&quot; [<a class="reference internal" href="#grammar-token-python-grammar-upper_bound"><code class="xref docutils literal notranslate"><span class="pre">upper_bound</span></code></a>] [ &quot;:&quot; [<a class="reference internal" href="#grammar-token-python-grammar-stride"><code class="xref docutils literal notranslate"><span class="pre">stride</span></code></a>] ]
  865. <strong id="grammar-token-python-grammar-lower_bound">lower_bound </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
  866. <strong id="grammar-token-python-grammar-upper_bound">upper_bound </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
  867. <strong id="grammar-token-python-grammar-stride">stride </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
  868. </pre>
  869. <p>There is ambiguity in the formal syntax here: anything that looks like an
  870. expression list also looks like a slice list, so any subscription can be
  871. interpreted as a slicing. Rather than further complicating the syntax, this is
  872. disambiguated by defining that in this case the interpretation as a subscription
  873. takes priority over the interpretation as a slicing (this is the case if the
  874. slice list contains no proper slice).</p>
  875. <p id="index-46">The semantics for a slicing are as follows. The primary is indexed (using the
  876. same <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> method as
  877. normal subscription) with a key that is constructed from the slice list, as
  878. follows. If the slice list contains at least one comma, the key is a tuple
  879. containing the conversion of the slice items; otherwise, the conversion of the
  880. lone slice item is the key. The conversion of a slice item that is an
  881. expression is that expression. The conversion of a proper slice is a slice
  882. object (see section <a class="reference internal" href="datamodel.html#types"><span class="std std-ref">The standard type hierarchy</span></a>) whose <a class="reference internal" href="../library/functions.html#slice.start" title="slice.start"><code class="xref py py-attr docutils literal notranslate"><span class="pre">start</span></code></a>,
  883. <a class="reference internal" href="../library/functions.html#slice.stop" title="slice.stop"><code class="xref py py-attr docutils literal notranslate"><span class="pre">stop</span></code></a> and <a class="reference internal" href="../library/functions.html#slice.step" title="slice.step"><code class="xref py py-attr docutils literal notranslate"><span class="pre">step</span></code></a> attributes are the values of the
  884. expressions given as lower bound, upper bound and stride, respectively,
  885. substituting <code class="docutils literal notranslate"><span class="pre">None</span></code> for missing expressions.</p>
  886. </section>
  887. <section id="calls">
  888. <span id="index-47"></span><span id="id8"></span><h3><span class="section-number">6.3.4. </span>Calls<a class="headerlink" href="#calls" title="Link to this heading">¶</a></h3>
  889. <p>A call calls a callable object (e.g., a <a class="reference internal" href="../glossary.html#term-function"><span class="xref std std-term">function</span></a>) with a possibly empty
  890. series of <a class="reference internal" href="../glossary.html#term-argument"><span class="xref std std-term">arguments</span></a>:</p>
  891. <pre>
  892. <strong id="grammar-token-python-grammar-call">call </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-primary"><code class="xref docutils literal notranslate"><span class="pre">primary</span></code></a> &quot;(&quot; [<a class="reference internal" href="#grammar-token-python-grammar-argument_list"><code class="xref docutils literal notranslate"><span class="pre">argument_list</span></code></a> [&quot;,&quot;] | <a class="reference internal" href="#grammar-token-python-grammar-comprehension"><code class="xref docutils literal notranslate"><span class="pre">comprehension</span></code></a>] &quot;)&quot;
  893. <strong id="grammar-token-python-grammar-argument_list">argument_list </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-positional_arguments"><code class="xref docutils literal notranslate"><span class="pre">positional_arguments</span></code></a> [&quot;,&quot; <a class="reference internal" href="#grammar-token-python-grammar-starred_and_keywords"><code class="xref docutils literal notranslate"><span class="pre">starred_and_keywords</span></code></a>]
  894. [&quot;,&quot; <a class="reference internal" href="#grammar-token-python-grammar-keywords_arguments"><code class="xref docutils literal notranslate"><span class="pre">keywords_arguments</span></code></a>]
  895. | <a class="reference internal" href="#grammar-token-python-grammar-starred_and_keywords"><code class="xref docutils literal notranslate"><span class="pre">starred_and_keywords</span></code></a> [&quot;,&quot; <a class="reference internal" href="#grammar-token-python-grammar-keywords_arguments"><code class="xref docutils literal notranslate"><span class="pre">keywords_arguments</span></code></a>]
  896. | <a class="reference internal" href="#grammar-token-python-grammar-keywords_arguments"><code class="xref docutils literal notranslate"><span class="pre">keywords_arguments</span></code></a>
  897. <strong id="grammar-token-python-grammar-positional_arguments">positional_arguments</strong> ::= positional_item (&quot;,&quot; positional_item)*
  898. <strong id="grammar-token-python-grammar-positional_item">positional_item </strong> ::= <a class="reference internal" href="#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-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
  899. <strong id="grammar-token-python-grammar-starred_and_keywords">starred_and_keywords</strong> ::= (&quot;*&quot; <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-keyword_item"><code class="xref docutils literal notranslate"><span class="pre">keyword_item</span></code></a>)
  900. (&quot;,&quot; &quot;*&quot; <a class="reference internal" href="#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-keyword_item"><code class="xref docutils literal notranslate"><span class="pre">keyword_item</span></code></a>)*
  901. <strong id="grammar-token-python-grammar-keywords_arguments">keywords_arguments </strong> ::= (<a class="reference internal" href="#grammar-token-python-grammar-keyword_item"><code class="xref docutils literal notranslate"><span class="pre">keyword_item</span></code></a> | &quot;**&quot; <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>)
  902. (&quot;,&quot; <a class="reference internal" href="#grammar-token-python-grammar-keyword_item"><code class="xref docutils literal notranslate"><span class="pre">keyword_item</span></code></a> | &quot;,&quot; &quot;**&quot; <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>)*
  903. <strong id="grammar-token-python-grammar-keyword_item">keyword_item </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="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
  904. </pre>
  905. <p>An optional trailing comma may be present after the positional and keyword arguments
  906. but does not affect the semantics.</p>
  907. <p id="index-48">The primary must evaluate to a callable object (user-defined functions, built-in
  908. functions, methods of built-in objects, class objects, methods of class
  909. instances, and all objects having a <a class="reference internal" href="datamodel.html#object.__call__" title="object.__call__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__call__()</span></code></a> method are callable). All
  910. argument expressions are evaluated before the call is attempted. Please refer
  911. to section <a class="reference internal" href="compound_stmts.html#function"><span class="std std-ref">Function definitions</span></a> for the syntax of formal <a class="reference internal" href="../glossary.html#term-parameter"><span class="xref std std-term">parameter</span></a> lists.</p>
  912. <p>If keyword arguments are present, they are first converted to positional
  913. arguments, as follows. First, a list of unfilled slots is created for the
  914. formal parameters. If there are N positional arguments, they are placed in the
  915. first N slots. Next, for each keyword argument, the identifier is used to
  916. determine the corresponding slot (if the identifier is the same as the first
  917. formal parameter name, the first slot is used, and so on). If the slot is
  918. already filled, a <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> exception is raised. Otherwise, the
  919. argument is placed in the slot, filling it (even if the expression is
  920. <code class="docutils literal notranslate"><span class="pre">None</span></code>, it fills the slot). When all arguments have been processed, the slots
  921. that are still unfilled are filled with the corresponding default value from the
  922. function definition. (Default values are calculated, once, when the function is
  923. defined; thus, a mutable object such as a list or dictionary used as default
  924. value will be shared by all calls that don’t specify an argument value for the
  925. corresponding slot; this should usually be avoided.) If there are any unfilled
  926. slots for which no default value is specified, a <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> exception is
  927. raised. Otherwise, the list of filled slots is used as the argument list for
  928. the call.</p>
  929. <div class="impl-detail compound">
  930. <p><strong>CPython implementation detail:</strong> An implementation may provide built-in functions whose positional parameters
  931. do not have names, even if they are ‘named’ for the purpose of documentation,
  932. and which therefore cannot be supplied by keyword. In CPython, this is the
  933. case for functions implemented in C that use <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> to
  934. parse their arguments.</p>
  935. </div>
  936. <p>If there are more positional arguments than there are formal parameter slots, a
  937. <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> exception is raised, unless a formal parameter using the syntax
  938. <code class="docutils literal notranslate"><span class="pre">*identifier</span></code> is present; in this case, that formal parameter receives a tuple
  939. containing the excess positional arguments (or an empty tuple if there were no
  940. excess positional arguments).</p>
  941. <p>If any keyword argument does not correspond to a formal parameter name, a
  942. <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> exception is raised, unless a formal parameter using the syntax
  943. <code class="docutils literal notranslate"><span class="pre">**identifier</span></code> is present; in this case, that formal parameter receives a
  944. dictionary containing the excess keyword arguments (using the keywords as keys
  945. and the argument values as corresponding values), or a (new) empty dictionary if
  946. there were no excess keyword arguments.</p>
  947. <p id="index-49">If the syntax <code class="docutils literal notranslate"><span class="pre">*expression</span></code> appears in the function call, <code class="docutils literal notranslate"><span class="pre">expression</span></code> must
  948. evaluate to an <a class="reference internal" href="../glossary.html#term-iterable"><span class="xref std std-term">iterable</span></a>. Elements from these iterables are
  949. treated as if they were additional positional arguments. For the call
  950. <code class="docutils literal notranslate"><span class="pre">f(x1,</span> <span class="pre">x2,</span> <span class="pre">*y,</span> <span class="pre">x3,</span> <span class="pre">x4)</span></code>, if <em>y</em> evaluates to a sequence <em>y1</em>, …, <em>yM</em>,
  951. this is equivalent to a call with M+4 positional arguments <em>x1</em>, <em>x2</em>,
  952. <em>y1</em>, …, <em>yM</em>, <em>x3</em>, <em>x4</em>.</p>
  953. <p>A consequence of this is that although the <code class="docutils literal notranslate"><span class="pre">*expression</span></code> syntax may appear
  954. <em>after</em> explicit keyword arguments, it is processed <em>before</em> the
  955. keyword arguments (and any <code class="docutils literal notranslate"><span class="pre">**expression</span></code> arguments – see below). So:</p>
  956. <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><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
  957. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">)</span>
  958. <span class="gp">...</span>
  959. <span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">(</span><span class="n">b</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="o">*</span><span class="p">(</span><span class="mi">2</span><span class="p">,))</span>
  960. <span class="go">2 1</span>
  961. <span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="o">*</span><span class="p">(</span><span class="mi">2</span><span class="p">,))</span>
  962. <span class="gt">Traceback (most recent call last):</span>
  963. File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
  964. <span class="gr">TypeError</span>: <span class="n">f() got multiple values for keyword argument &#39;a&#39;</span>
  965. <span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="o">*</span><span class="p">(</span><span class="mi">2</span><span class="p">,))</span>
  966. <span class="go">1 2</span>
  967. </pre></div>
  968. </div>
  969. <p>It is unusual for both keyword arguments and the <code class="docutils literal notranslate"><span class="pre">*expression</span></code> syntax to be
  970. used in the same call, so in practice this confusion does not often arise.</p>
  971. <p id="index-50">If the syntax <code class="docutils literal notranslate"><span class="pre">**expression</span></code> appears in the function call, <code class="docutils literal notranslate"><span class="pre">expression</span></code> must
  972. evaluate to a <a class="reference internal" href="../glossary.html#term-mapping"><span class="xref std std-term">mapping</span></a>, the contents of which are treated as
  973. additional keyword arguments. If a parameter matching a key has already been
  974. given a value (by an explicit keyword argument, or from another unpacking),
  975. a <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> exception is raised.</p>
  976. <p>When <code class="docutils literal notranslate"><span class="pre">**expression</span></code> is used, each key in this mapping must be
  977. a string.
  978. Each value from the mapping is assigned to the first formal parameter
  979. eligible for keyword assignment whose name is equal to the key.
  980. A key need not be a Python identifier (e.g. <code class="docutils literal notranslate"><span class="pre">&quot;max-temp</span> <span class="pre">°F&quot;</span></code> is acceptable,
  981. although it will not match any formal parameter that could be declared).
  982. If there is no match to a formal parameter
  983. the key-value pair is collected by the <code class="docutils literal notranslate"><span class="pre">**</span></code> parameter, if there is one,
  984. or if there is not, a <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> exception is raised.</p>
  985. <p>Formal parameters using the syntax <code class="docutils literal notranslate"><span class="pre">*identifier</span></code> or <code class="docutils literal notranslate"><span class="pre">**identifier</span></code> cannot be
  986. used as positional argument slots or as keyword argument names.</p>
  987. <div class="versionchanged">
  988. <p><span class="versionmodified changed">Changed in version 3.5: </span>Function calls accept any number of <code class="docutils literal notranslate"><span class="pre">*</span></code> and <code class="docutils literal notranslate"><span class="pre">**</span></code> unpackings,
  989. positional arguments may follow iterable unpackings (<code class="docutils literal notranslate"><span class="pre">*</span></code>),
  990. and keyword arguments may follow dictionary unpackings (<code class="docutils literal notranslate"><span class="pre">**</span></code>).
  991. Originally proposed by <span class="target" id="index-51"></span><a class="pep reference external" href="https://peps.python.org/pep-0448/"><strong>PEP 448</strong></a>.</p>
  992. </div>
  993. <p>A call always returns some value, possibly <code class="docutils literal notranslate"><span class="pre">None</span></code>, unless it raises an
  994. exception. How this value is computed depends on the type of the callable
  995. object.</p>
  996. <p>If it is—</p>
  997. <dl>
  998. <dt>a user-defined function:</dt><dd><p id="index-52">The code block for the function is executed, passing it the argument list. The
  999. first thing the code block will do is bind the formal parameters to the
  1000. arguments; this is described in section <a class="reference internal" href="compound_stmts.html#function"><span class="std std-ref">Function definitions</span></a>. When the code block
  1001. 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> statement, this specifies the return value of the
  1002. function call.</p>
  1003. </dd>
  1004. <dt>a built-in function or method:</dt><dd><p id="index-53">The result is up to the interpreter; see <a class="reference internal" href="../library/functions.html#built-in-funcs"><span class="std std-ref">Built-in Functions</span></a> for the
  1005. descriptions of built-in functions and methods.</p>
  1006. </dd>
  1007. <dt>a class object:</dt><dd><p id="index-54">A new instance of that class is returned.</p>
  1008. </dd>
  1009. <dt>a class instance method:</dt><dd><p id="index-55">The corresponding user-defined function is called, with an argument list that is
  1010. one longer than the argument list of the call: the instance becomes the first
  1011. argument.</p>
  1012. </dd>
  1013. <dt>a class instance:</dt><dd><p id="index-56">The class must define a <a class="reference internal" href="datamodel.html#object.__call__" title="object.__call__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__call__()</span></code></a> method; the effect is then the same as
  1014. if that method was called.</p>
  1015. </dd>
  1016. </dl>
  1017. </section>
  1018. </section>
  1019. <section id="await-expression">
  1020. <span id="await"></span><span id="index-57"></span><h2><span class="section-number">6.4. </span>Await expression<a class="headerlink" href="#await-expression" title="Link to this heading">¶</a></h2>
  1021. <p>Suspend the execution of <a class="reference internal" href="../glossary.html#term-coroutine"><span class="xref std std-term">coroutine</span></a> on an <a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a> object.
  1022. Can only be used inside a <a class="reference internal" href="../glossary.html#term-coroutine-function"><span class="xref std std-term">coroutine function</span></a>.</p>
  1023. <pre>
  1024. <strong id="grammar-token-python-grammar-await_expr">await_expr</strong> ::= &quot;await&quot; <a class="reference internal" href="#grammar-token-python-grammar-primary"><code class="xref docutils literal notranslate"><span class="pre">primary</span></code></a>
  1025. </pre>
  1026. <div class="versionadded">
  1027. <p><span class="versionmodified added">New in version 3.5.</span></p>
  1028. </div>
  1029. </section>
  1030. <section id="the-power-operator">
  1031. <span id="power"></span><h2><span class="section-number">6.5. </span>The power operator<a class="headerlink" href="#the-power-operator" title="Link to this heading">¶</a></h2>
  1032. <p id="index-58">The power operator binds more tightly than unary operators on its left; it binds
  1033. less tightly than unary operators on its right. The syntax is:</p>
  1034. <pre>
  1035. <strong id="grammar-token-python-grammar-power">power</strong> ::= (<a class="reference internal" href="#grammar-token-python-grammar-await_expr"><code class="xref docutils literal notranslate"><span class="pre">await_expr</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-primary"><code class="xref docutils literal notranslate"><span class="pre">primary</span></code></a>) [&quot;**&quot; <a class="reference internal" href="#grammar-token-python-grammar-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a>]
  1036. </pre>
  1037. <p>Thus, in an unparenthesized sequence of power and unary operators, the operators
  1038. are evaluated from right to left (this does not constrain the evaluation order
  1039. for the operands): <code class="docutils literal notranslate"><span class="pre">-1**2</span></code> results in <code class="docutils literal notranslate"><span class="pre">-1</span></code>.</p>
  1040. <p>The power operator has the same semantics as the built-in <a class="reference internal" href="../library/functions.html#pow" title="pow"><code class="xref py py-func docutils literal notranslate"><span class="pre">pow()</span></code></a> function,
  1041. when called with two arguments: it yields its left argument raised to the power
  1042. of its right argument. The numeric arguments are first converted to a common
  1043. type, and the result is of that type.</p>
  1044. <p>For int operands, the result has the same type as the operands unless the second
  1045. argument is negative; in that case, all arguments are converted to float and a
  1046. float result is delivered. For example, <code class="docutils literal notranslate"><span class="pre">10**2</span></code> returns <code class="docutils literal notranslate"><span class="pre">100</span></code>, but
  1047. <code class="docutils literal notranslate"><span class="pre">10**-2</span></code> returns <code class="docutils literal notranslate"><span class="pre">0.01</span></code>.</p>
  1048. <p>Raising <code class="docutils literal notranslate"><span class="pre">0.0</span></code> to a negative power results in a <a class="reference internal" href="../library/exceptions.html#ZeroDivisionError" title="ZeroDivisionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ZeroDivisionError</span></code></a>.
  1049. Raising a negative number to a fractional power results in a <a class="reference internal" href="../library/functions.html#complex" title="complex"><code class="xref py py-class docutils literal notranslate"><span class="pre">complex</span></code></a>
  1050. number. (In earlier versions it raised 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>.)</p>
  1051. <p>This operation can be customized using the special <a class="reference internal" href="datamodel.html#object.__pow__" title="object.__pow__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__pow__()</span></code></a> method.</p>
  1052. </section>
  1053. <section id="unary-arithmetic-and-bitwise-operations">
  1054. <span id="unary"></span><h2><span class="section-number">6.6. </span>Unary arithmetic and bitwise operations<a class="headerlink" href="#unary-arithmetic-and-bitwise-operations" title="Link to this heading">¶</a></h2>
  1055. <p id="index-59">All unary arithmetic and bitwise operations have the same priority:</p>
  1056. <pre>
  1057. <strong id="grammar-token-python-grammar-u_expr">u_expr</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-power"><code class="xref docutils literal notranslate"><span class="pre">power</span></code></a> | &quot;-&quot; <a class="reference internal" href="#grammar-token-python-grammar-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a> | &quot;+&quot; <a class="reference internal" href="#grammar-token-python-grammar-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a> | &quot;~&quot; <a class="reference internal" href="#grammar-token-python-grammar-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a>
  1058. </pre>
  1059. <p id="index-60">The unary <code class="docutils literal notranslate"><span class="pre">-</span></code> (minus) operator yields the negation of its numeric argument; the
  1060. operation can be overridden with the <a class="reference internal" href="datamodel.html#object.__neg__" title="object.__neg__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__neg__()</span></code></a> special method.</p>
  1061. <p id="index-61">The unary <code class="docutils literal notranslate"><span class="pre">+</span></code> (plus) operator yields its numeric argument unchanged; the
  1062. operation can be overridden with the <a class="reference internal" href="datamodel.html#object.__pos__" title="object.__pos__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__pos__()</span></code></a> special method.</p>
  1063. <p id="index-62">The unary <code class="docutils literal notranslate"><span class="pre">~</span></code> (invert) operator yields the bitwise inversion of its integer
  1064. argument. The bitwise inversion of <code class="docutils literal notranslate"><span class="pre">x</span></code> is defined as <code class="docutils literal notranslate"><span class="pre">-(x+1)</span></code>. It only
  1065. applies to integral numbers or to custom objects that override the
  1066. <a class="reference internal" href="datamodel.html#object.__invert__" title="object.__invert__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__invert__()</span></code></a> special method.</p>
  1067. <p id="index-63">In all three cases, if the argument does not have the proper type, a
  1068. <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> exception is raised.</p>
  1069. </section>
  1070. <section id="binary-arithmetic-operations">
  1071. <span id="binary"></span><h2><span class="section-number">6.7. </span>Binary arithmetic operations<a class="headerlink" href="#binary-arithmetic-operations" title="Link to this heading">¶</a></h2>
  1072. <p id="index-64">The binary arithmetic operations have the conventional priority levels. Note
  1073. that some of these operations also apply to certain non-numeric types. Apart
  1074. from the power operator, there are only two levels, one for multiplicative
  1075. operators and one for additive operators:</p>
  1076. <pre>
  1077. <strong id="grammar-token-python-grammar-m_expr">m_expr</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> &quot;*&quot; <a class="reference internal" href="#grammar-token-python-grammar-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> &quot;&#64;&quot; <a class="reference internal" href="#grammar-token-python-grammar-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> |
  1078. <a class="reference internal" href="#grammar-token-python-grammar-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> &quot;//&quot; <a class="reference internal" href="#grammar-token-python-grammar-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> &quot;/&quot; <a class="reference internal" href="#grammar-token-python-grammar-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a> |
  1079. <a class="reference internal" href="#grammar-token-python-grammar-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> &quot;%&quot; <a class="reference internal" href="#grammar-token-python-grammar-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a>
  1080. <strong id="grammar-token-python-grammar-a_expr">a_expr</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-a_expr"><code class="xref docutils literal notranslate"><span class="pre">a_expr</span></code></a> &quot;+&quot; <a class="reference internal" href="#grammar-token-python-grammar-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-a_expr"><code class="xref docutils literal notranslate"><span class="pre">a_expr</span></code></a> &quot;-&quot; <a class="reference internal" href="#grammar-token-python-grammar-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a>
  1081. </pre>
  1082. <p id="index-65">The <code class="docutils literal notranslate"><span class="pre">*</span></code> (multiplication) operator yields the product of its arguments. The
  1083. arguments must either both be numbers, or one argument must be an integer and
  1084. the other must be a sequence. In the former case, the numbers are converted to a
  1085. common type and then multiplied together. In the latter case, sequence
  1086. repetition is performed; a negative repetition factor yields an empty sequence.</p>
  1087. <p>This operation can be customized using the special <a class="reference internal" href="datamodel.html#object.__mul__" title="object.__mul__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__mul__()</span></code></a> and
  1088. <a class="reference internal" href="datamodel.html#object.__rmul__" title="object.__rmul__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__rmul__()</span></code></a> methods.</p>
  1089. <p id="index-66">The <code class="docutils literal notranslate"><span class="pre">&#64;</span></code> (at) operator is intended to be used for matrix multiplication. No
  1090. builtin Python types implement this operator.</p>
  1091. <div class="versionadded">
  1092. <p><span class="versionmodified added">New in version 3.5.</span></p>
  1093. </div>
  1094. <p id="index-67">The <code class="docutils literal notranslate"><span class="pre">/</span></code> (division) and <code class="docutils literal notranslate"><span class="pre">//</span></code> (floor division) operators yield the quotient of
  1095. their arguments. The numeric arguments are first converted to a common type.
  1096. Division of integers yields a float, while floor division of integers results in an
  1097. integer; the result is that of mathematical division with the ‘floor’ function
  1098. applied to the result. Division by zero raises the <a class="reference internal" href="../library/exceptions.html#ZeroDivisionError" title="ZeroDivisionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ZeroDivisionError</span></code></a>
  1099. exception.</p>
  1100. <p>This operation can be customized using the special <a class="reference internal" href="datamodel.html#object.__truediv__" title="object.__truediv__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__truediv__()</span></code></a> and
  1101. <a class="reference internal" href="datamodel.html#object.__floordiv__" title="object.__floordiv__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__floordiv__()</span></code></a> methods.</p>
  1102. <p id="index-68">The <code class="docutils literal notranslate"><span class="pre">%</span></code> (modulo) operator yields the remainder from the division of the first
  1103. argument by the second. The numeric arguments are first converted to a common
  1104. type. A zero right argument raises the <a class="reference internal" href="../library/exceptions.html#ZeroDivisionError" title="ZeroDivisionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ZeroDivisionError</span></code></a> exception. The
  1105. arguments may be floating point numbers, e.g., <code class="docutils literal notranslate"><span class="pre">3.14%0.7</span></code> equals <code class="docutils literal notranslate"><span class="pre">0.34</span></code>
  1106. (since <code class="docutils literal notranslate"><span class="pre">3.14</span></code> equals <code class="docutils literal notranslate"><span class="pre">4*0.7</span> <span class="pre">+</span> <span class="pre">0.34</span></code>.) The modulo operator always yields a
  1107. result with the same sign as its second operand (or zero); the absolute value of
  1108. the result is strictly smaller than the absolute value of the second operand
  1109. <a class="footnote-reference brackets" href="#id17" id="id9" role="doc-noteref"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></a>.</p>
  1110. <p>The floor division and modulo operators are connected by the following
  1111. identity: <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">(x//y)*y</span> <span class="pre">+</span> <span class="pre">(x%y)</span></code>. Floor division and modulo are also
  1112. connected with the built-in function <a class="reference internal" href="../library/functions.html#divmod" title="divmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">divmod()</span></code></a>: <code class="docutils literal notranslate"><span class="pre">divmod(x,</span> <span class="pre">y)</span> <span class="pre">==</span> <span class="pre">(x//y,</span>
  1113. <span class="pre">x%y)</span></code>. <a class="footnote-reference brackets" href="#id18" id="id10" role="doc-noteref"><span class="fn-bracket">[</span>2<span class="fn-bracket">]</span></a>.</p>
  1114. <p>In addition to performing the modulo operation on numbers, the <code class="docutils literal notranslate"><span class="pre">%</span></code> operator is
  1115. also overloaded by string objects to perform old-style string formatting (also
  1116. known as interpolation). The syntax for string formatting is described in the
  1117. Python Library Reference, section <a class="reference internal" href="../library/stdtypes.html#old-string-formatting"><span class="std std-ref">printf-style String Formatting</span></a>.</p>
  1118. <p>The <em>modulo</em> operation can be customized using the special <a class="reference internal" href="datamodel.html#object.__mod__" title="object.__mod__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__mod__()</span></code></a> method.</p>
  1119. <p>The floor division operator, the modulo operator, and the <a class="reference internal" href="../library/functions.html#divmod" title="divmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">divmod()</span></code></a>
  1120. function are not defined for complex numbers. Instead, convert to a floating
  1121. point number using the <a class="reference internal" href="../library/functions.html#abs" title="abs"><code class="xref py py-func docutils literal notranslate"><span class="pre">abs()</span></code></a> function if appropriate.</p>
  1122. <p id="index-69">The <code class="docutils literal notranslate"><span class="pre">+</span></code> (addition) operator yields the sum of its arguments. The arguments
  1123. must either both be numbers or both be sequences of the same type. In the
  1124. former case, the numbers are converted to a common type and then added together.
  1125. In the latter case, the sequences are concatenated.</p>
  1126. <p>This operation can be customized using the special <a class="reference internal" href="datamodel.html#object.__add__" title="object.__add__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__add__()</span></code></a> and
  1127. <a class="reference internal" href="datamodel.html#object.__radd__" title="object.__radd__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__radd__()</span></code></a> methods.</p>
  1128. <p id="index-70">The <code class="docutils literal notranslate"><span class="pre">-</span></code> (subtraction) operator yields the difference of its arguments. The
  1129. numeric arguments are first converted to a common type.</p>
  1130. <p>This operation can be customized using the special <a class="reference internal" href="datamodel.html#object.__sub__" title="object.__sub__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__sub__()</span></code></a> method.</p>
  1131. </section>
  1132. <section id="shifting-operations">
  1133. <span id="shifting"></span><h2><span class="section-number">6.8. </span>Shifting operations<a class="headerlink" href="#shifting-operations" title="Link to this heading">¶</a></h2>
  1134. <p id="index-71">The shifting operations have lower priority than the arithmetic operations:</p>
  1135. <pre>
  1136. <strong id="grammar-token-python-grammar-shift_expr">shift_expr</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-a_expr"><code class="xref docutils literal notranslate"><span class="pre">a_expr</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-shift_expr"><code class="xref docutils literal notranslate"><span class="pre">shift_expr</span></code></a> (&quot;&lt;&lt;&quot; | &quot;&gt;&gt;&quot;) <a class="reference internal" href="#grammar-token-python-grammar-a_expr"><code class="xref docutils literal notranslate"><span class="pre">a_expr</span></code></a>
  1137. </pre>
  1138. <p>These operators accept integers as arguments. They shift the first argument to
  1139. the left or right by the number of bits given by the second argument.</p>
  1140. <p>This operation can be customized using the special <a class="reference internal" href="datamodel.html#object.__lshift__" title="object.__lshift__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__lshift__()</span></code></a> and
  1141. <a class="reference internal" href="datamodel.html#object.__rshift__" title="object.__rshift__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__rshift__()</span></code></a> methods.</p>
  1142. <p id="index-72">A right shift by <em>n</em> bits is defined as floor division by <code class="docutils literal notranslate"><span class="pre">pow(2,n)</span></code>. A left
  1143. shift by <em>n</em> bits is defined as multiplication with <code class="docutils literal notranslate"><span class="pre">pow(2,n)</span></code>.</p>
  1144. </section>
  1145. <section id="binary-bitwise-operations">
  1146. <span id="bitwise"></span><h2><span class="section-number">6.9. </span>Binary bitwise operations<a class="headerlink" href="#binary-bitwise-operations" title="Link to this heading">¶</a></h2>
  1147. <p id="index-73">Each of the three bitwise operations has a different priority level:</p>
  1148. <pre>
  1149. <strong id="grammar-token-python-grammar-and_expr">and_expr</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-shift_expr"><code class="xref docutils literal notranslate"><span class="pre">shift_expr</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-and_expr"><code class="xref docutils literal notranslate"><span class="pre">and_expr</span></code></a> &quot;&amp;&quot; <a class="reference internal" href="#grammar-token-python-grammar-shift_expr"><code class="xref docutils literal notranslate"><span class="pre">shift_expr</span></code></a>
  1150. <strong id="grammar-token-python-grammar-xor_expr">xor_expr</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-and_expr"><code class="xref docutils literal notranslate"><span class="pre">and_expr</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-xor_expr"><code class="xref docutils literal notranslate"><span class="pre">xor_expr</span></code></a> &quot;^&quot; <a class="reference internal" href="#grammar-token-python-grammar-and_expr"><code class="xref docutils literal notranslate"><span class="pre">and_expr</span></code></a>
  1151. <strong id="grammar-token-python-grammar-or_expr">or_expr </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-xor_expr"><code class="xref docutils literal notranslate"><span class="pre">xor_expr</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-or_expr"><code class="xref docutils literal notranslate"><span class="pre">or_expr</span></code></a> &quot;|&quot; <a class="reference internal" href="#grammar-token-python-grammar-xor_expr"><code class="xref docutils literal notranslate"><span class="pre">xor_expr</span></code></a>
  1152. </pre>
  1153. <p id="index-74">The <code class="docutils literal notranslate"><span class="pre">&amp;</span></code> operator yields the bitwise AND of its arguments, which must be
  1154. integers or one of them must be a custom object overriding <a class="reference internal" href="datamodel.html#object.__and__" title="object.__and__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__and__()</span></code></a> or
  1155. <a class="reference internal" href="datamodel.html#object.__rand__" title="object.__rand__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__rand__()</span></code></a> special methods.</p>
  1156. <p id="index-75">The <code class="docutils literal notranslate"><span class="pre">^</span></code> operator yields the bitwise XOR (exclusive OR) of its arguments, which
  1157. must be integers or one of them must be a custom object overriding <a class="reference internal" href="datamodel.html#object.__xor__" title="object.__xor__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__xor__()</span></code></a> or
  1158. <a class="reference internal" href="datamodel.html#object.__rxor__" title="object.__rxor__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__rxor__()</span></code></a> special methods.</p>
  1159. <p id="index-76">The <code class="docutils literal notranslate"><span class="pre">|</span></code> operator yields the bitwise (inclusive) OR of its arguments, which
  1160. must be integers or one of them must be a custom object overriding <a class="reference internal" href="datamodel.html#object.__or__" title="object.__or__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__or__()</span></code></a> or
  1161. <a class="reference internal" href="datamodel.html#object.__ror__" title="object.__ror__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__ror__()</span></code></a> special methods.</p>
  1162. </section>
  1163. <section id="comparisons">
  1164. <span id="id11"></span><h2><span class="section-number">6.10. </span>Comparisons<a class="headerlink" href="#comparisons" title="Link to this heading">¶</a></h2>
  1165. <p id="index-77">Unlike C, all comparison operations in Python have the same priority, which is
  1166. lower than that of any arithmetic, shifting or bitwise operation. Also unlike
  1167. C, expressions like <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">&lt;</span> <span class="pre">b</span> <span class="pre">&lt;</span> <span class="pre">c</span></code> have the interpretation that is conventional
  1168. in mathematics:</p>
  1169. <pre>
  1170. <strong id="grammar-token-python-grammar-comparison">comparison </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-or_expr"><code class="xref docutils literal notranslate"><span class="pre">or_expr</span></code></a> (<a class="reference internal" href="#grammar-token-python-grammar-comp_operator"><code class="xref docutils literal notranslate"><span class="pre">comp_operator</span></code></a> <a class="reference internal" href="#grammar-token-python-grammar-or_expr"><code class="xref docutils literal notranslate"><span class="pre">or_expr</span></code></a>)*
  1171. <strong id="grammar-token-python-grammar-comp_operator">comp_operator</strong> ::= &quot;&lt;&quot; | &quot;&gt;&quot; | &quot;==&quot; | &quot;&gt;=&quot; | &quot;&lt;=&quot; | &quot;!=&quot;
  1172. | &quot;is&quot; [&quot;not&quot;] | [&quot;not&quot;] &quot;in&quot;
  1173. </pre>
  1174. <p>Comparisons yield boolean values: <code class="docutils literal notranslate"><span class="pre">True</span></code> or <code class="docutils literal notranslate"><span class="pre">False</span></code>. Custom
  1175. <em class="dfn">rich comparison methods</em> may return non-boolean values. In this case
  1176. Python will call <a class="reference internal" href="../library/functions.html#bool" title="bool"><code class="xref py py-func docutils literal notranslate"><span class="pre">bool()</span></code></a> on such value in boolean contexts.</p>
  1177. <p id="index-78">Comparisons can be chained arbitrarily, e.g., <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">y</span> <span class="pre">&lt;=</span> <span class="pre">z</span></code> is equivalent to
  1178. <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">y</span> <span class="pre">and</span> <span class="pre">y</span> <span class="pre">&lt;=</span> <span class="pre">z</span></code>, except that <code class="docutils literal notranslate"><span class="pre">y</span></code> is evaluated only once (but in both
  1179. cases <code class="docutils literal notranslate"><span class="pre">z</span></code> is not evaluated at all when <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">y</span></code> is found to be false).</p>
  1180. <p>Formally, if <em>a</em>, <em>b</em>, <em>c</em>, …, <em>y</em>, <em>z</em> are expressions and <em>op1</em>, <em>op2</em>, …,
  1181. <em>opN</em> are comparison operators, then <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">op1</span> <span class="pre">b</span> <span class="pre">op2</span> <span class="pre">c</span> <span class="pre">...</span> <span class="pre">y</span> <span class="pre">opN</span> <span class="pre">z</span></code> is equivalent
  1182. to <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">op1</span> <span class="pre">b</span> <span class="pre">and</span> <span class="pre">b</span> <span class="pre">op2</span> <span class="pre">c</span> <span class="pre">and</span> <span class="pre">...</span> <span class="pre">y</span> <span class="pre">opN</span> <span class="pre">z</span></code>, except that each expression is
  1183. evaluated at most once.</p>
  1184. <p>Note that <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">op1</span> <span class="pre">b</span> <span class="pre">op2</span> <span class="pre">c</span></code> doesn’t imply any kind of comparison between <em>a</em> and
  1185. <em>c</em>, so that, e.g., <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">y</span> <span class="pre">&gt;</span> <span class="pre">z</span></code> is perfectly legal (though perhaps not
  1186. pretty).</p>
  1187. <section id="value-comparisons">
  1188. <span id="expressions-value-comparisons"></span><h3><span class="section-number">6.10.1. </span>Value comparisons<a class="headerlink" href="#value-comparisons" title="Link to this heading">¶</a></h3>
  1189. <p>The operators <code class="docutils literal notranslate"><span class="pre">&lt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;</span></code>, <code class="docutils literal notranslate"><span class="pre">==</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;=</span></code>, <code class="docutils literal notranslate"><span class="pre">&lt;=</span></code>, and <code class="docutils literal notranslate"><span class="pre">!=</span></code> compare the
  1190. values of two objects. The objects do not need to have the same type.</p>
  1191. <p>Chapter <a class="reference internal" href="datamodel.html#objects"><span class="std std-ref">Objects, values and types</span></a> states that objects have a value (in addition to type
  1192. and identity). The value of an object is a rather abstract notion in Python:
  1193. For example, there is no canonical access method for an object’s value. Also,
  1194. there is no requirement that the value of an object should be constructed in a
  1195. particular way, e.g. comprised of all its data attributes. Comparison operators
  1196. implement a particular notion of what the value of an object is. One can think
  1197. of them as defining the value of an object indirectly, by means of their
  1198. comparison implementation.</p>
  1199. <p>Because all types are (direct or indirect) subtypes of <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>, they
  1200. inherit the default comparison behavior from <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>. Types can
  1201. customize their comparison behavior by implementing
  1202. <em class="dfn">rich comparison methods</em> like <a class="reference internal" href="datamodel.html#object.__lt__" title="object.__lt__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__lt__()</span></code></a>, described in
  1203. <a class="reference internal" href="datamodel.html#customization"><span class="std std-ref">Basic customization</span></a>.</p>
  1204. <p>The default behavior for equality comparison (<code class="docutils literal notranslate"><span class="pre">==</span></code> and <code class="docutils literal notranslate"><span class="pre">!=</span></code>) is based on
  1205. the identity of the objects. Hence, equality comparison of instances with the
  1206. same identity results in equality, and equality comparison of instances with
  1207. different identities results in inequality. A motivation for this default
  1208. behavior is the desire that all objects should be reflexive (i.e. <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">is</span> <span class="pre">y</span></code>
  1209. implies <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">y</span></code>).</p>
  1210. <p>A default order comparison (<code class="docutils literal notranslate"><span class="pre">&lt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&lt;=</span></code>, and <code class="docutils literal notranslate"><span class="pre">&gt;=</span></code>) is not provided;
  1211. an attempt raises <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>. A motivation for this default behavior is
  1212. the lack of a similar invariant as for equality.</p>
  1213. <p>The behavior of the default equality comparison, that instances with different
  1214. identities are always unequal, may be in contrast to what types will need that
  1215. have a sensible definition of object value and value-based equality. Such
  1216. types will need to customize their comparison behavior, and in fact, a number
  1217. of built-in types have done that.</p>
  1218. <p>The following list describes the comparison behavior of the most important
  1219. built-in types.</p>
  1220. <ul>
  1221. <li><p>Numbers of built-in numeric types (<a class="reference internal" href="../library/stdtypes.html#typesnumeric"><span class="std std-ref">Numeric Types — int, float, complex</span></a>) and of the standard
  1222. library types <a class="reference internal" href="../library/fractions.html#fractions.Fraction" title="fractions.Fraction"><code class="xref py py-class docutils literal notranslate"><span class="pre">fractions.Fraction</span></code></a> and <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">decimal.Decimal</span></code></a> can be
  1223. compared within and across their types, with the restriction that complex
  1224. numbers do not support order comparison. Within the limits of the types
  1225. involved, they compare mathematically (algorithmically) correct without loss
  1226. of precision.</p>
  1227. <p>The not-a-number values <code class="docutils literal notranslate"><span class="pre">float('NaN')</span></code> and <code class="docutils literal notranslate"><span class="pre">decimal.Decimal('NaN')</span></code> are
  1228. special. Any ordered comparison of a number to a not-a-number value is false.
  1229. A counter-intuitive implication is that not-a-number values are not equal to
  1230. themselves. For example, if <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">float('NaN')</span></code>, <code class="docutils literal notranslate"><span class="pre">3</span> <span class="pre">&lt;</span> <span class="pre">x</span></code>, <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">3</span></code> and
  1231. <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">x</span></code> are all false, while <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">!=</span> <span class="pre">x</span></code> is true. This behavior is
  1232. compliant with IEEE 754.</p>
  1233. </li>
  1234. <li><p><code class="docutils literal notranslate"><span class="pre">None</span></code> and <a class="reference internal" href="../library/constants.html#NotImplemented" title="NotImplemented"><code class="xref py py-data docutils literal notranslate"><span class="pre">NotImplemented</span></code></a> are singletons. <span class="target" id="index-79"></span><a class="pep reference external" href="https://peps.python.org/pep-0008/"><strong>PEP 8</strong></a> advises that
  1235. comparisons for singletons should always be done with <code class="docutils literal notranslate"><span class="pre">is</span></code> or <code class="docutils literal notranslate"><span class="pre">is</span> <span class="pre">not</span></code>,
  1236. never the equality operators.</p></li>
  1237. <li><p>Binary sequences (instances of <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> or <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>) can be
  1238. compared within and across their types. They compare lexicographically using
  1239. the numeric values of their elements.</p></li>
  1240. <li><p>Strings (instances of <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>) compare lexicographically using the
  1241. numerical Unicode code points (the result of the built-in function
  1242. <a class="reference internal" href="../library/functions.html#ord" title="ord"><code class="xref py py-func docutils literal notranslate"><span class="pre">ord()</span></code></a>) of their characters. <a class="footnote-reference brackets" href="#id19" id="id12" role="doc-noteref"><span class="fn-bracket">[</span>3<span class="fn-bracket">]</span></a></p>
  1243. <p>Strings and binary sequences cannot be directly compared.</p>
  1244. </li>
  1245. <li><p>Sequences (instances of <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>, <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>, or <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>) can
  1246. be compared only within each of their types, with the restriction that ranges
  1247. do not support order comparison. Equality comparison across these types
  1248. results in inequality, and ordering comparison across these types raises
  1249. <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>
  1250. <p>Sequences compare lexicographically using comparison of corresponding
  1251. elements. The built-in containers typically assume identical objects are
  1252. equal to themselves. That lets them bypass equality tests for identical
  1253. objects to improve performance and to maintain their internal invariants.</p>
  1254. <p>Lexicographical comparison between built-in collections works as follows:</p>
  1255. <ul class="simple">
  1256. <li><p>For two collections to compare equal, they must be of the same type, have
  1257. the same length, and each pair of corresponding elements must compare
  1258. equal (for example, <code class="docutils literal notranslate"><span class="pre">[1,2]</span> <span class="pre">==</span> <span class="pre">(1,2)</span></code> is false because the type is not the
  1259. same).</p></li>
  1260. <li><p>Collections that support order comparison are ordered the same as their
  1261. first unequal elements (for example, <code class="docutils literal notranslate"><span class="pre">[1,2,x]</span> <span class="pre">&lt;=</span> <span class="pre">[1,2,y]</span></code> has the same
  1262. value as <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;=</span> <span class="pre">y</span></code>). If a corresponding element does not exist, the
  1263. shorter collection is ordered first (for example, <code class="docutils literal notranslate"><span class="pre">[1,2]</span> <span class="pre">&lt;</span> <span class="pre">[1,2,3]</span></code> is
  1264. true).</p></li>
  1265. </ul>
  1266. </li>
  1267. <li><p>Mappings (instances of <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>) compare equal if and only if they have
  1268. equal <code class="docutils literal notranslate"><span class="pre">(key,</span> <span class="pre">value)</span></code> pairs. Equality comparison of the keys and values
  1269. enforces reflexivity.</p>
  1270. <p>Order comparisons (<code class="docutils literal notranslate"><span class="pre">&lt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&lt;=</span></code>, and <code class="docutils literal notranslate"><span class="pre">&gt;=</span></code>) raise <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.</p>
  1271. </li>
  1272. <li><p>Sets (instances of <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> or <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>) can be compared within
  1273. and across their types.</p>
  1274. <p>They define order
  1275. comparison operators to mean subset and superset tests. Those relations do
  1276. not define total orderings (for example, the two sets <code class="docutils literal notranslate"><span class="pre">{1,2}</span></code> and <code class="docutils literal notranslate"><span class="pre">{2,3}</span></code>
  1277. are not equal, nor subsets of one another, nor supersets of one
  1278. another). Accordingly, sets are not appropriate arguments for functions
  1279. which depend on total ordering (for example, <a class="reference internal" href="../library/functions.html#min" title="min"><code class="xref py py-func docutils literal notranslate"><span class="pre">min()</span></code></a>, <a class="reference internal" href="../library/functions.html#max" title="max"><code class="xref py py-func docutils literal notranslate"><span class="pre">max()</span></code></a>, and
  1280. <a class="reference internal" href="../library/functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> produce undefined results given a list of sets as inputs).</p>
  1281. <p>Comparison of sets enforces reflexivity of its elements.</p>
  1282. </li>
  1283. <li><p>Most other built-in types have no comparison methods implemented, so they
  1284. inherit the default comparison behavior.</p></li>
  1285. </ul>
  1286. <p>User-defined classes that customize their comparison behavior should follow
  1287. some consistency rules, if possible:</p>
  1288. <ul>
  1289. <li><p>Equality comparison should be reflexive.
  1290. In other words, identical objects should compare equal:</p>
  1291. <blockquote>
  1292. <div><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">is</span> <span class="pre">y</span></code> implies <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">y</span></code></p>
  1293. </div></blockquote>
  1294. </li>
  1295. <li><p>Comparison should be symmetric.
  1296. In other words, the following expressions should have the same result:</p>
  1297. <blockquote>
  1298. <div><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">y</span></code> and <code class="docutils literal notranslate"><span class="pre">y</span> <span class="pre">==</span> <span class="pre">x</span></code></p>
  1299. <p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">!=</span> <span class="pre">y</span></code> and <code class="docutils literal notranslate"><span class="pre">y</span> <span class="pre">!=</span> <span class="pre">x</span></code></p>
  1300. <p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">y</span></code> and <code class="docutils literal notranslate"><span class="pre">y</span> <span class="pre">&gt;</span> <span class="pre">x</span></code></p>
  1301. <p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;=</span> <span class="pre">y</span></code> and <code class="docutils literal notranslate"><span class="pre">y</span> <span class="pre">&gt;=</span> <span class="pre">x</span></code></p>
  1302. </div></blockquote>
  1303. </li>
  1304. <li><p>Comparison should be transitive.
  1305. The following (non-exhaustive) examples illustrate that:</p>
  1306. <blockquote>
  1307. <div><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&gt;</span> <span class="pre">y</span> <span class="pre">and</span> <span class="pre">y</span> <span class="pre">&gt;</span> <span class="pre">z</span></code> implies <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&gt;</span> <span class="pre">z</span></code></p>
  1308. <p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">y</span> <span class="pre">and</span> <span class="pre">y</span> <span class="pre">&lt;=</span> <span class="pre">z</span></code> implies <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">z</span></code></p>
  1309. </div></blockquote>
  1310. </li>
  1311. <li><p>Inverse comparison should result in the boolean negation.
  1312. In other words, the following expressions should have the same result:</p>
  1313. <blockquote>
  1314. <div><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">y</span></code> and <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">x</span> <span class="pre">!=</span> <span class="pre">y</span></code></p>
  1315. <p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">y</span></code> and <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">x</span> <span class="pre">&gt;=</span> <span class="pre">y</span></code> (for total ordering)</p>
  1316. <p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&gt;</span> <span class="pre">y</span></code> and <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">x</span> <span class="pre">&lt;=</span> <span class="pre">y</span></code> (for total ordering)</p>
  1317. </div></blockquote>
  1318. <p>The last two expressions apply to totally ordered collections (e.g. to
  1319. sequences, but not to sets or mappings). See also the
  1320. <a class="reference internal" href="../library/functools.html#functools.total_ordering" title="functools.total_ordering"><code class="xref py py-func docutils literal notranslate"><span class="pre">total_ordering()</span></code></a> decorator.</p>
  1321. </li>
  1322. <li><p>The <a class="reference internal" href="../library/functions.html#hash" title="hash"><code class="xref py py-func docutils literal notranslate"><span class="pre">hash()</span></code></a> result should be consistent with equality.
  1323. Objects that are equal should either have the same hash value,
  1324. or be marked as unhashable.</p></li>
  1325. </ul>
  1326. <p>Python does not enforce these consistency rules. In fact, the not-a-number
  1327. values are an example for not following these rules.</p>
  1328. </section>
  1329. <section id="membership-test-operations">
  1330. <span id="membership-test-details"></span><span id="not-in"></span><span id="in"></span><h3><span class="section-number">6.10.2. </span>Membership test operations<a class="headerlink" href="#membership-test-operations" title="Link to this heading">¶</a></h3>
  1331. <p>The operators <a class="reference internal" href="#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> and <a class="reference internal" href="#not-in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">not</span> <span class="pre">in</span></code></a> test for membership. <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span>
  1332. <span class="pre">s</span></code> evaluates to <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>x</em> is a member of <em>s</em>, and <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.
  1333. <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">not</span> <span class="pre">in</span> <span class="pre">s</span></code> returns the negation of <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">s</span></code>. All built-in sequences and
  1334. set types support this as well as dictionary, for which <code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code> tests
  1335. whether the dictionary has a given key. For container types such as list, tuple,
  1336. set, frozenset, dict, or collections.deque, the expression <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">y</span></code> is equivalent
  1337. to <code class="docutils literal notranslate"><span class="pre">any(x</span> <span class="pre">is</span> <span class="pre">e</span> <span class="pre">or</span> <span class="pre">x</span> <span class="pre">==</span> <span class="pre">e</span> <span class="pre">for</span> <span class="pre">e</span> <span class="pre">in</span> <span class="pre">y)</span></code>.</p>
  1338. <p>For the string and bytes types, <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">y</span></code> is <code class="docutils literal notranslate"><span class="pre">True</span></code> if and only if <em>x</em> is a
  1339. substring of <em>y</em>. An equivalent test is <code class="docutils literal notranslate"><span class="pre">y.find(x)</span> <span class="pre">!=</span> <span class="pre">-1</span></code>. Empty strings are
  1340. always considered to be a substring of any other string, so <code class="docutils literal notranslate"><span class="pre">&quot;&quot;</span> <span class="pre">in</span> <span class="pre">&quot;abc&quot;</span></code> will
  1341. return <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>
  1342. <p>For user-defined classes which define the <a class="reference internal" href="datamodel.html#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a> method, <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span>
  1343. <span class="pre">y</span></code> returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if <code class="docutils literal notranslate"><span class="pre">y.__contains__(x)</span></code> returns a true value, and
  1344. <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.</p>
  1345. <p>For user-defined classes which do not define <a class="reference internal" href="datamodel.html#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a> but do define
  1346. <a class="reference internal" href="datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a>, <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">y</span></code> is <code class="docutils literal notranslate"><span class="pre">True</span></code> if some value <code class="docutils literal notranslate"><span class="pre">z</span></code>, for which the
  1347. expression <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">is</span> <span class="pre">z</span> <span class="pre">or</span> <span class="pre">x</span> <span class="pre">==</span> <span class="pre">z</span></code> is true, is produced while iterating over <code class="docutils literal notranslate"><span class="pre">y</span></code>.
  1348. If an exception is raised during the iteration, it is as if <a class="reference internal" href="#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> raised
  1349. that exception.</p>
  1350. <p>Lastly, the old-style iteration protocol is tried: if a class defines
  1351. <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>, <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">y</span></code> is <code class="docutils literal notranslate"><span class="pre">True</span></code> if and only if there is a non-negative
  1352. integer index <em>i</em> such that <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">is</span> <span class="pre">y[i]</span> <span class="pre">or</span> <span class="pre">x</span> <span class="pre">==</span> <span class="pre">y[i]</span></code>, and no lower integer index
  1353. raises the <a class="reference internal" href="../library/exceptions.html#IndexError" title="IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> exception. (If any other exception is raised, it is as
  1354. if <a class="reference internal" href="#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> raised that exception).</p>
  1355. <p id="index-80">The operator <a class="reference internal" href="#not-in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">not</span> <span class="pre">in</span></code></a> is defined to have the inverse truth value of
  1356. <a class="reference internal" href="#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a>.</p>
  1357. </section>
  1358. <section id="is-not">
  1359. <span id="is"></span><span id="index-81"></span><span id="identity-comparisons"></span><h3><span class="section-number">6.10.3. </span>Identity comparisons<a class="headerlink" href="#is-not" title="Link to this heading">¶</a></h3>
  1360. <p>The operators <a class="reference internal" href="#is"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">is</span></code></a> and <a class="reference internal" href="#is-not"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">is</span> <span class="pre">not</span></code></a> test for an object’s identity: <code class="docutils literal notranslate"><span class="pre">x</span>
  1361. <span class="pre">is</span> <span class="pre">y</span></code> is true if and only if <em>x</em> and <em>y</em> are the same object. An Object’s identity
  1362. is determined using the <a class="reference internal" href="../library/functions.html#id" title="id"><code class="xref py py-meth docutils literal notranslate"><span class="pre">id()</span></code></a> function. <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">is</span> <span class="pre">not</span> <span class="pre">y</span></code> yields the inverse
  1363. truth value. <a class="footnote-reference brackets" href="#id20" id="id13" role="doc-noteref"><span class="fn-bracket">[</span>4<span class="fn-bracket">]</span></a></p>
  1364. </section>
  1365. </section>
  1366. <section id="boolean-operations">
  1367. <span id="not"></span><span id="or"></span><span id="and"></span><span id="booleans"></span><h2><span class="section-number">6.11. </span>Boolean operations<a class="headerlink" href="#boolean-operations" title="Link to this heading">¶</a></h2>
  1368. <pre id="index-82">
  1369. <strong id="grammar-token-python-grammar-or_test">or_test </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-and_test"><code class="xref docutils literal notranslate"><span class="pre">and_test</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-or_test"><code class="xref docutils literal notranslate"><span class="pre">or_test</span></code></a> &quot;or&quot; <a class="reference internal" href="#grammar-token-python-grammar-and_test"><code class="xref docutils literal notranslate"><span class="pre">and_test</span></code></a>
  1370. <strong id="grammar-token-python-grammar-and_test">and_test</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-not_test"><code class="xref docutils literal notranslate"><span class="pre">not_test</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-and_test"><code class="xref docutils literal notranslate"><span class="pre">and_test</span></code></a> &quot;and&quot; <a class="reference internal" href="#grammar-token-python-grammar-not_test"><code class="xref docutils literal notranslate"><span class="pre">not_test</span></code></a>
  1371. <strong id="grammar-token-python-grammar-not_test">not_test</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-comparison"><code class="xref docutils literal notranslate"><span class="pre">comparison</span></code></a> | &quot;not&quot; <a class="reference internal" href="#grammar-token-python-grammar-not_test"><code class="xref docutils literal notranslate"><span class="pre">not_test</span></code></a>
  1372. </pre>
  1373. <p>In the context of Boolean operations, and also when expressions are used by
  1374. control flow statements, the following values are interpreted as false:
  1375. <code class="docutils literal notranslate"><span class="pre">False</span></code>, <code class="docutils literal notranslate"><span class="pre">None</span></code>, numeric zero of all types, and empty strings and containers
  1376. (including strings, tuples, lists, dictionaries, sets and frozensets). All
  1377. other values are interpreted as true. User-defined objects can customize their
  1378. truth value by providing a <a class="reference internal" href="datamodel.html#object.__bool__" title="object.__bool__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__bool__()</span></code></a> method.</p>
  1379. <p id="index-83">The operator <a class="reference internal" href="#not"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">not</span></code></a> yields <code class="docutils literal notranslate"><span class="pre">True</span></code> if its argument is false, <code class="docutils literal notranslate"><span class="pre">False</span></code>
  1380. otherwise.</p>
  1381. <p id="index-84">The expression <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">and</span> <span class="pre">y</span></code> first evaluates <em>x</em>; if <em>x</em> is false, its value is
  1382. returned; otherwise, <em>y</em> is evaluated and the resulting value is returned.</p>
  1383. <p id="index-85">The expression <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">or</span> <span class="pre">y</span></code> first evaluates <em>x</em>; if <em>x</em> is true, its value is
  1384. returned; otherwise, <em>y</em> is evaluated and the resulting value is returned.</p>
  1385. <p>Note that neither <a class="reference internal" href="#and"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">and</span></code></a> nor <a class="reference internal" href="#or"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">or</span></code></a> restrict the value and type
  1386. they return to <code class="docutils literal notranslate"><span class="pre">False</span></code> and <code class="docutils literal notranslate"><span class="pre">True</span></code>, but rather return the last evaluated
  1387. argument. This is sometimes useful, e.g., if <code class="docutils literal notranslate"><span class="pre">s</span></code> is a string that should be
  1388. replaced by a default value if it is empty, the expression <code class="docutils literal notranslate"><span class="pre">s</span> <span class="pre">or</span> <span class="pre">'foo'</span></code> yields
  1389. the desired value. Because <a class="reference internal" href="#not"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">not</span></code></a> has to create a new value, it
  1390. returns a boolean value regardless of the type of its argument
  1391. (for example, <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">'foo'</span></code> produces <code class="docutils literal notranslate"><span class="pre">False</span></code> rather than <code class="docutils literal notranslate"><span class="pre">''</span></code>.)</p>
  1392. </section>
  1393. <section id="assignment-expressions">
  1394. <span id="index-86"></span><h2><span class="section-number">6.12. </span>Assignment expressions<a class="headerlink" href="#assignment-expressions" title="Link to this heading">¶</a></h2>
  1395. <pre>
  1396. <strong id="grammar-token-python-grammar-assignment_expression">assignment_expression</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="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
  1397. </pre>
  1398. <p>An assignment expression (sometimes also called a “named expression” or
  1399. “walrus”) assigns an <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref std std-token docutils literal notranslate"><span class="pre">expression</span></code></a> to an
  1400. <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-identifier"><code class="xref std std-token docutils literal notranslate"><span class="pre">identifier</span></code></a>, while also returning the value of the
  1401. <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref std std-token docutils literal notranslate"><span class="pre">expression</span></code></a>.</p>
  1402. <p>One common use case is when handling matched regular expressions:</p>
  1403. <div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">matching</span> <span class="o">:=</span> <span class="n">pattern</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="n">data</span><span class="p">):</span>
  1404. <span class="n">do_something</span><span class="p">(</span><span class="n">matching</span><span class="p">)</span>
  1405. </pre></div>
  1406. </div>
  1407. <p>Or, when processing a file stream in chunks:</p>
  1408. <div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">while</span> <span class="n">chunk</span> <span class="o">:=</span> <span class="n">file</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">9000</span><span class="p">):</span>
  1409. <span class="n">process</span><span class="p">(</span><span class="n">chunk</span><span class="p">)</span>
  1410. </pre></div>
  1411. </div>
  1412. <p>Assignment expressions must be surrounded by parentheses when
  1413. used as expression statements and when used as sub-expressions in
  1414. slicing, conditional, lambda,
  1415. keyword-argument, and comprehension-if expressions and
  1416. in <code class="docutils literal notranslate"><span class="pre">assert</span></code>, <code class="docutils literal notranslate"><span class="pre">with</span></code>, and <code class="docutils literal notranslate"><span class="pre">assignment</span></code> statements.
  1417. In all other places where they can be used, parentheses are not required,
  1418. including in <code class="docutils literal notranslate"><span class="pre">if</span></code> and <code class="docutils literal notranslate"><span class="pre">while</span></code> statements.</p>
  1419. <div class="versionadded">
  1420. <p><span class="versionmodified added">New in version 3.8: </span>See <span class="target" id="index-87"></span><a class="pep reference external" href="https://peps.python.org/pep-0572/"><strong>PEP 572</strong></a> for more details about assignment expressions.</p>
  1421. </div>
  1422. </section>
  1423. <section id="conditional-expressions">
  1424. <span id="if-expr"></span><h2><span class="section-number">6.13. </span>Conditional expressions<a class="headerlink" href="#conditional-expressions" title="Link to this heading">¶</a></h2>
  1425. <pre id="index-88">
  1426. <strong id="grammar-token-python-grammar-conditional_expression">conditional_expression</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-or_test"><code class="xref docutils literal notranslate"><span class="pre">or_test</span></code></a> [&quot;if&quot; <a class="reference internal" href="#grammar-token-python-grammar-or_test"><code class="xref docutils literal notranslate"><span class="pre">or_test</span></code></a> &quot;else&quot; <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>]
  1427. <strong id="grammar-token-python-grammar-expression">expression </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-conditional_expression"><code class="xref docutils literal notranslate"><span class="pre">conditional_expression</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-lambda_expr"><code class="xref docutils literal notranslate"><span class="pre">lambda_expr</span></code></a>
  1428. </pre>
  1429. <p>Conditional expressions (sometimes called a “ternary operator”) have the lowest
  1430. priority of all Python operations.</p>
  1431. <p>The expression <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">if</span> <span class="pre">C</span> <span class="pre">else</span> <span class="pre">y</span></code> first evaluates the condition, <em>C</em> rather than <em>x</em>.
  1432. If <em>C</em> is true, <em>x</em> is evaluated and its value is returned; otherwise, <em>y</em> is
  1433. evaluated and its value is returned.</p>
  1434. <p>See <span class="target" id="index-89"></span><a class="pep reference external" href="https://peps.python.org/pep-0308/"><strong>PEP 308</strong></a> for more details about conditional expressions.</p>
  1435. </section>
  1436. <section id="lambda">
  1437. <span id="lambdas"></span><span id="id14"></span><h2><span class="section-number">6.14. </span>Lambdas<a class="headerlink" href="#lambda" title="Link to this heading">¶</a></h2>
  1438. <pre id="index-90">
  1439. <strong id="grammar-token-python-grammar-lambda_expr">lambda_expr</strong> ::= &quot;lambda&quot; [<a class="reference internal" href="compound_stmts.html#grammar-token-python-grammar-parameter_list"><code class="xref docutils literal notranslate"><span class="pre">parameter_list</span></code></a>] &quot;:&quot; <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
  1440. </pre>
  1441. <p>Lambda expressions (sometimes called lambda forms) are used to create anonymous
  1442. functions. The expression <code class="docutils literal notranslate"><span class="pre">lambda</span> <span class="pre">parameters:</span> <span class="pre">expression</span></code> yields a function
  1443. object. The unnamed object behaves like a function object defined with:</p>
  1444. <div class="highlight-none notranslate"><div class="highlight"><pre><span></span>def &lt;lambda&gt;(parameters):
  1445. return expression
  1446. </pre></div>
  1447. </div>
  1448. <p>See section <a class="reference internal" href="compound_stmts.html#function"><span class="std std-ref">Function definitions</span></a> for the syntax of parameter lists. Note that
  1449. functions created with lambda expressions cannot contain statements or
  1450. annotations.</p>
  1451. </section>
  1452. <section id="expression-lists">
  1453. <span id="exprlists"></span><h2><span class="section-number">6.15. </span>Expression lists<a class="headerlink" href="#expression-lists" title="Link to this heading">¶</a></h2>
  1454. <pre id="index-91">
  1455. <strong id="grammar-token-python-grammar-expression_list">expression_list </strong> ::= <a class="reference internal" href="#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-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>)* [&quot;,&quot;]
  1456. <strong id="grammar-token-python-grammar-starred_list">starred_list </strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-starred_item"><code class="xref docutils literal notranslate"><span class="pre">starred_item</span></code></a> (&quot;,&quot; <a class="reference internal" href="#grammar-token-python-grammar-starred_item"><code class="xref docutils literal notranslate"><span class="pre">starred_item</span></code></a>)* [&quot;,&quot;]
  1457. <strong id="grammar-token-python-grammar-starred_expression">starred_expression</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> | (<a class="reference internal" href="#grammar-token-python-grammar-starred_item"><code class="xref docutils literal notranslate"><span class="pre">starred_item</span></code></a> &quot;,&quot;)* [<a class="reference internal" href="#grammar-token-python-grammar-starred_item"><code class="xref docutils literal notranslate"><span class="pre">starred_item</span></code></a>]
  1458. <strong id="grammar-token-python-grammar-starred_item">starred_item </strong> ::= <a class="reference internal" href="#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-or_expr"><code class="xref docutils literal notranslate"><span class="pre">or_expr</span></code></a>
  1459. </pre>
  1460. <p id="index-92">Except when part of a list or set display, an expression list
  1461. containing at least one comma yields a tuple. The length of
  1462. the tuple is the number of expressions in the list. The expressions are
  1463. evaluated from left to right.</p>
  1464. <p id="index-93">An asterisk <code class="docutils literal notranslate"><span class="pre">*</span></code> denotes <em class="dfn">iterable unpacking</em>. Its operand must be
  1465. an <a class="reference internal" href="../glossary.html#term-iterable"><span class="xref std std-term">iterable</span></a>. The iterable is expanded into a sequence of items,
  1466. which are included in the new tuple, list, or set, at the site of
  1467. the unpacking.</p>
  1468. <div class="versionadded">
  1469. <p><span class="versionmodified added">New in version 3.5: </span>Iterable unpacking in expression lists, originally proposed by <span class="target" id="index-94"></span><a class="pep reference external" href="https://peps.python.org/pep-0448/"><strong>PEP 448</strong></a>.</p>
  1470. </div>
  1471. <p id="index-95">A trailing comma is required only to create a one-item tuple,
  1472. such as <code class="docutils literal notranslate"><span class="pre">1,</span></code>; it is optional in all other cases.
  1473. A single expression without a
  1474. trailing comma doesn’t create a tuple, but rather yields the value of that
  1475. expression. (To create an empty tuple, use an empty pair of parentheses:
  1476. <code class="docutils literal notranslate"><span class="pre">()</span></code>.)</p>
  1477. </section>
  1478. <section id="evaluation-order">
  1479. <span id="evalorder"></span><h2><span class="section-number">6.16. </span>Evaluation order<a class="headerlink" href="#evaluation-order" title="Link to this heading">¶</a></h2>
  1480. <p id="index-96">Python evaluates expressions from left to right. Notice that while evaluating
  1481. an assignment, the right-hand side is evaluated before the left-hand side.</p>
  1482. <p>In the following lines, expressions will be evaluated in the arithmetic order of
  1483. their suffixes:</p>
  1484. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">expr1</span><span class="p">,</span> <span class="n">expr2</span><span class="p">,</span> <span class="n">expr3</span><span class="p">,</span> <span class="n">expr4</span>
  1485. <span class="p">(</span><span class="n">expr1</span><span class="p">,</span> <span class="n">expr2</span><span class="p">,</span> <span class="n">expr3</span><span class="p">,</span> <span class="n">expr4</span><span class="p">)</span>
  1486. <span class="p">{</span><span class="n">expr1</span><span class="p">:</span> <span class="n">expr2</span><span class="p">,</span> <span class="n">expr3</span><span class="p">:</span> <span class="n">expr4</span><span class="p">}</span>
  1487. <span class="n">expr1</span> <span class="o">+</span> <span class="n">expr2</span> <span class="o">*</span> <span class="p">(</span><span class="n">expr3</span> <span class="o">-</span> <span class="n">expr4</span><span class="p">)</span>
  1488. <span class="n">expr1</span><span class="p">(</span><span class="n">expr2</span><span class="p">,</span> <span class="n">expr3</span><span class="p">,</span> <span class="o">*</span><span class="n">expr4</span><span class="p">,</span> <span class="o">**</span><span class="n">expr5</span><span class="p">)</span>
  1489. <span class="n">expr3</span><span class="p">,</span> <span class="n">expr4</span> <span class="o">=</span> <span class="n">expr1</span><span class="p">,</span> <span class="n">expr2</span>
  1490. </pre></div>
  1491. </div>
  1492. </section>
  1493. <section id="operator-precedence">
  1494. <span id="operator-summary"></span><h2><span class="section-number">6.17. </span>Operator precedence<a class="headerlink" href="#operator-precedence" title="Link to this heading">¶</a></h2>
  1495. <p id="index-97">The following table summarizes the operator precedence in Python, from highest
  1496. precedence (most binding) to lowest precedence (least binding). Operators in
  1497. the same box have the same precedence. Unless the syntax is explicitly given,
  1498. operators are binary. Operators in the same box group left to right (except for
  1499. exponentiation and conditional expressions, which group from right to left).</p>
  1500. <p>Note that comparisons, membership tests, and identity tests, all have the same
  1501. precedence and have a left-to-right chaining feature as described in the
  1502. <a class="reference internal" href="#comparisons"><span class="std std-ref">Comparisons</span></a> section.</p>
  1503. <table class="docutils align-default">
  1504. <thead>
  1505. <tr class="row-odd"><th class="head"><p>Operator</p></th>
  1506. <th class="head"><p>Description</p></th>
  1507. </tr>
  1508. </thead>
  1509. <tbody>
  1510. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">(expressions...)</span></code>,</p>
  1511. <p><code class="docutils literal notranslate"><span class="pre">[expressions...]</span></code>,
  1512. <code class="docutils literal notranslate"><span class="pre">{key:</span> <span class="pre">value...}</span></code>,
  1513. <code class="docutils literal notranslate"><span class="pre">{expressions...}</span></code></p>
  1514. </td>
  1515. <td><p>Binding or parenthesized
  1516. expression,
  1517. list display,
  1518. dictionary display,
  1519. set display</p></td>
  1520. </tr>
  1521. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">x[index]</span></code>, <code class="docutils literal notranslate"><span class="pre">x[index:index]</span></code>,
  1522. <code class="docutils literal notranslate"><span class="pre">x(arguments...)</span></code>, <code class="docutils literal notranslate"><span class="pre">x.attribute</span></code></p></td>
  1523. <td><p>Subscription, slicing,
  1524. call, attribute reference</p></td>
  1525. </tr>
  1526. <tr class="row-even"><td><p><a class="reference internal" href="#await"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">await</span> <span class="pre">x</span></code></a></p></td>
  1527. <td><p>Await expression</p></td>
  1528. </tr>
  1529. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">**</span></code></p></td>
  1530. <td><p>Exponentiation <a class="footnote-reference brackets" href="#id21" id="id15" role="doc-noteref"><span class="fn-bracket">[</span>5<span class="fn-bracket">]</span></a></p></td>
  1531. </tr>
  1532. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">+x</span></code>, <code class="docutils literal notranslate"><span class="pre">-x</span></code>, <code class="docutils literal notranslate"><span class="pre">~x</span></code></p></td>
  1533. <td><p>Positive, negative, bitwise NOT</p></td>
  1534. </tr>
  1535. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">*</span></code>, <code class="docutils literal notranslate"><span class="pre">&#64;</span></code>, <code class="docutils literal notranslate"><span class="pre">/</span></code>, <code class="docutils literal notranslate"><span class="pre">//</span></code>, <code class="docutils literal notranslate"><span class="pre">%</span></code></p></td>
  1536. <td><p>Multiplication, matrix
  1537. multiplication, division, floor
  1538. division, remainder <a class="footnote-reference brackets" href="#id22" id="id16" role="doc-noteref"><span class="fn-bracket">[</span>6<span class="fn-bracket">]</span></a></p></td>
  1539. </tr>
  1540. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">+</span></code>, <code class="docutils literal notranslate"><span class="pre">-</span></code></p></td>
  1541. <td><p>Addition and subtraction</p></td>
  1542. </tr>
  1543. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">&lt;&lt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;&gt;</span></code></p></td>
  1544. <td><p>Shifts</p></td>
  1545. </tr>
  1546. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">&amp;</span></code></p></td>
  1547. <td><p>Bitwise AND</p></td>
  1548. </tr>
  1549. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">^</span></code></p></td>
  1550. <td><p>Bitwise XOR</p></td>
  1551. </tr>
  1552. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">|</span></code></p></td>
  1553. <td><p>Bitwise OR</p></td>
  1554. </tr>
  1555. <tr class="row-odd"><td><p><a class="reference internal" href="#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a>, <a class="reference internal" href="#not-in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">not</span> <span class="pre">in</span></code></a>,
  1556. <a class="reference internal" href="#is"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">is</span></code></a>, <a class="reference internal" href="#is-not"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">is</span> <span class="pre">not</span></code></a>, <code class="docutils literal notranslate"><span class="pre">&lt;</span></code>,
  1557. <code class="docutils literal notranslate"><span class="pre">&lt;=</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;=</span></code>, <code class="docutils literal notranslate"><span class="pre">!=</span></code>, <code class="docutils literal notranslate"><span class="pre">==</span></code></p></td>
  1558. <td><p>Comparisons, including membership
  1559. tests and identity tests</p></td>
  1560. </tr>
  1561. <tr class="row-even"><td><p><a class="reference internal" href="#not"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">not</span> <span class="pre">x</span></code></a></p></td>
  1562. <td><p>Boolean NOT</p></td>
  1563. </tr>
  1564. <tr class="row-odd"><td><p><a class="reference internal" href="#and"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">and</span></code></a></p></td>
  1565. <td><p>Boolean AND</p></td>
  1566. </tr>
  1567. <tr class="row-even"><td><p><a class="reference internal" href="#or"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">or</span></code></a></p></td>
  1568. <td><p>Boolean OR</p></td>
  1569. </tr>
  1570. <tr class="row-odd"><td><p><a class="reference internal" href="#if-expr"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> – <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></p></td>
  1571. <td><p>Conditional expression</p></td>
  1572. </tr>
  1573. <tr class="row-even"><td><p><a class="reference internal" href="#lambda"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">lambda</span></code></a></p></td>
  1574. <td><p>Lambda expression</p></td>
  1575. </tr>
  1576. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">:=</span></code></p></td>
  1577. <td><p>Assignment expression</p></td>
  1578. </tr>
  1579. </tbody>
  1580. </table>
  1581. <p class="rubric">Footnotes</p>
  1582. <aside class="footnote-list brackets">
  1583. <aside class="footnote brackets" id="id17" role="doc-footnote">
  1584. <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id9">1</a><span class="fn-bracket">]</span></span>
  1585. <p>While <code class="docutils literal notranslate"><span class="pre">abs(x%y)</span> <span class="pre">&lt;</span> <span class="pre">abs(y)</span></code> is true mathematically, for floats it may not be
  1586. true numerically due to roundoff. For example, and assuming a platform on which
  1587. a Python float is an IEEE 754 double-precision number, in order that <code class="docutils literal notranslate"><span class="pre">-1e-100</span> <span class="pre">%</span>
  1588. <span class="pre">1e100</span></code> have the same sign as <code class="docutils literal notranslate"><span class="pre">1e100</span></code>, the computed result is <code class="docutils literal notranslate"><span class="pre">-1e-100</span> <span class="pre">+</span>
  1589. <span class="pre">1e100</span></code>, which is numerically exactly equal to <code class="docutils literal notranslate"><span class="pre">1e100</span></code>. The function
  1590. <a class="reference internal" href="../library/math.html#math.fmod" title="math.fmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.fmod()</span></code></a> returns a result whose sign matches the sign of the
  1591. first argument instead, and so returns <code class="docutils literal notranslate"><span class="pre">-1e-100</span></code> in this case. Which approach
  1592. is more appropriate depends on the application.</p>
  1593. </aside>
  1594. <aside class="footnote brackets" id="id18" role="doc-footnote">
  1595. <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id10">2</a><span class="fn-bracket">]</span></span>
  1596. <p>If x is very close to an exact integer multiple of y, it’s possible for
  1597. <code class="docutils literal notranslate"><span class="pre">x//y</span></code> to be one larger than <code class="docutils literal notranslate"><span class="pre">(x-x%y)//y</span></code> due to rounding. In such
  1598. cases, Python returns the latter result, in order to preserve that
  1599. <code class="docutils literal notranslate"><span class="pre">divmod(x,y)[0]</span> <span class="pre">*</span> <span class="pre">y</span> <span class="pre">+</span> <span class="pre">x</span> <span class="pre">%</span> <span class="pre">y</span></code> be very close to <code class="docutils literal notranslate"><span class="pre">x</span></code>.</p>
  1600. </aside>
  1601. <aside class="footnote brackets" id="id19" role="doc-footnote">
  1602. <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id12">3</a><span class="fn-bracket">]</span></span>
  1603. <p>The Unicode standard distinguishes between <em class="dfn">code points</em>
  1604. (e.g. U+0041) and <em class="dfn">abstract characters</em> (e.g. “LATIN CAPITAL LETTER A”).
  1605. While most abstract characters in Unicode are only represented using one
  1606. code point, there is a number of abstract characters that can in addition be
  1607. represented using a sequence of more than one code point. For example, the
  1608. abstract character “LATIN CAPITAL LETTER C WITH CEDILLA” can be represented
  1609. as a single <em class="dfn">precomposed character</em> at code position U+00C7, or as a
  1610. sequence of a <em class="dfn">base character</em> at code position U+0043 (LATIN CAPITAL
  1611. LETTER C), followed by a <em class="dfn">combining character</em> at code position U+0327
  1612. (COMBINING CEDILLA).</p>
  1613. <p>The comparison operators on strings compare at the level of Unicode code
  1614. points. This may be counter-intuitive to humans. For example,
  1615. <code class="docutils literal notranslate"><span class="pre">&quot;\u00C7&quot;</span> <span class="pre">==</span> <span class="pre">&quot;\u0043\u0327&quot;</span></code> is <code class="docutils literal notranslate"><span class="pre">False</span></code>, even though both strings
  1616. represent the same abstract character “LATIN CAPITAL LETTER C WITH CEDILLA”.</p>
  1617. <p>To compare strings at the level of abstract characters (that is, in a way
  1618. intuitive to humans), use <a class="reference internal" href="../library/unicodedata.html#unicodedata.normalize" title="unicodedata.normalize"><code class="xref py py-func docutils literal notranslate"><span class="pre">unicodedata.normalize()</span></code></a>.</p>
  1619. </aside>
  1620. <aside class="footnote brackets" id="id20" role="doc-footnote">
  1621. <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id13">4</a><span class="fn-bracket">]</span></span>
  1622. <p>Due to automatic garbage-collection, free lists, and the dynamic nature of
  1623. descriptors, you may notice seemingly unusual behaviour in certain uses of
  1624. the <a class="reference internal" href="#is"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">is</span></code></a> operator, like those involving comparisons between instance
  1625. methods, or constants. Check their documentation for more info.</p>
  1626. </aside>
  1627. <aside class="footnote brackets" id="id21" role="doc-footnote">
  1628. <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id15">5</a><span class="fn-bracket">]</span></span>
  1629. <p>The power operator <code class="docutils literal notranslate"><span class="pre">**</span></code> binds less tightly than an arithmetic or
  1630. bitwise unary operator on its right, that is, <code class="docutils literal notranslate"><span class="pre">2**-1</span></code> is <code class="docutils literal notranslate"><span class="pre">0.5</span></code>.</p>
  1631. </aside>
  1632. <aside class="footnote brackets" id="id22" role="doc-footnote">
  1633. <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id16">6</a><span class="fn-bracket">]</span></span>
  1634. <p>The <code class="docutils literal notranslate"><span class="pre">%</span></code> operator is also used for string formatting; the same
  1635. precedence applies.</p>
  1636. </aside>
  1637. </aside>
  1638. </section>
  1639. </section>
  1640. <div class="clearer"></div>
  1641. </div>
  1642. </div>
  1643. </div>
  1644. <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
  1645. <div class="sphinxsidebarwrapper">
  1646. <div>
  1647. <h3><a href="../contents.html">Table of Contents</a></h3>
  1648. <ul>
  1649. <li><a class="reference internal" href="#">6. Expressions</a><ul>
  1650. <li><a class="reference internal" href="#arithmetic-conversions">6.1. Arithmetic conversions</a></li>
  1651. <li><a class="reference internal" href="#atoms">6.2. Atoms</a><ul>
  1652. <li><a class="reference internal" href="#atom-identifiers">6.2.1. Identifiers (Names)</a></li>
  1653. <li><a class="reference internal" href="#literals">6.2.2. Literals</a></li>
  1654. <li><a class="reference internal" href="#parenthesized-forms">6.2.3. Parenthesized forms</a></li>
  1655. <li><a class="reference internal" href="#displays-for-lists-sets-and-dictionaries">6.2.4. Displays for lists, sets and dictionaries</a></li>
  1656. <li><a class="reference internal" href="#list-displays">6.2.5. List displays</a></li>
  1657. <li><a class="reference internal" href="#set-displays">6.2.6. Set displays</a></li>
  1658. <li><a class="reference internal" href="#dictionary-displays">6.2.7. Dictionary displays</a></li>
  1659. <li><a class="reference internal" href="#generator-expressions">6.2.8. Generator expressions</a></li>
  1660. <li><a class="reference internal" href="#yield-expressions">6.2.9. Yield expressions</a><ul>
  1661. <li><a class="reference internal" href="#generator-iterator-methods">6.2.9.1. Generator-iterator methods</a></li>
  1662. <li><a class="reference internal" href="#examples">6.2.9.2. Examples</a></li>
  1663. <li><a class="reference internal" href="#asynchronous-generator-functions">6.2.9.3. Asynchronous generator functions</a></li>
  1664. <li><a class="reference internal" href="#asynchronous-generator-iterator-methods">6.2.9.4. Asynchronous generator-iterator methods</a></li>
  1665. </ul>
  1666. </li>
  1667. </ul>
  1668. </li>
  1669. <li><a class="reference internal" href="#primaries">6.3. Primaries</a><ul>
  1670. <li><a class="reference internal" href="#attribute-references">6.3.1. Attribute references</a></li>
  1671. <li><a class="reference internal" href="#subscriptions">6.3.2. Subscriptions</a></li>
  1672. <li><a class="reference internal" href="#slicings">6.3.3. Slicings</a></li>
  1673. <li><a class="reference internal" href="#calls">6.3.4. Calls</a></li>
  1674. </ul>
  1675. </li>
  1676. <li><a class="reference internal" href="#await-expression">6.4. Await expression</a></li>
  1677. <li><a class="reference internal" href="#the-power-operator">6.5. The power operator</a></li>
  1678. <li><a class="reference internal" href="#unary-arithmetic-and-bitwise-operations">6.6. Unary arithmetic and bitwise operations</a></li>
  1679. <li><a class="reference internal" href="#binary-arithmetic-operations">6.7. Binary arithmetic operations</a></li>
  1680. <li><a class="reference internal" href="#shifting-operations">6.8. Shifting operations</a></li>
  1681. <li><a class="reference internal" href="#binary-bitwise-operations">6.9. Binary bitwise operations</a></li>
  1682. <li><a class="reference internal" href="#comparisons">6.10. Comparisons</a><ul>
  1683. <li><a class="reference internal" href="#value-comparisons">6.10.1. Value comparisons</a></li>
  1684. <li><a class="reference internal" href="#membership-test-operations">6.10.2. Membership test operations</a></li>
  1685. <li><a class="reference internal" href="#is-not">6.10.3. Identity comparisons</a></li>
  1686. </ul>
  1687. </li>
  1688. <li><a class="reference internal" href="#boolean-operations">6.11. Boolean operations</a></li>
  1689. <li><a class="reference internal" href="#assignment-expressions">6.12. Assignment expressions</a></li>
  1690. <li><a class="reference internal" href="#conditional-expressions">6.13. Conditional expressions</a></li>
  1691. <li><a class="reference internal" href="#lambda">6.14. Lambdas</a></li>
  1692. <li><a class="reference internal" href="#expression-lists">6.15. Expression lists</a></li>
  1693. <li><a class="reference internal" href="#evaluation-order">6.16. Evaluation order</a></li>
  1694. <li><a class="reference internal" href="#operator-precedence">6.17. Operator precedence</a></li>
  1695. </ul>
  1696. </li>
  1697. </ul>
  1698. </div>
  1699. <div>
  1700. <h4>Previous topic</h4>
  1701. <p class="topless"><a href="import.html"
  1702. title="previous chapter"><span class="section-number">5. </span>The import system</a></p>
  1703. </div>
  1704. <div>
  1705. <h4>Next topic</h4>
  1706. <p class="topless"><a href="simple_stmts.html"
  1707. title="next chapter"><span class="section-number">7. </span>Simple statements</a></p>
  1708. </div>
  1709. <div role="note" aria-label="source link">
  1710. <h3>This Page</h3>
  1711. <ul class="this-page-menu">
  1712. <li><a href="../bugs.html">Report a Bug</a></li>
  1713. <li>
  1714. <a href="https://github.com/python/cpython/blob/main/Doc/reference/expressions.rst"
  1715. rel="nofollow">Show Source
  1716. </a>
  1717. </li>
  1718. </ul>
  1719. </div>
  1720. </div>
  1721. <div id="sidebarbutton" title="Collapse sidebar">
  1722. <span>«</span>
  1723. </div>
  1724. </div>
  1725. <div class="clearer"></div>
  1726. </div>
  1727. <div class="related" role="navigation" aria-label="related navigation">
  1728. <h3>Navigation</h3>
  1729. <ul>
  1730. <li class="right" style="margin-right: 10px">
  1731. <a href="../genindex.html" title="General Index"
  1732. >index</a></li>
  1733. <li class="right" >
  1734. <a href="../py-modindex.html" title="Python Module Index"
  1735. >modules</a> |</li>
  1736. <li class="right" >
  1737. <a href="simple_stmts.html" title="7. Simple statements"
  1738. >next</a> |</li>
  1739. <li class="right" >
  1740. <a href="import.html" title="5. The import system"
  1741. >previous</a> |</li>
  1742. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  1743. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  1744. <li class="switchers">
  1745. <div class="language_switcher_placeholder"></div>
  1746. <div class="version_switcher_placeholder"></div>
  1747. </li>
  1748. <li>
  1749. </li>
  1750. <li id="cpython-language-and-version">
  1751. <a href="../index.html">3.12.3 Documentation</a> &#187;
  1752. </li>
  1753. <li class="nav-item nav-item-1"><a href="index.html" >The Python Language Reference</a> &#187;</li>
  1754. <li class="nav-item nav-item-this"><a href=""><span class="section-number">6. </span>Expressions</a></li>
  1755. <li class="right">
  1756. <div class="inline-search" role="search">
  1757. <form class="inline-search" action="../search.html" method="get">
  1758. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  1759. <input type="submit" value="Go" />
  1760. </form>
  1761. </div>
  1762. |
  1763. </li>
  1764. <li class="right">
  1765. <label class="theme-selector-label">
  1766. Theme
  1767. <select class="theme-selector" oninput="activateTheme(this.value)">
  1768. <option value="auto" selected>Auto</option>
  1769. <option value="light">Light</option>
  1770. <option value="dark">Dark</option>
  1771. </select>
  1772. </label> |</li>
  1773. </ul>
  1774. </div>
  1775. <div class="footer">
  1776. &copy;
  1777. <a href="../copyright.html">
  1778. Copyright
  1779. </a>
  1780. 2001-2024, Python Software Foundation.
  1781. <br />
  1782. This page is licensed under the Python Software Foundation License Version 2.
  1783. <br />
  1784. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  1785. <br />
  1786. See <a href="/license.html">History and License</a> for more information.<br />
  1787. <br />
  1788. The Python Software Foundation is a non-profit corporation.
  1789. <a href="https://www.python.org/psf/donations/">Please donate.</a>
  1790. <br />
  1791. <br />
  1792. Last updated on Apr 09, 2024 (13:47 UTC).
  1793. <a href="/bugs.html">Found a bug</a>?
  1794. <br />
  1795. Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 7.2.6.
  1796. </div>
  1797. </body>
  1798. </html>
上海开阖软件有限公司 沪ICP备12045867号-1