gooderp18绿色标准版
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2399 lines
246KB

  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="Programming FAQ" />
  7. <meta property="og:type" content="website" />
  8. <meta property="og:url" content="https://docs.python.org/3/faq/programming.html" />
  9. <meta property="og:site_name" content="Python documentation" />
  10. <meta property="og:description" content="Contents: Programming FAQ- General Questions- Is there a source code level debugger with breakpoints, single-stepping, etc.?, Are there tools to help find bugs or perform static analysis?, How can ..." />
  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: Programming FAQ- General Questions- Is there a source code level debugger with breakpoints, single-stepping, etc.?, Are there tools to help find bugs or perform static analysis?, How can ..." />
  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>Programming 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="Design and History FAQ" href="design.html" />
  33. <link rel="prev" title="General Python FAQ" href="general.html" />
  34. <link rel="canonical" href="https://docs.python.org/3/faq/programming.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="#">Programming FAQ</a><ul>
  86. <li><a class="reference internal" href="#general-questions">General Questions</a></li>
  87. <li><a class="reference internal" href="#core-language">Core Language</a></li>
  88. <li><a class="reference internal" href="#numbers-and-strings">Numbers and strings</a></li>
  89. <li><a class="reference internal" href="#performance">Performance</a></li>
  90. <li><a class="reference internal" href="#sequences-tuples-lists">Sequences (Tuples/Lists)</a></li>
  91. <li><a class="reference internal" href="#objects">Objects</a></li>
  92. <li><a class="reference internal" href="#modules">Modules</a></li>
  93. </ul>
  94. </li>
  95. </ul>
  96. </div>
  97. <div>
  98. <h4>Previous topic</h4>
  99. <p class="topless"><a href="general.html"
  100. title="previous chapter">General Python FAQ</a></p>
  101. </div>
  102. <div>
  103. <h4>Next topic</h4>
  104. <p class="topless"><a href="design.html"
  105. title="next chapter">Design and History FAQ</a></p>
  106. </div>
  107. <div role="note" aria-label="source link">
  108. <h3>This Page</h3>
  109. <ul class="this-page-menu">
  110. <li><a href="../bugs.html">Report a Bug</a></li>
  111. <li>
  112. <a href="https://github.com/python/cpython/blob/main/Doc/faq/programming.rst"
  113. rel="nofollow">Show Source
  114. </a>
  115. </li>
  116. </ul>
  117. </div>
  118. </nav>
  119. </div>
  120. </div>
  121. <div class="related" role="navigation" aria-label="related navigation">
  122. <h3>Navigation</h3>
  123. <ul>
  124. <li class="right" style="margin-right: 10px">
  125. <a href="../genindex.html" title="General Index"
  126. accesskey="I">index</a></li>
  127. <li class="right" >
  128. <a href="../py-modindex.html" title="Python Module Index"
  129. >modules</a> |</li>
  130. <li class="right" >
  131. <a href="design.html" title="Design and History FAQ"
  132. accesskey="N">next</a> |</li>
  133. <li class="right" >
  134. <a href="general.html" title="General Python FAQ"
  135. accesskey="P">previous</a> |</li>
  136. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  137. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  138. <li class="switchers">
  139. <div class="language_switcher_placeholder"></div>
  140. <div class="version_switcher_placeholder"></div>
  141. </li>
  142. <li>
  143. </li>
  144. <li id="cpython-language-and-version">
  145. <a href="../index.html">3.12.3 Documentation</a> &#187;
  146. </li>
  147. <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python Frequently Asked Questions</a> &#187;</li>
  148. <li class="nav-item nav-item-this"><a href="">Programming FAQ</a></li>
  149. <li class="right">
  150. <div class="inline-search" role="search">
  151. <form class="inline-search" action="../search.html" method="get">
  152. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  153. <input type="submit" value="Go" />
  154. </form>
  155. </div>
  156. |
  157. </li>
  158. <li class="right">
  159. <label class="theme-selector-label">
  160. Theme
  161. <select class="theme-selector" oninput="activateTheme(this.value)">
  162. <option value="auto" selected>Auto</option>
  163. <option value="light">Light</option>
  164. <option value="dark">Dark</option>
  165. </select>
  166. </label> |</li>
  167. </ul>
  168. </div>
  169. <div class="document">
  170. <div class="documentwrapper">
  171. <div class="bodywrapper">
  172. <div class="body" role="main">
  173. <section id="programming-faq">
  174. <h1><a class="toc-backref" href="#id2" role="doc-backlink">Programming FAQ</a><a class="headerlink" href="#programming-faq" title="Link to this heading">¶</a></h1>
  175. <nav class="contents" id="contents">
  176. <p class="topic-title">Contents</p>
  177. <ul class="simple">
  178. <li><p><a class="reference internal" href="#programming-faq" id="id2">Programming FAQ</a></p>
  179. <ul>
  180. <li><p><a class="reference internal" href="#general-questions" id="id3">General Questions</a></p>
  181. <ul>
  182. <li><p><a class="reference internal" href="#is-there-a-source-code-level-debugger-with-breakpoints-single-stepping-etc" id="id4">Is there a source code level debugger with breakpoints, single-stepping, etc.?</a></p></li>
  183. <li><p><a class="reference internal" href="#are-there-tools-to-help-find-bugs-or-perform-static-analysis" id="id5">Are there tools to help find bugs or perform static analysis?</a></p></li>
  184. <li><p><a class="reference internal" href="#how-can-i-create-a-stand-alone-binary-from-a-python-script" id="id6">How can I create a stand-alone binary from a Python script?</a></p></li>
  185. <li><p><a class="reference internal" href="#are-there-coding-standards-or-a-style-guide-for-python-programs" id="id7">Are there coding standards or a style guide for Python programs?</a></p></li>
  186. </ul>
  187. </li>
  188. <li><p><a class="reference internal" href="#core-language" id="id8">Core Language</a></p>
  189. <ul>
  190. <li><p><a class="reference internal" href="#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value" id="id9">Why am I getting an UnboundLocalError when the variable has a value?</a></p></li>
  191. <li><p><a class="reference internal" href="#what-are-the-rules-for-local-and-global-variables-in-python" id="id10">What are the rules for local and global variables in Python?</a></p></li>
  192. <li><p><a class="reference internal" href="#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result" id="id11">Why do lambdas defined in a loop with different values all return the same result?</a></p></li>
  193. <li><p><a class="reference internal" href="#how-do-i-share-global-variables-across-modules" id="id12">How do I share global variables across modules?</a></p></li>
  194. <li><p><a class="reference internal" href="#what-are-the-best-practices-for-using-import-in-a-module" id="id13">What are the “best practices” for using import in a module?</a></p></li>
  195. <li><p><a class="reference internal" href="#why-are-default-values-shared-between-objects" id="id14">Why are default values shared between objects?</a></p></li>
  196. <li><p><a class="reference internal" href="#how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another" id="id15">How can I pass optional or keyword parameters from one function to another?</a></p></li>
  197. <li><p><a class="reference internal" href="#what-is-the-difference-between-arguments-and-parameters" id="id16">What is the difference between arguments and parameters?</a></p></li>
  198. <li><p><a class="reference internal" href="#why-did-changing-list-y-also-change-list-x" id="id17">Why did changing list ‘y’ also change list ‘x’?</a></p></li>
  199. <li><p><a class="reference internal" href="#how-do-i-write-a-function-with-output-parameters-call-by-reference" id="id18">How do I write a function with output parameters (call by reference)?</a></p></li>
  200. <li><p><a class="reference internal" href="#how-do-you-make-a-higher-order-function-in-python" id="id19">How do you make a higher order function in Python?</a></p></li>
  201. <li><p><a class="reference internal" href="#how-do-i-copy-an-object-in-python" id="id20">How do I copy an object in Python?</a></p></li>
  202. <li><p><a class="reference internal" href="#how-can-i-find-the-methods-or-attributes-of-an-object" id="id21">How can I find the methods or attributes of an object?</a></p></li>
  203. <li><p><a class="reference internal" href="#how-can-my-code-discover-the-name-of-an-object" id="id22">How can my code discover the name of an object?</a></p></li>
  204. <li><p><a class="reference internal" href="#what-s-up-with-the-comma-operator-s-precedence" id="id23">What’s up with the comma operator’s precedence?</a></p></li>
  205. <li><p><a class="reference internal" href="#is-there-an-equivalent-of-c-s-ternary-operator" id="id24">Is there an equivalent of C’s “?:” ternary operator?</a></p></li>
  206. <li><p><a class="reference internal" href="#is-it-possible-to-write-obfuscated-one-liners-in-python" id="id25">Is it possible to write obfuscated one-liners in Python?</a></p></li>
  207. <li><p><a class="reference internal" href="#what-does-the-slash-in-the-parameter-list-of-a-function-mean" id="id26">What does the slash(/) in the parameter list of a function mean?</a></p></li>
  208. </ul>
  209. </li>
  210. <li><p><a class="reference internal" href="#numbers-and-strings" id="id27">Numbers and strings</a></p>
  211. <ul>
  212. <li><p><a class="reference internal" href="#how-do-i-specify-hexadecimal-and-octal-integers" id="id28">How do I specify hexadecimal and octal integers?</a></p></li>
  213. <li><p><a class="reference internal" href="#why-does-22-10-return-3" id="id29">Why does -22 // 10 return -3?</a></p></li>
  214. <li><p><a class="reference internal" href="#how-do-i-get-int-literal-attribute-instead-of-syntaxerror" id="id30">How do I get int literal attribute instead of SyntaxError?</a></p></li>
  215. <li><p><a class="reference internal" href="#how-do-i-convert-a-string-to-a-number" id="id31">How do I convert a string to a number?</a></p></li>
  216. <li><p><a class="reference internal" href="#how-do-i-convert-a-number-to-a-string" id="id32">How do I convert a number to a string?</a></p></li>
  217. <li><p><a class="reference internal" href="#how-do-i-modify-a-string-in-place" id="id33">How do I modify a string in place?</a></p></li>
  218. <li><p><a class="reference internal" href="#how-do-i-use-strings-to-call-functions-methods" id="id34">How do I use strings to call functions/methods?</a></p></li>
  219. <li><p><a class="reference internal" href="#is-there-an-equivalent-to-perl-s-chomp-for-removing-trailing-newlines-from-strings" id="id35">Is there an equivalent to Perl’s chomp() for removing trailing newlines from strings?</a></p></li>
  220. <li><p><a class="reference internal" href="#is-there-a-scanf-or-sscanf-equivalent" id="id36">Is there a scanf() or sscanf() equivalent?</a></p></li>
  221. <li><p><a class="reference internal" href="#what-does-unicodedecodeerror-or-unicodeencodeerror-error-mean" id="id37">What does ‘UnicodeDecodeError’ or ‘UnicodeEncodeError’ error mean?</a></p></li>
  222. <li><p><a class="reference internal" href="#can-i-end-a-raw-string-with-an-odd-number-of-backslashes" id="id38">Can I end a raw string with an odd number of backslashes?</a></p></li>
  223. </ul>
  224. </li>
  225. <li><p><a class="reference internal" href="#performance" id="id39">Performance</a></p>
  226. <ul>
  227. <li><p><a class="reference internal" href="#my-program-is-too-slow-how-do-i-speed-it-up" id="id40">My program is too slow. How do I speed it up?</a></p></li>
  228. <li><p><a class="reference internal" href="#what-is-the-most-efficient-way-to-concatenate-many-strings-together" id="id41">What is the most efficient way to concatenate many strings together?</a></p></li>
  229. </ul>
  230. </li>
  231. <li><p><a class="reference internal" href="#sequences-tuples-lists" id="id42">Sequences (Tuples/Lists)</a></p>
  232. <ul>
  233. <li><p><a class="reference internal" href="#how-do-i-convert-between-tuples-and-lists" id="id43">How do I convert between tuples and lists?</a></p></li>
  234. <li><p><a class="reference internal" href="#what-s-a-negative-index" id="id44">What’s a negative index?</a></p></li>
  235. <li><p><a class="reference internal" href="#how-do-i-iterate-over-a-sequence-in-reverse-order" id="id45">How do I iterate over a sequence in reverse order?</a></p></li>
  236. <li><p><a class="reference internal" href="#how-do-you-remove-duplicates-from-a-list" id="id46">How do you remove duplicates from a list?</a></p></li>
  237. <li><p><a class="reference internal" href="#how-do-you-remove-multiple-items-from-a-list" id="id47">How do you remove multiple items from a list</a></p></li>
  238. <li><p><a class="reference internal" href="#how-do-you-make-an-array-in-python" id="id48">How do you make an array in Python?</a></p></li>
  239. <li><p><a class="reference internal" href="#how-do-i-create-a-multidimensional-list" id="id49">How do I create a multidimensional list?</a></p></li>
  240. <li><p><a class="reference internal" href="#how-do-i-apply-a-method-or-function-to-a-sequence-of-objects" id="id50">How do I apply a method or function to a sequence of objects?</a></p></li>
  241. <li><p><a class="reference internal" href="#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works" id="id51">Why does a_tuple[i] += [‘item’] raise an exception when the addition works?</a></p></li>
  242. <li><p><a class="reference internal" href="#i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python" id="id52">I want to do a complicated sort: can you do a Schwartzian Transform in Python?</a></p></li>
  243. <li><p><a class="reference internal" href="#how-can-i-sort-one-list-by-values-from-another-list" id="id53">How can I sort one list by values from another list?</a></p></li>
  244. </ul>
  245. </li>
  246. <li><p><a class="reference internal" href="#objects" id="id54">Objects</a></p>
  247. <ul>
  248. <li><p><a class="reference internal" href="#what-is-a-class" id="id55">What is a class?</a></p></li>
  249. <li><p><a class="reference internal" href="#what-is-a-method" id="id56">What is a method?</a></p></li>
  250. <li><p><a class="reference internal" href="#what-is-self" id="id57">What is self?</a></p></li>
  251. <li><p><a class="reference internal" href="#how-do-i-check-if-an-object-is-an-instance-of-a-given-class-or-of-a-subclass-of-it" id="id58">How do I check if an object is an instance of a given class or of a subclass of it?</a></p></li>
  252. <li><p><a class="reference internal" href="#what-is-delegation" id="id59">What is delegation?</a></p></li>
  253. <li><p><a class="reference internal" href="#how-do-i-call-a-method-defined-in-a-base-class-from-a-derived-class-that-extends-it" id="id60">How do I call a method defined in a base class from a derived class that extends it?</a></p></li>
  254. <li><p><a class="reference internal" href="#how-can-i-organize-my-code-to-make-it-easier-to-change-the-base-class" id="id61">How can I organize my code to make it easier to change the base class?</a></p></li>
  255. <li><p><a class="reference internal" href="#how-do-i-create-static-class-data-and-static-class-methods" id="id62">How do I create static class data and static class methods?</a></p></li>
  256. <li><p><a class="reference internal" href="#how-can-i-overload-constructors-or-methods-in-python" id="id63">How can I overload constructors (or methods) in Python?</a></p></li>
  257. <li><p><a class="reference internal" href="#i-try-to-use-spam-and-i-get-an-error-about-someclassname-spam" id="id64">I try to use __spam and I get an error about _SomeClassName__spam.</a></p></li>
  258. <li><p><a class="reference internal" href="#my-class-defines-del-but-it-is-not-called-when-i-delete-the-object" id="id65">My class defines __del__ but it is not called when I delete the object.</a></p></li>
  259. <li><p><a class="reference internal" href="#how-do-i-get-a-list-of-all-instances-of-a-given-class" id="id66">How do I get a list of all instances of a given class?</a></p></li>
  260. <li><p><a class="reference internal" href="#why-does-the-result-of-id-appear-to-be-not-unique" id="id67">Why does the result of <code class="docutils literal notranslate"><span class="pre">id()</span></code> appear to be not unique?</a></p></li>
  261. <li><p><a class="reference internal" href="#when-can-i-rely-on-identity-tests-with-the-is-operator" id="id68">When can I rely on identity tests with the <em>is</em> operator?</a></p></li>
  262. <li><p><a class="reference internal" href="#how-can-a-subclass-control-what-data-is-stored-in-an-immutable-instance" id="id69">How can a subclass control what data is stored in an immutable instance?</a></p></li>
  263. <li><p><a class="reference internal" href="#how-do-i-cache-method-calls" id="id70">How do I cache method calls?</a></p></li>
  264. </ul>
  265. </li>
  266. <li><p><a class="reference internal" href="#modules" id="id71">Modules</a></p>
  267. <ul>
  268. <li><p><a class="reference internal" href="#how-do-i-create-a-pyc-file" id="id72">How do I create a .pyc file?</a></p></li>
  269. <li><p><a class="reference internal" href="#how-do-i-find-the-current-module-name" id="id73">How do I find the current module name?</a></p></li>
  270. <li><p><a class="reference internal" href="#how-can-i-have-modules-that-mutually-import-each-other" id="id74">How can I have modules that mutually import each other?</a></p></li>
  271. <li><p><a class="reference internal" href="#import-x-y-z-returns-module-x-how-do-i-get-z" id="id75">__import__(‘x.y.z’) returns &lt;module ‘x’&gt;; how do I get z?</a></p></li>
  272. <li><p><a class="reference internal" href="#when-i-edit-an-imported-module-and-reimport-it-the-changes-don-t-show-up-why-does-this-happen" id="id76">When I edit an imported module and reimport it, the changes don’t show up. Why does this happen?</a></p></li>
  273. </ul>
  274. </li>
  275. </ul>
  276. </li>
  277. </ul>
  278. </nav>
  279. <section id="general-questions">
  280. <h2><a class="toc-backref" href="#id3" role="doc-backlink">General Questions</a><a class="headerlink" href="#general-questions" title="Link to this heading">¶</a></h2>
  281. <section id="is-there-a-source-code-level-debugger-with-breakpoints-single-stepping-etc">
  282. <h3><a class="toc-backref" href="#id4" role="doc-backlink">Is there a source code level debugger with breakpoints, single-stepping, etc.?</a><a class="headerlink" href="#is-there-a-source-code-level-debugger-with-breakpoints-single-stepping-etc" title="Link to this heading">¶</a></h3>
  283. <p>Yes.</p>
  284. <p>Several debuggers for Python are described below, and the built-in function
  285. <a class="reference internal" href="../library/functions.html#breakpoint" title="breakpoint"><code class="xref py py-func docutils literal notranslate"><span class="pre">breakpoint()</span></code></a> allows you to drop into any of them.</p>
  286. <p>The pdb module is a simple but adequate console-mode debugger for Python. It is
  287. part of the standard Python library, and is <a class="reference internal" href="../library/pdb.html#module-pdb" title="pdb: The Python debugger for interactive interpreters."><code class="xref py py-mod docutils literal notranslate"><span class="pre">documented</span> <span class="pre">in</span> <span class="pre">the</span> <span class="pre">Library</span>
  288. <span class="pre">Reference</span> <span class="pre">Manual</span></code></a>. You can also write your own debugger by using the code
  289. for pdb as an example.</p>
  290. <p>The IDLE interactive development environment, which is part of the standard
  291. Python distribution (normally available as
  292. <a class="reference external" href="https://github.com/python/cpython/blob/main/Tools/scripts/idle3">Tools/scripts/idle3</a>),
  293. includes a graphical debugger.</p>
  294. <p>PythonWin is a Python IDE that includes a GUI debugger based on pdb. The
  295. PythonWin debugger colors breakpoints and has quite a few cool features such as
  296. debugging non-PythonWin programs. PythonWin is available as part of
  297. <a class="reference external" href="https://github.com/mhammond/pywin32">pywin32</a> project and
  298. as a part of the
  299. <a class="reference external" href="https://www.activestate.com/products/python/">ActivePython</a> distribution.</p>
  300. <p><a class="reference external" href="https://eric-ide.python-projects.org/">Eric</a> is an IDE built on PyQt
  301. and the Scintilla editing component.</p>
  302. <p><a class="reference external" href="https://github.com/rocky/python3-trepan/">trepan3k</a> is a gdb-like debugger.</p>
  303. <p><a class="reference external" href="https://code.visualstudio.com/">Visual Studio Code</a> is an IDE with debugging
  304. tools that integrates with version-control software.</p>
  305. <p>There are a number of commercial Python IDEs that include graphical debuggers.
  306. They include:</p>
  307. <ul class="simple">
  308. <li><p><a class="reference external" href="https://wingware.com/">Wing IDE</a></p></li>
  309. <li><p><a class="reference external" href="https://www.activestate.com/products/komodo-ide/">Komodo IDE</a></p></li>
  310. <li><p><a class="reference external" href="https://www.jetbrains.com/pycharm/">PyCharm</a></p></li>
  311. </ul>
  312. </section>
  313. <section id="are-there-tools-to-help-find-bugs-or-perform-static-analysis">
  314. <h3><a class="toc-backref" href="#id5" role="doc-backlink">Are there tools to help find bugs or perform static analysis?</a><a class="headerlink" href="#are-there-tools-to-help-find-bugs-or-perform-static-analysis" title="Link to this heading">¶</a></h3>
  315. <p>Yes.</p>
  316. <p><a class="reference external" href="https://pylint.pycqa.org/en/latest/index.html">Pylint</a> and
  317. <a class="reference external" href="https://github.com/PyCQA/pyflakes">Pyflakes</a> do basic checking that will
  318. help you catch bugs sooner.</p>
  319. <p>Static type checkers such as <a class="reference external" href="https://mypy-lang.org/">Mypy</a>,
  320. <a class="reference external" href="https://pyre-check.org/">Pyre</a>, and
  321. <a class="reference external" href="https://github.com/google/pytype">Pytype</a> can check type hints in Python
  322. source code.</p>
  323. </section>
  324. <section id="how-can-i-create-a-stand-alone-binary-from-a-python-script">
  325. <span id="faq-create-standalone-binary"></span><h3><a class="toc-backref" href="#id6" role="doc-backlink">How can I create a stand-alone binary from a Python script?</a><a class="headerlink" href="#how-can-i-create-a-stand-alone-binary-from-a-python-script" title="Link to this heading">¶</a></h3>
  326. <p>You don’t need the ability to compile Python to C code if all you want is a
  327. stand-alone program that users can download and run without having to install
  328. the Python distribution first. There are a number of tools that determine the
  329. set of modules required by a program and bind these modules together with a
  330. Python binary to produce a single executable.</p>
  331. <p>One is to use the freeze tool, which is included in the Python source tree as
  332. <a class="reference external" href="https://github.com/python/cpython/tree/main/Tools/freeze">Tools/freeze</a>.
  333. It converts Python byte code to C arrays; with a C compiler you can
  334. embed all your modules into a new program, which is then linked with the
  335. standard Python modules.</p>
  336. <p>It works by scanning your source recursively for import statements (in both
  337. forms) and looking for the modules in the standard Python path as well as in the
  338. source directory (for built-in modules). It then turns the bytecode for modules
  339. written in Python into C code (array initializers that can be turned into code
  340. objects using the marshal module) and creates a custom-made config file that
  341. only contains those built-in modules which are actually used in the program. It
  342. then compiles the generated C code and links it with the rest of the Python
  343. interpreter to form a self-contained binary which acts exactly like your script.</p>
  344. <p>The following packages can help with the creation of console and GUI
  345. executables:</p>
  346. <ul class="simple">
  347. <li><p><a class="reference external" href="https://nuitka.net/">Nuitka</a> (Cross-platform)</p></li>
  348. <li><p><a class="reference external" href="https://pyinstaller.org/">PyInstaller</a> (Cross-platform)</p></li>
  349. <li><p><a class="reference external" href="https://pyoxidizer.readthedocs.io/en/stable/">PyOxidizer</a> (Cross-platform)</p></li>
  350. <li><p><a class="reference external" href="https://marcelotduarte.github.io/cx_Freeze/">cx_Freeze</a> (Cross-platform)</p></li>
  351. <li><p><a class="reference external" href="https://github.com/ronaldoussoren/py2app">py2app</a> (macOS only)</p></li>
  352. <li><p><a class="reference external" href="https://www.py2exe.org/">py2exe</a> (Windows only)</p></li>
  353. </ul>
  354. </section>
  355. <section id="are-there-coding-standards-or-a-style-guide-for-python-programs">
  356. <h3><a class="toc-backref" href="#id7" role="doc-backlink">Are there coding standards or a style guide for Python programs?</a><a class="headerlink" href="#are-there-coding-standards-or-a-style-guide-for-python-programs" title="Link to this heading">¶</a></h3>
  357. <p>Yes. The coding style required for standard library modules is documented as
  358. <span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0008/"><strong>PEP 8</strong></a>.</p>
  359. </section>
  360. </section>
  361. <section id="core-language">
  362. <h2><a class="toc-backref" href="#id8" role="doc-backlink">Core Language</a><a class="headerlink" href="#core-language" title="Link to this heading">¶</a></h2>
  363. <section id="why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value">
  364. <span id="faq-unboundlocalerror"></span><h3><a class="toc-backref" href="#id9" role="doc-backlink">Why am I getting an UnboundLocalError when the variable has a value?</a><a class="headerlink" href="#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value" title="Link to this heading">¶</a></h3>
  365. <p>It can be a surprise to get the <a class="reference internal" href="../library/exceptions.html#UnboundLocalError" title="UnboundLocalError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnboundLocalError</span></code></a> in previously working
  366. code when it is modified by adding an assignment statement somewhere in
  367. the body of a function.</p>
  368. <p>This code:</p>
  369. <div class="doctest highlight-default 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="mi">10</span>
  370. <span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">bar</span><span class="p">():</span>
  371. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
  372. <span class="gp">...</span>
  373. <span class="gp">&gt;&gt;&gt; </span><span class="n">bar</span><span class="p">()</span>
  374. <span class="go">10</span>
  375. </pre></div>
  376. </div>
  377. <p>works, but this code:</p>
  378. <div class="doctest highlight-default 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="mi">10</span>
  379. <span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">foo</span><span class="p">():</span>
  380. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
  381. <span class="gp">... </span> <span class="n">x</span> <span class="o">+=</span> <span class="mi">1</span>
  382. </pre></div>
  383. </div>
  384. <p>results in an <code class="xref py py-exc docutils literal notranslate"><span class="pre">UnboundLocalError</span></code>:</p>
  385. <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">foo</span><span class="p">()</span>
  386. <span class="gt">Traceback (most recent call last):</span>
  387. <span class="w"> </span><span class="c">...</span>
  388. <span class="gr">UnboundLocalError</span>: <span class="n">local variable &#39;x&#39; referenced before assignment</span>
  389. </pre></div>
  390. </div>
  391. <p>This is because when you make an assignment to a variable in a scope, that
  392. variable becomes local to that scope and shadows any similarly named variable
  393. in the outer scope. Since the last statement in foo assigns a new value to
  394. <code class="docutils literal notranslate"><span class="pre">x</span></code>, the compiler recognizes it as a local variable. Consequently when the
  395. earlier <code class="docutils literal notranslate"><span class="pre">print(x)</span></code> attempts to print the uninitialized local variable and
  396. an error results.</p>
  397. <p>In the example above you can access the outer scope variable by declaring it
  398. global:</p>
  399. <div class="doctest highlight-default 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="mi">10</span>
  400. <span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">foobar</span><span class="p">():</span>
  401. <span class="gp">... </span> <span class="k">global</span> <span class="n">x</span>
  402. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
  403. <span class="gp">... </span> <span class="n">x</span> <span class="o">+=</span> <span class="mi">1</span>
  404. <span class="gp">...</span>
  405. <span class="gp">&gt;&gt;&gt; </span><span class="n">foobar</span><span class="p">()</span>
  406. <span class="go">10</span>
  407. </pre></div>
  408. </div>
  409. <p>This explicit declaration is required in order to remind you that (unlike the
  410. superficially analogous situation with class and instance variables) you are
  411. actually modifying the value of the variable in the outer scope:</p>
  412. <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
  413. <span class="go">11</span>
  414. </pre></div>
  415. </div>
  416. <p>You can do a similar thing in a nested scope using the <a class="reference internal" href="../reference/simple_stmts.html#nonlocal"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">nonlocal</span></code></a>
  417. keyword:</p>
  418. <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">foo</span><span class="p">():</span>
  419. <span class="gp">... </span> <span class="n">x</span> <span class="o">=</span> <span class="mi">10</span>
  420. <span class="gp">... </span> <span class="k">def</span> <span class="nf">bar</span><span class="p">():</span>
  421. <span class="gp">... </span> <span class="k">nonlocal</span> <span class="n">x</span>
  422. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
  423. <span class="gp">... </span> <span class="n">x</span> <span class="o">+=</span> <span class="mi">1</span>
  424. <span class="gp">... </span> <span class="n">bar</span><span class="p">()</span>
  425. <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
  426. <span class="gp">...</span>
  427. <span class="gp">&gt;&gt;&gt; </span><span class="n">foo</span><span class="p">()</span>
  428. <span class="go">10</span>
  429. <span class="go">11</span>
  430. </pre></div>
  431. </div>
  432. </section>
  433. <section id="what-are-the-rules-for-local-and-global-variables-in-python">
  434. <h3><a class="toc-backref" href="#id10" role="doc-backlink">What are the rules for local and global variables in Python?</a><a class="headerlink" href="#what-are-the-rules-for-local-and-global-variables-in-python" title="Link to this heading">¶</a></h3>
  435. <p>In Python, variables that are only referenced inside a function are implicitly
  436. global. If a variable is assigned a value anywhere within the function’s body,
  437. it’s assumed to be a local unless explicitly declared as global.</p>
  438. <p>Though a bit surprising at first, a moment’s consideration explains this. On
  439. one hand, requiring <a class="reference internal" href="../reference/simple_stmts.html#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> for assigned variables provides a bar
  440. against unintended side-effects. On the other hand, if <code class="docutils literal notranslate"><span class="pre">global</span></code> was required
  441. for all global references, you’d be using <code class="docutils literal notranslate"><span class="pre">global</span></code> all the time. You’d have
  442. to declare as global every reference to a built-in function or to a component of
  443. an imported module. This clutter would defeat the usefulness of the <code class="docutils literal notranslate"><span class="pre">global</span></code>
  444. declaration for identifying side-effects.</p>
  445. </section>
  446. <section id="why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result">
  447. <h3><a class="toc-backref" href="#id11" role="doc-backlink">Why do lambdas defined in a loop with different values all return the same result?</a><a class="headerlink" href="#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result" title="Link to this heading">¶</a></h3>
  448. <p>Assume you use a for loop to define a few different lambdas (or even plain
  449. functions), e.g.:</p>
  450. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span> <span class="o">=</span> <span class="p">[]</span>
  451. <span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">5</span><span class="p">):</span>
  452. <span class="gp">... </span> <span class="n">squares</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="k">lambda</span><span class="p">:</span> <span class="n">x</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span>
  453. </pre></div>
  454. </div>
  455. <p>This gives you a list that contains 5 lambdas that calculate <code class="docutils literal notranslate"><span class="pre">x**2</span></code>. You
  456. might expect that, when called, they would return, respectively, <code class="docutils literal notranslate"><span class="pre">0</span></code>, <code class="docutils literal notranslate"><span class="pre">1</span></code>,
  457. <code class="docutils literal notranslate"><span class="pre">4</span></code>, <code class="docutils literal notranslate"><span class="pre">9</span></code>, and <code class="docutils literal notranslate"><span class="pre">16</span></code>. However, when you actually try you will see that
  458. they all return <code class="docutils literal notranslate"><span class="pre">16</span></code>:</p>
  459. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span><span class="p">[</span><span class="mi">2</span><span class="p">]()</span>
  460. <span class="go">16</span>
  461. <span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span><span class="p">[</span><span class="mi">4</span><span class="p">]()</span>
  462. <span class="go">16</span>
  463. </pre></div>
  464. </div>
  465. <p>This happens because <code class="docutils literal notranslate"><span class="pre">x</span></code> is not local to the lambdas, but is defined in
  466. the outer scope, and it is accessed when the lambda is called — not when it
  467. is defined. At the end of the loop, the value of <code class="docutils literal notranslate"><span class="pre">x</span></code> is <code class="docutils literal notranslate"><span class="pre">4</span></code>, so all the
  468. functions now return <code class="docutils literal notranslate"><span class="pre">4**2</span></code>, i.e. <code class="docutils literal notranslate"><span class="pre">16</span></code>. You can also verify this by
  469. changing the value of <code class="docutils literal notranslate"><span class="pre">x</span></code> and see how the results of the lambdas change:</p>
  470. <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="mi">8</span>
  471. <span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span><span class="p">[</span><span class="mi">2</span><span class="p">]()</span>
  472. <span class="go">64</span>
  473. </pre></div>
  474. </div>
  475. <p>In order to avoid this, you need to save the values in variables local to the
  476. lambdas, so that they don’t rely on the value of the global <code class="docutils literal notranslate"><span class="pre">x</span></code>:</p>
  477. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span> <span class="o">=</span> <span class="p">[]</span>
  478. <span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">5</span><span class="p">):</span>
  479. <span class="gp">... </span> <span class="n">squares</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="k">lambda</span> <span class="n">n</span><span class="o">=</span><span class="n">x</span><span class="p">:</span> <span class="n">n</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span>
  480. </pre></div>
  481. </div>
  482. <p>Here, <code class="docutils literal notranslate"><span class="pre">n=x</span></code> creates a new variable <code class="docutils literal notranslate"><span class="pre">n</span></code> local to the lambda and computed
  483. when the lambda is defined so that it has the same value that <code class="docutils literal notranslate"><span class="pre">x</span></code> had at
  484. that point in the loop. This means that the value of <code class="docutils literal notranslate"><span class="pre">n</span></code> will be <code class="docutils literal notranslate"><span class="pre">0</span></code>
  485. in the first lambda, <code class="docutils literal notranslate"><span class="pre">1</span></code> in the second, <code class="docutils literal notranslate"><span class="pre">2</span></code> in the third, and so on.
  486. Therefore each lambda will now return the correct result:</p>
  487. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span><span class="p">[</span><span class="mi">2</span><span class="p">]()</span>
  488. <span class="go">4</span>
  489. <span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span><span class="p">[</span><span class="mi">4</span><span class="p">]()</span>
  490. <span class="go">16</span>
  491. </pre></div>
  492. </div>
  493. <p>Note that this behaviour is not peculiar to lambdas, but applies to regular
  494. functions too.</p>
  495. </section>
  496. <section id="how-do-i-share-global-variables-across-modules">
  497. <h3><a class="toc-backref" href="#id12" role="doc-backlink">How do I share global variables across modules?</a><a class="headerlink" href="#how-do-i-share-global-variables-across-modules" title="Link to this heading">¶</a></h3>
  498. <p>The canonical way to share information across modules within a single program is
  499. to create a special module (often called config or cfg). Just import the config
  500. module in all modules of your application; the module then becomes available as
  501. a global name. Because there is only one instance of each module, any changes
  502. made to the module object get reflected everywhere. For example:</p>
  503. <p>config.py:</p>
  504. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="mi">0</span> <span class="c1"># Default value of the &#39;x&#39; configuration setting</span>
  505. </pre></div>
  506. </div>
  507. <p>mod.py:</p>
  508. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">config</span>
  509. <span class="n">config</span><span class="o">.</span><span class="n">x</span> <span class="o">=</span> <span class="mi">1</span>
  510. </pre></div>
  511. </div>
  512. <p>main.py:</p>
  513. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">config</span>
  514. <span class="kn">import</span> <span class="nn">mod</span>
  515. <span class="nb">print</span><span class="p">(</span><span class="n">config</span><span class="o">.</span><span class="n">x</span><span class="p">)</span>
  516. </pre></div>
  517. </div>
  518. <p>Note that using a module is also the basis for implementing the singleton design
  519. pattern, for the same reason.</p>
  520. </section>
  521. <section id="what-are-the-best-practices-for-using-import-in-a-module">
  522. <h3><a class="toc-backref" href="#id13" role="doc-backlink">What are the “best practices” for using import in a module?</a><a class="headerlink" href="#what-are-the-best-practices-for-using-import-in-a-module" title="Link to this heading">¶</a></h3>
  523. <p>In general, don’t use <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">modulename</span> <span class="pre">import</span> <span class="pre">*</span></code>. Doing so clutters the
  524. importer’s namespace, and makes it much harder for linters to detect undefined
  525. names.</p>
  526. <p>Import modules at the top of a file. Doing so makes it clear what other modules
  527. your code requires and avoids questions of whether the module name is in scope.
  528. Using one import per line makes it easy to add and delete module imports, but
  529. using multiple imports per line uses less screen space.</p>
  530. <p>It’s good practice if you import modules in the following order:</p>
  531. <ol class="arabic simple">
  532. <li><p>standard library modules – e.g. <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a>, <a class="reference internal" href="../library/os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a>, <a class="reference internal" href="../library/argparse.html#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a>, <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a></p></li>
  533. <li><p>third-party library modules (anything installed in Python’s site-packages
  534. directory) – e.g. <code class="xref py py-mod docutils literal notranslate"><span class="pre">dateutil</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">requests</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">PIL.Image</span></code></p></li>
  535. <li><p>locally developed modules</p></li>
  536. </ol>
  537. <p>It is sometimes necessary to move imports to a function or class to avoid
  538. problems with circular imports. Gordon McMillan says:</p>
  539. <blockquote>
  540. <div><p>Circular imports are fine where both modules use the “import &lt;module&gt;” form
  541. of import. They fail when the 2nd module wants to grab a name out of the
  542. first (“from module import name”) and the import is at the top level. That’s
  543. because names in the 1st are not yet available, because the first module is
  544. busy importing the 2nd.</p>
  545. </div></blockquote>
  546. <p>In this case, if the second module is only used in one function, then the import
  547. can easily be moved into that function. By the time the import is called, the
  548. first module will have finished initializing, and the second module can do its
  549. import.</p>
  550. <p>It may also be necessary to move imports out of the top level of code if some of
  551. the modules are platform-specific. In that case, it may not even be possible to
  552. import all of the modules at the top of the file. In this case, importing the
  553. correct modules in the corresponding platform-specific code is a good option.</p>
  554. <p>Only move imports into a local scope, such as inside a function definition, if
  555. it’s necessary to solve a problem such as avoiding a circular import or are
  556. trying to reduce the initialization time of a module. This technique is
  557. especially helpful if many of the imports are unnecessary depending on how the
  558. program executes. You may also want to move imports into a function if the
  559. modules are only ever used in that function. Note that loading a module the
  560. first time may be expensive because of the one time initialization of the
  561. module, but loading a module multiple times is virtually free, costing only a
  562. couple of dictionary lookups. Even if the module name has gone out of scope,
  563. the module is probably available in <a class="reference internal" href="../library/sys.html#sys.modules" title="sys.modules"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.modules</span></code></a>.</p>
  564. </section>
  565. <section id="why-are-default-values-shared-between-objects">
  566. <h3><a class="toc-backref" href="#id14" role="doc-backlink">Why are default values shared between objects?</a><a class="headerlink" href="#why-are-default-values-shared-between-objects" title="Link to this heading">¶</a></h3>
  567. <p>This type of bug commonly bites neophyte programmers. Consider this function:</p>
  568. <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">mydict</span><span class="o">=</span><span class="p">{}):</span> <span class="c1"># Danger: shared reference to one dict for all calls</span>
  569. <span class="o">...</span> <span class="n">compute</span> <span class="n">something</span> <span class="o">...</span>
  570. <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">value</span>
  571. <span class="k">return</span> <span class="n">mydict</span>
  572. </pre></div>
  573. </div>
  574. <p>The first time you call this function, <code class="docutils literal notranslate"><span class="pre">mydict</span></code> contains a single item. The
  575. second time, <code class="docutils literal notranslate"><span class="pre">mydict</span></code> contains two items because when <code class="docutils literal notranslate"><span class="pre">foo()</span></code> begins
  576. executing, <code class="docutils literal notranslate"><span class="pre">mydict</span></code> starts out with an item already in it.</p>
  577. <p>It is often expected that a function call creates new objects for default
  578. values. This is not what happens. Default values are created exactly once, when
  579. the function is defined. If that object is changed, like the dictionary in this
  580. example, subsequent calls to the function will refer to this changed object.</p>
  581. <p>By definition, immutable objects such as numbers, strings, tuples, and <code class="docutils literal notranslate"><span class="pre">None</span></code>,
  582. are safe from change. Changes to mutable objects such as dictionaries, lists,
  583. and class instances can lead to confusion.</p>
  584. <p>Because of this feature, it is good programming practice to not use mutable
  585. objects as default values. Instead, use <code class="docutils literal notranslate"><span class="pre">None</span></code> as the default value and
  586. inside the function, check if the parameter is <code class="docutils literal notranslate"><span class="pre">None</span></code> and create a new
  587. list/dictionary/whatever if it is. For example, don’t write:</p>
  588. <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">mydict</span><span class="o">=</span><span class="p">{}):</span>
  589. <span class="o">...</span>
  590. </pre></div>
  591. </div>
  592. <p>but:</p>
  593. <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">mydict</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
  594. <span class="k">if</span> <span class="n">mydict</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
  595. <span class="n">mydict</span> <span class="o">=</span> <span class="p">{}</span> <span class="c1"># create a new dict for local namespace</span>
  596. </pre></div>
  597. </div>
  598. <p>This feature can be useful. When you have a function that’s time-consuming to
  599. compute, a common technique is to cache the parameters and the resulting value
  600. of each call to the function, and return the cached value if the same value is
  601. requested again. This is called “memoizing”, and can be implemented like this:</p>
  602. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Callers can only provide two parameters and optionally pass _cache by keyword</span>
  603. <span class="k">def</span> <span class="nf">expensive</span><span class="p">(</span><span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">,</span> <span class="o">*</span><span class="p">,</span> <span class="n">_cache</span><span class="o">=</span><span class="p">{}):</span>
  604. <span class="k">if</span> <span class="p">(</span><span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">)</span> <span class="ow">in</span> <span class="n">_cache</span><span class="p">:</span>
  605. <span class="k">return</span> <span class="n">_cache</span><span class="p">[(</span><span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">)]</span>
  606. <span class="c1"># Calculate the value</span>
  607. <span class="n">result</span> <span class="o">=</span> <span class="o">...</span> <span class="n">expensive</span> <span class="n">computation</span> <span class="o">...</span>
  608. <span class="n">_cache</span><span class="p">[(</span><span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">)]</span> <span class="o">=</span> <span class="n">result</span> <span class="c1"># Store result in the cache</span>
  609. <span class="k">return</span> <span class="n">result</span>
  610. </pre></div>
  611. </div>
  612. <p>You could use a global variable containing a dictionary instead of the default
  613. value; it’s a matter of taste.</p>
  614. </section>
  615. <section id="how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another">
  616. <h3><a class="toc-backref" href="#id15" role="doc-backlink">How can I pass optional or keyword parameters from one function to another?</a><a class="headerlink" href="#how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another" title="Link to this heading">¶</a></h3>
  617. <p>Collect the arguments using the <code class="docutils literal notranslate"><span class="pre">*</span></code> and <code class="docutils literal notranslate"><span class="pre">**</span></code> specifiers in the function’s
  618. parameter list; this gives you the positional arguments as a tuple and the
  619. keyword arguments as a dictionary. You can then pass these arguments when
  620. calling another function by using <code class="docutils literal notranslate"><span class="pre">*</span></code> and <code class="docutils literal notranslate"><span class="pre">**</span></code>:</p>
  621. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
  622. <span class="o">...</span>
  623. <span class="n">kwargs</span><span class="p">[</span><span class="s1">&#39;width&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;14.3c&#39;</span>
  624. <span class="o">...</span>
  625. <span class="n">g</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
  626. </pre></div>
  627. </div>
  628. </section>
  629. <section id="what-is-the-difference-between-arguments-and-parameters">
  630. <span id="faq-argument-vs-parameter"></span><span id="index-1"></span><h3><a class="toc-backref" href="#id16" role="doc-backlink">What is the difference between arguments and parameters?</a><a class="headerlink" href="#what-is-the-difference-between-arguments-and-parameters" title="Link to this heading">¶</a></h3>
  631. <p><a class="reference internal" href="../glossary.html#term-parameter"><span class="xref std std-term">Parameters</span></a> are defined by the names that appear in a
  632. function definition, whereas <a class="reference internal" href="../glossary.html#term-argument"><span class="xref std std-term">arguments</span></a> are the values
  633. actually passed to a function when calling it. Parameters define what
  634. <a class="reference internal" href="../glossary.html#term-parameter"><span class="xref std std-term">kind of arguments</span></a> a function can accept. For
  635. example, given the function definition:</p>
  636. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">func</span><span class="p">(</span><span class="n">foo</span><span class="p">,</span> <span class="n">bar</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
  637. <span class="k">pass</span>
  638. </pre></div>
  639. </div>
  640. <p><em>foo</em>, <em>bar</em> and <em>kwargs</em> are parameters of <code class="docutils literal notranslate"><span class="pre">func</span></code>. However, when calling
  641. <code class="docutils literal notranslate"><span class="pre">func</span></code>, for example:</p>
  642. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">func</span><span class="p">(</span><span class="mi">42</span><span class="p">,</span> <span class="n">bar</span><span class="o">=</span><span class="mi">314</span><span class="p">,</span> <span class="n">extra</span><span class="o">=</span><span class="n">somevar</span><span class="p">)</span>
  643. </pre></div>
  644. </div>
  645. <p>the values <code class="docutils literal notranslate"><span class="pre">42</span></code>, <code class="docutils literal notranslate"><span class="pre">314</span></code>, and <code class="docutils literal notranslate"><span class="pre">somevar</span></code> are arguments.</p>
  646. </section>
  647. <section id="why-did-changing-list-y-also-change-list-x">
  648. <h3><a class="toc-backref" href="#id17" role="doc-backlink">Why did changing list ‘y’ also change list ‘x’?</a><a class="headerlink" href="#why-did-changing-list-y-also-change-list-x" title="Link to this heading">¶</a></h3>
  649. <p>If you wrote code like:</p>
  650. <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="p">[]</span>
  651. <span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="n">x</span>
  652. <span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
  653. <span class="gp">&gt;&gt;&gt; </span><span class="n">y</span>
  654. <span class="go">[10]</span>
  655. <span class="gp">&gt;&gt;&gt; </span><span class="n">x</span>
  656. <span class="go">[10]</span>
  657. </pre></div>
  658. </div>
  659. <p>you might be wondering why appending an element to <code class="docutils literal notranslate"><span class="pre">y</span></code> changed <code class="docutils literal notranslate"><span class="pre">x</span></code> too.</p>
  660. <p>There are two factors that produce this result:</p>
  661. <ol class="arabic simple">
  662. <li><p>Variables are simply names that refer to objects. Doing <code class="docutils literal notranslate"><span class="pre">y</span> <span class="pre">=</span> <span class="pre">x</span></code> doesn’t
  663. create a copy of the list – it creates a new variable <code class="docutils literal notranslate"><span class="pre">y</span></code> that refers to
  664. the same object <code class="docutils literal notranslate"><span class="pre">x</span></code> refers to. This means that there is only one object
  665. (the list), and both <code class="docutils literal notranslate"><span class="pre">x</span></code> and <code class="docutils literal notranslate"><span class="pre">y</span></code> refer to it.</p></li>
  666. <li><p>Lists are <a class="reference internal" href="../glossary.html#term-mutable"><span class="xref std std-term">mutable</span></a>, which means that you can change their content.</p></li>
  667. </ol>
  668. <p>After the call to <code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code>, the content of the mutable object has
  669. changed from <code class="docutils literal notranslate"><span class="pre">[]</span></code> to <code class="docutils literal notranslate"><span class="pre">[10]</span></code>. Since both the variables refer to the same
  670. object, using either name accesses the modified value <code class="docutils literal notranslate"><span class="pre">[10]</span></code>.</p>
  671. <p>If we instead assign an immutable object to <code class="docutils literal notranslate"><span class="pre">x</span></code>:</p>
  672. <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="mi">5</span> <span class="c1"># ints are immutable</span>
  673. <span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="n">x</span>
  674. <span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="n">x</span> <span class="o">+</span> <span class="mi">1</span> <span class="c1"># 5 can&#39;t be mutated, we are creating a new object here</span>
  675. <span class="gp">&gt;&gt;&gt; </span><span class="n">x</span>
  676. <span class="go">6</span>
  677. <span class="gp">&gt;&gt;&gt; </span><span class="n">y</span>
  678. <span class="go">5</span>
  679. </pre></div>
  680. </div>
  681. <p>we can see that in this case <code class="docutils literal notranslate"><span class="pre">x</span></code> and <code class="docutils literal notranslate"><span class="pre">y</span></code> are not equal anymore. This is
  682. because integers are <a class="reference internal" href="../glossary.html#term-immutable"><span class="xref std std-term">immutable</span></a>, and when we do <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">x</span> <span class="pre">+</span> <span class="pre">1</span></code> we are not
  683. mutating the int <code class="docutils literal notranslate"><span class="pre">5</span></code> by incrementing its value; instead, we are creating a
  684. new object (the int <code class="docutils literal notranslate"><span class="pre">6</span></code>) and assigning it to <code class="docutils literal notranslate"><span class="pre">x</span></code> (that is, changing which
  685. object <code class="docutils literal notranslate"><span class="pre">x</span></code> refers to). After this assignment we have two objects (the ints
  686. <code class="docutils literal notranslate"><span class="pre">6</span></code> and <code class="docutils literal notranslate"><span class="pre">5</span></code>) and two variables that refer to them (<code class="docutils literal notranslate"><span class="pre">x</span></code> now refers to
  687. <code class="docutils literal notranslate"><span class="pre">6</span></code> but <code class="docutils literal notranslate"><span class="pre">y</span></code> still refers to <code class="docutils literal notranslate"><span class="pre">5</span></code>).</p>
  688. <p>Some operations (for example <code class="docutils literal notranslate"><span class="pre">y.append(10)</span></code> and <code class="docutils literal notranslate"><span class="pre">y.sort()</span></code>) mutate the
  689. object, whereas superficially similar operations (for example <code class="docutils literal notranslate"><span class="pre">y</span> <span class="pre">=</span> <span class="pre">y</span> <span class="pre">+</span> <span class="pre">[10]</span></code>
  690. and <a class="reference internal" href="../library/functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted(y)</span></code></a>) create a new object. In general in Python (and in all cases
  691. in the standard library) a method that mutates an object will return <code class="docutils literal notranslate"><span class="pre">None</span></code>
  692. to help avoid getting the two types of operations confused. So if you
  693. mistakenly write <code class="docutils literal notranslate"><span class="pre">y.sort()</span></code> thinking it will give you a sorted copy of <code class="docutils literal notranslate"><span class="pre">y</span></code>,
  694. you’ll instead end up with <code class="docutils literal notranslate"><span class="pre">None</span></code>, which will likely cause your program to
  695. generate an easily diagnosed error.</p>
  696. <p>However, there is one class of operations where the same operation sometimes
  697. has different behaviors with different types: the augmented assignment
  698. operators. For example, <code class="docutils literal notranslate"><span class="pre">+=</span></code> mutates lists but not tuples or ints (<code class="docutils literal notranslate"><span class="pre">a_list</span>
  699. <span class="pre">+=</span> <span class="pre">[1,</span> <span class="pre">2,</span> <span class="pre">3]</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">a_list.extend([1,</span> <span class="pre">2,</span> <span class="pre">3])</span></code> and mutates
  700. <code class="docutils literal notranslate"><span class="pre">a_list</span></code>, whereas <code class="docutils literal notranslate"><span class="pre">some_tuple</span> <span class="pre">+=</span> <span class="pre">(1,</span> <span class="pre">2,</span> <span class="pre">3)</span></code> and <code class="docutils literal notranslate"><span class="pre">some_int</span> <span class="pre">+=</span> <span class="pre">1</span></code> create
  701. new objects).</p>
  702. <p>In other words:</p>
  703. <ul class="simple">
  704. <li><p>If we have a mutable object (<a class="reference internal" href="../library/stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a>, <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>, <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a>,
  705. etc.), we can use some specific operations to mutate it and all the variables
  706. that refer to it will see the change.</p></li>
  707. <li><p>If we have an immutable object (<a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>, <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>, <a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>,
  708. etc.), all the variables that refer to it will always see the same value,
  709. but operations that transform that value into a new value always return a new
  710. object.</p></li>
  711. </ul>
  712. <p>If you want to know if two variables refer to the same object or not, you can
  713. use the <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> operator, or the built-in function <a class="reference internal" href="../library/functions.html#id" title="id"><code class="xref py py-func docutils literal notranslate"><span class="pre">id()</span></code></a>.</p>
  714. </section>
  715. <section id="how-do-i-write-a-function-with-output-parameters-call-by-reference">
  716. <h3><a class="toc-backref" href="#id18" role="doc-backlink">How do I write a function with output parameters (call by reference)?</a><a class="headerlink" href="#how-do-i-write-a-function-with-output-parameters-call-by-reference" title="Link to this heading">¶</a></h3>
  717. <p>Remember that arguments are passed by assignment in Python. Since assignment
  718. just creates references to objects, there’s no alias between an argument name in
  719. the caller and callee, and so no call-by-reference per se. You can achieve the
  720. desired effect in a number of ways.</p>
  721. <ol class="arabic">
  722. <li><p>By returning a tuple of the results:</p>
  723. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">func1</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
  724. <span class="gp">... </span> <span class="n">a</span> <span class="o">=</span> <span class="s1">&#39;new-value&#39;</span> <span class="c1"># a and b are local names</span>
  725. <span class="gp">... </span> <span class="n">b</span> <span class="o">=</span> <span class="n">b</span> <span class="o">+</span> <span class="mi">1</span> <span class="c1"># assigned to new objects</span>
  726. <span class="gp">... </span> <span class="k">return</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="c1"># return new values</span>
  727. <span class="gp">...</span>
  728. <span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="s1">&#39;old-value&#39;</span><span class="p">,</span> <span class="mi">99</span>
  729. <span class="gp">&gt;&gt;&gt; </span><span class="n">func1</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
  730. <span class="go">(&#39;new-value&#39;, 100)</span>
  731. </pre></div>
  732. </div>
  733. <p>This is almost always the clearest solution.</p>
  734. </li>
  735. <li><p>By using global variables. This isn’t thread-safe, and is not recommended.</p></li>
  736. <li><p>By passing a mutable (changeable in-place) object:</p>
  737. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">func2</span><span class="p">(</span><span class="n">a</span><span class="p">):</span>
  738. <span class="gp">... </span> <span class="n">a</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;new-value&#39;</span> <span class="c1"># &#39;a&#39; references a mutable list</span>
  739. <span class="gp">... </span> <span class="n">a</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="n">a</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">+</span> <span class="mi">1</span> <span class="c1"># changes a shared object</span>
  740. <span class="gp">...</span>
  741. <span class="gp">&gt;&gt;&gt; </span><span class="n">args</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;old-value&#39;</span><span class="p">,</span> <span class="mi">99</span><span class="p">]</span>
  742. <span class="gp">&gt;&gt;&gt; </span><span class="n">func2</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
  743. <span class="gp">&gt;&gt;&gt; </span><span class="n">args</span>
  744. <span class="go">[&#39;new-value&#39;, 100]</span>
  745. </pre></div>
  746. </div>
  747. </li>
  748. <li><p>By passing in a dictionary that gets mutated:</p>
  749. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">func3</span><span class="p">(</span><span class="n">args</span><span class="p">):</span>
  750. <span class="gp">... </span> <span class="n">args</span><span class="p">[</span><span class="s1">&#39;a&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;new-value&#39;</span> <span class="c1"># args is a mutable dictionary</span>
  751. <span class="gp">... </span> <span class="n">args</span><span class="p">[</span><span class="s1">&#39;b&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">args</span><span class="p">[</span><span class="s1">&#39;b&#39;</span><span class="p">]</span> <span class="o">+</span> <span class="mi">1</span> <span class="c1"># change it in-place</span>
  752. <span class="gp">...</span>
  753. <span class="gp">&gt;&gt;&gt; </span><span class="n">args</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;a&#39;</span><span class="p">:</span> <span class="s1">&#39;old-value&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">:</span> <span class="mi">99</span><span class="p">}</span>
  754. <span class="gp">&gt;&gt;&gt; </span><span class="n">func3</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
  755. <span class="gp">&gt;&gt;&gt; </span><span class="n">args</span>
  756. <span class="go">{&#39;a&#39;: &#39;new-value&#39;, &#39;b&#39;: 100}</span>
  757. </pre></div>
  758. </div>
  759. </li>
  760. <li><p>Or bundle up values in a class instance:</p>
  761. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Namespace</span><span class="p">:</span>
  762. <span class="gp">... </span> <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="o">/</span><span class="p">,</span> <span class="o">**</span><span class="n">args</span><span class="p">):</span>
  763. <span class="gp">... </span> <span class="k">for</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span> <span class="ow">in</span> <span class="n">args</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
  764. <span class="gp">... </span> <span class="nb">setattr</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
  765. <span class="gp">...</span>
  766. <span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">func4</span><span class="p">(</span><span class="n">args</span><span class="p">):</span>
  767. <span class="gp">... </span> <span class="n">args</span><span class="o">.</span><span class="n">a</span> <span class="o">=</span> <span class="s1">&#39;new-value&#39;</span> <span class="c1"># args is a mutable Namespace</span>
  768. <span class="gp">... </span> <span class="n">args</span><span class="o">.</span><span class="n">b</span> <span class="o">=</span> <span class="n">args</span><span class="o">.</span><span class="n">b</span> <span class="o">+</span> <span class="mi">1</span> <span class="c1"># change object in-place</span>
  769. <span class="gp">...</span>
  770. <span class="gp">&gt;&gt;&gt; </span><span class="n">args</span> <span class="o">=</span> <span class="n">Namespace</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="s1">&#39;old-value&#39;</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">99</span><span class="p">)</span>
  771. <span class="gp">&gt;&gt;&gt; </span><span class="n">func4</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
  772. <span class="gp">&gt;&gt;&gt; </span><span class="nb">vars</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
  773. <span class="go">{&#39;a&#39;: &#39;new-value&#39;, &#39;b&#39;: 100}</span>
  774. </pre></div>
  775. </div>
  776. <p>There’s almost never a good reason to get this complicated.</p>
  777. </li>
  778. </ol>
  779. <p>Your best choice is to return a tuple containing the multiple results.</p>
  780. </section>
  781. <section id="how-do-you-make-a-higher-order-function-in-python">
  782. <h3><a class="toc-backref" href="#id19" role="doc-backlink">How do you make a higher order function in Python?</a><a class="headerlink" href="#how-do-you-make-a-higher-order-function-in-python" title="Link to this heading">¶</a></h3>
  783. <p>You have two choices: you can use nested scopes or you can use callable objects.
  784. For example, suppose you wanted to define <code class="docutils literal notranslate"><span class="pre">linear(a,b)</span></code> which returns a
  785. function <code class="docutils literal notranslate"><span class="pre">f(x)</span></code> that computes the value <code class="docutils literal notranslate"><span class="pre">a*x+b</span></code>. Using nested scopes:</p>
  786. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">linear</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
  787. <span class="k">def</span> <span class="nf">result</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
  788. <span class="k">return</span> <span class="n">a</span> <span class="o">*</span> <span class="n">x</span> <span class="o">+</span> <span class="n">b</span>
  789. <span class="k">return</span> <span class="n">result</span>
  790. </pre></div>
  791. </div>
  792. <p>Or using a callable object:</p>
  793. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">linear</span><span class="p">:</span>
  794. <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">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
  795. <span class="bp">self</span><span class="o">.</span><span class="n">a</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">b</span> <span class="o">=</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span>
  796. <span class="k">def</span> <span class="fm">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
  797. <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">a</span> <span class="o">*</span> <span class="n">x</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">b</span>
  798. </pre></div>
  799. </div>
  800. <p>In both cases,</p>
  801. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">taxes</span> <span class="o">=</span> <span class="n">linear</span><span class="p">(</span><span class="mf">0.3</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
  802. </pre></div>
  803. </div>
  804. <p>gives a callable object where <code class="docutils literal notranslate"><span class="pre">taxes(10e6)</span> <span class="pre">==</span> <span class="pre">0.3</span> <span class="pre">*</span> <span class="pre">10e6</span> <span class="pre">+</span> <span class="pre">2</span></code>.</p>
  805. <p>The callable object approach has the disadvantage that it is a bit slower and
  806. results in slightly longer code. However, note that a collection of callables
  807. can share their signature via inheritance:</p>
  808. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">exponential</span><span class="p">(</span><span class="n">linear</span><span class="p">):</span>
  809. <span class="c1"># __init__ inherited</span>
  810. <span class="k">def</span> <span class="fm">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
  811. <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">a</span> <span class="o">*</span> <span class="p">(</span><span class="n">x</span> <span class="o">**</span> <span class="bp">self</span><span class="o">.</span><span class="n">b</span><span class="p">)</span>
  812. </pre></div>
  813. </div>
  814. <p>Object can encapsulate state for several methods:</p>
  815. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">counter</span><span class="p">:</span>
  816. <span class="n">value</span> <span class="o">=</span> <span class="mi">0</span>
  817. <span class="k">def</span> <span class="nf">set</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
  818. <span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="n">x</span>
  819. <span class="k">def</span> <span class="nf">up</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  820. <span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">+</span> <span class="mi">1</span>
  821. <span class="k">def</span> <span class="nf">down</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  822. <span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">-</span> <span class="mi">1</span>
  823. <span class="n">count</span> <span class="o">=</span> <span class="n">counter</span><span class="p">()</span>
  824. <span class="n">inc</span><span class="p">,</span> <span class="n">dec</span><span class="p">,</span> <span class="n">reset</span> <span class="o">=</span> <span class="n">count</span><span class="o">.</span><span class="n">up</span><span class="p">,</span> <span class="n">count</span><span class="o">.</span><span class="n">down</span><span class="p">,</span> <span class="n">count</span><span class="o">.</span><span class="n">set</span>
  825. </pre></div>
  826. </div>
  827. <p>Here <code class="docutils literal notranslate"><span class="pre">inc()</span></code>, <code class="docutils literal notranslate"><span class="pre">dec()</span></code> and <code class="docutils literal notranslate"><span class="pre">reset()</span></code> act like functions which share the
  828. same counting variable.</p>
  829. </section>
  830. <section id="how-do-i-copy-an-object-in-python">
  831. <h3><a class="toc-backref" href="#id20" role="doc-backlink">How do I copy an object in Python?</a><a class="headerlink" href="#how-do-i-copy-an-object-in-python" title="Link to this heading">¶</a></h3>
  832. <p>In general, try <a class="reference internal" href="../library/copy.html#copy.copy" title="copy.copy"><code class="xref py py-func docutils literal notranslate"><span class="pre">copy.copy()</span></code></a> or <a class="reference internal" href="../library/copy.html#copy.deepcopy" title="copy.deepcopy"><code class="xref py py-func docutils literal notranslate"><span class="pre">copy.deepcopy()</span></code></a> for the general case.
  833. Not all objects can be copied, but most can.</p>
  834. <p>Some objects can be copied more easily. Dictionaries have a <a class="reference internal" href="../library/stdtypes.html#dict.copy" title="dict.copy"><code class="xref py py-meth docutils literal notranslate"><span class="pre">copy()</span></code></a>
  835. method:</p>
  836. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">newdict</span> <span class="o">=</span> <span class="n">olddict</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>
  837. </pre></div>
  838. </div>
  839. <p>Sequences can be copied by slicing:</p>
  840. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">new_l</span> <span class="o">=</span> <span class="n">l</span><span class="p">[:]</span>
  841. </pre></div>
  842. </div>
  843. </section>
  844. <section id="how-can-i-find-the-methods-or-attributes-of-an-object">
  845. <h3><a class="toc-backref" href="#id21" role="doc-backlink">How can I find the methods or attributes of an object?</a><a class="headerlink" href="#how-can-i-find-the-methods-or-attributes-of-an-object" title="Link to this heading">¶</a></h3>
  846. <p>For an instance <code class="docutils literal notranslate"><span class="pre">x</span></code> of a user-defined class, <a class="reference internal" href="../library/functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir(x)</span></code></a> returns an alphabetized
  847. list of the names containing the instance attributes and methods and attributes
  848. defined by its class.</p>
  849. </section>
  850. <section id="how-can-my-code-discover-the-name-of-an-object">
  851. <h3><a class="toc-backref" href="#id22" role="doc-backlink">How can my code discover the name of an object?</a><a class="headerlink" href="#how-can-my-code-discover-the-name-of-an-object" title="Link to this heading">¶</a></h3>
  852. <p>Generally speaking, it can’t, because objects don’t really have names.
  853. Essentially, assignment always binds a name to a value; the same is true of
  854. <code class="docutils literal notranslate"><span class="pre">def</span></code> and <code class="docutils literal notranslate"><span class="pre">class</span></code> statements, but in that case the value is a
  855. callable. Consider the following code:</p>
  856. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">A</span><span class="p">:</span>
  857. <span class="gp">... </span> <span class="k">pass</span>
  858. <span class="gp">...</span>
  859. <span class="gp">&gt;&gt;&gt; </span><span class="n">B</span> <span class="o">=</span> <span class="n">A</span>
  860. <span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">B</span><span class="p">()</span>
  861. <span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">a</span>
  862. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
  863. <span class="go">&lt;__main__.A object at 0x16D07CC&gt;</span>
  864. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
  865. <span class="go">&lt;__main__.A object at 0x16D07CC&gt;</span>
  866. </pre></div>
  867. </div>
  868. <p>Arguably the class has a name: even though it is bound to two names and invoked
  869. through the name <code class="docutils literal notranslate"><span class="pre">B</span></code> the created instance is still reported as an instance of
  870. class <code class="docutils literal notranslate"><span class="pre">A</span></code>. However, it is impossible to say whether the instance’s name is <code class="docutils literal notranslate"><span class="pre">a</span></code> or
  871. <code class="docutils literal notranslate"><span class="pre">b</span></code>, since both names are bound to the same value.</p>
  872. <p>Generally speaking it should not be necessary for your code to “know the names”
  873. of particular values. Unless you are deliberately writing introspective
  874. programs, this is usually an indication that a change of approach might be
  875. beneficial.</p>
  876. <p>In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to
  877. this question:</p>
  878. <blockquote>
  879. <div><p>The same way as you get the name of that cat you found on your porch: the cat
  880. (object) itself cannot tell you its name, and it doesn’t really care – so
  881. the only way to find out what it’s called is to ask all your neighbours
  882. (namespaces) if it’s their cat (object)…</p>
  883. <p>….and don’t be surprised if you’ll find that it’s known by many names, or
  884. no name at all!</p>
  885. </div></blockquote>
  886. </section>
  887. <section id="what-s-up-with-the-comma-operator-s-precedence">
  888. <h3><a class="toc-backref" href="#id23" role="doc-backlink">What’s up with the comma operator’s precedence?</a><a class="headerlink" href="#what-s-up-with-the-comma-operator-s-precedence" title="Link to this heading">¶</a></h3>
  889. <p>Comma is not an operator in Python. Consider this session:</p>
  890. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;a&quot;</span> <span class="ow">in</span> <span class="s2">&quot;b&quot;</span><span class="p">,</span> <span class="s2">&quot;a&quot;</span>
  891. <span class="go">(False, &#39;a&#39;)</span>
  892. </pre></div>
  893. </div>
  894. <p>Since the comma is not an operator, but a separator between expressions the
  895. above is evaluated as if you had entered:</p>
  896. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="p">(</span><span class="s2">&quot;a&quot;</span> <span class="ow">in</span> <span class="s2">&quot;b&quot;</span><span class="p">),</span> <span class="s2">&quot;a&quot;</span>
  897. </pre></div>
  898. </div>
  899. <p>not:</p>
  900. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="s2">&quot;a&quot;</span> <span class="ow">in</span> <span class="p">(</span><span class="s2">&quot;b&quot;</span><span class="p">,</span> <span class="s2">&quot;a&quot;</span><span class="p">)</span>
  901. </pre></div>
  902. </div>
  903. <p>The same is true of the various assignment operators (<code class="docutils literal notranslate"><span class="pre">=</span></code>, <code class="docutils literal notranslate"><span class="pre">+=</span></code> etc). They
  904. are not truly operators but syntactic delimiters in assignment statements.</p>
  905. </section>
  906. <section id="is-there-an-equivalent-of-c-s-ternary-operator">
  907. <h3><a class="toc-backref" href="#id24" role="doc-backlink">Is there an equivalent of C’s “?:” ternary operator?</a><a class="headerlink" href="#is-there-an-equivalent-of-c-s-ternary-operator" title="Link to this heading">¶</a></h3>
  908. <p>Yes, there is. The syntax is as follows:</p>
  909. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="n">on_true</span><span class="p">]</span> <span class="k">if</span> <span class="p">[</span><span class="n">expression</span><span class="p">]</span> <span class="k">else</span> <span class="p">[</span><span class="n">on_false</span><span class="p">]</span>
  910. <span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="mi">50</span><span class="p">,</span> <span class="mi">25</span>
  911. <span class="n">small</span> <span class="o">=</span> <span class="n">x</span> <span class="k">if</span> <span class="n">x</span> <span class="o">&lt;</span> <span class="n">y</span> <span class="k">else</span> <span class="n">y</span>
  912. </pre></div>
  913. </div>
  914. <p>Before this syntax was introduced in Python 2.5, a common idiom was to use
  915. logical operators:</p>
  916. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="n">expression</span><span class="p">]</span> <span class="ow">and</span> <span class="p">[</span><span class="n">on_true</span><span class="p">]</span> <span class="ow">or</span> <span class="p">[</span><span class="n">on_false</span><span class="p">]</span>
  917. </pre></div>
  918. </div>
  919. <p>However, this idiom is unsafe, as it can give wrong results when <em>on_true</em>
  920. has a false boolean value. Therefore, it is always better to use
  921. the <code class="docutils literal notranslate"><span class="pre">...</span> <span class="pre">if</span> <span class="pre">...</span> <span class="pre">else</span> <span class="pre">...</span></code> form.</p>
  922. </section>
  923. <section id="is-it-possible-to-write-obfuscated-one-liners-in-python">
  924. <h3><a class="toc-backref" href="#id25" role="doc-backlink">Is it possible to write obfuscated one-liners in Python?</a><a class="headerlink" href="#is-it-possible-to-write-obfuscated-one-liners-in-python" title="Link to this heading">¶</a></h3>
  925. <p>Yes. Usually this is done by nesting <a class="reference internal" href="../reference/expressions.html#lambda"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">lambda</span></code></a> within
  926. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">lambda</span></code>. See the following three examples, slightly adapted from Ulf Bartelt:</p>
  927. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">functools</span> <span class="kn">import</span> <span class="n">reduce</span>
  928. <span class="c1"># Primes &lt; 1000</span>
  929. <span class="nb">print</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="nb">filter</span><span class="p">(</span><span class="kc">None</span><span class="p">,</span><span class="nb">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">y</span><span class="p">:</span><span class="n">y</span><span class="o">*</span><span class="n">reduce</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">:</span><span class="n">x</span><span class="o">*</span><span class="n">y</span><span class="o">!=</span><span class="mi">0</span><span class="p">,</span>
  930. <span class="nb">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="o">=</span><span class="n">y</span><span class="p">:</span><span class="n">y</span><span class="o">%</span><span class="n">x</span><span class="p">,</span><span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span><span class="nb">int</span><span class="p">(</span><span class="nb">pow</span><span class="p">(</span><span class="n">y</span><span class="p">,</span><span class="mf">0.5</span><span class="p">)</span><span class="o">+</span><span class="mi">1</span><span class="p">))),</span><span class="mi">1</span><span class="p">),</span><span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span><span class="mi">1000</span><span class="p">)))))</span>
  931. <span class="c1"># First 10 Fibonacci numbers</span>
  932. <span class="nb">print</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="nb">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">f</span><span class="o">=</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">f</span><span class="p">:(</span><span class="n">f</span><span class="p">(</span><span class="n">x</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span><span class="n">f</span><span class="p">)</span><span class="o">+</span><span class="n">f</span><span class="p">(</span><span class="n">x</span><span class="o">-</span><span class="mi">2</span><span class="p">,</span><span class="n">f</span><span class="p">))</span> <span class="k">if</span> <span class="n">x</span><span class="o">&gt;</span><span class="mi">1</span> <span class="k">else</span> <span class="mi">1</span><span class="p">:</span>
  933. <span class="n">f</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">f</span><span class="p">),</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))))</span>
  934. <span class="c1"># Mandelbrot set</span>
  935. <span class="nb">print</span><span class="p">((</span><span class="k">lambda</span> <span class="n">Ru</span><span class="p">,</span><span class="n">Ro</span><span class="p">,</span><span class="n">Iu</span><span class="p">,</span><span class="n">Io</span><span class="p">,</span><span class="n">IM</span><span class="p">,</span><span class="n">Sx</span><span class="p">,</span><span class="n">Sy</span><span class="p">:</span><span class="n">reduce</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">:</span><span class="n">x</span><span class="o">+</span><span class="s1">&#39;</span><span class="se">\n</span><span class="s1">&#39;</span><span class="o">+</span><span class="n">y</span><span class="p">,</span><span class="nb">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">y</span><span class="p">,</span>
  936. <span class="n">Iu</span><span class="o">=</span><span class="n">Iu</span><span class="p">,</span><span class="n">Io</span><span class="o">=</span><span class="n">Io</span><span class="p">,</span><span class="n">Ru</span><span class="o">=</span><span class="n">Ru</span><span class="p">,</span><span class="n">Ro</span><span class="o">=</span><span class="n">Ro</span><span class="p">,</span><span class="n">Sy</span><span class="o">=</span><span class="n">Sy</span><span class="p">,</span><span class="n">L</span><span class="o">=</span><span class="k">lambda</span> <span class="n">yc</span><span class="p">,</span><span class="n">Iu</span><span class="o">=</span><span class="n">Iu</span><span class="p">,</span><span class="n">Io</span><span class="o">=</span><span class="n">Io</span><span class="p">,</span><span class="n">Ru</span><span class="o">=</span><span class="n">Ru</span><span class="p">,</span><span class="n">Ro</span><span class="o">=</span><span class="n">Ro</span><span class="p">,</span><span class="n">i</span><span class="o">=</span><span class="n">IM</span><span class="p">,</span>
  937. <span class="n">Sx</span><span class="o">=</span><span class="n">Sx</span><span class="p">,</span><span class="n">Sy</span><span class="o">=</span><span class="n">Sy</span><span class="p">:</span><span class="n">reduce</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">:</span><span class="n">x</span><span class="o">+</span><span class="n">y</span><span class="p">,</span><span class="nb">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">xc</span><span class="o">=</span><span class="n">Ru</span><span class="p">,</span><span class="n">yc</span><span class="o">=</span><span class="n">yc</span><span class="p">,</span><span class="n">Ru</span><span class="o">=</span><span class="n">Ru</span><span class="p">,</span><span class="n">Ro</span><span class="o">=</span><span class="n">Ro</span><span class="p">,</span>
  938. <span class="n">i</span><span class="o">=</span><span class="n">i</span><span class="p">,</span><span class="n">Sx</span><span class="o">=</span><span class="n">Sx</span><span class="p">,</span><span class="n">F</span><span class="o">=</span><span class="k">lambda</span> <span class="n">xc</span><span class="p">,</span><span class="n">yc</span><span class="p">,</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">,</span><span class="n">k</span><span class="p">,</span><span class="n">f</span><span class="o">=</span><span class="k">lambda</span> <span class="n">xc</span><span class="p">,</span><span class="n">yc</span><span class="p">,</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">,</span><span class="n">k</span><span class="p">,</span><span class="n">f</span><span class="p">:(</span><span class="n">k</span><span class="o">&lt;=</span><span class="mi">0</span><span class="p">)</span><span class="ow">or</span> <span class="p">(</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="o">+</span><span class="n">y</span><span class="o">*</span><span class="n">y</span>
  939. <span class="o">&gt;=</span><span class="mf">4.0</span><span class="p">)</span> <span class="ow">or</span> <span class="mi">1</span><span class="o">+</span><span class="n">f</span><span class="p">(</span><span class="n">xc</span><span class="p">,</span><span class="n">yc</span><span class="p">,</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="o">-</span><span class="n">y</span><span class="o">*</span><span class="n">y</span><span class="o">+</span><span class="n">xc</span><span class="p">,</span><span class="mf">2.0</span><span class="o">*</span><span class="n">x</span><span class="o">*</span><span class="n">y</span><span class="o">+</span><span class="n">yc</span><span class="p">,</span><span class="n">k</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span><span class="n">f</span><span class="p">):</span><span class="n">f</span><span class="p">(</span><span class="n">xc</span><span class="p">,</span><span class="n">yc</span><span class="p">,</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">,</span><span class="n">k</span><span class="p">,</span><span class="n">f</span><span class="p">):</span><span class="nb">chr</span><span class="p">(</span>
  940. <span class="mi">64</span><span class="o">+</span><span class="n">F</span><span class="p">(</span><span class="n">Ru</span><span class="o">+</span><span class="n">x</span><span class="o">*</span><span class="p">(</span><span class="n">Ro</span><span class="o">-</span><span class="n">Ru</span><span class="p">)</span><span class="o">/</span><span class="n">Sx</span><span class="p">,</span><span class="n">yc</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="n">i</span><span class="p">)),</span><span class="nb">range</span><span class="p">(</span><span class="n">Sx</span><span class="p">))):</span><span class="n">L</span><span class="p">(</span><span class="n">Iu</span><span class="o">+</span><span class="n">y</span><span class="o">*</span><span class="p">(</span><span class="n">Io</span><span class="o">-</span><span class="n">Iu</span><span class="p">)</span><span class="o">/</span><span class="n">Sy</span><span class="p">),</span><span class="nb">range</span><span class="p">(</span><span class="n">Sy</span>
  941. <span class="p">))))(</span><span class="o">-</span><span class="mf">2.1</span><span class="p">,</span> <span class="mf">0.7</span><span class="p">,</span> <span class="o">-</span><span class="mf">1.2</span><span class="p">,</span> <span class="mf">1.2</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">80</span><span class="p">,</span> <span class="mi">24</span><span class="p">))</span>
  942. <span class="c1"># \___ ___/ \___ ___/ | | |__ lines on screen</span>
  943. <span class="c1"># V V | |______ columns on screen</span>
  944. <span class="c1"># | | |__________ maximum of &quot;iterations&quot;</span>
  945. <span class="c1"># | |_________________ range on y axis</span>
  946. <span class="c1"># |____________________________ range on x axis</span>
  947. </pre></div>
  948. </div>
  949. <p>Don’t try this at home, kids!</p>
  950. </section>
  951. <section id="what-does-the-slash-in-the-parameter-list-of-a-function-mean">
  952. <span id="faq-positional-only-arguments"></span><h3><a class="toc-backref" href="#id26" role="doc-backlink">What does the slash(/) in the parameter list of a function mean?</a><a class="headerlink" href="#what-does-the-slash-in-the-parameter-list-of-a-function-mean" title="Link to this heading">¶</a></h3>
  953. <p>A slash in the argument list of a function denotes that the parameters prior to
  954. it are positional-only. Positional-only parameters are the ones without an
  955. externally usable name. Upon calling a function that accepts positional-only
  956. parameters, arguments are mapped to parameters based solely on their position.
  957. For example, <a class="reference internal" href="../library/functions.html#divmod" title="divmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">divmod()</span></code></a> is a function that accepts positional-only
  958. parameters. Its documentation looks like this:</p>
  959. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">help</span><span class="p">(</span><span class="nb">divmod</span><span class="p">)</span>
  960. <span class="go">Help on built-in function divmod in module builtins:</span>
  961. <span class="go">divmod(x, y, /)</span>
  962. <span class="go"> Return the tuple (x//y, x%y). Invariant: div*y + mod == x.</span>
  963. </pre></div>
  964. </div>
  965. <p>The slash at the end of the parameter list means that both parameters are
  966. positional-only. Thus, calling <a class="reference internal" href="../library/functions.html#divmod" title="divmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">divmod()</span></code></a> with keyword arguments would lead
  967. to an error:</p>
  968. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">divmod</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
  969. <span class="gt">Traceback (most recent call last):</span>
  970. File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
  971. <span class="gr">TypeError</span>: <span class="n">divmod() takes no keyword arguments</span>
  972. </pre></div>
  973. </div>
  974. </section>
  975. </section>
  976. <section id="numbers-and-strings">
  977. <h2><a class="toc-backref" href="#id27" role="doc-backlink">Numbers and strings</a><a class="headerlink" href="#numbers-and-strings" title="Link to this heading">¶</a></h2>
  978. <section id="how-do-i-specify-hexadecimal-and-octal-integers">
  979. <h3><a class="toc-backref" href="#id28" role="doc-backlink">How do I specify hexadecimal and octal integers?</a><a class="headerlink" href="#how-do-i-specify-hexadecimal-and-octal-integers" title="Link to this heading">¶</a></h3>
  980. <p>To specify an octal digit, precede the octal value with a zero, and then a lower
  981. or uppercase “o”. For example, to set the variable “a” to the octal value “10”
  982. (8 in decimal), type:</p>
  983. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="mo">0o10</span>
  984. <span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
  985. <span class="go">8</span>
  986. </pre></div>
  987. </div>
  988. <p>Hexadecimal is just as easy. Simply precede the hexadecimal number with a zero,
  989. and then a lower or uppercase “x”. Hexadecimal digits can be specified in lower
  990. or uppercase. For example, in the Python interpreter:</p>
  991. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="mh">0xa5</span>
  992. <span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
  993. <span class="go">165</span>
  994. <span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="mh">0XB2</span>
  995. <span class="gp">&gt;&gt;&gt; </span><span class="n">b</span>
  996. <span class="go">178</span>
  997. </pre></div>
  998. </div>
  999. </section>
  1000. <section id="why-does-22-10-return-3">
  1001. <h3><a class="toc-backref" href="#id29" role="doc-backlink">Why does -22 // 10 return -3?</a><a class="headerlink" href="#why-does-22-10-return-3" title="Link to this heading">¶</a></h3>
  1002. <p>It’s primarily driven by the desire that <code class="docutils literal notranslate"><span class="pre">i</span> <span class="pre">%</span> <span class="pre">j</span></code> have the same sign as <code class="docutils literal notranslate"><span class="pre">j</span></code>.
  1003. If you want that, and also want:</p>
  1004. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">i</span> <span class="o">==</span> <span class="p">(</span><span class="n">i</span> <span class="o">//</span> <span class="n">j</span><span class="p">)</span> <span class="o">*</span> <span class="n">j</span> <span class="o">+</span> <span class="p">(</span><span class="n">i</span> <span class="o">%</span> <span class="n">j</span><span class="p">)</span>
  1005. </pre></div>
  1006. </div>
  1007. <p>then integer division has to return the floor. C also requires that identity to
  1008. hold, and then compilers that truncate <code class="docutils literal notranslate"><span class="pre">i</span> <span class="pre">//</span> <span class="pre">j</span></code> need to make <code class="docutils literal notranslate"><span class="pre">i</span> <span class="pre">%</span> <span class="pre">j</span></code> have
  1009. the same sign as <code class="docutils literal notranslate"><span class="pre">i</span></code>.</p>
  1010. <p>There are few real use cases for <code class="docutils literal notranslate"><span class="pre">i</span> <span class="pre">%</span> <span class="pre">j</span></code> when <code class="docutils literal notranslate"><span class="pre">j</span></code> is negative. When <code class="docutils literal notranslate"><span class="pre">j</span></code>
  1011. is positive, there are many, and in virtually all of them it’s more useful for
  1012. <code class="docutils literal notranslate"><span class="pre">i</span> <span class="pre">%</span> <span class="pre">j</span></code> to be <code class="docutils literal notranslate"><span class="pre">&gt;=</span> <span class="pre">0</span></code>. If the clock says 10 now, what did it say 200 hours
  1013. ago? <code class="docutils literal notranslate"><span class="pre">-190</span> <span class="pre">%</span> <span class="pre">12</span> <span class="pre">==</span> <span class="pre">2</span></code> is useful; <code class="docutils literal notranslate"><span class="pre">-190</span> <span class="pre">%</span> <span class="pre">12</span> <span class="pre">==</span> <span class="pre">-10</span></code> is a bug waiting to
  1014. bite.</p>
  1015. </section>
  1016. <section id="how-do-i-get-int-literal-attribute-instead-of-syntaxerror">
  1017. <h3><a class="toc-backref" href="#id30" role="doc-backlink">How do I get int literal attribute instead of SyntaxError?</a><a class="headerlink" href="#how-do-i-get-int-literal-attribute-instead-of-syntaxerror" title="Link to this heading">¶</a></h3>
  1018. <p>Trying to lookup an <code class="docutils literal notranslate"><span class="pre">int</span></code> literal attribute in the normal manner gives
  1019. a <a class="reference internal" href="../library/exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> because the period is seen as a decimal point:</p>
  1020. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mf">1.</span><span class="vm">__class__</span>
  1021. File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>
  1022. <span class="gr"> 1.__class__</span>
  1023. <span class="gr"> ^</span>
  1024. <span class="gr">SyntaxError</span>: <span class="n">invalid decimal literal</span>
  1025. </pre></div>
  1026. </div>
  1027. <p>The solution is to separate the literal from the period
  1028. with either a space or parentheses.</p>
  1029. <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mi">1</span> <span class="o">.</span><span class="vm">__class__</span>
  1030. <span class="go">&lt;class &#39;int&#39;&gt;</span>
  1031. <span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="vm">__class__</span>
  1032. <span class="go">&lt;class &#39;int&#39;&gt;</span>
  1033. </pre></div>
  1034. </div>
  1035. </section>
  1036. <section id="how-do-i-convert-a-string-to-a-number">
  1037. <h3><a class="toc-backref" href="#id31" role="doc-backlink">How do I convert a string to a number?</a><a class="headerlink" href="#how-do-i-convert-a-string-to-a-number" title="Link to this heading">¶</a></h3>
  1038. <p>For integers, use the built-in <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> type constructor, e.g. <code class="docutils literal notranslate"><span class="pre">int('144')</span>
  1039. <span class="pre">==</span> <span class="pre">144</span></code>. Similarly, <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-func docutils literal notranslate"><span class="pre">float()</span></code></a> converts to floating-point,
  1040. e.g. <code class="docutils literal notranslate"><span class="pre">float('144')</span> <span class="pre">==</span> <span class="pre">144.0</span></code>.</p>
  1041. <p>By default, these interpret the number as decimal, so that <code class="docutils literal notranslate"><span class="pre">int('0144')</span> <span class="pre">==</span>
  1042. <span class="pre">144</span></code> holds true, and <code class="docutils literal notranslate"><span class="pre">int('0x144')</span></code> raises <a class="reference internal" href="../library/exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>. <code class="docutils literal notranslate"><span class="pre">int(string,</span>
  1043. <span class="pre">base)</span></code> takes the base to convert from as a second optional argument, so <code class="docutils literal notranslate"><span class="pre">int(</span>
  1044. <span class="pre">'0x144',</span> <span class="pre">16)</span> <span class="pre">==</span> <span class="pre">324</span></code>. If the base is specified as 0, the number is interpreted
  1045. using Python’s rules: a leading ‘0o’ indicates octal, and ‘0x’ indicates a hex
  1046. number.</p>
  1047. <p>Do not use the built-in function <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> if all you need is to convert
  1048. strings to numbers. <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> will be significantly slower and it presents a
  1049. security risk: someone could pass you a Python expression that might have
  1050. unwanted side effects. For example, someone could pass
  1051. <code class="docutils literal notranslate"><span class="pre">__import__('os').system(&quot;rm</span> <span class="pre">-rf</span> <span class="pre">$HOME&quot;)</span></code> which would erase your home
  1052. directory.</p>
  1053. <p><a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> also has the effect of interpreting numbers as Python expressions,
  1054. so that e.g. <code class="docutils literal notranslate"><span class="pre">eval('09')</span></code> gives a syntax error because Python does not allow
  1055. leading ‘0’ in a decimal number (except ‘0’).</p>
  1056. </section>
  1057. <section id="how-do-i-convert-a-number-to-a-string">
  1058. <h3><a class="toc-backref" href="#id32" role="doc-backlink">How do I convert a number to a string?</a><a class="headerlink" href="#how-do-i-convert-a-number-to-a-string" title="Link to this heading">¶</a></h3>
  1059. <p>To convert, e.g., the number <code class="docutils literal notranslate"><span class="pre">144</span></code> to the string <code class="docutils literal notranslate"><span class="pre">'144'</span></code>, use the built-in type
  1060. constructor <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a>. If you want a hexadecimal or octal representation, use
  1061. the built-in functions <a class="reference internal" href="../library/functions.html#hex" title="hex"><code class="xref py py-func docutils literal notranslate"><span class="pre">hex()</span></code></a> or <a class="reference internal" href="../library/functions.html#oct" title="oct"><code class="xref py py-func docutils literal notranslate"><span class="pre">oct()</span></code></a>. For fancy formatting, see
  1062. the <a class="reference internal" href="../reference/lexical_analysis.html#f-strings"><span class="std std-ref">f-strings</span></a> and <a class="reference internal" href="../library/string.html#formatstrings"><span class="std std-ref">Format String Syntax</span></a> sections,
  1063. e.g. <code class="docutils literal notranslate"><span class="pre">&quot;{:04d}&quot;.format(144)</span></code> yields
  1064. <code class="docutils literal notranslate"><span class="pre">'0144'</span></code> and <code class="docutils literal notranslate"><span class="pre">&quot;{:.3f}&quot;.format(1.0/3.0)</span></code> yields <code class="docutils literal notranslate"><span class="pre">'0.333'</span></code>.</p>
  1065. </section>
  1066. <section id="how-do-i-modify-a-string-in-place">
  1067. <h3><a class="toc-backref" href="#id33" role="doc-backlink">How do I modify a string in place?</a><a class="headerlink" href="#how-do-i-modify-a-string-in-place" title="Link to this heading">¶</a></h3>
  1068. <p>You can’t, because strings are immutable. In most situations, you should
  1069. simply construct a new string from the various parts you want to assemble
  1070. it from. However, if you need an object with the ability to modify in-place
  1071. unicode data, try using an <a class="reference internal" href="../library/io.html#io.StringIO" title="io.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.StringIO</span></code></a> object or the <a class="reference internal" href="../library/array.html#module-array" title="array: Space efficient arrays of uniformly typed numeric values."><code class="xref py py-mod docutils literal notranslate"><span class="pre">array</span></code></a>
  1072. module:</p>
  1073. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">io</span>
  1074. <span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;Hello, world&quot;</span>
  1075. <span class="gp">&gt;&gt;&gt; </span><span class="n">sio</span> <span class="o">=</span> <span class="n">io</span><span class="o">.</span><span class="n">StringIO</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
  1076. <span class="gp">&gt;&gt;&gt; </span><span class="n">sio</span><span class="o">.</span><span class="n">getvalue</span><span class="p">()</span>
  1077. <span class="go">&#39;Hello, world&#39;</span>
  1078. <span class="gp">&gt;&gt;&gt; </span><span class="n">sio</span><span class="o">.</span><span class="n">seek</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span>
  1079. <span class="go">7</span>
  1080. <span class="gp">&gt;&gt;&gt; </span><span class="n">sio</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">&quot;there!&quot;</span><span class="p">)</span>
  1081. <span class="go">6</span>
  1082. <span class="gp">&gt;&gt;&gt; </span><span class="n">sio</span><span class="o">.</span><span class="n">getvalue</span><span class="p">()</span>
  1083. <span class="go">&#39;Hello, there!&#39;</span>
  1084. <span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">array</span>
  1085. <span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">array</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="s1">&#39;u&#39;</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span>
  1086. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
  1087. <span class="go">array(&#39;u&#39;, &#39;Hello, world&#39;)</span>
  1088. <span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;y&#39;</span>
  1089. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
  1090. <span class="go">array(&#39;u&#39;, &#39;yello, world&#39;)</span>
  1091. <span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">.</span><span class="n">tounicode</span><span class="p">()</span>
  1092. <span class="go">&#39;yello, world&#39;</span>
  1093. </pre></div>
  1094. </div>
  1095. </section>
  1096. <section id="how-do-i-use-strings-to-call-functions-methods">
  1097. <h3><a class="toc-backref" href="#id34" role="doc-backlink">How do I use strings to call functions/methods?</a><a class="headerlink" href="#how-do-i-use-strings-to-call-functions-methods" title="Link to this heading">¶</a></h3>
  1098. <p>There are various techniques.</p>
  1099. <ul>
  1100. <li><p>The best is to use a dictionary that maps strings to functions. The primary
  1101. advantage of this technique is that the strings do not need to match the names
  1102. of the functions. This is also the primary technique used to emulate a case
  1103. construct:</p>
  1104. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">a</span><span class="p">():</span>
  1105. <span class="k">pass</span>
  1106. <span class="k">def</span> <span class="nf">b</span><span class="p">():</span>
  1107. <span class="k">pass</span>
  1108. <span class="n">dispatch</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;go&#39;</span><span class="p">:</span> <span class="n">a</span><span class="p">,</span> <span class="s1">&#39;stop&#39;</span><span class="p">:</span> <span class="n">b</span><span class="p">}</span> <span class="c1"># Note lack of parens for funcs</span>
  1109. <span class="n">dispatch</span><span class="p">[</span><span class="n">get_input</span><span class="p">()]()</span> <span class="c1"># Note trailing parens to call function</span>
  1110. </pre></div>
  1111. </div>
  1112. </li>
  1113. <li><p>Use the built-in function <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>:</p>
  1114. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">foo</span>
  1115. <span class="nb">getattr</span><span class="p">(</span><span class="n">foo</span><span class="p">,</span> <span class="s1">&#39;bar&#39;</span><span class="p">)()</span>
  1116. </pre></div>
  1117. </div>
  1118. <p>Note that <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> works on any object, including classes, class
  1119. instances, modules, and so on.</p>
  1120. <p>This is used in several places in the standard library, like this:</p>
  1121. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Foo</span><span class="p">:</span>
  1122. <span class="k">def</span> <span class="nf">do_foo</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  1123. <span class="o">...</span>
  1124. <span class="k">def</span> <span class="nf">do_bar</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  1125. <span class="o">...</span>
  1126. <span class="n">f</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">foo_instance</span><span class="p">,</span> <span class="s1">&#39;do_&#39;</span> <span class="o">+</span> <span class="n">opname</span><span class="p">)</span>
  1127. <span class="n">f</span><span class="p">()</span>
  1128. </pre></div>
  1129. </div>
  1130. </li>
  1131. <li><p>Use <a class="reference internal" href="../library/functions.html#locals" title="locals"><code class="xref py py-func docutils literal notranslate"><span class="pre">locals()</span></code></a> to resolve the function name:</p>
  1132. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">myFunc</span><span class="p">():</span>
  1133. <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;hello&quot;</span><span class="p">)</span>
  1134. <span class="n">fname</span> <span class="o">=</span> <span class="s2">&quot;myFunc&quot;</span>
  1135. <span class="n">f</span> <span class="o">=</span> <span class="nb">locals</span><span class="p">()[</span><span class="n">fname</span><span class="p">]</span>
  1136. <span class="n">f</span><span class="p">()</span>
  1137. </pre></div>
  1138. </div>
  1139. </li>
  1140. </ul>
  1141. </section>
  1142. <section id="is-there-an-equivalent-to-perl-s-chomp-for-removing-trailing-newlines-from-strings">
  1143. <h3><a class="toc-backref" href="#id35" role="doc-backlink">Is there an equivalent to Perl’s chomp() for removing trailing newlines from strings?</a><a class="headerlink" href="#is-there-an-equivalent-to-perl-s-chomp-for-removing-trailing-newlines-from-strings" title="Link to this heading">¶</a></h3>
  1144. <p>You can use <code class="docutils literal notranslate"><span class="pre">S.rstrip(&quot;\r\n&quot;)</span></code> to remove all occurrences of any line
  1145. terminator from the end of the string <code class="docutils literal notranslate"><span class="pre">S</span></code> without removing other trailing
  1146. whitespace. If the string <code class="docutils literal notranslate"><span class="pre">S</span></code> represents more than one line, with several
  1147. empty lines at the end, the line terminators for all the blank lines will
  1148. be removed:</p>
  1149. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">lines</span> <span class="o">=</span> <span class="p">(</span><span class="s2">&quot;line 1 </span><span class="se">\r\n</span><span class="s2">&quot;</span>
  1150. <span class="gp">... </span> <span class="s2">&quot;</span><span class="se">\r\n</span><span class="s2">&quot;</span>
  1151. <span class="gp">... </span> <span class="s2">&quot;</span><span class="se">\r\n</span><span class="s2">&quot;</span><span class="p">)</span>
  1152. <span class="gp">&gt;&gt;&gt; </span><span class="n">lines</span><span class="o">.</span><span class="n">rstrip</span><span class="p">(</span><span class="s2">&quot;</span><span class="se">\n\r</span><span class="s2">&quot;</span><span class="p">)</span>
  1153. <span class="go">&#39;line 1 &#39;</span>
  1154. </pre></div>
  1155. </div>
  1156. <p>Since this is typically only desired when reading text one line at a time, using
  1157. <code class="docutils literal notranslate"><span class="pre">S.rstrip()</span></code> this way works well.</p>
  1158. </section>
  1159. <section id="is-there-a-scanf-or-sscanf-equivalent">
  1160. <h3><a class="toc-backref" href="#id36" role="doc-backlink">Is there a scanf() or sscanf() equivalent?</a><a class="headerlink" href="#is-there-a-scanf-or-sscanf-equivalent" title="Link to this heading">¶</a></h3>
  1161. <p>Not as such.</p>
  1162. <p>For simple input parsing, the easiest approach is usually to split the line into
  1163. whitespace-delimited words using the <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> method of string objects
  1164. and then convert decimal strings to numeric values using <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> or
  1165. <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-func docutils literal notranslate"><span class="pre">float()</span></code></a>. <code class="xref py py-meth docutils literal notranslate"><span class="pre">split()</span></code> supports an optional “sep” parameter which is useful
  1166. if the line uses something other than whitespace as a separator.</p>
  1167. <p>For more complicated input parsing, regular expressions are more powerful
  1168. than C’s <code class="docutils literal notranslate"><span class="pre">sscanf</span></code> and better suited for the task.</p>
  1169. </section>
  1170. <section id="what-does-unicodedecodeerror-or-unicodeencodeerror-error-mean">
  1171. <h3><a class="toc-backref" href="#id37" role="doc-backlink">What does ‘UnicodeDecodeError’ or ‘UnicodeEncodeError’ error mean?</a><a class="headerlink" href="#what-does-unicodedecodeerror-or-unicodeencodeerror-error-mean" title="Link to this heading">¶</a></h3>
  1172. <p>See the <a class="reference internal" href="../howto/unicode.html#unicode-howto"><span class="std std-ref">Unicode HOWTO</span></a>.</p>
  1173. </section>
  1174. <section id="can-i-end-a-raw-string-with-an-odd-number-of-backslashes">
  1175. <span id="faq-programming-raw-string-backslash"></span><h3><a class="toc-backref" href="#id38" role="doc-backlink">Can I end a raw string with an odd number of backslashes?</a><a class="headerlink" href="#can-i-end-a-raw-string-with-an-odd-number-of-backslashes" title="Link to this heading">¶</a></h3>
  1176. <p>A raw string ending with an odd number of backslashes will escape the string’s quote:</p>
  1177. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">r</span><span class="s1">&#39;C:\this\will\not\work</span><span class="se">\&#39;</span>
  1178. File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>
  1179. <span class="w"> </span><span class="sa">r</span><span class="s1">&#39;C:\this\will\not\work</span><span class="se">\&#39;</span>
  1180. <span class="w"> </span><span class="pm">^</span>
  1181. <span class="gr">SyntaxError</span>: <span class="n">unterminated string literal (detected at line 1)</span>
  1182. </pre></div>
  1183. </div>
  1184. <p>There are several workarounds for this. One is to use regular strings and double
  1185. the backslashes:</p>
  1186. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;C:</span><span class="se">\\</span><span class="s1">this</span><span class="se">\\</span><span class="s1">will</span><span class="se">\\</span><span class="s1">work</span><span class="se">\\</span><span class="s1">&#39;</span>
  1187. <span class="go">&#39;C:\\this\\will\\work\\&#39;</span>
  1188. </pre></div>
  1189. </div>
  1190. <p>Another is to concatenate a regular string containing an escaped backslash to the
  1191. raw string:</p>
  1192. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">r</span><span class="s1">&#39;C:\this\will\work&#39;</span> <span class="s1">&#39;</span><span class="se">\\</span><span class="s1">&#39;</span>
  1193. <span class="go">&#39;C:\\this\\will\\work\\&#39;</span>
  1194. </pre></div>
  1195. </div>
  1196. <p>It is also possible to use <a class="reference internal" href="../library/os.path.html#os.path.join" title="os.path.join"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.path.join()</span></code></a> to append a backslash on Windows:</p>
  1197. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;C:\this\will\work&#39;</span><span class="p">,</span> <span class="s1">&#39;&#39;</span><span class="p">)</span>
  1198. <span class="go">&#39;C:\\this\\will\\work\\&#39;</span>
  1199. </pre></div>
  1200. </div>
  1201. <p>Note that while a backslash will “escape” a quote for the purposes of
  1202. determining where the raw string ends, no escaping occurs when interpreting the
  1203. value of the raw string. That is, the backslash remains present in the value of
  1204. the raw string:</p>
  1205. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">r</span><span class="s1">&#39;backslash</span><span class="se">\&#39;</span><span class="s1">preserved&#39;</span>
  1206. <span class="go">&quot;backslash\\&#39;preserved&quot;</span>
  1207. </pre></div>
  1208. </div>
  1209. <p>Also see the specification in the <a class="reference internal" href="../reference/lexical_analysis.html#strings"><span class="std std-ref">language reference</span></a>.</p>
  1210. </section>
  1211. </section>
  1212. <section id="performance">
  1213. <h2><a class="toc-backref" href="#id39" role="doc-backlink">Performance</a><a class="headerlink" href="#performance" title="Link to this heading">¶</a></h2>
  1214. <section id="my-program-is-too-slow-how-do-i-speed-it-up">
  1215. <h3><a class="toc-backref" href="#id40" role="doc-backlink">My program is too slow. How do I speed it up?</a><a class="headerlink" href="#my-program-is-too-slow-how-do-i-speed-it-up" title="Link to this heading">¶</a></h3>
  1216. <p>That’s a tough one, in general. First, here are a list of things to
  1217. remember before diving further:</p>
  1218. <ul class="simple">
  1219. <li><p>Performance characteristics vary across Python implementations. This FAQ
  1220. focuses on <a class="reference internal" href="../glossary.html#term-CPython"><span class="xref std std-term">CPython</span></a>.</p></li>
  1221. <li><p>Behaviour can vary across operating systems, especially when talking about
  1222. I/O or multi-threading.</p></li>
  1223. <li><p>You should always find the hot spots in your program <em>before</em> attempting to
  1224. optimize any code (see the <a class="reference internal" href="../library/profile.html#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> module).</p></li>
  1225. <li><p>Writing benchmark scripts will allow you to iterate quickly when searching
  1226. for improvements (see the <a class="reference internal" href="../library/timeit.html#module-timeit" title="timeit: Measure the execution time of small code snippets."><code class="xref py py-mod docutils literal notranslate"><span class="pre">timeit</span></code></a> module).</p></li>
  1227. <li><p>It is highly recommended to have good code coverage (through unit testing
  1228. or any other technique) before potentially introducing regressions hidden
  1229. in sophisticated optimizations.</p></li>
  1230. </ul>
  1231. <p>That being said, there are many tricks to speed up Python code. Here are
  1232. some general principles which go a long way towards reaching acceptable
  1233. performance levels:</p>
  1234. <ul class="simple">
  1235. <li><p>Making your algorithms faster (or changing to faster ones) can yield
  1236. much larger benefits than trying to sprinkle micro-optimization tricks
  1237. all over your code.</p></li>
  1238. <li><p>Use the right data structures. Study documentation for the <a class="reference internal" href="../library/stdtypes.html#bltin-types"><span class="std std-ref">Built-in Types</span></a>
  1239. and the <a class="reference internal" href="../library/collections.html#module-collections" title="collections: Container datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> module.</p></li>
  1240. <li><p>When the standard library provides a primitive for doing something, it is
  1241. likely (although not guaranteed) to be faster than any alternative you
  1242. may come up with. This is doubly true for primitives written in C, such
  1243. as builtins and some extension types. For example, be sure to use
  1244. either the <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> built-in method or the related <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>
  1245. function to do sorting (and see the <a class="reference internal" href="../howto/sorting.html#sortinghowto"><span class="std std-ref">Sorting Techniques</span></a> for examples
  1246. of moderately advanced usage).</p></li>
  1247. <li><p>Abstractions tend to create indirections and force the interpreter to work
  1248. more. If the levels of indirection outweigh the amount of useful work
  1249. done, your program will be slower. You should avoid excessive abstraction,
  1250. especially under the form of tiny functions or methods (which are also often
  1251. detrimental to readability).</p></li>
  1252. </ul>
  1253. <p>If you have reached the limit of what pure Python can allow, there are tools
  1254. to take you further away. For example, <a class="reference external" href="https://cython.org">Cython</a> can
  1255. compile a slightly modified version of Python code into a C extension, and
  1256. can be used on many different platforms. Cython can take advantage of
  1257. compilation (and optional type annotations) to make your code significantly
  1258. faster than when interpreted. If you are confident in your C programming
  1259. skills, you can also <a class="reference internal" href="../extending/index.html#extending-index"><span class="std std-ref">write a C extension module</span></a>
  1260. yourself.</p>
  1261. <div class="admonition seealso">
  1262. <p class="admonition-title">See also</p>
  1263. <p>The wiki page devoted to <a class="reference external" href="https://wiki.python.org/moin/PythonSpeed/PerformanceTips">performance tips</a>.</p>
  1264. </div>
  1265. </section>
  1266. <section id="what-is-the-most-efficient-way-to-concatenate-many-strings-together">
  1267. <span id="efficient-string-concatenation"></span><h3><a class="toc-backref" href="#id41" role="doc-backlink">What is the most efficient way to concatenate many strings together?</a><a class="headerlink" href="#what-is-the-most-efficient-way-to-concatenate-many-strings-together" title="Link to this heading">¶</a></h3>
  1268. <p><a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> and <a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> objects are immutable, therefore concatenating
  1269. many strings together is inefficient as each concatenation creates a new
  1270. object. In the general case, the total runtime cost is quadratic in the
  1271. total string length.</p>
  1272. <p>To accumulate many <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> objects, the recommended idiom is to place
  1273. them into a list and call <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">str.join()</span></code></a> at the end:</p>
  1274. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">chunks</span> <span class="o">=</span> <span class="p">[]</span>
  1275. <span class="k">for</span> <span class="n">s</span> <span class="ow">in</span> <span class="n">my_strings</span><span class="p">:</span>
  1276. <span class="n">chunks</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
  1277. <span class="n">result</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">chunks</span><span class="p">)</span>
  1278. </pre></div>
  1279. </div>
  1280. <p>(another reasonably efficient idiom is to use <a class="reference internal" href="../library/io.html#io.StringIO" title="io.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.StringIO</span></code></a>)</p>
  1281. <p>To accumulate many <a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> objects, the recommended idiom is to extend
  1282. a <a class="reference internal" href="../library/stdtypes.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> object using in-place concatenation (the <code class="docutils literal notranslate"><span class="pre">+=</span></code> operator):</p>
  1283. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">result</span> <span class="o">=</span> <span class="nb">bytearray</span><span class="p">()</span>
  1284. <span class="k">for</span> <span class="n">b</span> <span class="ow">in</span> <span class="n">my_bytes_objects</span><span class="p">:</span>
  1285. <span class="n">result</span> <span class="o">+=</span> <span class="n">b</span>
  1286. </pre></div>
  1287. </div>
  1288. </section>
  1289. </section>
  1290. <section id="sequences-tuples-lists">
  1291. <h2><a class="toc-backref" href="#id42" role="doc-backlink">Sequences (Tuples/Lists)</a><a class="headerlink" href="#sequences-tuples-lists" title="Link to this heading">¶</a></h2>
  1292. <section id="how-do-i-convert-between-tuples-and-lists">
  1293. <h3><a class="toc-backref" href="#id43" role="doc-backlink">How do I convert between tuples and lists?</a><a class="headerlink" href="#how-do-i-convert-between-tuples-and-lists" title="Link to this heading">¶</a></h3>
  1294. <p>The type constructor <code class="docutils literal notranslate"><span class="pre">tuple(seq)</span></code> converts any sequence (actually, any
  1295. iterable) into a tuple with the same items in the same order.</p>
  1296. <p>For example, <code class="docutils literal notranslate"><span class="pre">tuple([1,</span> <span class="pre">2,</span> <span class="pre">3])</span></code> yields <code class="docutils literal notranslate"><span class="pre">(1,</span> <span class="pre">2,</span> <span class="pre">3)</span></code> and <code class="docutils literal notranslate"><span class="pre">tuple('abc')</span></code>
  1297. yields <code class="docutils literal notranslate"><span class="pre">('a',</span> <span class="pre">'b',</span> <span class="pre">'c')</span></code>. If the argument is a tuple, it does not make a copy
  1298. but returns the same object, so it is cheap to call <a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-func docutils literal notranslate"><span class="pre">tuple()</span></code></a> when you
  1299. aren’t sure that an object is already a tuple.</p>
  1300. <p>The type constructor <code class="docutils literal notranslate"><span class="pre">list(seq)</span></code> converts any sequence or iterable into a list
  1301. with the same items in the same order. For example, <code class="docutils literal notranslate"><span class="pre">list((1,</span> <span class="pre">2,</span> <span class="pre">3))</span></code> yields
  1302. <code class="docutils literal notranslate"><span class="pre">[1,</span> <span class="pre">2,</span> <span class="pre">3]</span></code> and <code class="docutils literal notranslate"><span class="pre">list('abc')</span></code> yields <code class="docutils literal notranslate"><span class="pre">['a',</span> <span class="pre">'b',</span> <span class="pre">'c']</span></code>. If the argument
  1303. is a list, it makes a copy just like <code class="docutils literal notranslate"><span class="pre">seq[:]</span></code> would.</p>
  1304. </section>
  1305. <section id="what-s-a-negative-index">
  1306. <h3><a class="toc-backref" href="#id44" role="doc-backlink">What’s a negative index?</a><a class="headerlink" href="#what-s-a-negative-index" title="Link to this heading">¶</a></h3>
  1307. <p>Python sequences are indexed with positive numbers and negative numbers. For
  1308. positive numbers 0 is the first index 1 is the second index and so forth. For
  1309. negative indices -1 is the last index and -2 is the penultimate (next to last)
  1310. index and so forth. Think of <code class="docutils literal notranslate"><span class="pre">seq[-n]</span></code> as the same as <code class="docutils literal notranslate"><span class="pre">seq[len(seq)-n]</span></code>.</p>
  1311. <p>Using negative indices can be very convenient. For example <code class="docutils literal notranslate"><span class="pre">S[:-1]</span></code> is all of
  1312. the string except for its last character, which is useful for removing the
  1313. trailing newline from a string.</p>
  1314. </section>
  1315. <section id="how-do-i-iterate-over-a-sequence-in-reverse-order">
  1316. <h3><a class="toc-backref" href="#id45" role="doc-backlink">How do I iterate over a sequence in reverse order?</a><a class="headerlink" href="#how-do-i-iterate-over-a-sequence-in-reverse-order" title="Link to this heading">¶</a></h3>
  1317. <p>Use the <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal notranslate"><span class="pre">reversed()</span></code></a> built-in function:</p>
  1318. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">reversed</span><span class="p">(</span><span class="n">sequence</span><span class="p">):</span>
  1319. <span class="o">...</span> <span class="c1"># do something with x ...</span>
  1320. </pre></div>
  1321. </div>
  1322. <p>This won’t touch your original sequence, but build a new copy with reversed
  1323. order to iterate over.</p>
  1324. </section>
  1325. <section id="how-do-you-remove-duplicates-from-a-list">
  1326. <h3><a class="toc-backref" href="#id46" role="doc-backlink">How do you remove duplicates from a list?</a><a class="headerlink" href="#how-do-you-remove-duplicates-from-a-list" title="Link to this heading">¶</a></h3>
  1327. <p>See the Python Cookbook for a long discussion of many ways to do this:</p>
  1328. <blockquote>
  1329. <div><p><a class="reference external" href="https://code.activestate.com/recipes/52560/">https://code.activestate.com/recipes/52560/</a></p>
  1330. </div></blockquote>
  1331. <p>If you don’t mind reordering the list, sort it and then scan from the end of the
  1332. list, deleting duplicates as you go:</p>
  1333. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">mylist</span><span class="p">:</span>
  1334. <span class="n">mylist</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span>
  1335. <span class="n">last</span> <span class="o">=</span> <span class="n">mylist</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
  1336. <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">mylist</span><span class="p">)</span><span class="o">-</span><span class="mi">2</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">):</span>
  1337. <span class="k">if</span> <span class="n">last</span> <span class="o">==</span> <span class="n">mylist</span><span class="p">[</span><span class="n">i</span><span class="p">]:</span>
  1338. <span class="k">del</span> <span class="n">mylist</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
  1339. <span class="k">else</span><span class="p">:</span>
  1340. <span class="n">last</span> <span class="o">=</span> <span class="n">mylist</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
  1341. </pre></div>
  1342. </div>
  1343. <p>If all elements of the list may be used as set keys (i.e. they are all
  1344. <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a>) this is often faster</p>
  1345. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">mylist</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="nb">set</span><span class="p">(</span><span class="n">mylist</span><span class="p">))</span>
  1346. </pre></div>
  1347. </div>
  1348. <p>This converts the list into a set, thereby removing duplicates, and then back
  1349. into a list.</p>
  1350. </section>
  1351. <section id="how-do-you-remove-multiple-items-from-a-list">
  1352. <h3><a class="toc-backref" href="#id47" role="doc-backlink">How do you remove multiple items from a list</a><a class="headerlink" href="#how-do-you-remove-multiple-items-from-a-list" title="Link to this heading">¶</a></h3>
  1353. <p>As with removing duplicates, explicitly iterating in reverse with a
  1354. delete condition is one possibility. However, it is easier and faster
  1355. to use slice replacement with an implicit or explicit forward iteration.
  1356. Here are three variations.:</p>
  1357. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">mylist</span><span class="p">[:]</span> <span class="o">=</span> <span class="nb">filter</span><span class="p">(</span><span class="n">keep_function</span><span class="p">,</span> <span class="n">mylist</span><span class="p">)</span>
  1358. <span class="n">mylist</span><span class="p">[:]</span> <span class="o">=</span> <span class="p">(</span><span class="n">x</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">mylist</span> <span class="k">if</span> <span class="n">keep_condition</span><span class="p">)</span>
  1359. <span class="n">mylist</span><span class="p">[:]</span> <span class="o">=</span> <span class="p">[</span><span class="n">x</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">mylist</span> <span class="k">if</span> <span class="n">keep_condition</span><span class="p">]</span>
  1360. </pre></div>
  1361. </div>
  1362. <p>The list comprehension may be fastest.</p>
  1363. </section>
  1364. <section id="how-do-you-make-an-array-in-python">
  1365. <h3><a class="toc-backref" href="#id48" role="doc-backlink">How do you make an array in Python?</a><a class="headerlink" href="#how-do-you-make-an-array-in-python" title="Link to this heading">¶</a></h3>
  1366. <p>Use a list:</p>
  1367. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="s2">&quot;this&quot;</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="s2">&quot;is&quot;</span><span class="p">,</span> <span class="s2">&quot;an&quot;</span><span class="p">,</span> <span class="s2">&quot;array&quot;</span><span class="p">]</span>
  1368. </pre></div>
  1369. </div>
  1370. <p>Lists are equivalent to C or Pascal arrays in their time complexity; the primary
  1371. difference is that a Python list can contain objects of many different types.</p>
  1372. <p>The <code class="docutils literal notranslate"><span class="pre">array</span></code> module also provides methods for creating arrays of fixed types
  1373. with compact representations, but they are slower to index than lists. Also
  1374. note that <a class="reference external" href="https://numpy.org/">NumPy</a>
  1375. and other third party packages define array-like structures with
  1376. various characteristics as well.</p>
  1377. <p>To get Lisp-style linked lists, you can emulate <em>cons cells</em> using tuples:</p>
  1378. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">lisp_list</span> <span class="o">=</span> <span class="p">(</span><span class="s2">&quot;like&quot;</span><span class="p">,</span> <span class="p">(</span><span class="s2">&quot;this&quot;</span><span class="p">,</span> <span class="p">(</span><span class="s2">&quot;example&quot;</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span> <span class="p">)</span> <span class="p">)</span>
  1379. </pre></div>
  1380. </div>
  1381. <p>If mutability is desired, you could use lists instead of tuples. Here the
  1382. analogue of a Lisp <em>car</em> is <code class="docutils literal notranslate"><span class="pre">lisp_list[0]</span></code> and the analogue of <em>cdr</em> is
  1383. <code class="docutils literal notranslate"><span class="pre">lisp_list[1]</span></code>. Only do this if you’re sure you really need to, because it’s
  1384. usually a lot slower than using Python lists.</p>
  1385. </section>
  1386. <section id="how-do-i-create-a-multidimensional-list">
  1387. <span id="faq-multidimensional-list"></span><h3><a class="toc-backref" href="#id49" role="doc-backlink">How do I create a multidimensional list?</a><a class="headerlink" href="#how-do-i-create-a-multidimensional-list" title="Link to this heading">¶</a></h3>
  1388. <p>You probably tried to make a multidimensional array like this:</p>
  1389. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">A</span> <span class="o">=</span> <span class="p">[[</span><span class="kc">None</span><span class="p">]</span> <span class="o">*</span> <span class="mi">2</span><span class="p">]</span> <span class="o">*</span> <span class="mi">3</span>
  1390. </pre></div>
  1391. </div>
  1392. <p>This looks correct if you print it:</p>
  1393. <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">A</span>
  1394. <span class="go">[[None, None], [None, None], [None, None]]</span>
  1395. </pre></div>
  1396. </div>
  1397. <p>But when you assign a value, it shows up in multiple places:</p>
  1398. <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">A</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="mi">5</span>
  1399. <span class="gp">&gt;&gt;&gt; </span><span class="n">A</span>
  1400. <span class="go">[[5, None], [5, None], [5, None]]</span>
  1401. </pre></div>
  1402. </div>
  1403. <p>The reason is that replicating a list with <code class="docutils literal notranslate"><span class="pre">*</span></code> doesn’t create copies, it only
  1404. creates references to the existing objects. The <code class="docutils literal notranslate"><span class="pre">*3</span></code> creates a list
  1405. containing 3 references to the same list of length two. Changes to one row will
  1406. show in all rows, which is almost certainly not what you want.</p>
  1407. <p>The suggested approach is to create a list of the desired length first and then
  1408. fill in each element with a newly created list:</p>
  1409. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">A</span> <span class="o">=</span> <span class="p">[</span><span class="kc">None</span><span class="p">]</span> <span class="o">*</span> <span class="mi">3</span>
  1410. <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">):</span>
  1411. <span class="n">A</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="kc">None</span><span class="p">]</span> <span class="o">*</span> <span class="mi">2</span>
  1412. </pre></div>
  1413. </div>
  1414. <p>This generates a list containing 3 different lists of length two. You can also
  1415. use a list comprehension:</p>
  1416. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">w</span><span class="p">,</span> <span class="n">h</span> <span class="o">=</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span>
  1417. <span class="n">A</span> <span class="o">=</span> <span class="p">[[</span><span class="kc">None</span><span class="p">]</span> <span class="o">*</span> <span class="n">w</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">h</span><span class="p">)]</span>
  1418. </pre></div>
  1419. </div>
  1420. <p>Or, you can use an extension that provides a matrix datatype; <a class="reference external" href="https://numpy.org/">NumPy</a> is the best known.</p>
  1421. </section>
  1422. <section id="how-do-i-apply-a-method-or-function-to-a-sequence-of-objects">
  1423. <h3><a class="toc-backref" href="#id50" role="doc-backlink">How do I apply a method or function to a sequence of objects?</a><a class="headerlink" href="#how-do-i-apply-a-method-or-function-to-a-sequence-of-objects" title="Link to this heading">¶</a></h3>
  1424. <p>To call a method or function and accumulate the return values is a list,
  1425. a <a class="reference internal" href="../glossary.html#term-list-comprehension"><span class="xref std std-term">list comprehension</span></a> is an elegant solution:</p>
  1426. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">result</span> <span class="o">=</span> <span class="p">[</span><span class="n">obj</span><span class="o">.</span><span class="n">method</span><span class="p">()</span> <span class="k">for</span> <span class="n">obj</span> <span class="ow">in</span> <span class="n">mylist</span><span class="p">]</span>
  1427. <span class="n">result</span> <span class="o">=</span> <span class="p">[</span><span class="n">function</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span> <span class="k">for</span> <span class="n">obj</span> <span class="ow">in</span> <span class="n">mylist</span><span class="p">]</span>
  1428. </pre></div>
  1429. </div>
  1430. <p>To just run the method or function without saving the return values,
  1431. a plain <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> loop will suffice:</p>
  1432. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">obj</span> <span class="ow">in</span> <span class="n">mylist</span><span class="p">:</span>
  1433. <span class="n">obj</span><span class="o">.</span><span class="n">method</span><span class="p">()</span>
  1434. <span class="k">for</span> <span class="n">obj</span> <span class="ow">in</span> <span class="n">mylist</span><span class="p">:</span>
  1435. <span class="n">function</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>
  1436. </pre></div>
  1437. </div>
  1438. </section>
  1439. <section id="why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works">
  1440. <span id="faq-augmented-assignment-tuple-error"></span><h3><a class="toc-backref" href="#id51" role="doc-backlink">Why does a_tuple[i] += [‘item’] raise an exception when the addition works?</a><a class="headerlink" href="#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works" title="Link to this heading">¶</a></h3>
  1441. <p>This is because of a combination of the fact that augmented assignment
  1442. operators are <em>assignment</em> operators, and the difference between mutable and
  1443. immutable objects in Python.</p>
  1444. <p>This discussion applies in general when augmented assignment operators are
  1445. applied to elements of a tuple that point to mutable objects, but we’ll use
  1446. a <code class="docutils literal notranslate"><span class="pre">list</span></code> and <code class="docutils literal notranslate"><span class="pre">+=</span></code> as our exemplar.</p>
  1447. <p>If you wrote:</p>
  1448. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a_tuple</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>
  1449. <span class="gp">&gt;&gt;&gt; </span><span class="n">a_tuple</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">+=</span> <span class="mi">1</span>
  1450. <span class="gt">Traceback (most recent call last):</span>
  1451. <span class="w"> </span><span class="c">...</span>
  1452. <span class="gr">TypeError</span>: <span class="n">&#39;tuple&#39; object does not support item assignment</span>
  1453. </pre></div>
  1454. </div>
  1455. <p>The reason for the exception should be immediately clear: <code class="docutils literal notranslate"><span class="pre">1</span></code> is added to the
  1456. object <code class="docutils literal notranslate"><span class="pre">a_tuple[0]</span></code> points to (<code class="docutils literal notranslate"><span class="pre">1</span></code>), producing the result object, <code class="docutils literal notranslate"><span class="pre">2</span></code>,
  1457. but when we attempt to assign the result of the computation, <code class="docutils literal notranslate"><span class="pre">2</span></code>, to element
  1458. <code class="docutils literal notranslate"><span class="pre">0</span></code> of the tuple, we get an error because we can’t change what an element of
  1459. a tuple points to.</p>
  1460. <p>Under the covers, what this augmented assignment statement is doing is
  1461. approximately this:</p>
  1462. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">result</span> <span class="o">=</span> <span class="n">a_tuple</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">+</span> <span class="mi">1</span>
  1463. <span class="gp">&gt;&gt;&gt; </span><span class="n">a_tuple</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="n">result</span>
  1464. <span class="gt">Traceback (most recent call last):</span>
  1465. <span class="w"> </span><span class="c">...</span>
  1466. <span class="gr">TypeError</span>: <span class="n">&#39;tuple&#39; object does not support item assignment</span>
  1467. </pre></div>
  1468. </div>
  1469. <p>It is the assignment part of the operation that produces the error, since a
  1470. tuple is immutable.</p>
  1471. <p>When you write something like:</p>
  1472. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a_tuple</span> <span class="o">=</span> <span class="p">([</span><span class="s1">&#39;foo&#39;</span><span class="p">],</span> <span class="s1">&#39;bar&#39;</span><span class="p">)</span>
  1473. <span class="gp">&gt;&gt;&gt; </span><span class="n">a_tuple</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">+=</span> <span class="p">[</span><span class="s1">&#39;item&#39;</span><span class="p">]</span>
  1474. <span class="gt">Traceback (most recent call last):</span>
  1475. <span class="w"> </span><span class="c">...</span>
  1476. <span class="gr">TypeError</span>: <span class="n">&#39;tuple&#39; object does not support item assignment</span>
  1477. </pre></div>
  1478. </div>
  1479. <p>The exception is a bit more surprising, and even more surprising is the fact
  1480. that even though there was an error, the append worked:</p>
  1481. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a_tuple</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
  1482. <span class="go">[&#39;foo&#39;, &#39;item&#39;]</span>
  1483. </pre></div>
  1484. </div>
  1485. <p>To see why this happens, you need to know that (a) if an object implements an
  1486. <a class="reference internal" href="../reference/datamodel.html#object.__iadd__" title="object.__iadd__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iadd__()</span></code></a> magic method, it gets called when the <code class="docutils literal notranslate"><span class="pre">+=</span></code> augmented
  1487. assignment
  1488. is executed, and its return value is what gets used in the assignment statement;
  1489. and (b) for lists, <code class="xref py py-meth docutils literal notranslate"><span class="pre">__iadd__()</span></code> is equivalent to calling <code class="xref py py-meth docutils literal notranslate"><span class="pre">extend()</span></code> on the list
  1490. and returning the list. That’s why we say that for lists, <code class="docutils literal notranslate"><span class="pre">+=</span></code> is a
  1491. “shorthand” for <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.extend()</span></code>:</p>
  1492. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a_list</span> <span class="o">=</span> <span class="p">[]</span>
  1493. <span class="gp">&gt;&gt;&gt; </span><span class="n">a_list</span> <span class="o">+=</span> <span class="p">[</span><span class="mi">1</span><span class="p">]</span>
  1494. <span class="gp">&gt;&gt;&gt; </span><span class="n">a_list</span>
  1495. <span class="go">[1]</span>
  1496. </pre></div>
  1497. </div>
  1498. <p>This is equivalent to:</p>
  1499. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">result</span> <span class="o">=</span> <span class="n">a_list</span><span class="o">.</span><span class="fm">__iadd__</span><span class="p">([</span><span class="mi">1</span><span class="p">])</span>
  1500. <span class="gp">&gt;&gt;&gt; </span><span class="n">a_list</span> <span class="o">=</span> <span class="n">result</span>
  1501. </pre></div>
  1502. </div>
  1503. <p>The object pointed to by a_list has been mutated, and the pointer to the
  1504. mutated object is assigned back to <code class="docutils literal notranslate"><span class="pre">a_list</span></code>. The end result of the
  1505. assignment is a no-op, since it is a pointer to the same object that <code class="docutils literal notranslate"><span class="pre">a_list</span></code>
  1506. was previously pointing to, but the assignment still happens.</p>
  1507. <p>Thus, in our tuple example what is happening is equivalent to:</p>
  1508. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">result</span> <span class="o">=</span> <span class="n">a_tuple</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="fm">__iadd__</span><span class="p">([</span><span class="s1">&#39;item&#39;</span><span class="p">])</span>
  1509. <span class="gp">&gt;&gt;&gt; </span><span class="n">a_tuple</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="n">result</span>
  1510. <span class="gt">Traceback (most recent call last):</span>
  1511. <span class="w"> </span><span class="c">...</span>
  1512. <span class="gr">TypeError</span>: <span class="n">&#39;tuple&#39; object does not support item assignment</span>
  1513. </pre></div>
  1514. </div>
  1515. <p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">__iadd__()</span></code> succeeds, and thus the list is extended, but even though
  1516. <code class="docutils literal notranslate"><span class="pre">result</span></code> points to the same object that <code class="docutils literal notranslate"><span class="pre">a_tuple[0]</span></code> already points to,
  1517. that final assignment still results in an error, because tuples are immutable.</p>
  1518. </section>
  1519. <section id="i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python">
  1520. <h3><a class="toc-backref" href="#id52" role="doc-backlink">I want to do a complicated sort: can you do a Schwartzian Transform in Python?</a><a class="headerlink" href="#i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python" title="Link to this heading">¶</a></h3>
  1521. <p>The technique, attributed to Randal Schwartz of the Perl community, sorts the
  1522. elements of a list by a metric which maps each element to its “sort value”. In
  1523. Python, use the <code class="docutils literal notranslate"><span class="pre">key</span></code> argument for the <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> method:</p>
  1524. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">Isorted</span> <span class="o">=</span> <span class="n">L</span><span class="p">[:]</span>
  1525. <span class="n">Isorted</span><span class="o">.</span><span class="n">sort</span><span class="p">(</span><span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">s</span><span class="p">:</span> <span class="nb">int</span><span class="p">(</span><span class="n">s</span><span class="p">[</span><span class="mi">10</span><span class="p">:</span><span class="mi">15</span><span class="p">]))</span>
  1526. </pre></div>
  1527. </div>
  1528. </section>
  1529. <section id="how-can-i-sort-one-list-by-values-from-another-list">
  1530. <h3><a class="toc-backref" href="#id53" role="doc-backlink">How can I sort one list by values from another list?</a><a class="headerlink" href="#how-can-i-sort-one-list-by-values-from-another-list" title="Link to this heading">¶</a></h3>
  1531. <p>Merge them into an iterator of tuples, sort the resulting list, and then pick
  1532. out the element you want.</p>
  1533. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">list1</span> <span class="o">=</span> <span class="p">[</span><span class="s2">&quot;what&quot;</span><span class="p">,</span> <span class="s2">&quot;I&#39;m&quot;</span><span class="p">,</span> <span class="s2">&quot;sorting&quot;</span><span class="p">,</span> <span class="s2">&quot;by&quot;</span><span class="p">]</span>
  1534. <span class="gp">&gt;&gt;&gt; </span><span class="n">list2</span> <span class="o">=</span> <span class="p">[</span><span class="s2">&quot;something&quot;</span><span class="p">,</span> <span class="s2">&quot;else&quot;</span><span class="p">,</span> <span class="s2">&quot;to&quot;</span><span class="p">,</span> <span class="s2">&quot;sort&quot;</span><span class="p">]</span>
  1535. <span class="gp">&gt;&gt;&gt; </span><span class="n">pairs</span> <span class="o">=</span> <span class="nb">zip</span><span class="p">(</span><span class="n">list1</span><span class="p">,</span> <span class="n">list2</span><span class="p">)</span>
  1536. <span class="gp">&gt;&gt;&gt; </span><span class="n">pairs</span> <span class="o">=</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">pairs</span><span class="p">)</span>
  1537. <span class="gp">&gt;&gt;&gt; </span><span class="n">pairs</span>
  1538. <span class="go">[(&quot;I&#39;m&quot;, &#39;else&#39;), (&#39;by&#39;, &#39;sort&#39;), (&#39;sorting&#39;, &#39;to&#39;), (&#39;what&#39;, &#39;something&#39;)]</span>
  1539. <span class="gp">&gt;&gt;&gt; </span><span class="n">result</span> <span class="o">=</span> <span class="p">[</span><span class="n">x</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">pairs</span><span class="p">]</span>
  1540. <span class="gp">&gt;&gt;&gt; </span><span class="n">result</span>
  1541. <span class="go">[&#39;else&#39;, &#39;sort&#39;, &#39;to&#39;, &#39;something&#39;]</span>
  1542. </pre></div>
  1543. </div>
  1544. </section>
  1545. </section>
  1546. <section id="objects">
  1547. <h2><a class="toc-backref" href="#id54" role="doc-backlink">Objects</a><a class="headerlink" href="#objects" title="Link to this heading">¶</a></h2>
  1548. <section id="what-is-a-class">
  1549. <h3><a class="toc-backref" href="#id55" role="doc-backlink">What is a class?</a><a class="headerlink" href="#what-is-a-class" title="Link to this heading">¶</a></h3>
  1550. <p>A class is the particular object type created by executing a class statement.
  1551. Class objects are used as templates to create instance objects, which embody
  1552. both the data (attributes) and code (methods) specific to a datatype.</p>
  1553. <p>A class can be based on one or more other classes, called its base class(es). It
  1554. then inherits the attributes and methods of its base classes. This allows an
  1555. object model to be successively refined by inheritance. You might have a
  1556. generic <code class="docutils literal notranslate"><span class="pre">Mailbox</span></code> class that provides basic accessor methods for a mailbox,
  1557. and subclasses such as <code class="docutils literal notranslate"><span class="pre">MboxMailbox</span></code>, <code class="docutils literal notranslate"><span class="pre">MaildirMailbox</span></code>, <code class="docutils literal notranslate"><span class="pre">OutlookMailbox</span></code>
  1558. that handle various specific mailbox formats.</p>
  1559. </section>
  1560. <section id="what-is-a-method">
  1561. <h3><a class="toc-backref" href="#id56" role="doc-backlink">What is a method?</a><a class="headerlink" href="#what-is-a-method" title="Link to this heading">¶</a></h3>
  1562. <p>A method is a function on some object <code class="docutils literal notranslate"><span class="pre">x</span></code> that you normally call as
  1563. <code class="docutils literal notranslate"><span class="pre">x.name(arguments...)</span></code>. Methods are defined as functions inside the class
  1564. definition:</p>
  1565. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
  1566. <span class="k">def</span> <span class="nf">meth</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">arg</span><span class="p">):</span>
  1567. <span class="k">return</span> <span class="n">arg</span> <span class="o">*</span> <span class="mi">2</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">attribute</span>
  1568. </pre></div>
  1569. </div>
  1570. </section>
  1571. <section id="what-is-self">
  1572. <h3><a class="toc-backref" href="#id57" role="doc-backlink">What is self?</a><a class="headerlink" href="#what-is-self" title="Link to this heading">¶</a></h3>
  1573. <p>Self is merely a conventional name for the first argument of a method. A method
  1574. defined as <code class="docutils literal notranslate"><span class="pre">meth(self,</span> <span class="pre">a,</span> <span class="pre">b,</span> <span class="pre">c)</span></code> should be called as <code class="docutils literal notranslate"><span class="pre">x.meth(a,</span> <span class="pre">b,</span> <span class="pre">c)</span></code> for
  1575. some instance <code class="docutils literal notranslate"><span class="pre">x</span></code> of the class in which the definition occurs; the called
  1576. method will think it is called as <code class="docutils literal notranslate"><span class="pre">meth(x,</span> <span class="pre">a,</span> <span class="pre">b,</span> <span class="pre">c)</span></code>.</p>
  1577. <p>See also <a class="reference internal" href="design.html#why-self"><span class="std std-ref">Why must ‘self’ be used explicitly in method definitions and calls?</span></a>.</p>
  1578. </section>
  1579. <section id="how-do-i-check-if-an-object-is-an-instance-of-a-given-class-or-of-a-subclass-of-it">
  1580. <h3><a class="toc-backref" href="#id58" role="doc-backlink">How do I check if an object is an instance of a given class or of a subclass of it?</a><a class="headerlink" href="#how-do-i-check-if-an-object-is-an-instance-of-a-given-class-or-of-a-subclass-of-it" title="Link to this heading">¶</a></h3>
  1581. <p>Use the built-in function <a class="reference internal" href="../library/functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance(obj,</span> <span class="pre">cls)</span></code></a>. You can
  1582. check if an object
  1583. is an instance of any of a number of classes by providing a tuple instead of a
  1584. single class, e.g. <code class="docutils literal notranslate"><span class="pre">isinstance(obj,</span> <span class="pre">(class1,</span> <span class="pre">class2,</span> <span class="pre">...))</span></code>, and can also
  1585. check whether an object is one of Python’s built-in types, e.g.
  1586. <code class="docutils literal notranslate"><span class="pre">isinstance(obj,</span> <span class="pre">str)</span></code> or <code class="docutils literal notranslate"><span class="pre">isinstance(obj,</span> <span class="pre">(int,</span> <span class="pre">float,</span> <span class="pre">complex))</span></code>.</p>
  1587. <p>Note that <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> also checks for virtual inheritance from an
  1588. <a class="reference internal" href="../glossary.html#term-abstract-base-class"><span class="xref std std-term">abstract base class</span></a>. So, the test will return <code class="docutils literal notranslate"><span class="pre">True</span></code> for a
  1589. registered class even if hasn’t directly or indirectly inherited from it. To
  1590. test for “true inheritance”, scan the <a class="reference internal" href="../glossary.html#term-MRO"><span class="xref std std-term">MRO</span></a> of the class:</p>
  1591. <div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">collections.abc</span> <span class="kn">import</span> <span class="n">Mapping</span>
  1592. <span class="k">class</span> <span class="nc">P</span><span class="p">:</span>
  1593. <span class="k">pass</span>
  1594. <span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="n">P</span><span class="p">):</span>
  1595. <span class="k">pass</span>
  1596. <span class="n">Mapping</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">P</span><span class="p">)</span>
  1597. </pre></div>
  1598. </div>
  1599. <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span>
  1600. <span class="gp">&gt;&gt;&gt; </span><span class="nb">isinstance</span><span class="p">(</span><span class="n">c</span><span class="p">,</span> <span class="n">C</span><span class="p">)</span> <span class="c1"># direct</span>
  1601. <span class="go">True</span>
  1602. <span class="gp">&gt;&gt;&gt; </span><span class="nb">isinstance</span><span class="p">(</span><span class="n">c</span><span class="p">,</span> <span class="n">P</span><span class="p">)</span> <span class="c1"># indirect</span>
  1603. <span class="go">True</span>
  1604. <span class="gp">&gt;&gt;&gt; </span><span class="nb">isinstance</span><span class="p">(</span><span class="n">c</span><span class="p">,</span> <span class="n">Mapping</span><span class="p">)</span> <span class="c1"># virtual</span>
  1605. <span class="go">True</span>
  1606. <span class="go"># Actual inheritance chain</span>
  1607. <span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="n">c</span><span class="p">)</span><span class="o">.</span><span class="vm">__mro__</span>
  1608. <span class="go">(&lt;class &#39;C&#39;&gt;, &lt;class &#39;P&#39;&gt;, &lt;class &#39;object&#39;&gt;)</span>
  1609. <span class="go"># Test for &quot;true inheritance&quot;</span>
  1610. <span class="gp">&gt;&gt;&gt; </span><span class="n">Mapping</span> <span class="ow">in</span> <span class="nb">type</span><span class="p">(</span><span class="n">c</span><span class="p">)</span><span class="o">.</span><span class="vm">__mro__</span>
  1611. <span class="go">False</span>
  1612. </pre></div>
  1613. </div>
  1614. <p>Note that most programs do not 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> on user-defined classes
  1615. very often. If you are developing the classes yourself, a more proper
  1616. object-oriented style is to define methods on the classes that encapsulate a
  1617. particular behaviour, instead of checking the object’s class and doing a
  1618. different thing based on what class it is. For example, if you have a function
  1619. that does something:</p>
  1620. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">search</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span>
  1621. <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">Mailbox</span><span class="p">):</span>
  1622. <span class="o">...</span> <span class="c1"># code to search a mailbox</span>
  1623. <span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">Document</span><span class="p">):</span>
  1624. <span class="o">...</span> <span class="c1"># code to search a document</span>
  1625. <span class="k">elif</span> <span class="o">...</span>
  1626. </pre></div>
  1627. </div>
  1628. <p>A better approach is to define a <code class="docutils literal notranslate"><span class="pre">search()</span></code> method on all the classes and just
  1629. call it:</p>
  1630. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Mailbox</span><span class="p">:</span>
  1631. <span class="k">def</span> <span class="nf">search</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  1632. <span class="o">...</span> <span class="c1"># code to search a mailbox</span>
  1633. <span class="k">class</span> <span class="nc">Document</span><span class="p">:</span>
  1634. <span class="k">def</span> <span class="nf">search</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  1635. <span class="o">...</span> <span class="c1"># code to search a document</span>
  1636. <span class="n">obj</span><span class="o">.</span><span class="n">search</span><span class="p">()</span>
  1637. </pre></div>
  1638. </div>
  1639. </section>
  1640. <section id="what-is-delegation">
  1641. <h3><a class="toc-backref" href="#id59" role="doc-backlink">What is delegation?</a><a class="headerlink" href="#what-is-delegation" title="Link to this heading">¶</a></h3>
  1642. <p>Delegation is an object oriented technique (also called a design pattern).
  1643. Let’s say you have an object <code class="docutils literal notranslate"><span class="pre">x</span></code> and want to change the behaviour of just one
  1644. of its methods. You can create a new class that provides a new implementation
  1645. of the method you’re interested in changing and delegates all other methods to
  1646. the corresponding method of <code class="docutils literal notranslate"><span class="pre">x</span></code>.</p>
  1647. <p>Python programmers can easily implement delegation. For example, the following
  1648. class implements a class that behaves like a file but converts all written data
  1649. to uppercase:</p>
  1650. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">UpperOut</span><span class="p">:</span>
  1651. <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">outfile</span><span class="p">):</span>
  1652. <span class="bp">self</span><span class="o">.</span><span class="n">_outfile</span> <span class="o">=</span> <span class="n">outfile</span>
  1653. <span class="k">def</span> <span class="nf">write</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">s</span><span class="p">):</span>
  1654. <span class="bp">self</span><span class="o">.</span><span class="n">_outfile</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">s</span><span class="o">.</span><span class="n">upper</span><span class="p">())</span>
  1655. <span class="k">def</span> <span class="fm">__getattr__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
  1656. <span class="k">return</span> <span class="nb">getattr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_outfile</span><span class="p">,</span> <span class="n">name</span><span class="p">)</span>
  1657. </pre></div>
  1658. </div>
  1659. <p>Here the <code class="docutils literal notranslate"><span class="pre">UpperOut</span></code> class redefines the <code class="docutils literal notranslate"><span class="pre">write()</span></code> method to convert the
  1660. argument string to uppercase before calling the underlying
  1661. <code class="docutils literal notranslate"><span class="pre">self._outfile.write()</span></code> method. All other methods are delegated to the
  1662. underlying <code class="docutils literal notranslate"><span class="pre">self._outfile</span></code> object. The delegation is accomplished via the
  1663. <a class="reference internal" href="../reference/datamodel.html#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> method; consult <a class="reference internal" href="../reference/datamodel.html#attribute-access"><span class="std std-ref">the language reference</span></a>
  1664. for more information about controlling attribute access.</p>
  1665. <p>Note that for more general cases delegation can get trickier. When attributes
  1666. must be set as well as retrieved, the class must define a <a class="reference internal" href="../reference/datamodel.html#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setattr__()</span></code></a>
  1667. method too, and it must do so carefully. The basic implementation of
  1668. <code class="xref py py-meth docutils literal notranslate"><span class="pre">__setattr__()</span></code> is roughly equivalent to the following:</p>
  1669. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">X</span><span class="p">:</span>
  1670. <span class="o">...</span>
  1671. <span class="k">def</span> <span class="fm">__setattr__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
  1672. <span class="bp">self</span><span class="o">.</span><span class="vm">__dict__</span><span class="p">[</span><span class="n">name</span><span class="p">]</span> <span class="o">=</span> <span class="n">value</span>
  1673. <span class="o">...</span>
  1674. </pre></div>
  1675. </div>
  1676. <p>Most <code class="xref py py-meth docutils literal notranslate"><span class="pre">__setattr__()</span></code> implementations must modify
  1677. <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">self.__dict__</span></code></a> to store
  1678. local state for self without causing an infinite recursion.</p>
  1679. </section>
  1680. <section id="how-do-i-call-a-method-defined-in-a-base-class-from-a-derived-class-that-extends-it">
  1681. <h3><a class="toc-backref" href="#id60" role="doc-backlink">How do I call a method defined in a base class from a derived class that extends it?</a><a class="headerlink" href="#how-do-i-call-a-method-defined-in-a-base-class-from-a-derived-class-that-extends-it" title="Link to this heading">¶</a></h3>
  1682. <p>Use the built-in <a class="reference internal" href="../library/functions.html#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a> function:</p>
  1683. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Derived</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span>
  1684. <span class="k">def</span> <span class="nf">meth</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  1685. <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="n">meth</span><span class="p">()</span> <span class="c1"># calls Base.meth</span>
  1686. </pre></div>
  1687. </div>
  1688. <p>In the example, <a class="reference internal" href="../library/functions.html#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a> will automatically determine the instance from
  1689. which it was called (the <code class="docutils literal notranslate"><span class="pre">self</span></code> value), look up the <a class="reference internal" href="../glossary.html#term-method-resolution-order"><span class="xref std std-term">method resolution
  1690. order</span></a> (MRO) with <code class="docutils literal notranslate"><span class="pre">type(self).__mro__</span></code>, and return the next in line after
  1691. <code class="docutils literal notranslate"><span class="pre">Derived</span></code> in the MRO: <code class="docutils literal notranslate"><span class="pre">Base</span></code>.</p>
  1692. </section>
  1693. <section id="how-can-i-organize-my-code-to-make-it-easier-to-change-the-base-class">
  1694. <h3><a class="toc-backref" href="#id61" role="doc-backlink">How can I organize my code to make it easier to change the base class?</a><a class="headerlink" href="#how-can-i-organize-my-code-to-make-it-easier-to-change-the-base-class" title="Link to this heading">¶</a></h3>
  1695. <p>You could assign the base class to an alias and derive from the alias. Then all
  1696. you have to change is the value assigned to the alias. Incidentally, this trick
  1697. is also handy if you want to decide dynamically (e.g. depending on availability
  1698. of resources) which base class to use. Example:</p>
  1699. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Base</span><span class="p">:</span>
  1700. <span class="o">...</span>
  1701. <span class="n">BaseAlias</span> <span class="o">=</span> <span class="n">Base</span>
  1702. <span class="k">class</span> <span class="nc">Derived</span><span class="p">(</span><span class="n">BaseAlias</span><span class="p">):</span>
  1703. <span class="o">...</span>
  1704. </pre></div>
  1705. </div>
  1706. </section>
  1707. <section id="how-do-i-create-static-class-data-and-static-class-methods">
  1708. <h3><a class="toc-backref" href="#id62" role="doc-backlink">How do I create static class data and static class methods?</a><a class="headerlink" href="#how-do-i-create-static-class-data-and-static-class-methods" title="Link to this heading">¶</a></h3>
  1709. <p>Both static data and static methods (in the sense of C++ or Java) are supported
  1710. in Python.</p>
  1711. <p>For static data, simply define a class attribute. To assign a new value to the
  1712. attribute, you have to explicitly use the class name in the assignment:</p>
  1713. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
  1714. <span class="n">count</span> <span class="o">=</span> <span class="mi">0</span> <span class="c1"># number of times C.__init__ called</span>
  1715. <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  1716. <span class="n">C</span><span class="o">.</span><span class="n">count</span> <span class="o">=</span> <span class="n">C</span><span class="o">.</span><span class="n">count</span> <span class="o">+</span> <span class="mi">1</span>
  1717. <span class="k">def</span> <span class="nf">getcount</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  1718. <span class="k">return</span> <span class="n">C</span><span class="o">.</span><span class="n">count</span> <span class="c1"># or return self.count</span>
  1719. </pre></div>
  1720. </div>
  1721. <p><code class="docutils literal notranslate"><span class="pre">c.count</span></code> also refers to <code class="docutils literal notranslate"><span class="pre">C.count</span></code> for any <code class="docutils literal notranslate"><span class="pre">c</span></code> such that <code class="docutils literal notranslate"><span class="pre">isinstance(c,</span>
  1722. <span class="pre">C)</span></code> holds, unless overridden by <code class="docutils literal notranslate"><span class="pre">c</span></code> itself or by some class on the base-class
  1723. search path from <code class="docutils literal notranslate"><span class="pre">c.__class__</span></code> back to <code class="docutils literal notranslate"><span class="pre">C</span></code>.</p>
  1724. <p>Caution: within a method of C, an assignment like <code class="docutils literal notranslate"><span class="pre">self.count</span> <span class="pre">=</span> <span class="pre">42</span></code> creates a
  1725. new and unrelated instance named “count” in <code class="docutils literal notranslate"><span class="pre">self</span></code>’s own dict. Rebinding of a
  1726. class-static data name must always specify the class whether inside a method or
  1727. not:</p>
  1728. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">C</span><span class="o">.</span><span class="n">count</span> <span class="o">=</span> <span class="mi">314</span>
  1729. </pre></div>
  1730. </div>
  1731. <p>Static methods are possible:</p>
  1732. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
  1733. <span class="nd">@staticmethod</span>
  1734. <span class="k">def</span> <span class="nf">static</span><span class="p">(</span><span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">,</span> <span class="n">arg3</span><span class="p">):</span>
  1735. <span class="c1"># No &#39;self&#39; parameter!</span>
  1736. <span class="o">...</span>
  1737. </pre></div>
  1738. </div>
  1739. <p>However, a far more straightforward way to get the effect of a static method is
  1740. via a simple module-level function:</p>
  1741. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">getcount</span><span class="p">():</span>
  1742. <span class="k">return</span> <span class="n">C</span><span class="o">.</span><span class="n">count</span>
  1743. </pre></div>
  1744. </div>
  1745. <p>If your code is structured so as to define one class (or tightly related class
  1746. hierarchy) per module, this supplies the desired encapsulation.</p>
  1747. </section>
  1748. <section id="how-can-i-overload-constructors-or-methods-in-python">
  1749. <h3><a class="toc-backref" href="#id63" role="doc-backlink">How can I overload constructors (or methods) in Python?</a><a class="headerlink" href="#how-can-i-overload-constructors-or-methods-in-python" title="Link to this heading">¶</a></h3>
  1750. <p>This answer actually applies to all methods, but the question usually comes up
  1751. first in the context of constructors.</p>
  1752. <p>In C++ you’d write</p>
  1753. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">class</span><span class="w"> </span><span class="n">C</span><span class="w"> </span><span class="p">{</span>
  1754. <span class="w"> </span><span class="n">C</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="n">cout</span><span class="w"> </span><span class="o">&lt;&lt;</span><span class="w"> </span><span class="s">&quot;No arguments</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">;</span><span class="w"> </span><span class="p">}</span>
  1755. <span class="w"> </span><span class="n">C</span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">i</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="n">cout</span><span class="w"> </span><span class="o">&lt;&lt;</span><span class="w"> </span><span class="s">&quot;Argument is &quot;</span><span class="w"> </span><span class="o">&lt;&lt;</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">&lt;&lt;</span><span class="w"> </span><span class="s">&quot;</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">;</span><span class="w"> </span><span class="p">}</span>
  1756. <span class="p">}</span>
  1757. </pre></div>
  1758. </div>
  1759. <p>In Python you have to write a single constructor that catches all cases using
  1760. default arguments. For example:</p>
  1761. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
  1762. <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">i</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
  1763. <span class="k">if</span> <span class="n">i</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
  1764. <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;No arguments&quot;</span><span class="p">)</span>
  1765. <span class="k">else</span><span class="p">:</span>
  1766. <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Argument is&quot;</span><span class="p">,</span> <span class="n">i</span><span class="p">)</span>
  1767. </pre></div>
  1768. </div>
  1769. <p>This is not entirely equivalent, but close enough in practice.</p>
  1770. <p>You could also try a variable-length argument list, e.g.</p>
  1771. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><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="o">*</span><span class="n">args</span><span class="p">):</span>
  1772. <span class="o">...</span>
  1773. </pre></div>
  1774. </div>
  1775. <p>The same approach works for all method definitions.</p>
  1776. </section>
  1777. <section id="i-try-to-use-spam-and-i-get-an-error-about-someclassname-spam">
  1778. <h3><a class="toc-backref" href="#id64" role="doc-backlink">I try to use __spam and I get an error about _SomeClassName__spam.</a><a class="headerlink" href="#i-try-to-use-spam-and-i-get-an-error-about-someclassname-spam" title="Link to this heading">¶</a></h3>
  1779. <p>Variable names with double leading underscores are “mangled” to provide a simple
  1780. but effective way to define class private variables. Any identifier of the form
  1781. <code class="docutils literal notranslate"><span class="pre">__spam</span></code> (at least two leading underscores, at most one trailing underscore)
  1782. is textually replaced with <code class="docutils literal notranslate"><span class="pre">_classname__spam</span></code>, where <code class="docutils literal notranslate"><span class="pre">classname</span></code> is the
  1783. current class name with any leading underscores stripped.</p>
  1784. <p>This doesn’t guarantee privacy: an outside user can still deliberately access
  1785. the “_classname__spam” attribute, and private values are visible in the object’s
  1786. <code class="docutils literal notranslate"><span class="pre">__dict__</span></code>. Many Python programmers never bother to use private variable
  1787. names at all.</p>
  1788. </section>
  1789. <section id="my-class-defines-del-but-it-is-not-called-when-i-delete-the-object">
  1790. <h3><a class="toc-backref" href="#id65" role="doc-backlink">My class defines __del__ but it is not called when I delete the object.</a><a class="headerlink" href="#my-class-defines-del-but-it-is-not-called-when-i-delete-the-object" title="Link to this heading">¶</a></h3>
  1791. <p>There are several possible reasons for this.</p>
  1792. <p>The <a class="reference internal" href="../reference/simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> statement does not necessarily call <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> – it simply
  1793. decrements the object’s reference count, and if this reaches zero
  1794. <code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code> is called.</p>
  1795. <p>If your data structures contain circular links (e.g. a tree where each child has
  1796. a parent reference and each parent has a list of children) the reference counts
  1797. will never go back to zero. Once in a while Python runs an algorithm to detect
  1798. such cycles, but the garbage collector might run some time after the last
  1799. reference to your data structure vanishes, so your <code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code> method may be
  1800. called at an inconvenient and random time. This is inconvenient if you’re trying
  1801. to reproduce a problem. Worse, the order in which object’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code>
  1802. methods are executed is arbitrary. You can run <a class="reference internal" href="../library/gc.html#gc.collect" title="gc.collect"><code class="xref py py-func docutils literal notranslate"><span class="pre">gc.collect()</span></code></a> to force a
  1803. collection, but there <em>are</em> pathological cases where objects will never be
  1804. collected.</p>
  1805. <p>Despite the cycle collector, it’s still a good idea to define an explicit
  1806. <code class="docutils literal notranslate"><span class="pre">close()</span></code> method on objects to be called whenever you’re done with them. The
  1807. <code class="docutils literal notranslate"><span class="pre">close()</span></code> method can then remove attributes that refer to subobjects. Don’t
  1808. call <code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code> directly – <code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code> should call <code class="docutils literal notranslate"><span class="pre">close()</span></code> and
  1809. <code class="docutils literal notranslate"><span class="pre">close()</span></code> should make sure that it can be called more than once for the same
  1810. object.</p>
  1811. <p>Another way to avoid cyclical references is to use the <a class="reference internal" href="../library/weakref.html#module-weakref" title="weakref: Support for weak references and weak dictionaries."><code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code></a> module,
  1812. which allows you to point to objects without incrementing their reference count.
  1813. Tree data structures, for instance, should use weak references for their parent
  1814. and sibling references (if they need them!).</p>
  1815. <p>Finally, if your <code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code> method raises an exception, a warning message
  1816. is printed to <a class="reference internal" href="../library/sys.html#sys.stderr" title="sys.stderr"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stderr</span></code></a>.</p>
  1817. </section>
  1818. <section id="how-do-i-get-a-list-of-all-instances-of-a-given-class">
  1819. <h3><a class="toc-backref" href="#id66" role="doc-backlink">How do I get a list of all instances of a given class?</a><a class="headerlink" href="#how-do-i-get-a-list-of-all-instances-of-a-given-class" title="Link to this heading">¶</a></h3>
  1820. <p>Python does not keep track of all instances of a class (or of a built-in type).
  1821. You can program the class’s constructor to keep track of all instances by
  1822. keeping a list of weak references to each instance.</p>
  1823. </section>
  1824. <section id="why-does-the-result-of-id-appear-to-be-not-unique">
  1825. <h3><a class="toc-backref" href="#id67" role="doc-backlink">Why does the result of <code class="docutils literal notranslate"><span class="pre">id()</span></code> appear to be not unique?</a><a class="headerlink" href="#why-does-the-result-of-id-appear-to-be-not-unique" title="Link to this heading">¶</a></h3>
  1826. <p>The <a class="reference internal" href="../library/functions.html#id" title="id"><code class="xref py py-func docutils literal notranslate"><span class="pre">id()</span></code></a> builtin returns an integer that is guaranteed to be unique during
  1827. the lifetime of the object. Since in CPython, this is the object’s memory
  1828. address, it happens frequently that after an object is deleted from memory, the
  1829. next freshly created object is allocated at the same position in memory. This
  1830. is illustrated by this example:</p>
  1831. <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">id</span><span class="p">(</span><span class="mi">1000</span><span class="p">)</span>
  1832. <span class="go">13901272</span>
  1833. <span class="gp">&gt;&gt;&gt; </span><span class="nb">id</span><span class="p">(</span><span class="mi">2000</span><span class="p">)</span>
  1834. <span class="go">13901272</span>
  1835. </pre></div>
  1836. </div>
  1837. <p>The two ids belong to different integer objects that are created before, and
  1838. deleted immediately after execution of the <code class="docutils literal notranslate"><span class="pre">id()</span></code> call. To be sure that
  1839. objects whose id you want to examine are still alive, create another reference
  1840. to the object:</p>
  1841. <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="mi">1000</span><span class="p">;</span> <span class="n">b</span> <span class="o">=</span> <span class="mi">2000</span>
  1842. <span class="gp">&gt;&gt;&gt; </span><span class="nb">id</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
  1843. <span class="go">13901272</span>
  1844. <span class="gp">&gt;&gt;&gt; </span><span class="nb">id</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
  1845. <span class="go">13891296</span>
  1846. </pre></div>
  1847. </div>
  1848. </section>
  1849. <section id="when-can-i-rely-on-identity-tests-with-the-is-operator">
  1850. <h3><a class="toc-backref" href="#id68" role="doc-backlink">When can I rely on identity tests with the <em>is</em> operator?</a><a class="headerlink" href="#when-can-i-rely-on-identity-tests-with-the-is-operator" title="Link to this heading">¶</a></h3>
  1851. <p>The <code class="docutils literal notranslate"><span class="pre">is</span></code> operator tests for object identity. The test <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">is</span> <span class="pre">b</span></code> is
  1852. equivalent to <code class="docutils literal notranslate"><span class="pre">id(a)</span> <span class="pre">==</span> <span class="pre">id(b)</span></code>.</p>
  1853. <p>The most important property of an identity test is that an object is always
  1854. identical to itself, <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">is</span> <span class="pre">a</span></code> always returns <code class="docutils literal notranslate"><span class="pre">True</span></code>. Identity tests are
  1855. usually faster than equality tests. And unlike equality tests, identity tests
  1856. are guaranteed to return a boolean <code class="docutils literal notranslate"><span class="pre">True</span></code> or <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
  1857. <p>However, identity tests can <em>only</em> be substituted for equality tests when
  1858. object identity is assured. Generally, there are three circumstances where
  1859. identity is guaranteed:</p>
  1860. <p>1) Assignments create new names but do not change object identity. After the
  1861. assignment <code class="docutils literal notranslate"><span class="pre">new</span> <span class="pre">=</span> <span class="pre">old</span></code>, it is guaranteed that <code class="docutils literal notranslate"><span class="pre">new</span> <span class="pre">is</span> <span class="pre">old</span></code>.</p>
  1862. <p>2) Putting an object in a container that stores object references does not
  1863. change object identity. After the list assignment <code class="docutils literal notranslate"><span class="pre">s[0]</span> <span class="pre">=</span> <span class="pre">x</span></code>, it is
  1864. guaranteed that <code class="docutils literal notranslate"><span class="pre">s[0]</span> <span class="pre">is</span> <span class="pre">x</span></code>.</p>
  1865. <p>3) If an object is a singleton, it means that only one instance of that object
  1866. can exist. After the assignments <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">None</span></code> and <code class="docutils literal notranslate"><span class="pre">b</span> <span class="pre">=</span> <span class="pre">None</span></code>, it is
  1867. guaranteed that <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">is</span> <span class="pre">b</span></code> because <code class="docutils literal notranslate"><span class="pre">None</span></code> is a singleton.</p>
  1868. <p>In most other circumstances, identity tests are inadvisable and equality tests
  1869. are preferred. In particular, identity tests should not be used to check
  1870. constants such as <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> and <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> which aren’t guaranteed to be
  1871. singletons:</p>
  1872. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="mi">1000</span>
  1873. <span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="mi">500</span>
  1874. <span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">b</span> <span class="o">+</span> <span class="mi">500</span>
  1875. <span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="ow">is</span> <span class="n">c</span>
  1876. <span class="go">False</span>
  1877. <span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="s1">&#39;Python&#39;</span>
  1878. <span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="s1">&#39;Py&#39;</span>
  1879. <span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">b</span> <span class="o">+</span> <span class="s1">&#39;thon&#39;</span>
  1880. <span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="ow">is</span> <span class="n">c</span>
  1881. <span class="go">False</span>
  1882. </pre></div>
  1883. </div>
  1884. <p>Likewise, new instances of mutable containers are never identical:</p>
  1885. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="p">[]</span>
  1886. <span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="p">[]</span>
  1887. <span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="ow">is</span> <span class="n">b</span>
  1888. <span class="go">False</span>
  1889. </pre></div>
  1890. </div>
  1891. <p>In the standard library code, you will see several common patterns for
  1892. correctly using identity tests:</p>
  1893. <p>1) As recommended by <span class="target" id="index-2"></span><a class="pep reference external" href="https://peps.python.org/pep-0008/"><strong>PEP 8</strong></a>, an identity test is the preferred way to check
  1894. for <code class="docutils literal notranslate"><span class="pre">None</span></code>. This reads like plain English in code and avoids confusion with
  1895. other objects that may have boolean values that evaluate to false.</p>
  1896. <p>2) Detecting optional arguments can be tricky when <code class="docutils literal notranslate"><span class="pre">None</span></code> is a valid input
  1897. value. In those situations, you can create a singleton sentinel object
  1898. guaranteed to be distinct from other objects. For example, here is how
  1899. to implement a method that behaves like <a class="reference internal" href="../library/stdtypes.html#dict.pop" title="dict.pop"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.pop()</span></code></a>:</p>
  1900. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">_sentinel</span> <span class="o">=</span> <span class="nb">object</span><span class="p">()</span>
  1901. <span class="k">def</span> <span class="nf">pop</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="n">_sentinel</span><span class="p">):</span>
  1902. <span class="k">if</span> <span class="n">key</span> <span class="ow">in</span> <span class="bp">self</span><span class="p">:</span>
  1903. <span class="n">value</span> <span class="o">=</span> <span class="bp">self</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>
  1904. <span class="k">del</span> <span class="bp">self</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>
  1905. <span class="k">return</span> <span class="n">value</span>
  1906. <span class="k">if</span> <span class="n">default</span> <span class="ow">is</span> <span class="n">_sentinel</span><span class="p">:</span>
  1907. <span class="k">raise</span> <span class="ne">KeyError</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
  1908. <span class="k">return</span> <span class="n">default</span>
  1909. </pre></div>
  1910. </div>
  1911. <p>3) Container implementations sometimes need to augment equality tests with
  1912. identity tests. This prevents the code from being confused by objects such as
  1913. <code class="docutils literal notranslate"><span class="pre">float('NaN')</span></code> that are not equal to themselves.</p>
  1914. <p>For example, here is the implementation of
  1915. <code class="xref py py-meth docutils literal notranslate"><span class="pre">collections.abc.Sequence.__contains__()</span></code>:</p>
  1916. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="fm">__contains__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
  1917. <span class="k">for</span> <span class="n">v</span> <span class="ow">in</span> <span class="bp">self</span><span class="p">:</span>
  1918. <span class="k">if</span> <span class="n">v</span> <span class="ow">is</span> <span class="n">value</span> <span class="ow">or</span> <span class="n">v</span> <span class="o">==</span> <span class="n">value</span><span class="p">:</span>
  1919. <span class="k">return</span> <span class="kc">True</span>
  1920. <span class="k">return</span> <span class="kc">False</span>
  1921. </pre></div>
  1922. </div>
  1923. </section>
  1924. <section id="how-can-a-subclass-control-what-data-is-stored-in-an-immutable-instance">
  1925. <h3><a class="toc-backref" href="#id69" role="doc-backlink">How can a subclass control what data is stored in an immutable instance?</a><a class="headerlink" href="#how-can-a-subclass-control-what-data-is-stored-in-an-immutable-instance" title="Link to this heading">¶</a></h3>
  1926. <p>When subclassing an immutable type, override the <a class="reference internal" href="../reference/datamodel.html#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> method
  1927. instead of the <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> method. The latter only runs <em>after</em> an
  1928. instance is created, which is too late to alter data in an immutable
  1929. instance.</p>
  1930. <p>All of these immutable classes have a different signature than their
  1931. parent class:</p>
  1932. <div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">datetime</span> <span class="kn">import</span> <span class="n">date</span>
  1933. <span class="k">class</span> <span class="nc">FirstOfMonthDate</span><span class="p">(</span><span class="n">date</span><span class="p">):</span>
  1934. <span class="s2">&quot;Always choose the first day of the month&quot;</span>
  1935. <span class="k">def</span> <span class="fm">__new__</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">year</span><span class="p">,</span> <span class="n">month</span><span class="p">,</span> <span class="n">day</span><span class="p">):</span>
  1936. <span class="k">return</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__new__</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">year</span><span class="p">,</span> <span class="n">month</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
  1937. <span class="k">class</span> <span class="nc">NamedInt</span><span class="p">(</span><span class="nb">int</span><span class="p">):</span>
  1938. <span class="s2">&quot;Allow text names for some numbers&quot;</span>
  1939. <span class="n">xlat</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;zero&#39;</span><span class="p">:</span> <span class="mi">0</span><span class="p">,</span> <span class="s1">&#39;one&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;ten&#39;</span><span class="p">:</span> <span class="mi">10</span><span class="p">}</span>
  1940. <span class="k">def</span> <span class="fm">__new__</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
  1941. <span class="n">value</span> <span class="o">=</span> <span class="bp">cls</span><span class="o">.</span><span class="n">xlat</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">value</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
  1942. <span class="k">return</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__new__</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
  1943. <span class="k">class</span> <span class="nc">TitleStr</span><span class="p">(</span><span class="nb">str</span><span class="p">):</span>
  1944. <span class="s2">&quot;Convert str to name suitable for a URL path&quot;</span>
  1945. <span class="k">def</span> <span class="fm">__new__</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">s</span><span class="p">):</span>
  1946. <span class="n">s</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s1">&#39; &#39;</span><span class="p">,</span> <span class="s1">&#39;-&#39;</span><span class="p">)</span>
  1947. <span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">([</span><span class="n">c</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">s</span> <span class="k">if</span> <span class="n">c</span><span class="o">.</span><span class="n">isalnum</span><span class="p">()</span> <span class="ow">or</span> <span class="n">c</span> <span class="o">==</span> <span class="s1">&#39;-&#39;</span><span class="p">])</span>
  1948. <span class="k">return</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__new__</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span>
  1949. </pre></div>
  1950. </div>
  1951. <p>The classes can be used like this:</p>
  1952. <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">FirstOfMonthDate</span><span class="p">(</span><span class="mi">2012</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">14</span><span class="p">)</span>
  1953. <span class="go">FirstOfMonthDate(2012, 2, 1)</span>
  1954. <span class="gp">&gt;&gt;&gt; </span><span class="n">NamedInt</span><span class="p">(</span><span class="s1">&#39;ten&#39;</span><span class="p">)</span>
  1955. <span class="go">10</span>
  1956. <span class="gp">&gt;&gt;&gt; </span><span class="n">NamedInt</span><span class="p">(</span><span class="mi">20</span><span class="p">)</span>
  1957. <span class="go">20</span>
  1958. <span class="gp">&gt;&gt;&gt; </span><span class="n">TitleStr</span><span class="p">(</span><span class="s1">&#39;Blog: Why Python Rocks&#39;</span><span class="p">)</span>
  1959. <span class="go">&#39;blog-why-python-rocks&#39;</span>
  1960. </pre></div>
  1961. </div>
  1962. </section>
  1963. <section id="how-do-i-cache-method-calls">
  1964. <span id="faq-cache-method-calls"></span><h3><a class="toc-backref" href="#id70" role="doc-backlink">How do I cache method calls?</a><a class="headerlink" href="#how-do-i-cache-method-calls" title="Link to this heading">¶</a></h3>
  1965. <p>The two principal tools for caching methods are
  1966. <a class="reference internal" href="../library/functools.html#functools.cached_property" title="functools.cached_property"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.cached_property()</span></code></a> and <a class="reference internal" href="../library/functools.html#functools.lru_cache" title="functools.lru_cache"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.lru_cache()</span></code></a>. The
  1967. former stores results at the instance level and the latter at the class
  1968. level.</p>
  1969. <p>The <em>cached_property</em> approach only works with methods that do not take
  1970. any arguments. It does not create a reference to the instance. The
  1971. cached method result will be kept only as long as the instance is alive.</p>
  1972. <p>The advantage is that when an instance is no longer used, the cached
  1973. method result will be released right away. The disadvantage is that if
  1974. instances accumulate, so too will the accumulated method results. They
  1975. can grow without bound.</p>
  1976. <p>The <em>lru_cache</em> approach works with methods that have <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a>
  1977. arguments. It creates a reference to the instance unless special
  1978. efforts are made to pass in weak references.</p>
  1979. <p>The advantage of the least recently used algorithm is that the cache is
  1980. bounded by the specified <em>maxsize</em>. The disadvantage is that instances
  1981. are kept alive until they age out of the cache or until the cache is
  1982. cleared.</p>
  1983. <p>This example shows the various techniques:</p>
  1984. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Weather</span><span class="p">:</span>
  1985. <span class="s2">&quot;Lookup weather information on a government website&quot;</span>
  1986. <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">station_id</span><span class="p">):</span>
  1987. <span class="bp">self</span><span class="o">.</span><span class="n">_station_id</span> <span class="o">=</span> <span class="n">station_id</span>
  1988. <span class="c1"># The _station_id is private and immutable</span>
  1989. <span class="k">def</span> <span class="nf">current_temperature</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  1990. <span class="s2">&quot;Latest hourly observation&quot;</span>
  1991. <span class="c1"># Do not cache this because old results</span>
  1992. <span class="c1"># can be out of date.</span>
  1993. <span class="nd">@cached_property</span>
  1994. <span class="k">def</span> <span class="nf">location</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  1995. <span class="s2">&quot;Return the longitude/latitude coordinates of the station&quot;</span>
  1996. <span class="c1"># Result only depends on the station_id</span>
  1997. <span class="nd">@lru_cache</span><span class="p">(</span><span class="n">maxsize</span><span class="o">=</span><span class="mi">20</span><span class="p">)</span>
  1998. <span class="k">def</span> <span class="nf">historic_rainfall</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">date</span><span class="p">,</span> <span class="n">units</span><span class="o">=</span><span class="s1">&#39;mm&#39;</span><span class="p">):</span>
  1999. <span class="s2">&quot;Rainfall on a given date&quot;</span>
  2000. <span class="c1"># Depends on the station_id, date, and units.</span>
  2001. </pre></div>
  2002. </div>
  2003. <p>The above example assumes that the <em>station_id</em> never changes. If the
  2004. relevant instance attributes are mutable, the <em>cached_property</em> approach
  2005. can’t be made to work because it cannot detect changes to the
  2006. attributes.</p>
  2007. <p>To make the <em>lru_cache</em> approach work when the <em>station_id</em> is mutable,
  2008. the class needs to define the <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 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>
  2009. methods so that the cache can detect relevant attribute updates:</p>
  2010. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Weather</span><span class="p">:</span>
  2011. <span class="s2">&quot;Example with a mutable station identifier&quot;</span>
  2012. <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">station_id</span><span class="p">):</span>
  2013. <span class="bp">self</span><span class="o">.</span><span class="n">station_id</span> <span class="o">=</span> <span class="n">station_id</span>
  2014. <span class="k">def</span> <span class="nf">change_station</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">station_id</span><span class="p">):</span>
  2015. <span class="bp">self</span><span class="o">.</span><span class="n">station_id</span> <span class="o">=</span> <span class="n">station_id</span>
  2016. <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>
  2017. <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">station_id</span> <span class="o">==</span> <span class="n">other</span><span class="o">.</span><span class="n">station_id</span>
  2018. <span class="k">def</span> <span class="fm">__hash__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  2019. <span class="k">return</span> <span class="nb">hash</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">station_id</span><span class="p">)</span>
  2020. <span class="nd">@lru_cache</span><span class="p">(</span><span class="n">maxsize</span><span class="o">=</span><span class="mi">20</span><span class="p">)</span>
  2021. <span class="k">def</span> <span class="nf">historic_rainfall</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">date</span><span class="p">,</span> <span class="n">units</span><span class="o">=</span><span class="s1">&#39;cm&#39;</span><span class="p">):</span>
  2022. <span class="s1">&#39;Rainfall on a given date&#39;</span>
  2023. <span class="c1"># Depends on the station_id, date, and units.</span>
  2024. </pre></div>
  2025. </div>
  2026. </section>
  2027. </section>
  2028. <section id="modules">
  2029. <h2><a class="toc-backref" href="#id71" role="doc-backlink">Modules</a><a class="headerlink" href="#modules" title="Link to this heading">¶</a></h2>
  2030. <section id="how-do-i-create-a-pyc-file">
  2031. <h3><a class="toc-backref" href="#id72" role="doc-backlink">How do I create a .pyc file?</a><a class="headerlink" href="#how-do-i-create-a-pyc-file" title="Link to this heading">¶</a></h3>
  2032. <p>When a module is imported for the first time (or when the source file has
  2033. changed since the current compiled file was created) a <code class="docutils literal notranslate"><span class="pre">.pyc</span></code> file containing
  2034. the compiled code should be created in a <code class="docutils literal notranslate"><span class="pre">__pycache__</span></code> subdirectory of the
  2035. directory containing the <code class="docutils literal notranslate"><span class="pre">.py</span></code> file. The <code class="docutils literal notranslate"><span class="pre">.pyc</span></code> file will have a
  2036. filename that starts with the same name as the <code class="docutils literal notranslate"><span class="pre">.py</span></code> file, and ends with
  2037. <code class="docutils literal notranslate"><span class="pre">.pyc</span></code>, with a middle component that depends on the particular <code class="docutils literal notranslate"><span class="pre">python</span></code>
  2038. binary that created it. (See <span class="target" id="index-3"></span><a class="pep reference external" href="https://peps.python.org/pep-3147/"><strong>PEP 3147</strong></a> for details.)</p>
  2039. <p>One reason that a <code class="docutils literal notranslate"><span class="pre">.pyc</span></code> file may not be created is a permissions problem
  2040. with the directory containing the source file, meaning that the <code class="docutils literal notranslate"><span class="pre">__pycache__</span></code>
  2041. subdirectory cannot be created. This can happen, for example, if you develop as
  2042. one user but run as another, such as if you are testing with a web server.</p>
  2043. <p>Unless the <span class="target" id="index-4"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONDONTWRITEBYTECODE</span></code></a> environment variable is set,
  2044. creation of a .pyc file is automatic if you’re importing a module and Python
  2045. has the ability (permissions, free space, etc…) to create a <code class="docutils literal notranslate"><span class="pre">__pycache__</span></code>
  2046. subdirectory and write the compiled module to that subdirectory.</p>
  2047. <p>Running Python on a top level script is not considered an import and no
  2048. <code class="docutils literal notranslate"><span class="pre">.pyc</span></code> will be created. For example, if you have a top-level module
  2049. <code class="docutils literal notranslate"><span class="pre">foo.py</span></code> that imports another module <code class="docutils literal notranslate"><span class="pre">xyz.py</span></code>, when you run <code class="docutils literal notranslate"><span class="pre">foo</span></code> (by
  2050. typing <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">foo.py</span></code> as a shell command), a <code class="docutils literal notranslate"><span class="pre">.pyc</span></code> will be created for
  2051. <code class="docutils literal notranslate"><span class="pre">xyz</span></code> because <code class="docutils literal notranslate"><span class="pre">xyz</span></code> is imported, but no <code class="docutils literal notranslate"><span class="pre">.pyc</span></code> file will be created for
  2052. <code class="docutils literal notranslate"><span class="pre">foo</span></code> since <code class="docutils literal notranslate"><span class="pre">foo.py</span></code> isn’t being imported.</p>
  2053. <p>If you need to create a <code class="docutils literal notranslate"><span class="pre">.pyc</span></code> file for <code class="docutils literal notranslate"><span class="pre">foo</span></code> – that is, to create a
  2054. <code class="docutils literal notranslate"><span class="pre">.pyc</span></code> file for a module that is not imported – you can, using the
  2055. <a class="reference internal" href="../library/py_compile.html#module-py_compile" title="py_compile: Generate byte-code files from Python source files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">py_compile</span></code></a> and <a class="reference internal" href="../library/compileall.html#module-compileall" title="compileall: Tools for byte-compiling all Python source files in a directory tree."><code class="xref py py-mod docutils literal notranslate"><span class="pre">compileall</span></code></a> modules.</p>
  2056. <p>The <a class="reference internal" href="../library/py_compile.html#module-py_compile" title="py_compile: Generate byte-code files from Python source files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">py_compile</span></code></a> module can manually compile any module. One way is to use
  2057. the <code class="docutils literal notranslate"><span class="pre">compile()</span></code> function in that module interactively:</p>
  2058. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">py_compile</span>
  2059. <span class="gp">&gt;&gt;&gt; </span><span class="n">py_compile</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;foo.py&#39;</span><span class="p">)</span>
  2060. </pre></div>
  2061. </div>
  2062. <p>This will write the <code class="docutils literal notranslate"><span class="pre">.pyc</span></code> to a <code class="docutils literal notranslate"><span class="pre">__pycache__</span></code> subdirectory in the same
  2063. location as <code class="docutils literal notranslate"><span class="pre">foo.py</span></code> (or you can override that with the optional parameter
  2064. <code class="docutils literal notranslate"><span class="pre">cfile</span></code>).</p>
  2065. <p>You can also automatically compile all files in a directory or directories using
  2066. the <a class="reference internal" href="../library/compileall.html#module-compileall" title="compileall: Tools for byte-compiling all Python source files in a directory tree."><code class="xref py py-mod docutils literal notranslate"><span class="pre">compileall</span></code></a> module. You can do it from the shell prompt by running
  2067. <code class="docutils literal notranslate"><span class="pre">compileall.py</span></code> and providing the path of a directory containing Python files
  2068. to compile:</p>
  2069. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">compileall</span> <span class="o">.</span>
  2070. </pre></div>
  2071. </div>
  2072. </section>
  2073. <section id="how-do-i-find-the-current-module-name">
  2074. <h3><a class="toc-backref" href="#id73" role="doc-backlink">How do I find the current module name?</a><a class="headerlink" href="#how-do-i-find-the-current-module-name" title="Link to this heading">¶</a></h3>
  2075. <p>A module can find out its own module name by looking at the predefined global
  2076. variable <code class="docutils literal notranslate"><span class="pre">__name__</span></code>. If this has the value <code class="docutils literal notranslate"><span class="pre">'__main__'</span></code>, the program is
  2077. running as a script. Many modules that are usually used by importing them also
  2078. provide a command-line interface or a self-test, and only execute this code
  2079. after checking <code class="docutils literal notranslate"><span class="pre">__name__</span></code>:</p>
  2080. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
  2081. <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Running test...&#39;</span><span class="p">)</span>
  2082. <span class="o">...</span>
  2083. <span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
  2084. <span class="n">main</span><span class="p">()</span>
  2085. </pre></div>
  2086. </div>
  2087. </section>
  2088. <section id="how-can-i-have-modules-that-mutually-import-each-other">
  2089. <h3><a class="toc-backref" href="#id74" role="doc-backlink">How can I have modules that mutually import each other?</a><a class="headerlink" href="#how-can-i-have-modules-that-mutually-import-each-other" title="Link to this heading">¶</a></h3>
  2090. <p>Suppose you have the following modules:</p>
  2091. <p><code class="file docutils literal notranslate"><span class="pre">foo.py</span></code>:</p>
  2092. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">bar</span> <span class="kn">import</span> <span class="n">bar_var</span>
  2093. <span class="n">foo_var</span> <span class="o">=</span> <span class="mi">1</span>
  2094. </pre></div>
  2095. </div>
  2096. <p><code class="file docutils literal notranslate"><span class="pre">bar.py</span></code>:</p>
  2097. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">foo</span> <span class="kn">import</span> <span class="n">foo_var</span>
  2098. <span class="n">bar_var</span> <span class="o">=</span> <span class="mi">2</span>
  2099. </pre></div>
  2100. </div>
  2101. <p>The problem is that the interpreter will perform the following steps:</p>
  2102. <ul class="simple">
  2103. <li><p>main imports <code class="docutils literal notranslate"><span class="pre">foo</span></code></p></li>
  2104. <li><p>Empty globals for <code class="docutils literal notranslate"><span class="pre">foo</span></code> are created</p></li>
  2105. <li><p><code class="docutils literal notranslate"><span class="pre">foo</span></code> is compiled and starts executing</p></li>
  2106. <li><p><code class="docutils literal notranslate"><span class="pre">foo</span></code> imports <code class="docutils literal notranslate"><span class="pre">bar</span></code></p></li>
  2107. <li><p>Empty globals for <code class="docutils literal notranslate"><span class="pre">bar</span></code> are created</p></li>
  2108. <li><p><code class="docutils literal notranslate"><span class="pre">bar</span></code> is compiled and starts executing</p></li>
  2109. <li><p><code class="docutils literal notranslate"><span class="pre">bar</span></code> imports <code class="docutils literal notranslate"><span class="pre">foo</span></code> (which is a no-op since there already is a module named <code class="docutils literal notranslate"><span class="pre">foo</span></code>)</p></li>
  2110. <li><p>The import mechanism tries to read <code class="docutils literal notranslate"><span class="pre">foo_var</span></code> from <code class="docutils literal notranslate"><span class="pre">foo</span></code> globals, to set <code class="docutils literal notranslate"><span class="pre">bar.foo_var</span> <span class="pre">=</span> <span class="pre">foo.foo_var</span></code></p></li>
  2111. </ul>
  2112. <p>The last step fails, because Python isn’t done with interpreting <code class="docutils literal notranslate"><span class="pre">foo</span></code> yet and
  2113. the global symbol dictionary for <code class="docutils literal notranslate"><span class="pre">foo</span></code> is still empty.</p>
  2114. <p>The same thing happens when you use <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">foo</span></code>, and then try to access
  2115. <code class="docutils literal notranslate"><span class="pre">foo.foo_var</span></code> in global code.</p>
  2116. <p>There are (at least) three possible workarounds for this problem.</p>
  2117. <p>Guido van Rossum recommends avoiding all uses of <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">&lt;module&gt;</span> <span class="pre">import</span> <span class="pre">...</span></code>,
  2118. and placing all code inside functions. Initializations of global variables and
  2119. class variables should use constants or built-in functions only. This means
  2120. everything from an imported module is referenced as <code class="docutils literal notranslate"><span class="pre">&lt;module&gt;.&lt;name&gt;</span></code>.</p>
  2121. <p>Jim Roskind suggests performing steps in the following order in each module:</p>
  2122. <ul class="simple">
  2123. <li><p>exports (globals, functions, and classes that don’t need imported base
  2124. classes)</p></li>
  2125. <li><p><code class="docutils literal notranslate"><span class="pre">import</span></code> statements</p></li>
  2126. <li><p>active code (including globals that are initialized from imported values).</p></li>
  2127. </ul>
  2128. <p>Van Rossum doesn’t like this approach much because the imports appear in a
  2129. strange place, but it does work.</p>
  2130. <p>Matthias Urlichs recommends restructuring your code so that the recursive import
  2131. is not necessary in the first place.</p>
  2132. <p>These solutions are not mutually exclusive.</p>
  2133. </section>
  2134. <section id="import-x-y-z-returns-module-x-how-do-i-get-z">
  2135. <h3><a class="toc-backref" href="#id75" role="doc-backlink">__import__(‘x.y.z’) returns &lt;module ‘x’&gt;; how do I get z?</a><a class="headerlink" href="#import-x-y-z-returns-module-x-how-do-i-get-z" title="Link to this heading">¶</a></h3>
  2136. <p>Consider using the convenience function <a class="reference internal" href="../library/importlib.html#importlib.import_module" title="importlib.import_module"><code class="xref py py-func docutils literal notranslate"><span class="pre">import_module()</span></code></a> from
  2137. <a class="reference internal" href="../library/importlib.html#module-importlib" title="importlib: The implementation of the import machinery."><code class="xref py py-mod docutils literal notranslate"><span class="pre">importlib</span></code></a> instead:</p>
  2138. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">z</span> <span class="o">=</span> <span class="n">importlib</span><span class="o">.</span><span class="n">import_module</span><span class="p">(</span><span class="s1">&#39;x.y.z&#39;</span><span class="p">)</span>
  2139. </pre></div>
  2140. </div>
  2141. </section>
  2142. <section id="when-i-edit-an-imported-module-and-reimport-it-the-changes-don-t-show-up-why-does-this-happen">
  2143. <h3><a class="toc-backref" href="#id76" role="doc-backlink">When I edit an imported module and reimport it, the changes don’t show up. Why does this happen?</a><a class="headerlink" href="#when-i-edit-an-imported-module-and-reimport-it-the-changes-don-t-show-up-why-does-this-happen" title="Link to this heading">¶</a></h3>
  2144. <p>For reasons of efficiency as well as consistency, Python only reads the module
  2145. file on the first time a module is imported. If it didn’t, in a program
  2146. consisting of many modules where each one imports the same basic module, the
  2147. basic module would be parsed and re-parsed many times. To force re-reading of a
  2148. changed module, do this:</p>
  2149. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">importlib</span>
  2150. <span class="kn">import</span> <span class="nn">modname</span>
  2151. <span class="n">importlib</span><span class="o">.</span><span class="n">reload</span><span class="p">(</span><span class="n">modname</span><span class="p">)</span>
  2152. </pre></div>
  2153. </div>
  2154. <p>Warning: this technique is not 100% fool-proof. In particular, modules
  2155. containing statements like</p>
  2156. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">modname</span> <span class="kn">import</span> <span class="n">some_objects</span>
  2157. </pre></div>
  2158. </div>
  2159. <p>will continue to work with the old version of the imported objects. If the
  2160. module contains class definitions, existing class instances will <em>not</em> be
  2161. updated to use the new class definition. This can result in the following
  2162. paradoxical behaviour:</p>
  2163. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">importlib</span>
  2164. <span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">cls</span>
  2165. <span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="bp">cls</span><span class="o">.</span><span class="n">C</span><span class="p">()</span> <span class="c1"># Create an instance of C</span>
  2166. <span class="gp">&gt;&gt;&gt; </span><span class="n">importlib</span><span class="o">.</span><span class="n">reload</span><span class="p">(</span><span class="bp">cls</span><span class="p">)</span>
  2167. <span class="go">&lt;module &#39;cls&#39; from &#39;cls.py&#39;&gt;</span>
  2168. <span class="gp">&gt;&gt;&gt; </span><span class="nb">isinstance</span><span class="p">(</span><span class="n">c</span><span class="p">,</span> <span class="bp">cls</span><span class="o">.</span><span class="n">C</span><span class="p">)</span> <span class="c1"># isinstance is false?!?</span>
  2169. <span class="go">False</span>
  2170. </pre></div>
  2171. </div>
  2172. <p>The nature of the problem is made clear if you print out the “identity” of the
  2173. class objects:</p>
  2174. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">hex</span><span class="p">(</span><span class="nb">id</span><span class="p">(</span><span class="n">c</span><span class="o">.</span><span class="vm">__class__</span><span class="p">))</span>
  2175. <span class="go">&#39;0x7352a0&#39;</span>
  2176. <span class="gp">&gt;&gt;&gt; </span><span class="nb">hex</span><span class="p">(</span><span class="nb">id</span><span class="p">(</span><span class="bp">cls</span><span class="o">.</span><span class="n">C</span><span class="p">))</span>
  2177. <span class="go">&#39;0x4198d0&#39;</span>
  2178. </pre></div>
  2179. </div>
  2180. </section>
  2181. </section>
  2182. </section>
  2183. <div class="clearer"></div>
  2184. </div>
  2185. </div>
  2186. </div>
  2187. <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
  2188. <div class="sphinxsidebarwrapper">
  2189. <div>
  2190. <h3><a href="../contents.html">Table of Contents</a></h3>
  2191. <ul>
  2192. <li><a class="reference internal" href="#">Programming FAQ</a><ul>
  2193. <li><a class="reference internal" href="#general-questions">General Questions</a></li>
  2194. <li><a class="reference internal" href="#core-language">Core Language</a></li>
  2195. <li><a class="reference internal" href="#numbers-and-strings">Numbers and strings</a></li>
  2196. <li><a class="reference internal" href="#performance">Performance</a></li>
  2197. <li><a class="reference internal" href="#sequences-tuples-lists">Sequences (Tuples/Lists)</a></li>
  2198. <li><a class="reference internal" href="#objects">Objects</a></li>
  2199. <li><a class="reference internal" href="#modules">Modules</a></li>
  2200. </ul>
  2201. </li>
  2202. </ul>
  2203. </div>
  2204. <div>
  2205. <h4>Previous topic</h4>
  2206. <p class="topless"><a href="general.html"
  2207. title="previous chapter">General Python FAQ</a></p>
  2208. </div>
  2209. <div>
  2210. <h4>Next topic</h4>
  2211. <p class="topless"><a href="design.html"
  2212. title="next chapter">Design and History FAQ</a></p>
  2213. </div>
  2214. <div role="note" aria-label="source link">
  2215. <h3>This Page</h3>
  2216. <ul class="this-page-menu">
  2217. <li><a href="../bugs.html">Report a Bug</a></li>
  2218. <li>
  2219. <a href="https://github.com/python/cpython/blob/main/Doc/faq/programming.rst"
  2220. rel="nofollow">Show Source
  2221. </a>
  2222. </li>
  2223. </ul>
  2224. </div>
  2225. </div>
  2226. <div id="sidebarbutton" title="Collapse sidebar">
  2227. <span>«</span>
  2228. </div>
  2229. </div>
  2230. <div class="clearer"></div>
  2231. </div>
  2232. <div class="related" role="navigation" aria-label="related navigation">
  2233. <h3>Navigation</h3>
  2234. <ul>
  2235. <li class="right" style="margin-right: 10px">
  2236. <a href="../genindex.html" title="General Index"
  2237. >index</a></li>
  2238. <li class="right" >
  2239. <a href="../py-modindex.html" title="Python Module Index"
  2240. >modules</a> |</li>
  2241. <li class="right" >
  2242. <a href="design.html" title="Design and History FAQ"
  2243. >next</a> |</li>
  2244. <li class="right" >
  2245. <a href="general.html" title="General Python FAQ"
  2246. >previous</a> |</li>
  2247. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  2248. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  2249. <li class="switchers">
  2250. <div class="language_switcher_placeholder"></div>
  2251. <div class="version_switcher_placeholder"></div>
  2252. </li>
  2253. <li>
  2254. </li>
  2255. <li id="cpython-language-and-version">
  2256. <a href="../index.html">3.12.3 Documentation</a> &#187;
  2257. </li>
  2258. <li class="nav-item nav-item-1"><a href="index.html" >Python Frequently Asked Questions</a> &#187;</li>
  2259. <li class="nav-item nav-item-this"><a href="">Programming FAQ</a></li>
  2260. <li class="right">
  2261. <div class="inline-search" role="search">
  2262. <form class="inline-search" action="../search.html" method="get">
  2263. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  2264. <input type="submit" value="Go" />
  2265. </form>
  2266. </div>
  2267. |
  2268. </li>
  2269. <li class="right">
  2270. <label class="theme-selector-label">
  2271. Theme
  2272. <select class="theme-selector" oninput="activateTheme(this.value)">
  2273. <option value="auto" selected>Auto</option>
  2274. <option value="light">Light</option>
  2275. <option value="dark">Dark</option>
  2276. </select>
  2277. </label> |</li>
  2278. </ul>
  2279. </div>
  2280. <div class="footer">
  2281. &copy;
  2282. <a href="../copyright.html">
  2283. Copyright
  2284. </a>
  2285. 2001-2024, Python Software Foundation.
  2286. <br />
  2287. This page is licensed under the Python Software Foundation License Version 2.
  2288. <br />
  2289. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  2290. <br />
  2291. See <a href="/license.html">History and License</a> for more information.<br />
  2292. <br />
  2293. The Python Software Foundation is a non-profit corporation.
  2294. <a href="https://www.python.org/psf/donations/">Please donate.</a>
  2295. <br />
  2296. <br />
  2297. Last updated on Apr 09, 2024 (13:47 UTC).
  2298. <a href="/bugs.html">Found a bug</a>?
  2299. <br />
  2300. Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 7.2.6.
  2301. </div>
  2302. </body>
  2303. </html>
上海开阖软件有限公司 沪ICP备12045867号-1