gooderp18绿色标准版
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

1082 行
94KB

  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="Design and History FAQ" />
  7. <meta property="og:type" content="website" />
  8. <meta property="og:url" content="https://docs.python.org/3/faq/design.html" />
  9. <meta property="og:site_name" content="Python documentation" />
  10. <meta property="og:description" content="Contents: Design and History FAQ- Why does Python use indentation for grouping of statements?, Why am I getting strange results with simple arithmetic operations?, Why are floating-point calculatio..." />
  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="Contents: Design and History FAQ- Why does Python use indentation for grouping of statements?, Why am I getting strange results with simple arithmetic operations?, Why are floating-point calculatio..." />
  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>Design and History FAQ &#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="Library and Extension FAQ" href="library.html" />
  33. <link rel="prev" title="Programming FAQ" href="programming.html" />
  34. <link rel="canonical" href="https://docs.python.org/3/faq/design.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="#">Design and History FAQ</a><ul>
  86. <li><a class="reference internal" href="#why-does-python-use-indentation-for-grouping-of-statements">Why does Python use indentation for grouping of statements?</a></li>
  87. <li><a class="reference internal" href="#why-am-i-getting-strange-results-with-simple-arithmetic-operations">Why am I getting strange results with simple arithmetic operations?</a></li>
  88. <li><a class="reference internal" href="#why-are-floating-point-calculations-so-inaccurate">Why are floating-point calculations so inaccurate?</a></li>
  89. <li><a class="reference internal" href="#why-are-python-strings-immutable">Why are Python strings immutable?</a></li>
  90. <li><a class="reference internal" href="#why-must-self-be-used-explicitly-in-method-definitions-and-calls">Why must ‘self’ be used explicitly in method definitions and calls?</a></li>
  91. <li><a class="reference internal" href="#why-can-t-i-use-an-assignment-in-an-expression">Why can’t I use an assignment in an expression?</a></li>
  92. <li><a class="reference internal" href="#why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list">Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?</a></li>
  93. <li><a class="reference internal" href="#why-is-join-a-string-method-instead-of-a-list-or-tuple-method">Why is join() a string method instead of a list or tuple method?</a></li>
  94. <li><a class="reference internal" href="#how-fast-are-exceptions">How fast are exceptions?</a></li>
  95. <li><a class="reference internal" href="#why-isn-t-there-a-switch-or-case-statement-in-python">Why isn’t there a switch or case statement in Python?</a></li>
  96. <li><a class="reference internal" href="#can-t-you-emulate-threads-in-the-interpreter-instead-of-relying-on-an-os-specific-thread-implementation">Can’t you emulate threads in the interpreter instead of relying on an OS-specific thread implementation?</a></li>
  97. <li><a class="reference internal" href="#why-can-t-lambda-expressions-contain-statements">Why can’t lambda expressions contain statements?</a></li>
  98. <li><a class="reference internal" href="#can-python-be-compiled-to-machine-code-c-or-some-other-language">Can Python be compiled to machine code, C or some other language?</a></li>
  99. <li><a class="reference internal" href="#how-does-python-manage-memory">How does Python manage memory?</a></li>
  100. <li><a class="reference internal" href="#why-doesn-t-cpython-use-a-more-traditional-garbage-collection-scheme">Why doesn’t CPython use a more traditional garbage collection scheme?</a></li>
  101. <li><a class="reference internal" href="#why-isn-t-all-memory-freed-when-cpython-exits">Why isn’t all memory freed when CPython exits?</a></li>
  102. <li><a class="reference internal" href="#why-are-there-separate-tuple-and-list-data-types">Why are there separate tuple and list data types?</a></li>
  103. <li><a class="reference internal" href="#how-are-lists-implemented-in-cpython">How are lists implemented in CPython?</a></li>
  104. <li><a class="reference internal" href="#how-are-dictionaries-implemented-in-cpython">How are dictionaries implemented in CPython?</a></li>
  105. <li><a class="reference internal" href="#why-must-dictionary-keys-be-immutable">Why must dictionary keys be immutable?</a></li>
  106. <li><a class="reference internal" href="#why-doesn-t-list-sort-return-the-sorted-list">Why doesn’t list.sort() return the sorted list?</a></li>
  107. <li><a class="reference internal" href="#how-do-you-specify-and-enforce-an-interface-spec-in-python">How do you specify and enforce an interface spec in Python?</a></li>
  108. <li><a class="reference internal" href="#why-is-there-no-goto">Why is there no goto?</a></li>
  109. <li><a class="reference internal" href="#why-can-t-raw-strings-r-strings-end-with-a-backslash">Why can’t raw strings (r-strings) end with a backslash?</a></li>
  110. <li><a class="reference internal" href="#why-doesn-t-python-have-a-with-statement-for-attribute-assignments">Why doesn’t Python have a “with” statement for attribute assignments?</a></li>
  111. <li><a class="reference internal" href="#why-don-t-generators-support-the-with-statement">Why don’t generators support the with statement?</a></li>
  112. <li><a class="reference internal" href="#why-are-colons-required-for-the-if-while-def-class-statements">Why are colons required for the if/while/def/class statements?</a></li>
  113. <li><a class="reference internal" href="#why-does-python-allow-commas-at-the-end-of-lists-and-tuples">Why does Python allow commas at the end of lists and tuples?</a></li>
  114. </ul>
  115. </li>
  116. </ul>
  117. </div>
  118. <div>
  119. <h4>Previous topic</h4>
  120. <p class="topless"><a href="programming.html"
  121. title="previous chapter">Programming FAQ</a></p>
  122. </div>
  123. <div>
  124. <h4>Next topic</h4>
  125. <p class="topless"><a href="library.html"
  126. title="next chapter">Library and Extension FAQ</a></p>
  127. </div>
  128. <div role="note" aria-label="source link">
  129. <h3>This Page</h3>
  130. <ul class="this-page-menu">
  131. <li><a href="../bugs.html">Report a Bug</a></li>
  132. <li>
  133. <a href="https://github.com/python/cpython/blob/main/Doc/faq/design.rst"
  134. rel="nofollow">Show Source
  135. </a>
  136. </li>
  137. </ul>
  138. </div>
  139. </nav>
  140. </div>
  141. </div>
  142. <div class="related" role="navigation" aria-label="related navigation">
  143. <h3>Navigation</h3>
  144. <ul>
  145. <li class="right" style="margin-right: 10px">
  146. <a href="../genindex.html" title="General Index"
  147. accesskey="I">index</a></li>
  148. <li class="right" >
  149. <a href="../py-modindex.html" title="Python Module Index"
  150. >modules</a> |</li>
  151. <li class="right" >
  152. <a href="library.html" title="Library and Extension FAQ"
  153. accesskey="N">next</a> |</li>
  154. <li class="right" >
  155. <a href="programming.html" title="Programming FAQ"
  156. accesskey="P">previous</a> |</li>
  157. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  158. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  159. <li class="switchers">
  160. <div class="language_switcher_placeholder"></div>
  161. <div class="version_switcher_placeholder"></div>
  162. </li>
  163. <li>
  164. </li>
  165. <li id="cpython-language-and-version">
  166. <a href="../index.html">3.12.3 Documentation</a> &#187;
  167. </li>
  168. <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python Frequently Asked Questions</a> &#187;</li>
  169. <li class="nav-item nav-item-this"><a href="">Design and History FAQ</a></li>
  170. <li class="right">
  171. <div class="inline-search" role="search">
  172. <form class="inline-search" action="../search.html" method="get">
  173. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  174. <input type="submit" value="Go" />
  175. </form>
  176. </div>
  177. |
  178. </li>
  179. <li class="right">
  180. <label class="theme-selector-label">
  181. Theme
  182. <select class="theme-selector" oninput="activateTheme(this.value)">
  183. <option value="auto" selected>Auto</option>
  184. <option value="light">Light</option>
  185. <option value="dark">Dark</option>
  186. </select>
  187. </label> |</li>
  188. </ul>
  189. </div>
  190. <div class="document">
  191. <div class="documentwrapper">
  192. <div class="bodywrapper">
  193. <div class="body" role="main">
  194. <section id="design-and-history-faq">
  195. <h1><a class="toc-backref" href="#id2" role="doc-backlink">Design and History FAQ</a><a class="headerlink" href="#design-and-history-faq" title="Link to this heading">¶</a></h1>
  196. <nav class="contents" id="contents">
  197. <p class="topic-title">Contents</p>
  198. <ul class="simple">
  199. <li><p><a class="reference internal" href="#design-and-history-faq" id="id2">Design and History FAQ</a></p>
  200. <ul>
  201. <li><p><a class="reference internal" href="#why-does-python-use-indentation-for-grouping-of-statements" id="id3">Why does Python use indentation for grouping of statements?</a></p></li>
  202. <li><p><a class="reference internal" href="#why-am-i-getting-strange-results-with-simple-arithmetic-operations" id="id4">Why am I getting strange results with simple arithmetic operations?</a></p></li>
  203. <li><p><a class="reference internal" href="#why-are-floating-point-calculations-so-inaccurate" id="id5">Why are floating-point calculations so inaccurate?</a></p></li>
  204. <li><p><a class="reference internal" href="#why-are-python-strings-immutable" id="id6">Why are Python strings immutable?</a></p></li>
  205. <li><p><a class="reference internal" href="#why-must-self-be-used-explicitly-in-method-definitions-and-calls" id="id7">Why must ‘self’ be used explicitly in method definitions and calls?</a></p></li>
  206. <li><p><a class="reference internal" href="#why-can-t-i-use-an-assignment-in-an-expression" id="id8">Why can’t I use an assignment in an expression?</a></p></li>
  207. <li><p><a class="reference internal" href="#why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list" id="id9">Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?</a></p></li>
  208. <li><p><a class="reference internal" href="#why-is-join-a-string-method-instead-of-a-list-or-tuple-method" id="id10">Why is join() a string method instead of a list or tuple method?</a></p></li>
  209. <li><p><a class="reference internal" href="#how-fast-are-exceptions" id="id11">How fast are exceptions?</a></p></li>
  210. <li><p><a class="reference internal" href="#why-isn-t-there-a-switch-or-case-statement-in-python" id="id12">Why isn’t there a switch or case statement in Python?</a></p></li>
  211. <li><p><a class="reference internal" href="#can-t-you-emulate-threads-in-the-interpreter-instead-of-relying-on-an-os-specific-thread-implementation" id="id13">Can’t you emulate threads in the interpreter instead of relying on an OS-specific thread implementation?</a></p></li>
  212. <li><p><a class="reference internal" href="#why-can-t-lambda-expressions-contain-statements" id="id14">Why can’t lambda expressions contain statements?</a></p></li>
  213. <li><p><a class="reference internal" href="#can-python-be-compiled-to-machine-code-c-or-some-other-language" id="id15">Can Python be compiled to machine code, C or some other language?</a></p></li>
  214. <li><p><a class="reference internal" href="#how-does-python-manage-memory" id="id16">How does Python manage memory?</a></p></li>
  215. <li><p><a class="reference internal" href="#why-doesn-t-cpython-use-a-more-traditional-garbage-collection-scheme" id="id17">Why doesn’t CPython use a more traditional garbage collection scheme?</a></p></li>
  216. <li><p><a class="reference internal" href="#why-isn-t-all-memory-freed-when-cpython-exits" id="id18">Why isn’t all memory freed when CPython exits?</a></p></li>
  217. <li><p><a class="reference internal" href="#why-are-there-separate-tuple-and-list-data-types" id="id19">Why are there separate tuple and list data types?</a></p></li>
  218. <li><p><a class="reference internal" href="#how-are-lists-implemented-in-cpython" id="id20">How are lists implemented in CPython?</a></p></li>
  219. <li><p><a class="reference internal" href="#how-are-dictionaries-implemented-in-cpython" id="id21">How are dictionaries implemented in CPython?</a></p></li>
  220. <li><p><a class="reference internal" href="#why-must-dictionary-keys-be-immutable" id="id22">Why must dictionary keys be immutable?</a></p></li>
  221. <li><p><a class="reference internal" href="#why-doesn-t-list-sort-return-the-sorted-list" id="id23">Why doesn’t list.sort() return the sorted list?</a></p></li>
  222. <li><p><a class="reference internal" href="#how-do-you-specify-and-enforce-an-interface-spec-in-python" id="id24">How do you specify and enforce an interface spec in Python?</a></p></li>
  223. <li><p><a class="reference internal" href="#why-is-there-no-goto" id="id25">Why is there no goto?</a></p></li>
  224. <li><p><a class="reference internal" href="#why-can-t-raw-strings-r-strings-end-with-a-backslash" id="id26">Why can’t raw strings (r-strings) end with a backslash?</a></p></li>
  225. <li><p><a class="reference internal" href="#why-doesn-t-python-have-a-with-statement-for-attribute-assignments" id="id27">Why doesn’t Python have a “with” statement for attribute assignments?</a></p></li>
  226. <li><p><a class="reference internal" href="#why-don-t-generators-support-the-with-statement" id="id28">Why don’t generators support the with statement?</a></p></li>
  227. <li><p><a class="reference internal" href="#why-are-colons-required-for-the-if-while-def-class-statements" id="id29">Why are colons required for the if/while/def/class statements?</a></p></li>
  228. <li><p><a class="reference internal" href="#why-does-python-allow-commas-at-the-end-of-lists-and-tuples" id="id30">Why does Python allow commas at the end of lists and tuples?</a></p></li>
  229. </ul>
  230. </li>
  231. </ul>
  232. </nav>
  233. <section id="why-does-python-use-indentation-for-grouping-of-statements">
  234. <h2><a class="toc-backref" href="#id3" role="doc-backlink">Why does Python use indentation for grouping of statements?</a><a class="headerlink" href="#why-does-python-use-indentation-for-grouping-of-statements" title="Link to this heading">¶</a></h2>
  235. <p>Guido van Rossum believes that using indentation for grouping is extremely
  236. elegant and contributes a lot to the clarity of the average Python program.
  237. Most people learn to love this feature after a while.</p>
  238. <p>Since there are no begin/end brackets there cannot be a disagreement between
  239. grouping perceived by the parser and the human reader. Occasionally C
  240. programmers will encounter a fragment of code like this:</p>
  241. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="p">(</span><span class="n">x</span> <span class="o">&lt;=</span> <span class="n">y</span><span class="p">)</span>
  242. <span class="n">x</span><span class="o">++</span><span class="p">;</span>
  243. <span class="n">y</span><span class="o">--</span><span class="p">;</span>
  244. <span class="n">z</span><span class="o">++</span><span class="p">;</span>
  245. </pre></div>
  246. </div>
  247. <p>Only the <code class="docutils literal notranslate"><span class="pre">x++</span></code> statement is executed if the condition is true, but the
  248. indentation leads many to believe otherwise. Even experienced C programmers will
  249. sometimes stare at it a long time wondering as to why <code class="docutils literal notranslate"><span class="pre">y</span></code> is being decremented even
  250. for <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&gt;</span> <span class="pre">y</span></code>.</p>
  251. <p>Because there are no begin/end brackets, Python is much less prone to
  252. coding-style conflicts. In C there are many different ways to place the braces.
  253. After becoming used to reading and writing code using a particular style,
  254. it is normal to feel somewhat uneasy when reading (or being required to write)
  255. in a different one.</p>
  256. <p>Many coding styles place begin/end brackets on a line by themselves. This makes
  257. programs considerably longer and wastes valuable screen space, making it harder
  258. to get a good overview of a program. Ideally, a function should fit on one
  259. screen (say, 20–30 lines). 20 lines of Python can do a lot more work than 20
  260. lines of C. This is not solely due to the lack of begin/end brackets – the
  261. lack of declarations and the high-level data types are also responsible – but
  262. the indentation-based syntax certainly helps.</p>
  263. </section>
  264. <section id="why-am-i-getting-strange-results-with-simple-arithmetic-operations">
  265. <h2><a class="toc-backref" href="#id4" role="doc-backlink">Why am I getting strange results with simple arithmetic operations?</a><a class="headerlink" href="#why-am-i-getting-strange-results-with-simple-arithmetic-operations" title="Link to this heading">¶</a></h2>
  266. <p>See the next question.</p>
  267. </section>
  268. <section id="why-are-floating-point-calculations-so-inaccurate">
  269. <h2><a class="toc-backref" href="#id5" role="doc-backlink">Why are floating-point calculations so inaccurate?</a><a class="headerlink" href="#why-are-floating-point-calculations-so-inaccurate" title="Link to this heading">¶</a></h2>
  270. <p>Users are often surprised by results like this:</p>
  271. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mf">1.2</span> <span class="o">-</span> <span class="mf">1.0</span>
  272. <span class="go">0.19999999999999996</span>
  273. </pre></div>
  274. </div>
  275. <p>and think it is a bug in Python. It’s not. This has little to do with Python,
  276. and much more to do with how the underlying platform handles floating-point
  277. numbers.</p>
  278. <p>The <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a> type in CPython uses a C <code class="docutils literal notranslate"><span class="pre">double</span></code> for storage. A
  279. <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a> object’s value is stored in binary floating-point with a fixed
  280. precision (typically 53 bits) and Python uses C operations, which in turn rely
  281. on the hardware implementation in the processor, to perform floating-point
  282. operations. This means that as far as floating-point operations are concerned,
  283. Python behaves like many popular languages including C and Java.</p>
  284. <p>Many numbers that can be written easily in decimal notation cannot be expressed
  285. exactly in binary floating-point. For example, after:</p>
  286. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="mf">1.2</span>
  287. </pre></div>
  288. </div>
  289. <p>the value stored for <code class="docutils literal notranslate"><span class="pre">x</span></code> is a (very good) approximation to the decimal value
  290. <code class="docutils literal notranslate"><span class="pre">1.2</span></code>, but is not exactly equal to it. On a typical machine, the actual
  291. stored value is:</p>
  292. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="mf">1.0011001100110011001100110011001100110011001100110011</span> <span class="p">(</span><span class="n">binary</span><span class="p">)</span>
  293. </pre></div>
  294. </div>
  295. <p>which is exactly:</p>
  296. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="mf">1.1999999999999999555910790149937383830547332763671875</span> <span class="p">(</span><span class="n">decimal</span><span class="p">)</span>
  297. </pre></div>
  298. </div>
  299. <p>The typical precision of 53 bits provides Python floats with 15–16
  300. decimal digits of accuracy.</p>
  301. <p>For a fuller explanation, please see the <a class="reference internal" href="../tutorial/floatingpoint.html#tut-fp-issues"><span class="std std-ref">floating point arithmetic</span></a> chapter in the Python tutorial.</p>
  302. </section>
  303. <section id="why-are-python-strings-immutable">
  304. <h2><a class="toc-backref" href="#id6" role="doc-backlink">Why are Python strings immutable?</a><a class="headerlink" href="#why-are-python-strings-immutable" title="Link to this heading">¶</a></h2>
  305. <p>There are several advantages.</p>
  306. <p>One is performance: knowing that a string is immutable means we can allocate
  307. space for it at creation time, and the storage requirements are fixed and
  308. unchanging. This is also one of the reasons for the distinction between tuples
  309. and lists.</p>
  310. <p>Another advantage is that strings in Python are considered as “elemental” as
  311. numbers. No amount of activity will change the value 8 to anything else, and in
  312. Python, no amount of activity will change the string “eight” to anything else.</p>
  313. </section>
  314. <section id="why-must-self-be-used-explicitly-in-method-definitions-and-calls">
  315. <span id="why-self"></span><h2><a class="toc-backref" href="#id7" role="doc-backlink">Why must ‘self’ be used explicitly in method definitions and calls?</a><a class="headerlink" href="#why-must-self-be-used-explicitly-in-method-definitions-and-calls" title="Link to this heading">¶</a></h2>
  316. <p>The idea was borrowed from Modula-3. It turns out to be very useful, for a
  317. variety of reasons.</p>
  318. <p>First, it’s more obvious that you are using a method or instance attribute
  319. instead of a local variable. Reading <code class="docutils literal notranslate"><span class="pre">self.x</span></code> or <code class="docutils literal notranslate"><span class="pre">self.meth()</span></code> makes it
  320. absolutely clear that an instance variable or method is used even if you don’t
  321. know the class definition by heart. In C++, you can sort of tell by the lack of
  322. a local variable declaration (assuming globals are rare or easily recognizable)
  323. – but in Python, there are no local variable declarations, so you’d have to
  324. look up the class definition to be sure. Some C++ and Java coding standards
  325. call for instance attributes to have an <code class="docutils literal notranslate"><span class="pre">m_</span></code> prefix, so this explicitness is
  326. still useful in those languages, too.</p>
  327. <p>Second, it means that no special syntax is necessary if you want to explicitly
  328. reference or call the method from a particular class. In C++, if you want to
  329. use a method from a base class which is overridden in a derived class, you have
  330. to use the <code class="docutils literal notranslate"><span class="pre">::</span></code> operator – in Python you can write
  331. <code class="docutils literal notranslate"><span class="pre">baseclass.methodname(self,</span> <span class="pre">&lt;argument</span> <span class="pre">list&gt;)</span></code>. This is particularly useful
  332. for <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> methods, and in general in cases where a derived class
  333. method wants to extend the base class method of the same name and thus has to
  334. call the base class method somehow.</p>
  335. <p>Finally, for instance variables it solves a syntactic problem with assignment:
  336. since local variables in Python are (by definition!) those variables to which a
  337. value is assigned in a function body (and that aren’t explicitly declared
  338. global), there has to be some way to tell the interpreter that an assignment was
  339. meant to assign to an instance variable instead of to a local variable, and it
  340. should preferably be syntactic (for efficiency reasons). C++ does this through
  341. declarations, but Python doesn’t have declarations and it would be a pity having
  342. to introduce them just for this purpose. Using the explicit <code class="docutils literal notranslate"><span class="pre">self.var</span></code> solves
  343. this nicely. Similarly, for using instance variables, having to write
  344. <code class="docutils literal notranslate"><span class="pre">self.var</span></code> means that references to unqualified names inside a method don’t
  345. have to search the instance’s directories. To put it another way, local
  346. variables and instance variables live in two different namespaces, and you need
  347. to tell Python which namespace to use.</p>
  348. </section>
  349. <section id="why-can-t-i-use-an-assignment-in-an-expression">
  350. <span id="id1"></span><h2><a class="toc-backref" href="#id8" role="doc-backlink">Why can’t I use an assignment in an expression?</a><a class="headerlink" href="#why-can-t-i-use-an-assignment-in-an-expression" title="Link to this heading">¶</a></h2>
  351. <p>Starting in Python 3.8, you can!</p>
  352. <p>Assignment expressions using the walrus operator <code class="docutils literal notranslate"><span class="pre">:=</span></code> assign a variable in an
  353. expression:</p>
  354. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">while</span> <span class="n">chunk</span> <span class="o">:=</span> <span class="n">fp</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">200</span><span class="p">):</span>
  355. <span class="nb">print</span><span class="p">(</span><span class="n">chunk</span><span class="p">)</span>
  356. </pre></div>
  357. </div>
  358. <p>See <span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0572/"><strong>PEP 572</strong></a> for more information.</p>
  359. </section>
  360. <section id="why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list">
  361. <h2><a class="toc-backref" href="#id9" role="doc-backlink">Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?</a><a class="headerlink" href="#why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list" title="Link to this heading">¶</a></h2>
  362. <p>As Guido said:</p>
  363. <blockquote>
  364. <div><p>(a) For some operations, prefix notation just reads better than
  365. postfix – prefix (and infix!) operations have a long tradition in
  366. mathematics which likes notations where the visuals help the
  367. mathematician thinking about a problem. Compare the easy with which we
  368. rewrite a formula like x*(a+b) into x*a + x*b to the clumsiness of
  369. doing the same thing using a raw OO notation.</p>
  370. <p>(b) When I read code that says len(x) I <em>know</em> that it is asking for
  371. the length of something. This tells me two things: the result is an
  372. integer, and the argument is some kind of container. To the contrary,
  373. when I read x.len(), I have to already know that x is some kind of
  374. container implementing an interface or inheriting from a class that
  375. has a standard len(). Witness the confusion we occasionally have when
  376. a class that is not implementing a mapping has a get() or keys()
  377. method, or something that isn’t a file has a write() method.</p>
  378. <p class="attribution">—<a class="reference external" href="https://mail.python.org/pipermail/python-3000/2006-November/004643.html">https://mail.python.org/pipermail/python-3000/2006-November/004643.html</a></p>
  379. </div></blockquote>
  380. </section>
  381. <section id="why-is-join-a-string-method-instead-of-a-list-or-tuple-method">
  382. <h2><a class="toc-backref" href="#id10" role="doc-backlink">Why is join() a string method instead of a list or tuple method?</a><a class="headerlink" href="#why-is-join-a-string-method-instead-of-a-list-or-tuple-method" title="Link to this heading">¶</a></h2>
  383. <p>Strings became much more like other standard types starting in Python 1.6, when
  384. methods were added which give the same functionality that has always been
  385. available using the functions of the string module. Most of these new methods
  386. have been widely accepted, but the one which appears to make some programmers
  387. feel uncomfortable is:</p>
  388. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="s2">&quot;, &quot;</span><span class="o">.</span><span class="n">join</span><span class="p">([</span><span class="s1">&#39;1&#39;</span><span class="p">,</span> <span class="s1">&#39;2&#39;</span><span class="p">,</span> <span class="s1">&#39;4&#39;</span><span class="p">,</span> <span class="s1">&#39;8&#39;</span><span class="p">,</span> <span class="s1">&#39;16&#39;</span><span class="p">])</span>
  389. </pre></div>
  390. </div>
  391. <p>which gives the result:</p>
  392. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="s2">&quot;1, 2, 4, 8, 16&quot;</span>
  393. </pre></div>
  394. </div>
  395. <p>There are two common arguments against this usage.</p>
  396. <p>The first runs along the lines of: “It looks really ugly using a method of a
  397. string literal (string constant)”, to which the answer is that it might, but a
  398. string literal is just a fixed value. If the methods are to be allowed on names
  399. bound to strings there is no logical reason to make them unavailable on
  400. literals.</p>
  401. <p>The second objection is typically cast as: “I am really telling a sequence to
  402. join its members together with a string constant”. Sadly, you aren’t. For some
  403. reason there seems to be much less difficulty with having <a class="reference internal" href="../library/stdtypes.html#str.split" title="str.split"><code class="xref py py-meth docutils literal notranslate"><span class="pre">split()</span></code></a> as
  404. a string method, since in that case it is easy to see that</p>
  405. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="s2">&quot;1, 2, 4, 8, 16&quot;</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">&quot;, &quot;</span><span class="p">)</span>
  406. </pre></div>
  407. </div>
  408. <p>is an instruction to a string literal to return the substrings delimited by the
  409. given separator (or, by default, arbitrary runs of white space).</p>
  410. <p><a class="reference internal" href="../library/stdtypes.html#str.join" title="str.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> is a string method because in using it you are telling the
  411. separator string to iterate over a sequence of strings and insert itself between
  412. adjacent elements. This method can be used with any argument which obeys the
  413. rules for sequence objects, including any new classes you might define yourself.
  414. Similar methods exist for bytes and bytearray objects.</p>
  415. </section>
  416. <section id="how-fast-are-exceptions">
  417. <h2><a class="toc-backref" href="#id11" role="doc-backlink">How fast are exceptions?</a><a class="headerlink" href="#how-fast-are-exceptions" title="Link to this heading">¶</a></h2>
  418. <p>A <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>/<a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> block is extremely efficient if no exceptions
  419. are raised. Actually
  420. catching an exception is expensive. In versions of Python prior to 2.0 it was
  421. common to use this idiom:</p>
  422. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
  423. <span class="n">value</span> <span class="o">=</span> <span class="n">mydict</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>
  424. <span class="k">except</span> <span class="ne">KeyError</span><span class="p">:</span>
  425. <span class="n">mydict</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="n">getvalue</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
  426. <span class="n">value</span> <span class="o">=</span> <span class="n">mydict</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>
  427. </pre></div>
  428. </div>
  429. <p>This only made sense when you expected the dict to have the key almost all the
  430. time. If that wasn’t the case, you coded it like this:</p>
  431. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">mydict</span><span class="p">:</span>
  432. <span class="n">value</span> <span class="o">=</span> <span class="n">mydict</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>
  433. <span class="k">else</span><span class="p">:</span>
  434. <span class="n">value</span> <span class="o">=</span> <span class="n">mydict</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="n">getvalue</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
  435. </pre></div>
  436. </div>
  437. <p>For this specific case, you could also use <code class="docutils literal notranslate"><span class="pre">value</span> <span class="pre">=</span> <span class="pre">dict.setdefault(key,</span>
  438. <span class="pre">getvalue(key))</span></code>, but only if the <code class="docutils literal notranslate"><span class="pre">getvalue()</span></code> call is cheap enough because it
  439. is evaluated in all cases.</p>
  440. </section>
  441. <section id="why-isn-t-there-a-switch-or-case-statement-in-python">
  442. <h2><a class="toc-backref" href="#id12" role="doc-backlink">Why isn’t there a switch or case statement in Python?</a><a class="headerlink" href="#why-isn-t-there-a-switch-or-case-statement-in-python" title="Link to this heading">¶</a></h2>
  443. <p>In general, structured switch statements execute one block of code
  444. when an expression has a particular value or set of values.
  445. Since Python 3.10 one can easily match literal values, or constants
  446. within a namespace, with a <code class="docutils literal notranslate"><span class="pre">match</span> <span class="pre">...</span> <span class="pre">case</span></code> statement.
  447. An older alternative is a sequence of <code class="docutils literal notranslate"><span class="pre">if...</span> <span class="pre">elif...</span> <span class="pre">elif...</span> <span class="pre">else</span></code>.</p>
  448. <p>For cases where you need to choose from a very large number of possibilities,
  449. you can create a dictionary mapping case values to functions to call. For
  450. example:</p>
  451. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">functions</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;a&#39;</span><span class="p">:</span> <span class="n">function_1</span><span class="p">,</span>
  452. <span class="s1">&#39;b&#39;</span><span class="p">:</span> <span class="n">function_2</span><span class="p">,</span>
  453. <span class="s1">&#39;c&#39;</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">method_1</span><span class="p">}</span>
  454. <span class="n">func</span> <span class="o">=</span> <span class="n">functions</span><span class="p">[</span><span class="n">value</span><span class="p">]</span>
  455. <span class="n">func</span><span class="p">()</span>
  456. </pre></div>
  457. </div>
  458. <p>For calling methods on objects, you can simplify yet further by using the
  459. <a class="reference internal" href="../library/functions.html#getattr" title="getattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">getattr()</span></code></a> built-in to retrieve methods with a particular name:</p>
  460. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyVisitor</span><span class="p">:</span>
  461. <span class="k">def</span> <span class="nf">visit_a</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  462. <span class="o">...</span>
  463. <span class="k">def</span> <span class="nf">dispatch</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
  464. <span class="n">method_name</span> <span class="o">=</span> <span class="s1">&#39;visit_&#39;</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
  465. <span class="n">method</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">method_name</span><span class="p">)</span>
  466. <span class="n">method</span><span class="p">()</span>
  467. </pre></div>
  468. </div>
  469. <p>It’s suggested that you use a prefix for the method names, such as <code class="docutils literal notranslate"><span class="pre">visit_</span></code> in
  470. this example. Without such a prefix, if values are coming from an untrusted
  471. source, an attacker would be able to call any method on your object.</p>
  472. <p>Imitating switch with fallthrough, as with C’s switch-case-default,
  473. is possible, much harder, and less needed.</p>
  474. </section>
  475. <section id="can-t-you-emulate-threads-in-the-interpreter-instead-of-relying-on-an-os-specific-thread-implementation">
  476. <h2><a class="toc-backref" href="#id13" role="doc-backlink">Can’t you emulate threads in the interpreter instead of relying on an OS-specific thread implementation?</a><a class="headerlink" href="#can-t-you-emulate-threads-in-the-interpreter-instead-of-relying-on-an-os-specific-thread-implementation" title="Link to this heading">¶</a></h2>
  477. <p>Answer 1: Unfortunately, the interpreter pushes at least one C stack frame for
  478. each Python stack frame. Also, extensions can call back into Python at almost
  479. random moments. Therefore, a complete threads implementation requires thread
  480. support for C.</p>
  481. <p>Answer 2: Fortunately, there is <a class="reference external" href="https://github.com/stackless-dev/stackless/wiki">Stackless Python</a>,
  482. which has a completely redesigned interpreter loop that avoids the C stack.</p>
  483. </section>
  484. <section id="why-can-t-lambda-expressions-contain-statements">
  485. <h2><a class="toc-backref" href="#id14" role="doc-backlink">Why can’t lambda expressions contain statements?</a><a class="headerlink" href="#why-can-t-lambda-expressions-contain-statements" title="Link to this heading">¶</a></h2>
  486. <p>Python lambda expressions cannot contain statements because Python’s syntactic
  487. framework can’t handle statements nested inside expressions. However, in
  488. Python, this is not a serious problem. Unlike lambda forms in other languages,
  489. where they add functionality, Python lambdas are only a shorthand notation if
  490. you’re too lazy to define a function.</p>
  491. <p>Functions are already first class objects in Python, and can be declared in a
  492. local scope. Therefore the only advantage of using a lambda instead of a
  493. locally defined function is that you don’t need to invent a name for the
  494. function – but that’s just a local variable to which the function object (which
  495. is exactly the same type of object that a lambda expression yields) is assigned!</p>
  496. </section>
  497. <section id="can-python-be-compiled-to-machine-code-c-or-some-other-language">
  498. <h2><a class="toc-backref" href="#id15" role="doc-backlink">Can Python be compiled to machine code, C or some other language?</a><a class="headerlink" href="#can-python-be-compiled-to-machine-code-c-or-some-other-language" title="Link to this heading">¶</a></h2>
  499. <p><a class="reference external" href="https://cython.org/">Cython</a> compiles a modified version of Python with
  500. optional annotations into C extensions. <a class="reference external" href="https://www.nuitka.net/">Nuitka</a> is
  501. an up-and-coming compiler of Python into C++ code, aiming to support the full
  502. Python language.</p>
  503. </section>
  504. <section id="how-does-python-manage-memory">
  505. <h2><a class="toc-backref" href="#id16" role="doc-backlink">How does Python manage memory?</a><a class="headerlink" href="#how-does-python-manage-memory" title="Link to this heading">¶</a></h2>
  506. <p>The details of Python memory management depend on the implementation. The
  507. standard implementation of Python, <a class="reference internal" href="../glossary.html#term-CPython"><span class="xref std std-term">CPython</span></a>, uses reference counting to
  508. detect inaccessible objects, and another mechanism to collect reference cycles,
  509. periodically executing a cycle detection algorithm which looks for inaccessible
  510. cycles and deletes the objects involved. The <a class="reference internal" href="../library/gc.html#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gc</span></code></a> module provides functions
  511. to perform a garbage collection, obtain debugging statistics, and tune the
  512. collector’s parameters.</p>
  513. <p>Other implementations (such as <a class="reference external" href="https://www.jython.org">Jython</a> or
  514. <a class="reference external" href="https://www.pypy.org">PyPy</a>), however, can rely on a different mechanism
  515. such as a full-blown garbage collector. This difference can cause some
  516. subtle porting problems if your Python code depends on the behavior of the
  517. reference counting implementation.</p>
  518. <p>In some Python implementations, the following code (which is fine in CPython)
  519. will probably run out of file descriptors:</p>
  520. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">file</span> <span class="ow">in</span> <span class="n">very_long_list_of_files</span><span class="p">:</span>
  521. <span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">file</span><span class="p">)</span>
  522. <span class="n">c</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
  523. </pre></div>
  524. </div>
  525. <p>Indeed, using CPython’s reference counting and destructor scheme, each new
  526. assignment to <code class="docutils literal notranslate"><span class="pre">f</span></code> closes the previous file. With a traditional GC, however,
  527. those file objects will only get collected (and closed) at varying and possibly
  528. long intervals.</p>
  529. <p>If you want to write code that will work with any Python implementation,
  530. you should explicitly close the file or use the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement;
  531. this will work regardless of memory management scheme:</p>
  532. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">file</span> <span class="ow">in</span> <span class="n">very_long_list_of_files</span><span class="p">:</span>
  533. <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">file</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
  534. <span class="n">c</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
  535. </pre></div>
  536. </div>
  537. </section>
  538. <section id="why-doesn-t-cpython-use-a-more-traditional-garbage-collection-scheme">
  539. <h2><a class="toc-backref" href="#id17" role="doc-backlink">Why doesn’t CPython use a more traditional garbage collection scheme?</a><a class="headerlink" href="#why-doesn-t-cpython-use-a-more-traditional-garbage-collection-scheme" title="Link to this heading">¶</a></h2>
  540. <p>For one thing, this is not a C standard feature and hence it’s not portable.
  541. (Yes, we know about the Boehm GC library. It has bits of assembler code for
  542. <em>most</em> common platforms, not for all of them, and although it is mostly
  543. transparent, it isn’t completely transparent; patches are required to get
  544. Python to work with it.)</p>
  545. <p>Traditional GC also becomes a problem when Python is embedded into other
  546. applications. While in a standalone Python it’s fine to replace the standard
  547. <code class="docutils literal notranslate"><span class="pre">malloc()</span></code> and <code class="docutils literal notranslate"><span class="pre">free()</span></code> with versions provided by the GC library, an application
  548. embedding Python may want to have its <em>own</em> substitute for <code class="docutils literal notranslate"><span class="pre">malloc()</span></code> and <code class="docutils literal notranslate"><span class="pre">free()</span></code>,
  549. and may not want Python’s. Right now, CPython works with anything that
  550. implements <code class="docutils literal notranslate"><span class="pre">malloc()</span></code> and <code class="docutils literal notranslate"><span class="pre">free()</span></code> properly.</p>
  551. </section>
  552. <section id="why-isn-t-all-memory-freed-when-cpython-exits">
  553. <h2><a class="toc-backref" href="#id18" role="doc-backlink">Why isn’t all memory freed when CPython exits?</a><a class="headerlink" href="#why-isn-t-all-memory-freed-when-cpython-exits" title="Link to this heading">¶</a></h2>
  554. <p>Objects referenced from the global namespaces of Python modules are not always
  555. deallocated when Python exits. This may happen if there are circular
  556. references. There are also certain bits of memory that are allocated by the C
  557. library that are impossible to free (e.g. a tool like Purify will complain about
  558. these). Python is, however, aggressive about cleaning up memory on exit and
  559. does try to destroy every single object.</p>
  560. <p>If you want to force Python to delete certain things on deallocation use the
  561. <a class="reference internal" href="../library/atexit.html#module-atexit" title="atexit: Register and execute cleanup functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">atexit</span></code></a> module to run a function that will force those deletions.</p>
  562. </section>
  563. <section id="why-are-there-separate-tuple-and-list-data-types">
  564. <h2><a class="toc-backref" href="#id19" role="doc-backlink">Why are there separate tuple and list data types?</a><a class="headerlink" href="#why-are-there-separate-tuple-and-list-data-types" title="Link to this heading">¶</a></h2>
  565. <p>Lists and tuples, while similar in many respects, are generally used in
  566. fundamentally different ways. Tuples can be thought of as being similar to
  567. Pascal <code class="docutils literal notranslate"><span class="pre">records</span></code> or C <code class="docutils literal notranslate"><span class="pre">structs</span></code>; they’re small collections of related data which may
  568. be of different types which are operated on as a group. For example, a
  569. Cartesian coordinate is appropriately represented as a tuple of two or three
  570. numbers.</p>
  571. <p>Lists, on the other hand, are more like arrays in other languages. They tend to
  572. hold a varying number of objects all of which have the same type and which are
  573. operated on one-by-one. For example, <a class="reference internal" href="../library/os.html#os.listdir" title="os.listdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.listdir('.')</span></code></a>
  574. returns a list of
  575. strings representing the files in the current directory. Functions which
  576. operate on this output would generally not break if you added another file or
  577. two to the directory.</p>
  578. <p>Tuples are immutable, meaning that once a tuple has been created, you can’t
  579. replace any of its elements with a new value. Lists are mutable, meaning that
  580. you can always change a list’s elements. Only immutable elements can be used as
  581. dictionary keys, and hence only tuples and not lists can be used as keys.</p>
  582. </section>
  583. <section id="how-are-lists-implemented-in-cpython">
  584. <h2><a class="toc-backref" href="#id20" role="doc-backlink">How are lists implemented in CPython?</a><a class="headerlink" href="#how-are-lists-implemented-in-cpython" title="Link to this heading">¶</a></h2>
  585. <p>CPython’s lists are really variable-length arrays, not Lisp-style linked lists.
  586. The implementation uses a contiguous array of references to other objects, and
  587. keeps a pointer to this array and the array’s length in a list head structure.</p>
  588. <p>This makes indexing a list <code class="docutils literal notranslate"><span class="pre">a[i]</span></code> an operation whose cost is independent of
  589. the size of the list or the value of the index.</p>
  590. <p>When items are appended or inserted, the array of references is resized. Some
  591. cleverness is applied to improve the performance of appending items repeatedly;
  592. when the array must be grown, some extra space is allocated so the next few
  593. times don’t require an actual resize.</p>
  594. </section>
  595. <section id="how-are-dictionaries-implemented-in-cpython">
  596. <h2><a class="toc-backref" href="#id21" role="doc-backlink">How are dictionaries implemented in CPython?</a><a class="headerlink" href="#how-are-dictionaries-implemented-in-cpython" title="Link to this heading">¶</a></h2>
  597. <p>CPython’s dictionaries are implemented as resizable hash tables. Compared to
  598. B-trees, this gives better performance for lookup (the most common operation by
  599. far) under most circumstances, and the implementation is simpler.</p>
  600. <p>Dictionaries work by computing a hash code for each key stored in the dictionary
  601. using 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> built-in function. The hash code varies widely depending
  602. on the key and a per-process seed; for example, <code class="docutils literal notranslate"><span class="pre">'Python'</span></code> could hash to
  603. <code class="docutils literal notranslate"><span class="pre">-539294296</span></code> while <code class="docutils literal notranslate"><span class="pre">'python'</span></code>, a string that differs by a single bit, could hash
  604. to <code class="docutils literal notranslate"><span class="pre">1142331976</span></code>. The hash code is then used to calculate a location in an
  605. internal array where the value will be stored. Assuming that you’re storing
  606. keys that all have different hash values, this means that dictionaries take
  607. constant time – <em>O</em>(1), in Big-O notation – to retrieve a key.</p>
  608. </section>
  609. <section id="why-must-dictionary-keys-be-immutable">
  610. <h2><a class="toc-backref" href="#id22" role="doc-backlink">Why must dictionary keys be immutable?</a><a class="headerlink" href="#why-must-dictionary-keys-be-immutable" title="Link to this heading">¶</a></h2>
  611. <p>The hash table implementation of dictionaries uses a hash value calculated from
  612. the key value to find the key. If the key were a mutable object, its value
  613. could change, and thus its hash could also change. But since whoever changes
  614. the key object can’t tell that it was being used as a dictionary key, it can’t
  615. move the entry around in the dictionary. Then, when you try to look up the same
  616. object in the dictionary it won’t be found because its hash value is different.
  617. If you tried to look up the old value it wouldn’t be found either, because the
  618. value of the object found in that hash bin would be different.</p>
  619. <p>If you want a dictionary indexed with a list, simply convert the list to a tuple
  620. first; the function <code class="docutils literal notranslate"><span class="pre">tuple(L)</span></code> creates a tuple with the same entries as the
  621. list <code class="docutils literal notranslate"><span class="pre">L</span></code>. Tuples are immutable and can therefore be used as dictionary keys.</p>
  622. <p>Some unacceptable solutions that have been proposed:</p>
  623. <ul>
  624. <li><p>Hash lists by their address (object ID). This doesn’t work because if you
  625. construct a new list with the same value it won’t be found; e.g.:</p>
  626. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">mydict</span> <span class="o">=</span> <span class="p">{[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">]:</span> <span class="s1">&#39;12&#39;</span><span class="p">}</span>
  627. <span class="nb">print</span><span class="p">(</span><span class="n">mydict</span><span class="p">[[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">]])</span>
  628. </pre></div>
  629. </div>
  630. <p>would raise a <a class="reference internal" href="../library/exceptions.html#KeyError" title="KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> exception because the id of the <code class="docutils literal notranslate"><span class="pre">[1,</span> <span class="pre">2]</span></code> used in the
  631. second line differs from that in the first line. In other words, dictionary
  632. keys should be compared using <code class="docutils literal notranslate"><span class="pre">==</span></code>, not using <a class="reference internal" href="../reference/expressions.html#is"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">is</span></code></a>.</p>
  633. </li>
  634. <li><p>Make a copy when using a list as a key. This doesn’t work because the list,
  635. being a mutable object, could contain a reference to itself, and then the
  636. copying code would run into an infinite loop.</p></li>
  637. <li><p>Allow lists as keys but tell the user not to modify them. This would allow a
  638. class of hard-to-track bugs in programs when you forgot or modified a list by
  639. accident. It also invalidates an important invariant of dictionaries: every
  640. value in <code class="docutils literal notranslate"><span class="pre">d.keys()</span></code> is usable as a key of the dictionary.</p></li>
  641. <li><p>Mark lists as read-only once they are used as a dictionary key. The problem
  642. is that it’s not just the top-level object that could change its value; you
  643. could use a tuple containing a list as a key. Entering anything as a key into
  644. a dictionary would require marking all objects reachable from there as
  645. read-only – and again, self-referential objects could cause an infinite loop.</p></li>
  646. </ul>
  647. <p>There is a trick to get around this if you need to, but use it at your own risk:
  648. You can wrap a mutable structure inside a class instance which has both a
  649. <a class="reference internal" href="../reference/datamodel.html#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> and a <a class="reference internal" href="../reference/datamodel.html#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> method.
  650. You must then make sure that the
  651. hash value for all such wrapper objects that reside in a dictionary (or other
  652. hash based structure), remain fixed while the object is in the dictionary (or
  653. other structure).</p>
  654. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">ListWrapper</span><span class="p">:</span>
  655. <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">the_list</span><span class="p">):</span>
  656. <span class="bp">self</span><span class="o">.</span><span class="n">the_list</span> <span class="o">=</span> <span class="n">the_list</span>
  657. <span class="k">def</span> <span class="fm">__eq__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
  658. <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">the_list</span> <span class="o">==</span> <span class="n">other</span><span class="o">.</span><span class="n">the_list</span>
  659. <span class="k">def</span> <span class="fm">__hash__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  660. <span class="n">l</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">the_list</span>
  661. <span class="n">result</span> <span class="o">=</span> <span class="mi">98767</span> <span class="o">-</span> <span class="nb">len</span><span class="p">(</span><span class="n">l</span><span class="p">)</span><span class="o">*</span><span class="mi">555</span>
  662. <span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">el</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">l</span><span class="p">):</span>
  663. <span class="k">try</span><span class="p">:</span>
  664. <span class="n">result</span> <span class="o">=</span> <span class="n">result</span> <span class="o">+</span> <span class="p">(</span><span class="nb">hash</span><span class="p">(</span><span class="n">el</span><span class="p">)</span> <span class="o">%</span> <span class="mi">9999999</span><span class="p">)</span> <span class="o">*</span> <span class="mi">1001</span> <span class="o">+</span> <span class="n">i</span>
  665. <span class="k">except</span> <span class="ne">Exception</span><span class="p">:</span>
  666. <span class="n">result</span> <span class="o">=</span> <span class="p">(</span><span class="n">result</span> <span class="o">%</span> <span class="mi">7777777</span><span class="p">)</span> <span class="o">+</span> <span class="n">i</span> <span class="o">*</span> <span class="mi">333</span>
  667. <span class="k">return</span> <span class="n">result</span>
  668. </pre></div>
  669. </div>
  670. <p>Note that the hash computation is complicated by the possibility that some
  671. members of the list may be unhashable and also by the possibility of arithmetic
  672. overflow.</p>
  673. <p>Furthermore it must always be the case that if <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">==</span> <span class="pre">o2</span></code> (ie <code class="docutils literal notranslate"><span class="pre">o1.__eq__(o2)</span>
  674. <span class="pre">is</span> <span class="pre">True</span></code>) then <code class="docutils literal notranslate"><span class="pre">hash(o1)</span> <span class="pre">==</span> <span class="pre">hash(o2)</span></code> (ie, <code class="docutils literal notranslate"><span class="pre">o1.__hash__()</span> <span class="pre">==</span> <span class="pre">o2.__hash__()</span></code>),
  675. regardless of whether the object is in a dictionary or not. If you fail to meet
  676. these restrictions dictionaries and other hash based structures will misbehave.</p>
  677. <p>In the case of <code class="xref py py-class docutils literal notranslate"><span class="pre">ListWrapper</span></code>, whenever the wrapper object is in a dictionary the
  678. wrapped list must not change to avoid anomalies. Don’t do this unless you are
  679. prepared to think hard about the requirements and the consequences of not
  680. meeting them correctly. Consider yourself warned.</p>
  681. </section>
  682. <section id="why-doesn-t-list-sort-return-the-sorted-list">
  683. <h2><a class="toc-backref" href="#id23" role="doc-backlink">Why doesn’t list.sort() return the sorted list?</a><a class="headerlink" href="#why-doesn-t-list-sort-return-the-sorted-list" title="Link to this heading">¶</a></h2>
  684. <p>In situations where performance matters, making a copy of the list just to sort
  685. it would be wasteful. Therefore, <a class="reference internal" href="../library/stdtypes.html#list.sort" title="list.sort"><code class="xref py py-meth docutils literal notranslate"><span class="pre">list.sort()</span></code></a> sorts the list in place. In
  686. order to remind you of that fact, it does not return the sorted list. This way,
  687. you won’t be fooled into accidentally overwriting a list when you need a sorted
  688. copy but also need to keep the unsorted version around.</p>
  689. <p>If you want to return a new list, use the built-in <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> function
  690. instead. This function creates a new list from a provided iterable, sorts
  691. it and returns it. For example, here’s how to iterate over the keys of a
  692. dictionary in sorted order:</p>
  693. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">key</span> <span class="ow">in</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">mydict</span><span class="p">):</span>
  694. <span class="o">...</span> <span class="c1"># do whatever with mydict[key]...</span>
  695. </pre></div>
  696. </div>
  697. </section>
  698. <section id="how-do-you-specify-and-enforce-an-interface-spec-in-python">
  699. <h2><a class="toc-backref" href="#id24" role="doc-backlink">How do you specify and enforce an interface spec in Python?</a><a class="headerlink" href="#how-do-you-specify-and-enforce-an-interface-spec-in-python" title="Link to this heading">¶</a></h2>
  700. <p>An interface specification for a module as provided by languages such as C++ and
  701. Java describes the prototypes for the methods and functions of the module. Many
  702. feel that compile-time enforcement of interface specifications helps in the
  703. construction of large programs.</p>
  704. <p>Python 2.6 adds an <a class="reference internal" href="../library/abc.html#module-abc" title="abc: Abstract base classes according to :pep:`3119`."><code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code></a> module that lets you define Abstract Base Classes
  705. (ABCs). You can then use <a class="reference internal" href="../library/functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a> and <a class="reference internal" href="../library/functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal notranslate"><span class="pre">issubclass()</span></code></a> to check
  706. whether an instance or a class implements a particular ABC. The
  707. <a class="reference internal" href="../library/collections.abc.html#module-collections.abc" title="collections.abc: Abstract base classes for containers"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections.abc</span></code></a> module defines a set of useful ABCs such as
  708. <a class="reference internal" href="../library/collections.abc.html#collections.abc.Iterable" title="collections.abc.Iterable"><code class="xref py py-class docutils literal notranslate"><span class="pre">Iterable</span></code></a>, <a class="reference internal" href="../library/collections.abc.html#collections.abc.Container" title="collections.abc.Container"><code class="xref py py-class docutils literal notranslate"><span class="pre">Container</span></code></a>, and
  709. <a class="reference internal" href="../library/collections.abc.html#collections.abc.MutableMapping" title="collections.abc.MutableMapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">MutableMapping</span></code></a>.</p>
  710. <p>For Python, many of the advantages of interface specifications can be obtained
  711. by an appropriate test discipline for components.</p>
  712. <p>A good test suite for a module can both provide a regression test and serve as a
  713. module interface specification and a set of examples. Many Python modules can
  714. be run as a script to provide a simple “self test.” Even modules which use
  715. complex external interfaces can often be tested in isolation using trivial
  716. “stub” emulations of the external interface. The <a class="reference internal" href="../library/doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> and
  717. <a class="reference internal" href="../library/unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> modules or third-party test frameworks can be used to construct
  718. exhaustive test suites that exercise every line of code in a module.</p>
  719. <p>An appropriate testing discipline can help build large complex applications in
  720. Python as well as having interface specifications would. In fact, it can be
  721. better because an interface specification cannot test certain properties of a
  722. program. For example, the <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.append()</span></code> method is expected to add new elements
  723. to the end of some internal list; an interface specification cannot test that
  724. your <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.append()</span></code> implementation will actually do this correctly, but it’s
  725. trivial to check this property in a test suite.</p>
  726. <p>Writing test suites is very helpful, and you might want to design your code to
  727. make it easily tested. One increasingly popular technique, test-driven
  728. development, calls for writing parts of the test suite first, before you write
  729. any of the actual code. Of course Python allows you to be sloppy and not write
  730. test cases at all.</p>
  731. </section>
  732. <section id="why-is-there-no-goto">
  733. <h2><a class="toc-backref" href="#id25" role="doc-backlink">Why is there no goto?</a><a class="headerlink" href="#why-is-there-no-goto" title="Link to this heading">¶</a></h2>
  734. <p>In the 1970s people realized that unrestricted goto could lead
  735. to messy “spaghetti” code that was hard to understand and revise.
  736. In a high-level language, it is also unneeded as long as there
  737. are ways to branch (in Python, with <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statements and <a class="reference internal" href="../reference/expressions.html#or"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">or</span></code></a>,
  738. <a class="reference internal" href="../reference/expressions.html#and"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">and</span></code></a>, and <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a>/<a class="reference internal" href="../reference/compound_stmts.html#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> expressions) and loop (with <a class="reference internal" href="../reference/compound_stmts.html#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a>
  739. and <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> statements, possibly containing <a class="reference internal" href="../reference/simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> and <a class="reference internal" href="../reference/simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a>).</p>
  740. <p>One can also use exceptions to provide a “structured goto”
  741. that works even across
  742. function calls. Many feel that exceptions can conveniently emulate all
  743. reasonable uses of the <code class="docutils literal notranslate"><span class="pre">go</span></code> or <code class="docutils literal notranslate"><span class="pre">goto</span></code> constructs of C, Fortran, and other
  744. languages. For example:</p>
  745. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">label</span><span class="p">(</span><span class="ne">Exception</span><span class="p">):</span> <span class="k">pass</span> <span class="c1"># declare a label</span>
  746. <span class="k">try</span><span class="p">:</span>
  747. <span class="o">...</span>
  748. <span class="k">if</span> <span class="n">condition</span><span class="p">:</span> <span class="k">raise</span> <span class="n">label</span><span class="p">()</span> <span class="c1"># goto label</span>
  749. <span class="o">...</span>
  750. <span class="k">except</span> <span class="n">label</span><span class="p">:</span> <span class="c1"># where to goto</span>
  751. <span class="k">pass</span>
  752. <span class="o">...</span>
  753. </pre></div>
  754. </div>
  755. <p>This doesn’t allow you to jump into the middle of a loop, but that’s usually
  756. considered an abuse of <code class="docutils literal notranslate"><span class="pre">goto</span></code> anyway. Use sparingly.</p>
  757. </section>
  758. <section id="why-can-t-raw-strings-r-strings-end-with-a-backslash">
  759. <h2><a class="toc-backref" href="#id26" role="doc-backlink">Why can’t raw strings (r-strings) end with a backslash?</a><a class="headerlink" href="#why-can-t-raw-strings-r-strings-end-with-a-backslash" title="Link to this heading">¶</a></h2>
  760. <p>More precisely, they can’t end with an odd number of backslashes: the unpaired
  761. backslash at the end escapes the closing quote character, leaving an
  762. unterminated string.</p>
  763. <p>Raw strings were designed to ease creating input for processors (chiefly regular
  764. expression engines) that want to do their own backslash escape processing. Such
  765. processors consider an unmatched trailing backslash to be an error anyway, so
  766. raw strings disallow that. In return, they allow you to pass on the string
  767. quote character by escaping it with a backslash. These rules work well when
  768. r-strings are used for their intended purpose.</p>
  769. <p>If you’re trying to build Windows pathnames, note that all Windows system calls
  770. accept forward slashes too:</p>
  771. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s2">&quot;/mydir/file.txt&quot;</span><span class="p">)</span> <span class="c1"># works fine!</span>
  772. </pre></div>
  773. </div>
  774. <p>If you’re trying to build a pathname for a DOS command, try e.g. one of</p>
  775. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nb">dir</span> <span class="o">=</span> <span class="sa">r</span><span class="s2">&quot;\this\is\my\dos\dir&quot;</span> <span class="s2">&quot;</span><span class="se">\\</span><span class="s2">&quot;</span>
  776. <span class="nb">dir</span> <span class="o">=</span> <span class="sa">r</span><span class="s2">&quot;\this\is\my\dos\dir\ &quot;</span><span class="p">[:</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
  777. <span class="nb">dir</span> <span class="o">=</span> <span class="s2">&quot;</span><span class="se">\\</span><span class="s2">this</span><span class="se">\\</span><span class="s2">is</span><span class="se">\\</span><span class="s2">my</span><span class="se">\\</span><span class="s2">dos</span><span class="se">\\</span><span class="s2">dir</span><span class="se">\\</span><span class="s2">&quot;</span>
  778. </pre></div>
  779. </div>
  780. </section>
  781. <section id="why-doesn-t-python-have-a-with-statement-for-attribute-assignments">
  782. <h2><a class="toc-backref" href="#id27" role="doc-backlink">Why doesn’t Python have a “with” statement for attribute assignments?</a><a class="headerlink" href="#why-doesn-t-python-have-a-with-statement-for-attribute-assignments" title="Link to this heading">¶</a></h2>
  783. <p>Python has a <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement that wraps the execution of a block, calling code
  784. on the entrance and exit from the block. Some languages have a construct that
  785. looks like this:</p>
  786. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">obj</span><span class="p">:</span>
  787. <span class="n">a</span> <span class="o">=</span> <span class="mi">1</span> <span class="c1"># equivalent to obj.a = 1</span>
  788. <span class="n">total</span> <span class="o">=</span> <span class="n">total</span> <span class="o">+</span> <span class="mi">1</span> <span class="c1"># obj.total = obj.total + 1</span>
  789. </pre></div>
  790. </div>
  791. <p>In Python, such a construct would be ambiguous.</p>
  792. <p>Other languages, such as Object Pascal, Delphi, and C++, use static types, so
  793. it’s possible to know, in an unambiguous way, what member is being assigned
  794. to. This is the main point of static typing – the compiler <em>always</em> knows the
  795. scope of every variable at compile time.</p>
  796. <p>Python uses dynamic types. It is impossible to know in advance which attribute
  797. will be referenced at runtime. Member attributes may be added or removed from
  798. objects on the fly. This makes it impossible to know, from a simple reading,
  799. what attribute is being referenced: a local one, a global one, or a member
  800. attribute?</p>
  801. <p>For instance, take the following incomplete snippet:</p>
  802. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">a</span><span class="p">):</span>
  803. <span class="k">with</span> <span class="n">a</span><span class="p">:</span>
  804. <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
  805. </pre></div>
  806. </div>
  807. <p>The snippet assumes that <code class="docutils literal notranslate"><span class="pre">a</span></code> must have a member attribute called <code class="docutils literal notranslate"><span class="pre">x</span></code>. However,
  808. there is nothing in Python that tells the interpreter this. What should happen
  809. if <code class="docutils literal notranslate"><span class="pre">a</span></code> is, let us say, an integer? If there is a global variable named <code class="docutils literal notranslate"><span class="pre">x</span></code>,
  810. will it be used inside the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> block? As you see, the dynamic nature of Python
  811. makes such choices much harder.</p>
  812. <p>The primary benefit of <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> and similar language features (reduction of code
  813. volume) can, however, easily be achieved in Python by assignment. Instead of:</p>
  814. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">function</span><span class="p">(</span><span class="n">args</span><span class="p">)</span><span class="o">.</span><span class="n">mydict</span><span class="p">[</span><span class="n">index</span><span class="p">][</span><span class="n">index</span><span class="p">]</span><span class="o">.</span><span class="n">a</span> <span class="o">=</span> <span class="mi">21</span>
  815. <span class="n">function</span><span class="p">(</span><span class="n">args</span><span class="p">)</span><span class="o">.</span><span class="n">mydict</span><span class="p">[</span><span class="n">index</span><span class="p">][</span><span class="n">index</span><span class="p">]</span><span class="o">.</span><span class="n">b</span> <span class="o">=</span> <span class="mi">42</span>
  816. <span class="n">function</span><span class="p">(</span><span class="n">args</span><span class="p">)</span><span class="o">.</span><span class="n">mydict</span><span class="p">[</span><span class="n">index</span><span class="p">][</span><span class="n">index</span><span class="p">]</span><span class="o">.</span><span class="n">c</span> <span class="o">=</span> <span class="mi">63</span>
  817. </pre></div>
  818. </div>
  819. <p>write this:</p>
  820. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">ref</span> <span class="o">=</span> <span class="n">function</span><span class="p">(</span><span class="n">args</span><span class="p">)</span><span class="o">.</span><span class="n">mydict</span><span class="p">[</span><span class="n">index</span><span class="p">][</span><span class="n">index</span><span class="p">]</span>
  821. <span class="n">ref</span><span class="o">.</span><span class="n">a</span> <span class="o">=</span> <span class="mi">21</span>
  822. <span class="n">ref</span><span class="o">.</span><span class="n">b</span> <span class="o">=</span> <span class="mi">42</span>
  823. <span class="n">ref</span><span class="o">.</span><span class="n">c</span> <span class="o">=</span> <span class="mi">63</span>
  824. </pre></div>
  825. </div>
  826. <p>This also has the side-effect of increasing execution speed because name
  827. bindings are resolved at run-time in Python, and the second version only needs
  828. to perform the resolution once.</p>
  829. <p>Similar proposals that would introduce syntax to further reduce code volume,
  830. such as using a ‘leading dot’, have been rejected in favour of explicitness (see
  831. <a class="reference external" href="https://mail.python.org/pipermail/python-ideas/2016-May/040070.html">https://mail.python.org/pipermail/python-ideas/2016-May/040070.html</a>).</p>
  832. </section>
  833. <section id="why-don-t-generators-support-the-with-statement">
  834. <h2><a class="toc-backref" href="#id28" role="doc-backlink">Why don’t generators support the with statement?</a><a class="headerlink" href="#why-don-t-generators-support-the-with-statement" title="Link to this heading">¶</a></h2>
  835. <p>For technical reasons, a generator used directly as a context manager
  836. would not work correctly. When, as is most common, a generator is used as
  837. an iterator run to completion, no closing is needed. When it is, wrap
  838. it as <a class="reference internal" href="../library/contextlib.html#contextlib.closing" title="contextlib.closing"><code class="xref py py-func docutils literal notranslate"><span class="pre">contextlib.closing(generator)</span></code></a>
  839. in the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement.</p>
  840. </section>
  841. <section id="why-are-colons-required-for-the-if-while-def-class-statements">
  842. <h2><a class="toc-backref" href="#id29" role="doc-backlink">Why are colons required for the if/while/def/class statements?</a><a class="headerlink" href="#why-are-colons-required-for-the-if-while-def-class-statements" title="Link to this heading">¶</a></h2>
  843. <p>The colon is required primarily to enhance readability (one of the results of
  844. the experimental ABC language). Consider this:</p>
  845. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">a</span> <span class="o">==</span> <span class="n">b</span>
  846. <span class="nb">print</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
  847. </pre></div>
  848. </div>
  849. <p>versus</p>
  850. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">a</span> <span class="o">==</span> <span class="n">b</span><span class="p">:</span>
  851. <span class="nb">print</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
  852. </pre></div>
  853. </div>
  854. <p>Notice how the second one is slightly easier to read. Notice further how a
  855. colon sets off the example in this FAQ answer; it’s a standard usage in English.</p>
  856. <p>Another minor reason is that the colon makes it easier for editors with syntax
  857. highlighting; they can look for colons to decide when indentation needs to be
  858. increased instead of having to do a more elaborate parsing of the program text.</p>
  859. </section>
  860. <section id="why-does-python-allow-commas-at-the-end-of-lists-and-tuples">
  861. <h2><a class="toc-backref" href="#id30" role="doc-backlink">Why does Python allow commas at the end of lists and tuples?</a><a class="headerlink" href="#why-does-python-allow-commas-at-the-end-of-lists-and-tuples" title="Link to this heading">¶</a></h2>
  862. <p>Python lets you add a trailing comma at the end of lists, tuples, and
  863. dictionaries:</p>
  864. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,]</span>
  865. <span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">,)</span>
  866. <span class="n">d</span> <span class="o">=</span> <span class="p">{</span>
  867. <span class="s2">&quot;A&quot;</span><span class="p">:</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">5</span><span class="p">],</span>
  868. <span class="s2">&quot;B&quot;</span><span class="p">:</span> <span class="p">[</span><span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">],</span> <span class="c1"># last trailing comma is optional but good style</span>
  869. <span class="p">}</span>
  870. </pre></div>
  871. </div>
  872. <p>There are several reasons to allow this.</p>
  873. <p>When you have a literal value for a list, tuple, or dictionary spread across
  874. multiple lines, it’s easier to add more elements because you don’t have to
  875. remember to add a comma to the previous line. The lines can also be reordered
  876. without creating a syntax error.</p>
  877. <p>Accidentally omitting the comma can lead to errors that are hard to diagnose.
  878. For example:</p>
  879. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="p">[</span>
  880. <span class="s2">&quot;fee&quot;</span><span class="p">,</span>
  881. <span class="s2">&quot;fie&quot;</span>
  882. <span class="s2">&quot;foo&quot;</span><span class="p">,</span>
  883. <span class="s2">&quot;fum&quot;</span>
  884. <span class="p">]</span>
  885. </pre></div>
  886. </div>
  887. <p>This list looks like it has four elements, but it actually contains three:
  888. “fee”, “fiefoo” and “fum”. Always adding the comma avoids this source of error.</p>
  889. <p>Allowing the trailing comma may also make programmatic code generation easier.</p>
  890. </section>
  891. </section>
  892. <div class="clearer"></div>
  893. </div>
  894. </div>
  895. </div>
  896. <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
  897. <div class="sphinxsidebarwrapper">
  898. <div>
  899. <h3><a href="../contents.html">Table of Contents</a></h3>
  900. <ul>
  901. <li><a class="reference internal" href="#">Design and History FAQ</a><ul>
  902. <li><a class="reference internal" href="#why-does-python-use-indentation-for-grouping-of-statements">Why does Python use indentation for grouping of statements?</a></li>
  903. <li><a class="reference internal" href="#why-am-i-getting-strange-results-with-simple-arithmetic-operations">Why am I getting strange results with simple arithmetic operations?</a></li>
  904. <li><a class="reference internal" href="#why-are-floating-point-calculations-so-inaccurate">Why are floating-point calculations so inaccurate?</a></li>
  905. <li><a class="reference internal" href="#why-are-python-strings-immutable">Why are Python strings immutable?</a></li>
  906. <li><a class="reference internal" href="#why-must-self-be-used-explicitly-in-method-definitions-and-calls">Why must ‘self’ be used explicitly in method definitions and calls?</a></li>
  907. <li><a class="reference internal" href="#why-can-t-i-use-an-assignment-in-an-expression">Why can’t I use an assignment in an expression?</a></li>
  908. <li><a class="reference internal" href="#why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list">Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?</a></li>
  909. <li><a class="reference internal" href="#why-is-join-a-string-method-instead-of-a-list-or-tuple-method">Why is join() a string method instead of a list or tuple method?</a></li>
  910. <li><a class="reference internal" href="#how-fast-are-exceptions">How fast are exceptions?</a></li>
  911. <li><a class="reference internal" href="#why-isn-t-there-a-switch-or-case-statement-in-python">Why isn’t there a switch or case statement in Python?</a></li>
  912. <li><a class="reference internal" href="#can-t-you-emulate-threads-in-the-interpreter-instead-of-relying-on-an-os-specific-thread-implementation">Can’t you emulate threads in the interpreter instead of relying on an OS-specific thread implementation?</a></li>
  913. <li><a class="reference internal" href="#why-can-t-lambda-expressions-contain-statements">Why can’t lambda expressions contain statements?</a></li>
  914. <li><a class="reference internal" href="#can-python-be-compiled-to-machine-code-c-or-some-other-language">Can Python be compiled to machine code, C or some other language?</a></li>
  915. <li><a class="reference internal" href="#how-does-python-manage-memory">How does Python manage memory?</a></li>
  916. <li><a class="reference internal" href="#why-doesn-t-cpython-use-a-more-traditional-garbage-collection-scheme">Why doesn’t CPython use a more traditional garbage collection scheme?</a></li>
  917. <li><a class="reference internal" href="#why-isn-t-all-memory-freed-when-cpython-exits">Why isn’t all memory freed when CPython exits?</a></li>
  918. <li><a class="reference internal" href="#why-are-there-separate-tuple-and-list-data-types">Why are there separate tuple and list data types?</a></li>
  919. <li><a class="reference internal" href="#how-are-lists-implemented-in-cpython">How are lists implemented in CPython?</a></li>
  920. <li><a class="reference internal" href="#how-are-dictionaries-implemented-in-cpython">How are dictionaries implemented in CPython?</a></li>
  921. <li><a class="reference internal" href="#why-must-dictionary-keys-be-immutable">Why must dictionary keys be immutable?</a></li>
  922. <li><a class="reference internal" href="#why-doesn-t-list-sort-return-the-sorted-list">Why doesn’t list.sort() return the sorted list?</a></li>
  923. <li><a class="reference internal" href="#how-do-you-specify-and-enforce-an-interface-spec-in-python">How do you specify and enforce an interface spec in Python?</a></li>
  924. <li><a class="reference internal" href="#why-is-there-no-goto">Why is there no goto?</a></li>
  925. <li><a class="reference internal" href="#why-can-t-raw-strings-r-strings-end-with-a-backslash">Why can’t raw strings (r-strings) end with a backslash?</a></li>
  926. <li><a class="reference internal" href="#why-doesn-t-python-have-a-with-statement-for-attribute-assignments">Why doesn’t Python have a “with” statement for attribute assignments?</a></li>
  927. <li><a class="reference internal" href="#why-don-t-generators-support-the-with-statement">Why don’t generators support the with statement?</a></li>
  928. <li><a class="reference internal" href="#why-are-colons-required-for-the-if-while-def-class-statements">Why are colons required for the if/while/def/class statements?</a></li>
  929. <li><a class="reference internal" href="#why-does-python-allow-commas-at-the-end-of-lists-and-tuples">Why does Python allow commas at the end of lists and tuples?</a></li>
  930. </ul>
  931. </li>
  932. </ul>
  933. </div>
  934. <div>
  935. <h4>Previous topic</h4>
  936. <p class="topless"><a href="programming.html"
  937. title="previous chapter">Programming FAQ</a></p>
  938. </div>
  939. <div>
  940. <h4>Next topic</h4>
  941. <p class="topless"><a href="library.html"
  942. title="next chapter">Library and Extension FAQ</a></p>
  943. </div>
  944. <div role="note" aria-label="source link">
  945. <h3>This Page</h3>
  946. <ul class="this-page-menu">
  947. <li><a href="../bugs.html">Report a Bug</a></li>
  948. <li>
  949. <a href="https://github.com/python/cpython/blob/main/Doc/faq/design.rst"
  950. rel="nofollow">Show Source
  951. </a>
  952. </li>
  953. </ul>
  954. </div>
  955. </div>
  956. <div id="sidebarbutton" title="Collapse sidebar">
  957. <span>«</span>
  958. </div>
  959. </div>
  960. <div class="clearer"></div>
  961. </div>
  962. <div class="related" role="navigation" aria-label="related navigation">
  963. <h3>Navigation</h3>
  964. <ul>
  965. <li class="right" style="margin-right: 10px">
  966. <a href="../genindex.html" title="General Index"
  967. >index</a></li>
  968. <li class="right" >
  969. <a href="../py-modindex.html" title="Python Module Index"
  970. >modules</a> |</li>
  971. <li class="right" >
  972. <a href="library.html" title="Library and Extension FAQ"
  973. >next</a> |</li>
  974. <li class="right" >
  975. <a href="programming.html" title="Programming FAQ"
  976. >previous</a> |</li>
  977. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  978. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  979. <li class="switchers">
  980. <div class="language_switcher_placeholder"></div>
  981. <div class="version_switcher_placeholder"></div>
  982. </li>
  983. <li>
  984. </li>
  985. <li id="cpython-language-and-version">
  986. <a href="../index.html">3.12.3 Documentation</a> &#187;
  987. </li>
  988. <li class="nav-item nav-item-1"><a href="index.html" >Python Frequently Asked Questions</a> &#187;</li>
  989. <li class="nav-item nav-item-this"><a href="">Design and History FAQ</a></li>
  990. <li class="right">
  991. <div class="inline-search" role="search">
  992. <form class="inline-search" action="../search.html" method="get">
  993. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  994. <input type="submit" value="Go" />
  995. </form>
  996. </div>
  997. |
  998. </li>
  999. <li class="right">
  1000. <label class="theme-selector-label">
  1001. Theme
  1002. <select class="theme-selector" oninput="activateTheme(this.value)">
  1003. <option value="auto" selected>Auto</option>
  1004. <option value="light">Light</option>
  1005. <option value="dark">Dark</option>
  1006. </select>
  1007. </label> |</li>
  1008. </ul>
  1009. </div>
  1010. <div class="footer">
  1011. &copy;
  1012. <a href="../copyright.html">
  1013. Copyright
  1014. </a>
  1015. 2001-2024, Python Software Foundation.
  1016. <br />
  1017. This page is licensed under the Python Software Foundation License Version 2.
  1018. <br />
  1019. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  1020. <br />
  1021. See <a href="/license.html">History and License</a> for more information.<br />
  1022. <br />
  1023. The Python Software Foundation is a non-profit corporation.
  1024. <a href="https://www.python.org/psf/donations/">Please donate.</a>
  1025. <br />
  1026. <br />
  1027. Last updated on Apr 09, 2024 (13:47 UTC).
  1028. <a href="/bugs.html">Found a bug</a>?
  1029. <br />
  1030. Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 7.2.6.
  1031. </div>
  1032. </body>
  1033. </html>
上海开阖软件有限公司 沪ICP备12045867号-1