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.

2207 line
241KB

  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="What’s New in Python 2.3" />
  7. <meta property="og:type" content="website" />
  8. <meta property="og:url" content="https://docs.python.org/3/whatsnew/2.3.html" />
  9. <meta property="og:site_name" content="Python documentation" />
  10. <meta property="og:description" content="Author, A.M. Kuchling,. This article explains the new features in Python 2.3. Python 2.3 was released on July 29, 2003. The main themes for Python 2.3 are polishing some of the features added in 2...." />
  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="Author, A.M. Kuchling,. This article explains the new features in Python 2.3. Python 2.3 was released on July 29, 2003. The main themes for Python 2.3 are polishing some of the features added in 2...." />
  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>What’s New in Python 2.3 &#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="What’s New in Python 2.2" href="2.2.html" />
  33. <link rel="prev" title="What’s New in Python 2.4" href="2.4.html" />
  34. <link rel="canonical" href="https://docs.python.org/3/whatsnew/2.3.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="#">What’s New in Python 2.3</a><ul>
  86. <li><a class="reference internal" href="#pep-218-a-standard-set-datatype">PEP 218: A Standard Set Datatype</a></li>
  87. <li><a class="reference internal" href="#pep-255-simple-generators">PEP 255: Simple Generators</a></li>
  88. <li><a class="reference internal" href="#pep-263-source-code-encodings">PEP 263: Source Code Encodings</a></li>
  89. <li><a class="reference internal" href="#pep-273-importing-modules-from-zip-archives">PEP 273: Importing Modules from ZIP Archives</a></li>
  90. <li><a class="reference internal" href="#pep-277-unicode-file-name-support-for-windows-nt">PEP 277: Unicode file name support for Windows NT</a></li>
  91. <li><a class="reference internal" href="#pep-278-universal-newline-support">PEP 278: Universal Newline Support</a></li>
  92. <li><a class="reference internal" href="#pep-279-enumerate">PEP 279: enumerate()</a></li>
  93. <li><a class="reference internal" href="#pep-282-the-logging-package">PEP 282: The logging Package</a></li>
  94. <li><a class="reference internal" href="#pep-285-a-boolean-type">PEP 285: A Boolean Type</a></li>
  95. <li><a class="reference internal" href="#pep-293-codec-error-handling-callbacks">PEP 293: Codec Error Handling Callbacks</a></li>
  96. <li><a class="reference internal" href="#pep-301-package-index-and-metadata-for-distutils">PEP 301: Package Index and Metadata for Distutils</a></li>
  97. <li><a class="reference internal" href="#pep-302-new-import-hooks">PEP 302: New Import Hooks</a></li>
  98. <li><a class="reference internal" href="#pep-305-comma-separated-files">PEP 305: Comma-separated Files</a></li>
  99. <li><a class="reference internal" href="#pep-307-pickle-enhancements">PEP 307: Pickle Enhancements</a></li>
  100. <li><a class="reference internal" href="#extended-slices">Extended Slices</a></li>
  101. <li><a class="reference internal" href="#other-language-changes">Other Language Changes</a><ul>
  102. <li><a class="reference internal" href="#string-changes">String Changes</a></li>
  103. <li><a class="reference internal" href="#optimizations">Optimizations</a></li>
  104. </ul>
  105. </li>
  106. <li><a class="reference internal" href="#new-improved-and-deprecated-modules">New, Improved, and Deprecated Modules</a><ul>
  107. <li><a class="reference internal" href="#date-time-type">Date/Time Type</a></li>
  108. <li><a class="reference internal" href="#the-optparse-module">The optparse Module</a></li>
  109. </ul>
  110. </li>
  111. <li><a class="reference internal" href="#pymalloc-a-specialized-object-allocator">Pymalloc: A Specialized Object Allocator</a></li>
  112. <li><a class="reference internal" href="#build-and-c-api-changes">Build and C API Changes</a><ul>
  113. <li><a class="reference internal" href="#port-specific-changes">Port-Specific Changes</a></li>
  114. </ul>
  115. </li>
  116. <li><a class="reference internal" href="#other-changes-and-fixes">Other Changes and Fixes</a></li>
  117. <li><a class="reference internal" href="#porting-to-python-2-3">Porting to Python 2.3</a></li>
  118. <li><a class="reference internal" href="#acknowledgements">Acknowledgements</a></li>
  119. </ul>
  120. </li>
  121. </ul>
  122. </div>
  123. <div>
  124. <h4>Previous topic</h4>
  125. <p class="topless"><a href="2.4.html"
  126. title="previous chapter">What’s New in Python 2.4</a></p>
  127. </div>
  128. <div>
  129. <h4>Next topic</h4>
  130. <p class="topless"><a href="2.2.html"
  131. title="next chapter">What’s New in Python 2.2</a></p>
  132. </div>
  133. <div role="note" aria-label="source link">
  134. <h3>This Page</h3>
  135. <ul class="this-page-menu">
  136. <li><a href="../bugs.html">Report a Bug</a></li>
  137. <li>
  138. <a href="https://github.com/python/cpython/blob/main/Doc/whatsnew/2.3.rst"
  139. rel="nofollow">Show Source
  140. </a>
  141. </li>
  142. </ul>
  143. </div>
  144. </nav>
  145. </div>
  146. </div>
  147. <div class="related" role="navigation" aria-label="related navigation">
  148. <h3>Navigation</h3>
  149. <ul>
  150. <li class="right" style="margin-right: 10px">
  151. <a href="../genindex.html" title="General Index"
  152. accesskey="I">index</a></li>
  153. <li class="right" >
  154. <a href="../py-modindex.html" title="Python Module Index"
  155. >modules</a> |</li>
  156. <li class="right" >
  157. <a href="2.2.html" title="What’s New in Python 2.2"
  158. accesskey="N">next</a> |</li>
  159. <li class="right" >
  160. <a href="2.4.html" title="What’s New in Python 2.4"
  161. accesskey="P">previous</a> |</li>
  162. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  163. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  164. <li class="switchers">
  165. <div class="language_switcher_placeholder"></div>
  166. <div class="version_switcher_placeholder"></div>
  167. </li>
  168. <li>
  169. </li>
  170. <li id="cpython-language-and-version">
  171. <a href="../index.html">3.12.3 Documentation</a> &#187;
  172. </li>
  173. <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">What’s New in Python</a> &#187;</li>
  174. <li class="nav-item nav-item-this"><a href="">What’s New in Python 2.3</a></li>
  175. <li class="right">
  176. <div class="inline-search" role="search">
  177. <form class="inline-search" action="../search.html" method="get">
  178. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  179. <input type="submit" value="Go" />
  180. </form>
  181. </div>
  182. |
  183. </li>
  184. <li class="right">
  185. <label class="theme-selector-label">
  186. Theme
  187. <select class="theme-selector" oninput="activateTheme(this.value)">
  188. <option value="auto" selected>Auto</option>
  189. <option value="light">Light</option>
  190. <option value="dark">Dark</option>
  191. </select>
  192. </label> |</li>
  193. </ul>
  194. </div>
  195. <div class="document">
  196. <div class="documentwrapper">
  197. <div class="bodywrapper">
  198. <div class="body" role="main">
  199. <section id="what-s-new-in-python-2-3">
  200. <h1>What’s New in Python 2.3<a class="headerlink" href="#what-s-new-in-python-2-3" title="Link to this heading">¶</a></h1>
  201. <dl class="field-list simple">
  202. <dt class="field-odd">Author<span class="colon">:</span></dt>
  203. <dd class="field-odd"><p>A.M. Kuchling</p>
  204. </dd>
  205. </dl>
  206. <p>This article explains the new features in Python 2.3. Python 2.3 was released
  207. on July 29, 2003.</p>
  208. <p>The main themes for Python 2.3 are polishing some of the features added in 2.2,
  209. adding various small but useful enhancements to the core language, and expanding
  210. the standard library. The new object model introduced in the previous version
  211. has benefited from 18 months of bugfixes and from optimization efforts that have
  212. improved the performance of new-style classes. A few new built-in functions
  213. have been added such as <a class="reference internal" href="../library/functions.html#sum" title="sum"><code class="xref py py-func docutils literal notranslate"><span class="pre">sum()</span></code></a> and <a class="reference internal" href="../library/functions.html#enumerate" title="enumerate"><code class="xref py py-func docutils literal notranslate"><span class="pre">enumerate()</span></code></a>. The <a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a>
  214. operator can now be used for substring searches (e.g. <code class="docutils literal notranslate"><span class="pre">&quot;ab&quot;</span> <span class="pre">in</span> <span class="pre">&quot;abc&quot;</span></code> returns
  215. <a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>).</p>
  216. <p>Some of the many new library features include Boolean, set, heap, and date/time
  217. data types, the ability to import modules from ZIP-format archives, metadata
  218. support for the long-awaited Python catalog, an updated version of IDLE, and
  219. modules for logging messages, wrapping text, parsing CSV files, processing
  220. command-line options, using BerkeleyDB databases… the list of new and
  221. enhanced modules is lengthy.</p>
  222. <p>This article doesn’t attempt to provide a complete specification of the new
  223. features, but instead provides a convenient overview. For full details, you
  224. should refer to the documentation for Python 2.3, such as the Python Library
  225. Reference and the Python Reference Manual. If you want to understand the
  226. complete implementation and design rationale, refer to the PEP for a particular
  227. new feature.</p>
  228. <section id="pep-218-a-standard-set-datatype">
  229. <h2>PEP 218: A Standard Set Datatype<a class="headerlink" href="#pep-218-a-standard-set-datatype" title="Link to this heading">¶</a></h2>
  230. <p>The new <code class="xref py py-mod docutils literal notranslate"><span class="pre">sets</span></code> module contains an implementation of a set datatype. The
  231. <code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code> class is for mutable sets, sets that can have members added and
  232. removed. The <code class="xref py py-class docutils literal notranslate"><span class="pre">ImmutableSet</span></code> class is for sets that can’t be modified,
  233. and instances of <code class="xref py py-class docutils literal notranslate"><span class="pre">ImmutableSet</span></code> can therefore be used as dictionary keys.
  234. Sets are built on top of dictionaries, so the elements within a set must be
  235. hashable.</p>
  236. <p>Here’s a simple example:</p>
  237. <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">sets</span>
  238. <span class="gp">&gt;&gt;&gt; </span><span class="n">S</span> <span class="o">=</span> <span class="n">sets</span><span class="o">.</span><span class="n">Set</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span>
  239. <span class="gp">&gt;&gt;&gt; </span><span class="n">S</span>
  240. <span class="go">Set([1, 2, 3])</span>
  241. <span class="gp">&gt;&gt;&gt; </span><span class="mi">1</span> <span class="ow">in</span> <span class="n">S</span>
  242. <span class="go">True</span>
  243. <span class="gp">&gt;&gt;&gt; </span><span class="mi">0</span> <span class="ow">in</span> <span class="n">S</span>
  244. <span class="go">False</span>
  245. <span class="gp">&gt;&gt;&gt; </span><span class="n">S</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
  246. <span class="gp">&gt;&gt;&gt; </span><span class="n">S</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
  247. <span class="gp">&gt;&gt;&gt; </span><span class="n">S</span>
  248. <span class="go">Set([1, 2, 5])</span>
  249. <span class="gp">&gt;&gt;&gt;</span>
  250. </pre></div>
  251. </div>
  252. <p>The union and intersection of sets can be computed with the <a class="reference internal" href="../library/stdtypes.html#frozenset.union" title="frozenset.union"><code class="xref py py-meth docutils literal notranslate"><span class="pre">union()</span></code></a> and
  253. <a class="reference internal" href="../library/stdtypes.html#frozenset.intersection" title="frozenset.intersection"><code class="xref py py-meth docutils literal notranslate"><span class="pre">intersection()</span></code></a> methods; an alternative notation uses the bitwise operators
  254. <code class="docutils literal notranslate"><span class="pre">&amp;</span></code> and <code class="docutils literal notranslate"><span class="pre">|</span></code>. Mutable sets also have in-place versions of these methods,
  255. <code class="xref py py-meth docutils literal notranslate"><span class="pre">union_update()</span></code> and <a class="reference internal" href="../library/stdtypes.html#frozenset.intersection_update" title="frozenset.intersection_update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">intersection_update()</span></code></a>.</p>
  256. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">S1</span> <span class="o">=</span> <span class="n">sets</span><span class="o">.</span><span class="n">Set</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span>
  257. <span class="gp">&gt;&gt;&gt; </span><span class="n">S2</span> <span class="o">=</span> <span class="n">sets</span><span class="o">.</span><span class="n">Set</span><span class="p">([</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">6</span><span class="p">])</span>
  258. <span class="gp">&gt;&gt;&gt; </span><span class="n">S1</span><span class="o">.</span><span class="n">union</span><span class="p">(</span><span class="n">S2</span><span class="p">)</span>
  259. <span class="go">Set([1, 2, 3, 4, 5, 6])</span>
  260. <span class="gp">&gt;&gt;&gt; </span><span class="n">S1</span> <span class="o">|</span> <span class="n">S2</span> <span class="c1"># Alternative notation</span>
  261. <span class="go">Set([1, 2, 3, 4, 5, 6])</span>
  262. <span class="gp">&gt;&gt;&gt; </span><span class="n">S1</span><span class="o">.</span><span class="n">intersection</span><span class="p">(</span><span class="n">S2</span><span class="p">)</span>
  263. <span class="go">Set([])</span>
  264. <span class="gp">&gt;&gt;&gt; </span><span class="n">S1</span> <span class="o">&amp;</span> <span class="n">S2</span> <span class="c1"># Alternative notation</span>
  265. <span class="go">Set([])</span>
  266. <span class="gp">&gt;&gt;&gt; </span><span class="n">S1</span><span class="o">.</span><span class="n">union_update</span><span class="p">(</span><span class="n">S2</span><span class="p">)</span>
  267. <span class="gp">&gt;&gt;&gt; </span><span class="n">S1</span>
  268. <span class="go">Set([1, 2, 3, 4, 5, 6])</span>
  269. <span class="gp">&gt;&gt;&gt;</span>
  270. </pre></div>
  271. </div>
  272. <p>It’s also possible to take the symmetric difference of two sets. This is the
  273. set of all elements in the union that aren’t in the intersection. Another way
  274. of putting it is that the symmetric difference contains all elements that are in
  275. exactly one set. Again, there’s an alternative notation (<code class="docutils literal notranslate"><span class="pre">^</span></code>), and an
  276. in-place version with the ungainly name <a class="reference internal" href="../library/stdtypes.html#frozenset.symmetric_difference_update" title="frozenset.symmetric_difference_update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">symmetric_difference_update()</span></code></a>.</p>
  277. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">S1</span> <span class="o">=</span> <span class="n">sets</span><span class="o">.</span><span class="n">Set</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">])</span>
  278. <span class="gp">&gt;&gt;&gt; </span><span class="n">S2</span> <span class="o">=</span> <span class="n">sets</span><span class="o">.</span><span class="n">Set</span><span class="p">([</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">6</span><span class="p">])</span>
  279. <span class="gp">&gt;&gt;&gt; </span><span class="n">S1</span><span class="o">.</span><span class="n">symmetric_difference</span><span class="p">(</span><span class="n">S2</span><span class="p">)</span>
  280. <span class="go">Set([1, 2, 5, 6])</span>
  281. <span class="gp">&gt;&gt;&gt; </span><span class="n">S1</span> <span class="o">^</span> <span class="n">S2</span>
  282. <span class="go">Set([1, 2, 5, 6])</span>
  283. <span class="gp">&gt;&gt;&gt;</span>
  284. </pre></div>
  285. </div>
  286. <p>There are also <code class="xref py py-meth docutils literal notranslate"><span class="pre">issubset()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">issuperset()</span></code> methods for checking
  287. whether one set is a subset or superset of another:</p>
  288. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">S1</span> <span class="o">=</span> <span class="n">sets</span><span class="o">.</span><span class="n">Set</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span>
  289. <span class="gp">&gt;&gt;&gt; </span><span class="n">S2</span> <span class="o">=</span> <span class="n">sets</span><span class="o">.</span><span class="n">Set</span><span class="p">([</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span>
  290. <span class="gp">&gt;&gt;&gt; </span><span class="n">S2</span><span class="o">.</span><span class="n">issubset</span><span class="p">(</span><span class="n">S1</span><span class="p">)</span>
  291. <span class="go">True</span>
  292. <span class="gp">&gt;&gt;&gt; </span><span class="n">S1</span><span class="o">.</span><span class="n">issubset</span><span class="p">(</span><span class="n">S2</span><span class="p">)</span>
  293. <span class="go">False</span>
  294. <span class="gp">&gt;&gt;&gt; </span><span class="n">S1</span><span class="o">.</span><span class="n">issuperset</span><span class="p">(</span><span class="n">S2</span><span class="p">)</span>
  295. <span class="go">True</span>
  296. <span class="gp">&gt;&gt;&gt;</span>
  297. </pre></div>
  298. </div>
  299. <div class="admonition seealso">
  300. <p class="admonition-title">See also</p>
  301. <dl class="simple">
  302. <dt><span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0218/"><strong>PEP 218</strong></a> - Adding a Built-In Set Object Type</dt><dd><p>PEP written by Greg V. Wilson. Implemented by Greg V. Wilson, Alex Martelli, and
  303. GvR.</p>
  304. </dd>
  305. </dl>
  306. </div>
  307. </section>
  308. <section id="pep-255-simple-generators">
  309. <span id="section-generators"></span><h2>PEP 255: Simple Generators<a class="headerlink" href="#pep-255-simple-generators" title="Link to this heading">¶</a></h2>
  310. <p>In Python 2.2, generators were added as an optional feature, to be enabled by a
  311. <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">generators</span></code> directive. In 2.3 generators no longer
  312. need to be specially enabled, and are now always present; this means that
  313. <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> is now always a keyword. The rest of this section is a copy of
  314. the description of generators from the “What’s New in Python 2.2” document; if
  315. you read it back when Python 2.2 came out, you can skip the rest of this
  316. section.</p>
  317. <p>You’re doubtless familiar with how function calls work in Python or C. When you
  318. call a function, it gets a private namespace where its local variables are
  319. created. When the function reaches a <a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement, the local
  320. variables are destroyed and the resulting value is returned to the caller. A
  321. later call to the same function will get a fresh new set of local variables.
  322. But, what if the local variables weren’t thrown away on exiting a function?
  323. What if you could later resume the function where it left off? This is what
  324. generators provide; they can be thought of as resumable functions.</p>
  325. <p>Here’s the simplest example of a generator function:</p>
  326. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">generate_ints</span><span class="p">(</span><span class="n">N</span><span class="p">):</span>
  327. <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">N</span><span class="p">):</span>
  328. <span class="k">yield</span> <span class="n">i</span>
  329. </pre></div>
  330. </div>
  331. <p>A new keyword, <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a>, was introduced for generators. Any function
  332. containing a <code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code> statement is a generator function; this is
  333. detected by Python’s bytecode compiler which compiles the function specially as
  334. a result.</p>
  335. <p>When you call a generator function, it doesn’t return a single value; instead it
  336. returns a generator object that supports the iterator protocol. On executing
  337. the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement, the generator outputs the value of <code class="docutils literal notranslate"><span class="pre">i</span></code>,
  338. similar to a <a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement. The big difference between
  339. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code> and a <code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code> statement is that on reaching a
  340. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code> the generator’s state of execution is suspended and local
  341. variables are preserved. On the next call to the generator’s <code class="docutils literal notranslate"><span class="pre">.next()</span></code>
  342. method, the function will resume executing immediately after the
  343. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code> statement. (For complicated reasons, the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code>
  344. statement isn’t allowed inside the <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> block of a
  345. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code>…<code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> statement; read <span class="target" id="index-1"></span><a class="pep reference external" href="https://peps.python.org/pep-0255/"><strong>PEP 255</strong></a> for a full
  346. explanation of the interaction between <code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code> and exceptions.)</p>
  347. <p>Here’s a sample usage of the <code class="xref py py-func docutils literal notranslate"><span class="pre">generate_ints()</span></code> generator:</p>
  348. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">gen</span> <span class="o">=</span> <span class="n">generate_ints</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
  349. <span class="gp">&gt;&gt;&gt; </span><span class="n">gen</span>
  350. <span class="go">&lt;generator object at 0x8117f90&gt;</span>
  351. <span class="gp">&gt;&gt;&gt; </span><span class="n">gen</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
  352. <span class="go">0</span>
  353. <span class="gp">&gt;&gt;&gt; </span><span class="n">gen</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
  354. <span class="go">1</span>
  355. <span class="gp">&gt;&gt;&gt; </span><span class="n">gen</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
  356. <span class="go">2</span>
  357. <span class="gp">&gt;&gt;&gt; </span><span class="n">gen</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
  358. <span class="gt">Traceback (most recent call last):</span>
  359. File <span class="nb">&quot;stdin&quot;</span>, line <span class="m">1</span>, in <span class="n">?</span>
  360. File <span class="nb">&quot;stdin&quot;</span>, line <span class="m">2</span>, in <span class="n">generate_ints</span>
  361. <span class="gr">StopIteration</span>
  362. </pre></div>
  363. </div>
  364. <p>You could equally write <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">i</span> <span class="pre">in</span> <span class="pre">generate_ints(5)</span></code>, or <code class="docutils literal notranslate"><span class="pre">a,b,c</span> <span class="pre">=</span>
  365. <span class="pre">generate_ints(3)</span></code>.</p>
  366. <p>Inside a generator function, the <a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement can only be used
  367. without a value, and signals the end of the procession of values; afterwards the
  368. generator cannot return any further values. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code> with a value, such
  369. as <code class="docutils literal notranslate"><span class="pre">return</span> <span class="pre">5</span></code>, is a syntax error inside a generator function. The end of the
  370. generator’s results can also be indicated by raising <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a>
  371. manually, or by just letting the flow of execution fall off the bottom of the
  372. function.</p>
  373. <p>You could achieve the effect of generators manually by writing your own class
  374. and storing all the local variables of the generator as instance variables. For
  375. example, returning a list of integers could be done by setting <code class="docutils literal notranslate"><span class="pre">self.count</span></code> to
  376. 0, and having the <a class="reference internal" href="../library/functions.html#next" title="next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> method increment <code class="docutils literal notranslate"><span class="pre">self.count</span></code> and return it.
  377. However, for a moderately complicated generator, writing a corresponding class
  378. would be much messier. <code class="file docutils literal notranslate"><span class="pre">Lib/test/test_generators.py</span></code> contains a number of
  379. more interesting examples. The simplest one implements an in-order traversal of
  380. a tree using generators recursively.</p>
  381. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># A recursive generator that generates Tree leaves in in-order.</span>
  382. <span class="k">def</span> <span class="nf">inorder</span><span class="p">(</span><span class="n">t</span><span class="p">):</span>
  383. <span class="k">if</span> <span class="n">t</span><span class="p">:</span>
  384. <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">inorder</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">left</span><span class="p">):</span>
  385. <span class="k">yield</span> <span class="n">x</span>
  386. <span class="k">yield</span> <span class="n">t</span><span class="o">.</span><span class="n">label</span>
  387. <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">inorder</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">right</span><span class="p">):</span>
  388. <span class="k">yield</span> <span class="n">x</span>
  389. </pre></div>
  390. </div>
  391. <p>Two other examples in <code class="file docutils literal notranslate"><span class="pre">Lib/test/test_generators.py</span></code> produce solutions for
  392. the N-Queens problem (placing $N$ queens on an $NxN$ chess board so that no
  393. queen threatens another) and the Knight’s Tour (a route that takes a knight to
  394. every square of an $NxN$ chessboard without visiting any square twice).</p>
  395. <p>The idea of generators comes from other programming languages, especially Icon
  396. (<a class="reference external" href="https://www2.cs.arizona.edu/icon/">https://www2.cs.arizona.edu/icon/</a>), where the idea of generators is central. In
  397. Icon, every expression and function call behaves like a generator. One example
  398. from “An Overview of the Icon Programming Language” at
  399. <a class="reference external" href="https://www2.cs.arizona.edu/icon/docs/ipd266.htm">https://www2.cs.arizona.edu/icon/docs/ipd266.htm</a> gives an idea of what this looks
  400. like:</p>
  401. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">sentence</span> <span class="o">:=</span> <span class="s2">&quot;Store it in the neighboring harbor&quot;</span>
  402. <span class="k">if</span> <span class="p">(</span><span class="n">i</span> <span class="o">:=</span> <span class="n">find</span><span class="p">(</span><span class="s2">&quot;or&quot;</span><span class="p">,</span> <span class="n">sentence</span><span class="p">))</span> <span class="o">&gt;</span> <span class="mi">5</span> <span class="n">then</span> <span class="n">write</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
  403. </pre></div>
  404. </div>
  405. <p>In Icon the <code class="xref py py-func docutils literal notranslate"><span class="pre">find()</span></code> function returns the indexes at which the substring
  406. “or” is found: 3, 23, 33. In the <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement, <code class="docutils literal notranslate"><span class="pre">i</span></code> is first
  407. assigned a value of 3, but 3 is less than 5, so the comparison fails, and Icon
  408. retries it with the second value of 23. 23 is greater than 5, so the comparison
  409. now succeeds, and the code prints the value 23 to the screen.</p>
  410. <p>Python doesn’t go nearly as far as Icon in adopting generators as a central
  411. concept. Generators are considered part of the core Python language, but
  412. learning or using them isn’t compulsory; if they don’t solve any problems that
  413. you have, feel free to ignore them. One novel feature of Python’s interface as
  414. compared to Icon’s is that a generator’s state is represented as a concrete
  415. object (the iterator) that can be passed around to other functions or stored in
  416. a data structure.</p>
  417. <div class="admonition seealso">
  418. <p class="admonition-title">See also</p>
  419. <dl class="simple">
  420. <dt><span class="target" id="index-2"></span><a class="pep reference external" href="https://peps.python.org/pep-0255/"><strong>PEP 255</strong></a> - Simple Generators</dt><dd><p>Written by Neil Schemenauer, Tim Peters, Magnus Lie Hetland. Implemented mostly
  421. by Neil Schemenauer and Tim Peters, with other fixes from the Python Labs crew.</p>
  422. </dd>
  423. </dl>
  424. </div>
  425. </section>
  426. <section id="pep-263-source-code-encodings">
  427. <span id="section-encodings"></span><h2>PEP 263: Source Code Encodings<a class="headerlink" href="#pep-263-source-code-encodings" title="Link to this heading">¶</a></h2>
  428. <p>Python source files can now be declared as being in different character set
  429. encodings. Encodings are declared by including a specially formatted comment in
  430. the first or second line of the source file. For example, a UTF-8 file can be
  431. declared with:</p>
  432. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/bin/env python</span>
  433. <span class="c1"># -*- coding: UTF-8 -*-</span>
  434. </pre></div>
  435. </div>
  436. <p>Without such an encoding declaration, the default encoding used is 7-bit ASCII.
  437. Executing or importing modules that contain string literals with 8-bit
  438. characters and have no encoding declaration will result in a
  439. <a class="reference internal" href="../library/exceptions.html#DeprecationWarning" title="DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a> being signalled by Python 2.3; in 2.4 this will be a
  440. syntax error.</p>
  441. <p>The encoding declaration only affects Unicode string literals, which will be
  442. converted to Unicode using the specified encoding. Note that Python identifiers
  443. are still restricted to ASCII characters, so you can’t have variable names that
  444. use characters outside of the usual alphanumerics.</p>
  445. <div class="admonition seealso">
  446. <p class="admonition-title">See also</p>
  447. <dl class="simple">
  448. <dt><span class="target" id="index-3"></span><a class="pep reference external" href="https://peps.python.org/pep-0263/"><strong>PEP 263</strong></a> - Defining Python Source Code Encodings</dt><dd><p>Written by Marc-André Lemburg and Martin von Löwis; implemented by Suzuki Hisao
  449. and Martin von Löwis.</p>
  450. </dd>
  451. </dl>
  452. </div>
  453. </section>
  454. <section id="pep-273-importing-modules-from-zip-archives">
  455. <h2>PEP 273: Importing Modules from ZIP Archives<a class="headerlink" href="#pep-273-importing-modules-from-zip-archives" title="Link to this heading">¶</a></h2>
  456. <p>The new <a class="reference internal" href="../library/zipimport.html#module-zipimport" title="zipimport: Support for importing Python modules from ZIP archives."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipimport</span></code></a> module adds support for importing modules from a
  457. ZIP-format archive. You don’t need to import the module explicitly; it will be
  458. automatically imported if a ZIP archive’s filename is added to <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>.
  459. For example:</p>
  460. <div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">amk@nyman:~/src/python$ </span>unzip<span class="w"> </span>-l<span class="w"> </span>/tmp/example.zip
  461. <span class="go">Archive: /tmp/example.zip</span>
  462. <span class="go"> Length Date Time Name</span>
  463. <span class="go"> -------- ---- ---- ----</span>
  464. <span class="go"> 8467 11-26-02 22:30 jwzthreading.py</span>
  465. <span class="go"> -------- -------</span>
  466. <span class="go"> 8467 1 file</span>
  467. <span class="gp">amk@nyman:~/src/python$ </span>./python
  468. <span class="go">Python 2.3 (#1, Aug 1 2003, 19:54:32)</span>
  469. <span class="go">&gt;&gt;&gt; import sys</span>
  470. <span class="go">&gt;&gt;&gt; sys.path.insert(0, &#39;/tmp/example.zip&#39;) # Add .zip file to front of path</span>
  471. <span class="go">&gt;&gt;&gt; import jwzthreading</span>
  472. <span class="go">&gt;&gt;&gt; jwzthreading.__file__</span>
  473. <span class="go">&#39;/tmp/example.zip/jwzthreading.py&#39;</span>
  474. <span class="go">&gt;&gt;&gt;</span>
  475. </pre></div>
  476. </div>
  477. <p>An entry in <code class="docutils literal notranslate"><span class="pre">sys.path</span></code> can now be the filename of a ZIP archive. The ZIP
  478. archive can contain any kind of files, but only files named <code class="file docutils literal notranslate"><span class="pre">*.py</span></code>,
  479. <code class="file docutils literal notranslate"><span class="pre">*.pyc</span></code>, or <code class="file docutils literal notranslate"><span class="pre">*.pyo</span></code> can be imported. If an archive only contains
  480. <code class="file docutils literal notranslate"><span class="pre">*.py</span></code> files, Python will not attempt to modify the archive by adding the
  481. corresponding <code class="file docutils literal notranslate"><span class="pre">*.pyc</span></code> file, meaning that if a ZIP archive doesn’t contain
  482. <code class="file docutils literal notranslate"><span class="pre">*.pyc</span></code> files, importing may be rather slow.</p>
  483. <p>A path within the archive can also be specified to only import from a
  484. subdirectory; for example, the path <code class="file docutils literal notranslate"><span class="pre">/tmp/example.zip/lib/</span></code> would only
  485. import from the <code class="file docutils literal notranslate"><span class="pre">lib/</span></code> subdirectory within the archive.</p>
  486. <div class="admonition seealso">
  487. <p class="admonition-title">See also</p>
  488. <dl class="simple">
  489. <dt><span class="target" id="index-4"></span><a class="pep reference external" href="https://peps.python.org/pep-0273/"><strong>PEP 273</strong></a> - Import Modules from Zip Archives</dt><dd><p>Written by James C. Ahlstrom, who also provided an implementation. Python 2.3
  490. follows the specification in <span class="target" id="index-5"></span><a class="pep reference external" href="https://peps.python.org/pep-0273/"><strong>PEP 273</strong></a>, but uses an implementation written by
  491. Just van Rossum that uses the import hooks described in <span class="target" id="index-6"></span><a class="pep reference external" href="https://peps.python.org/pep-0302/"><strong>PEP 302</strong></a>. See section
  492. <a class="reference internal" href="#section-pep302"><span class="std std-ref">PEP 302: New Import Hooks</span></a> for a description of the new import hooks.</p>
  493. </dd>
  494. </dl>
  495. </div>
  496. </section>
  497. <section id="pep-277-unicode-file-name-support-for-windows-nt">
  498. <h2>PEP 277: Unicode file name support for Windows NT<a class="headerlink" href="#pep-277-unicode-file-name-support-for-windows-nt" title="Link to this heading">¶</a></h2>
  499. <p>On Windows NT, 2000, and XP, the system stores file names as Unicode strings.
  500. Traditionally, Python has represented file names as byte strings, which is
  501. inadequate because it renders some file names inaccessible.</p>
  502. <p>Python now allows using arbitrary Unicode strings (within the limitations of the
  503. file system) for all functions that expect file names, most notably the
  504. <a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> built-in function. If a Unicode string is passed to
  505. <a class="reference internal" href="../library/os.html#os.listdir" title="os.listdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.listdir()</span></code></a>, Python now returns a list of Unicode strings. A new
  506. function, <code class="xref py py-func docutils literal notranslate"><span class="pre">os.getcwdu()</span></code>, returns the current directory as a Unicode string.</p>
  507. <p>Byte strings still work as file names, and on Windows Python will transparently
  508. convert them to Unicode using the <code class="docutils literal notranslate"><span class="pre">mbcs</span></code> encoding.</p>
  509. <p>Other systems also allow Unicode strings as file names but convert them to byte
  510. strings before passing them to the system, which can cause a <a class="reference internal" href="../library/exceptions.html#UnicodeError" title="UnicodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeError</span></code></a>
  511. to be raised. Applications can test whether arbitrary Unicode strings are
  512. supported as file names by checking <a class="reference internal" href="../library/os.path.html#os.path.supports_unicode_filenames" title="os.path.supports_unicode_filenames"><code class="xref py py-attr docutils literal notranslate"><span class="pre">os.path.supports_unicode_filenames</span></code></a>,
  513. a Boolean value.</p>
  514. <p>Under MacOS, <a class="reference internal" href="../library/os.html#os.listdir" title="os.listdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.listdir()</span></code></a> may now return Unicode filenames.</p>
  515. <div class="admonition seealso">
  516. <p class="admonition-title">See also</p>
  517. <dl class="simple">
  518. <dt><span class="target" id="index-7"></span><a class="pep reference external" href="https://peps.python.org/pep-0277/"><strong>PEP 277</strong></a> - Unicode file name support for Windows NT</dt><dd><p>Written by Neil Hodgson; implemented by Neil Hodgson, Martin von Löwis, and Mark
  519. Hammond.</p>
  520. </dd>
  521. </dl>
  522. </div>
  523. </section>
  524. <section id="pep-278-universal-newline-support">
  525. <span id="index-8"></span><h2>PEP 278: Universal Newline Support<a class="headerlink" href="#pep-278-universal-newline-support" title="Link to this heading">¶</a></h2>
  526. <p>The three major operating systems used today are Microsoft Windows, Apple’s
  527. Macintosh OS, and the various Unix derivatives. A minor irritation of
  528. cross-platform work is that these three platforms all use different characters to
  529. mark the ends of lines in text files. Unix uses the linefeed (ASCII character
  530. 10), MacOS uses the carriage return (ASCII character 13), and Windows uses a
  531. two-character sequence of a carriage return plus a newline.</p>
  532. <p>Python’s file objects can now support end of line conventions other than the
  533. one followed by the platform on which Python is running. Opening a file with
  534. the mode <code class="docutils literal notranslate"><span class="pre">'U'</span></code> or <code class="docutils literal notranslate"><span class="pre">'rU'</span></code> will open a file for reading in <a class="reference internal" href="../glossary.html#term-universal-newlines"><span class="xref std std-term">universal
  535. newlines</span></a> mode. All three line ending conventions will be translated to a
  536. <code class="docutils literal notranslate"><span class="pre">'\n'</span></code> in the strings returned by the various file methods such as
  537. <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code>.</p>
  538. <p>Universal newline support is also used when importing modules and when executing
  539. a file with the <code class="xref py py-func docutils literal notranslate"><span class="pre">execfile()</span></code> function. This means that Python modules can
  540. be shared between all three operating systems without needing to convert the
  541. line-endings.</p>
  542. <p>This feature can be disabled when compiling Python by specifying the
  543. <code class="xref std std-option docutils literal notranslate"><span class="pre">--without-universal-newlines</span></code> switch when running Python’s
  544. <strong class="program">configure</strong> script.</p>
  545. <div class="admonition seealso">
  546. <p class="admonition-title">See also</p>
  547. <dl class="simple">
  548. <dt><span class="target" id="index-9"></span><a class="pep reference external" href="https://peps.python.org/pep-0278/"><strong>PEP 278</strong></a> - Universal Newline Support</dt><dd><p>Written and implemented by Jack Jansen.</p>
  549. </dd>
  550. </dl>
  551. </div>
  552. </section>
  553. <section id="pep-279-enumerate">
  554. <span id="section-enumerate"></span><h2>PEP 279: enumerate()<a class="headerlink" href="#pep-279-enumerate" title="Link to this heading">¶</a></h2>
  555. <p>A new built-in function, <a class="reference internal" href="../library/functions.html#enumerate" title="enumerate"><code class="xref py py-func docutils literal notranslate"><span class="pre">enumerate()</span></code></a>, will make certain loops a bit
  556. clearer. <code class="docutils literal notranslate"><span class="pre">enumerate(thing)</span></code>, where <em>thing</em> is either an iterator or a
  557. sequence, returns an iterator that will return <code class="docutils literal notranslate"><span class="pre">(0,</span> <span class="pre">thing[0])</span></code>, <code class="docutils literal notranslate"><span class="pre">(1,</span>
  558. <span class="pre">thing[1])</span></code>, <code class="docutils literal notranslate"><span class="pre">(2,</span> <span class="pre">thing[2])</span></code>, and so forth.</p>
  559. <p>A common idiom to change every element of a list looks like this:</p>
  560. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">L</span><span class="p">)):</span>
  561. <span class="n">item</span> <span class="o">=</span> <span class="n">L</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
  562. <span class="c1"># ... compute some result based on item ...</span>
  563. <span class="n">L</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="n">result</span>
  564. </pre></div>
  565. </div>
  566. <p>This can be rewritten using <a class="reference internal" href="../library/functions.html#enumerate" title="enumerate"><code class="xref py py-func docutils literal notranslate"><span class="pre">enumerate()</span></code></a> as:</p>
  567. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">item</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">L</span><span class="p">):</span>
  568. <span class="c1"># ... compute some result based on item ...</span>
  569. <span class="n">L</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="n">result</span>
  570. </pre></div>
  571. </div>
  572. <div class="admonition seealso">
  573. <p class="admonition-title">See also</p>
  574. <dl class="simple">
  575. <dt><span class="target" id="index-10"></span><a class="pep reference external" href="https://peps.python.org/pep-0279/"><strong>PEP 279</strong></a> - The enumerate() built-in function</dt><dd><p>Written and implemented by Raymond D. Hettinger.</p>
  576. </dd>
  577. </dl>
  578. </div>
  579. </section>
  580. <section id="pep-282-the-logging-package">
  581. <h2>PEP 282: The logging Package<a class="headerlink" href="#pep-282-the-logging-package" title="Link to this heading">¶</a></h2>
  582. <p>A standard package for writing logs, <a class="reference internal" href="../library/logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a>, has been added to Python
  583. 2.3. It provides a powerful and flexible mechanism for generating logging
  584. output which can then be filtered and processed in various ways. A
  585. configuration file written in a standard format can be used to control the
  586. logging behavior of a program. Python includes handlers that will write log
  587. records to standard error or to a file or socket, send them to the system log,
  588. or even e-mail them to a particular address; of course, it’s also possible to
  589. write your own handler classes.</p>
  590. <p>The <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a> class is the primary class. Most application code will deal
  591. with one or more <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a> objects, each one used by a particular
  592. subsystem of the application. Each <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a> is identified by a name, and
  593. names are organized into a hierarchy using <code class="docutils literal notranslate"><span class="pre">.</span></code> as the component separator.
  594. For example, you might have <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a> instances named <code class="docutils literal notranslate"><span class="pre">server</span></code>,
  595. <code class="docutils literal notranslate"><span class="pre">server.auth</span></code> and <code class="docutils literal notranslate"><span class="pre">server.network</span></code>. The latter two instances are below
  596. <code class="docutils literal notranslate"><span class="pre">server</span></code> in the hierarchy. This means that if you turn up the verbosity for
  597. <code class="docutils literal notranslate"><span class="pre">server</span></code> or direct <code class="docutils literal notranslate"><span class="pre">server</span></code> messages to a different handler, the changes
  598. will also apply to records logged to <code class="docutils literal notranslate"><span class="pre">server.auth</span></code> and <code class="docutils literal notranslate"><span class="pre">server.network</span></code>.
  599. There’s also a root <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a> that’s the parent of all other loggers.</p>
  600. <p>For simple uses, the <a class="reference internal" href="../library/logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> package contains some convenience functions
  601. that always use the root log:</p>
  602. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
  603. <span class="n">logging</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;Debugging information&#39;</span><span class="p">)</span>
  604. <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;Informational message&#39;</span><span class="p">)</span>
  605. <span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;Warning:config file </span><span class="si">%s</span><span class="s1"> not found&#39;</span><span class="p">,</span> <span class="s1">&#39;server.conf&#39;</span><span class="p">)</span>
  606. <span class="n">logging</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s1">&#39;Error occurred&#39;</span><span class="p">)</span>
  607. <span class="n">logging</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s1">&#39;Critical error -- shutting down&#39;</span><span class="p">)</span>
  608. </pre></div>
  609. </div>
  610. <p>This produces the following output:</p>
  611. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">WARNING</span><span class="p">:</span><span class="n">root</span><span class="p">:</span><span class="ne">Warning</span><span class="p">:</span><span class="n">config</span> <span class="n">file</span> <span class="n">server</span><span class="o">.</span><span class="n">conf</span> <span class="ow">not</span> <span class="n">found</span>
  612. <span class="n">ERROR</span><span class="p">:</span><span class="n">root</span><span class="p">:</span><span class="n">Error</span> <span class="n">occurred</span>
  613. <span class="n">CRITICAL</span><span class="p">:</span><span class="n">root</span><span class="p">:</span><span class="n">Critical</span> <span class="n">error</span> <span class="o">--</span> <span class="n">shutting</span> <span class="n">down</span>
  614. </pre></div>
  615. </div>
  616. <p>In the default configuration, informational and debugging messages are
  617. suppressed and the output is sent to standard error. You can enable the display
  618. of informational and debugging messages by calling the <a class="reference internal" href="../library/logging.html#logging.Logger.setLevel" title="logging.Logger.setLevel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setLevel()</span></code></a> method
  619. on the root logger.</p>
  620. <p>Notice the <a class="reference internal" href="../library/logging.html#logging.warning" title="logging.warning"><code class="xref py py-func docutils literal notranslate"><span class="pre">warning()</span></code></a> call’s use of string formatting operators; all of the
  621. functions for logging messages take the arguments <code class="docutils literal notranslate"><span class="pre">(msg,</span> <span class="pre">arg1,</span> <span class="pre">arg2,</span> <span class="pre">...)</span></code> and
  622. log the string resulting from <code class="docutils literal notranslate"><span class="pre">msg</span> <span class="pre">%</span> <span class="pre">(arg1,</span> <span class="pre">arg2,</span> <span class="pre">...)</span></code>.</p>
  623. <p>There’s also an <a class="reference internal" href="../library/logging.html#logging.exception" title="logging.exception"><code class="xref py py-func docutils literal notranslate"><span class="pre">exception()</span></code></a> function that records the most recent
  624. traceback. Any of the other functions will also record the traceback if you
  625. specify a true value for the keyword argument <em>exc_info</em>.</p>
  626. <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>
  627. <span class="k">try</span><span class="p">:</span> <span class="mi">1</span><span class="o">/</span><span class="mi">0</span>
  628. <span class="k">except</span><span class="p">:</span> <span class="n">logging</span><span class="o">.</span><span class="n">exception</span><span class="p">(</span><span class="s1">&#39;Problem recorded&#39;</span><span class="p">)</span>
  629. <span class="n">f</span><span class="p">()</span>
  630. </pre></div>
  631. </div>
  632. <p>This produces the following output:</p>
  633. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">ERROR</span><span class="p">:</span><span class="n">root</span><span class="p">:</span><span class="n">Problem</span> <span class="n">recorded</span>
  634. <span class="n">Traceback</span> <span class="p">(</span><span class="n">most</span> <span class="n">recent</span> <span class="n">call</span> <span class="n">last</span><span class="p">):</span>
  635. <span class="n">File</span> <span class="s2">&quot;t.py&quot;</span><span class="p">,</span> <span class="n">line</span> <span class="mi">6</span><span class="p">,</span> <span class="ow">in</span> <span class="n">f</span>
  636. <span class="mi">1</span><span class="o">/</span><span class="mi">0</span>
  637. <span class="ne">ZeroDivisionError</span><span class="p">:</span> <span class="n">integer</span> <span class="n">division</span> <span class="ow">or</span> <span class="n">modulo</span> <span class="n">by</span> <span class="n">zero</span>
  638. </pre></div>
  639. </div>
  640. <p>Slightly more advanced programs will use a logger other than the root logger.
  641. The <code class="docutils literal notranslate"><span class="pre">getLogger(name)</span></code> function is used to get a particular log, creating
  642. it if it doesn’t exist yet. <code class="docutils literal notranslate"><span class="pre">getLogger(None)</span></code> returns the root logger.</p>
  643. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">log</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;server&#39;</span><span class="p">)</span>
  644. <span class="o">...</span>
  645. <span class="n">log</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;Listening on port </span><span class="si">%i</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">port</span><span class="p">)</span>
  646. <span class="o">...</span>
  647. <span class="n">log</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s1">&#39;Disk full&#39;</span><span class="p">)</span>
  648. <span class="o">...</span>
  649. </pre></div>
  650. </div>
  651. <p>Log records are usually propagated up the hierarchy, so a message logged to
  652. <code class="docutils literal notranslate"><span class="pre">server.auth</span></code> is also seen by <code class="docutils literal notranslate"><span class="pre">server</span></code> and <code class="docutils literal notranslate"><span class="pre">root</span></code>, but a <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a>
  653. can prevent this by setting its <a class="reference internal" href="../library/logging.html#logging.Logger.propagate" title="logging.Logger.propagate"><code class="xref py py-attr docutils literal notranslate"><span class="pre">propagate</span></code></a> attribute to <a class="reference internal" href="../library/constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>.</p>
  654. <p>There are more classes provided by the <a class="reference internal" href="../library/logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> package that can be
  655. customized. When a <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a> instance is told to log a message, it
  656. creates a <a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a> instance that is sent to any number of different
  657. <a class="reference internal" href="../library/logging.html#logging.Handler" title="logging.Handler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Handler</span></code></a> instances. Loggers and handlers can also have an attached list
  658. of filters, and each filter can cause the <a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a> to be ignored or
  659. can modify the record before passing it along. When they’re finally output,
  660. <a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a> instances are converted to text by a <a class="reference internal" href="../library/logging.html#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a>
  661. class. All of these classes can be replaced by your own specially written
  662. classes.</p>
  663. <p>With all of these features the <a class="reference internal" href="../library/logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> package should provide enough
  664. flexibility for even the most complicated applications. This is only an
  665. incomplete overview of its features, so please see the package’s reference
  666. documentation for all of the details. Reading <span class="target" id="index-11"></span><a class="pep reference external" href="https://peps.python.org/pep-0282/"><strong>PEP 282</strong></a> will also be helpful.</p>
  667. <div class="admonition seealso">
  668. <p class="admonition-title">See also</p>
  669. <dl class="simple">
  670. <dt><span class="target" id="index-12"></span><a class="pep reference external" href="https://peps.python.org/pep-0282/"><strong>PEP 282</strong></a> - A Logging System</dt><dd><p>Written by Vinay Sajip and Trent Mick; implemented by Vinay Sajip.</p>
  671. </dd>
  672. </dl>
  673. </div>
  674. </section>
  675. <section id="pep-285-a-boolean-type">
  676. <span id="section-bool"></span><h2>PEP 285: A Boolean Type<a class="headerlink" href="#pep-285-a-boolean-type" title="Link to this heading">¶</a></h2>
  677. <p>A Boolean type was added to Python 2.3. Two new constants were added to the
  678. <code class="xref py py-mod docutils literal notranslate"><span class="pre">__builtin__</span></code> module, <a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> and <a class="reference internal" href="../library/constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>. (<a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> and
  679. <a class="reference internal" href="../library/constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> constants were added to the built-ins in Python 2.2.1, but the
  680. 2.2.1 versions are simply set to integer values of 1 and 0 and aren’t a
  681. different type.)</p>
  682. <p>The type object for this new type is named <a class="reference internal" href="../library/functions.html#bool" title="bool"><code class="xref py py-class docutils literal notranslate"><span class="pre">bool</span></code></a>; the constructor for it
  683. takes any Python value and converts it to <a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> or <a class="reference internal" href="../library/constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>.</p>
  684. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">bool</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
  685. <span class="go">True</span>
  686. <span class="gp">&gt;&gt;&gt; </span><span class="nb">bool</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
  687. <span class="go">False</span>
  688. <span class="gp">&gt;&gt;&gt; </span><span class="nb">bool</span><span class="p">([])</span>
  689. <span class="go">False</span>
  690. <span class="gp">&gt;&gt;&gt; </span><span class="nb">bool</span><span class="p">(</span> <span class="p">(</span><span class="mi">1</span><span class="p">,)</span> <span class="p">)</span>
  691. <span class="go">True</span>
  692. </pre></div>
  693. </div>
  694. <p>Most of the standard library modules and built-in functions have been changed to
  695. return Booleans.</p>
  696. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">obj</span> <span class="o">=</span> <span class="p">[]</span>
  697. <span class="gp">&gt;&gt;&gt; </span><span class="nb">hasattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="s1">&#39;append&#39;</span><span class="p">)</span>
  698. <span class="go">True</span>
  699. <span class="gp">&gt;&gt;&gt; </span><span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="nb">list</span><span class="p">)</span>
  700. <span class="go">True</span>
  701. <span class="gp">&gt;&gt;&gt; </span><span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="nb">tuple</span><span class="p">)</span>
  702. <span class="go">False</span>
  703. </pre></div>
  704. </div>
  705. <p>Python’s Booleans were added with the primary goal of making code clearer. For
  706. example, if you’re reading a function and encounter the statement <code class="docutils literal notranslate"><span class="pre">return</span> <span class="pre">1</span></code>,
  707. you might wonder whether the <code class="docutils literal notranslate"><span class="pre">1</span></code> represents a Boolean truth value, an index,
  708. or a coefficient that multiplies some other quantity. If the statement is
  709. <code class="docutils literal notranslate"><span class="pre">return</span> <span class="pre">True</span></code>, however, the meaning of the return value is quite clear.</p>
  710. <p>Python’s Booleans were <em>not</em> added for the sake of strict type-checking. A very
  711. strict language such as Pascal would also prevent you performing arithmetic with
  712. Booleans, and would require that the expression in an <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement
  713. always evaluate to a Boolean result. Python is not this strict and never will
  714. be, as <span class="target" id="index-13"></span><a class="pep reference external" href="https://peps.python.org/pep-0285/"><strong>PEP 285</strong></a> explicitly says. This means you can still use any expression
  715. in an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code> statement, even ones that evaluate to a list or tuple or
  716. some random object. The Boolean type is a subclass of the <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> class so
  717. that arithmetic using a Boolean still works.</p>
  718. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kc">True</span> <span class="o">+</span> <span class="mi">1</span>
  719. <span class="go">2</span>
  720. <span class="gp">&gt;&gt;&gt; </span><span class="kc">False</span> <span class="o">+</span> <span class="mi">1</span>
  721. <span class="go">1</span>
  722. <span class="gp">&gt;&gt;&gt; </span><span class="kc">False</span> <span class="o">*</span> <span class="mi">75</span>
  723. <span class="go">0</span>
  724. <span class="gp">&gt;&gt;&gt; </span><span class="kc">True</span> <span class="o">*</span> <span class="mi">75</span>
  725. <span class="go">75</span>
  726. </pre></div>
  727. </div>
  728. <p>To sum up <a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> and <a class="reference internal" href="../library/constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> in a sentence: they’re alternative
  729. ways to spell the integer values 1 and 0, with the single difference that
  730. <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> and <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> return the strings <code class="docutils literal notranslate"><span class="pre">'True'</span></code> and <code class="docutils literal notranslate"><span class="pre">'False'</span></code>
  731. instead of <code class="docutils literal notranslate"><span class="pre">'1'</span></code> and <code class="docutils literal notranslate"><span class="pre">'0'</span></code>.</p>
  732. <div class="admonition seealso">
  733. <p class="admonition-title">See also</p>
  734. <dl class="simple">
  735. <dt><span class="target" id="index-14"></span><a class="pep reference external" href="https://peps.python.org/pep-0285/"><strong>PEP 285</strong></a> - Adding a bool type</dt><dd><p>Written and implemented by GvR.</p>
  736. </dd>
  737. </dl>
  738. </div>
  739. </section>
  740. <section id="pep-293-codec-error-handling-callbacks">
  741. <h2>PEP 293: Codec Error Handling Callbacks<a class="headerlink" href="#pep-293-codec-error-handling-callbacks" title="Link to this heading">¶</a></h2>
  742. <p>When encoding a Unicode string into a byte string, unencodable characters may be
  743. encountered. So far, Python has allowed specifying the error processing as
  744. either “strict” (raising <a class="reference internal" href="../library/exceptions.html#UnicodeError" title="UnicodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeError</span></code></a>), “ignore” (skipping the
  745. character), or “replace” (using a question mark in the output string), with
  746. “strict” being the default behavior. It may be desirable to specify alternative
  747. processing of such errors, such as inserting an XML character reference or HTML
  748. entity reference into the converted string.</p>
  749. <p>Python now has a flexible framework to add different processing strategies. New
  750. error handlers can be added with <a class="reference internal" href="../library/codecs.html#codecs.register_error" title="codecs.register_error"><code class="xref py py-func docutils literal notranslate"><span class="pre">codecs.register_error()</span></code></a>, and codecs then
  751. can access the error handler with <a class="reference internal" href="../library/codecs.html#codecs.lookup_error" title="codecs.lookup_error"><code class="xref py py-func docutils literal notranslate"><span class="pre">codecs.lookup_error()</span></code></a>. An equivalent C
  752. API has been added for codecs written in C. The error handler gets the necessary
  753. state information such as the string being converted, the position in the string
  754. where the error was detected, and the target encoding. The handler can then
  755. either raise an exception or return a replacement string.</p>
  756. <p>Two additional error handlers have been implemented using this framework:
  757. “backslashreplace” uses Python backslash quoting to represent unencodable
  758. characters and “xmlcharrefreplace” emits XML character references.</p>
  759. <div class="admonition seealso">
  760. <p class="admonition-title">See also</p>
  761. <dl class="simple">
  762. <dt><span class="target" id="index-15"></span><a class="pep reference external" href="https://peps.python.org/pep-0293/"><strong>PEP 293</strong></a> - Codec Error Handling Callbacks</dt><dd><p>Written and implemented by Walter Dörwald.</p>
  763. </dd>
  764. </dl>
  765. </div>
  766. </section>
  767. <section id="pep-301-package-index-and-metadata-for-distutils">
  768. <span id="section-pep301"></span><h2>PEP 301: Package Index and Metadata for Distutils<a class="headerlink" href="#pep-301-package-index-and-metadata-for-distutils" title="Link to this heading">¶</a></h2>
  769. <p>Support for the long-requested Python catalog makes its first appearance in 2.3.</p>
  770. <p>The heart of the catalog is the new Distutils <strong class="command">register</strong> command.
  771. Running <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">setup.py</span> <span class="pre">register</span></code> will collect the metadata describing a
  772. package, such as its name, version, maintainer, description, &amp;c., and send it to
  773. a central catalog server. The resulting catalog is available from
  774. <a class="reference external" href="https://pypi.org">https://pypi.org</a>.</p>
  775. <p>To make the catalog a bit more useful, a new optional <em>classifiers</em> keyword
  776. argument has been added to the Distutils <code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code> function. A list of
  777. <a class="reference external" href="http://catb.org/~esr/trove/">Trove</a>-style strings can be supplied to help
  778. classify the software.</p>
  779. <p>Here’s an example <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code> with classifiers, written to be compatible
  780. with older versions of the Distutils:</p>
  781. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">distutils</span> <span class="kn">import</span> <span class="n">core</span>
  782. <span class="n">kw</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;name&#39;</span><span class="p">:</span> <span class="s2">&quot;Quixote&quot;</span><span class="p">,</span>
  783. <span class="s1">&#39;version&#39;</span><span class="p">:</span> <span class="s2">&quot;0.5.1&quot;</span><span class="p">,</span>
  784. <span class="s1">&#39;description&#39;</span><span class="p">:</span> <span class="s2">&quot;A highly Pythonic Web application framework&quot;</span><span class="p">,</span>
  785. <span class="c1"># ...</span>
  786. <span class="p">}</span>
  787. <span class="k">if</span> <span class="p">(</span><span class="nb">hasattr</span><span class="p">(</span><span class="n">core</span><span class="p">,</span> <span class="s1">&#39;setup_keywords&#39;</span><span class="p">)</span> <span class="ow">and</span>
  788. <span class="s1">&#39;classifiers&#39;</span> <span class="ow">in</span> <span class="n">core</span><span class="o">.</span><span class="n">setup_keywords</span><span class="p">):</span>
  789. <span class="n">kw</span><span class="p">[</span><span class="s1">&#39;classifiers&#39;</span><span class="p">]</span> <span class="o">=</span> \
  790. <span class="p">[</span><span class="s1">&#39;Topic :: Internet :: WWW/HTTP :: Dynamic Content&#39;</span><span class="p">,</span>
  791. <span class="s1">&#39;Environment :: No Input/Output (Daemon)&#39;</span><span class="p">,</span>
  792. <span class="s1">&#39;Intended Audience :: Developers&#39;</span><span class="p">],</span>
  793. <span class="n">core</span><span class="o">.</span><span class="n">setup</span><span class="p">(</span><span class="o">**</span><span class="n">kw</span><span class="p">)</span>
  794. </pre></div>
  795. </div>
  796. <p>The full list of classifiers can be obtained by running <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">setup.py</span>
  797. <span class="pre">register</span> <span class="pre">--list-classifiers</span></code>.</p>
  798. <div class="admonition seealso">
  799. <p class="admonition-title">See also</p>
  800. <dl class="simple">
  801. <dt><span class="target" id="index-16"></span><a class="pep reference external" href="https://peps.python.org/pep-0301/"><strong>PEP 301</strong></a> - Package Index and Metadata for Distutils</dt><dd><p>Written and implemented by Richard Jones.</p>
  802. </dd>
  803. </dl>
  804. </div>
  805. </section>
  806. <section id="pep-302-new-import-hooks">
  807. <span id="section-pep302"></span><h2>PEP 302: New Import Hooks<a class="headerlink" href="#pep-302-new-import-hooks" title="Link to this heading">¶</a></h2>
  808. <p>While it’s been possible to write custom import hooks ever since the
  809. <code class="xref py py-mod docutils literal notranslate"><span class="pre">ihooks</span></code> module was introduced in Python 1.3, no one has ever been really
  810. happy with it because writing new import hooks is difficult and messy. There
  811. have been various proposed alternatives such as the <code class="xref py py-mod docutils literal notranslate"><span class="pre">imputil</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">iu</span></code>
  812. modules, but none of them has ever gained much acceptance, and none of them were
  813. easily usable from C code.</p>
  814. <p><span class="target" id="index-17"></span><a class="pep reference external" href="https://peps.python.org/pep-0302/"><strong>PEP 302</strong></a> borrows ideas from its predecessors, especially from Gordon
  815. McMillan’s <code class="xref py py-mod docutils literal notranslate"><span class="pre">iu</span></code> module. Three new items are added to the <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a>
  816. module:</p>
  817. <ul class="simple">
  818. <li><p><code class="docutils literal notranslate"><span class="pre">sys.path_hooks</span></code> is a list of callable objects; most often they’ll be
  819. classes. Each callable takes a string containing a path and either returns an
  820. importer object that will handle imports from this path or raises an
  821. <a class="reference internal" href="../library/exceptions.html#ImportError" title="ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a> exception if it can’t handle this path.</p></li>
  822. <li><p><code class="docutils literal notranslate"><span class="pre">sys.path_importer_cache</span></code> caches importer objects for each path, so
  823. <code class="docutils literal notranslate"><span class="pre">sys.path_hooks</span></code> will only need to be traversed once for each path.</p></li>
  824. <li><p><code class="docutils literal notranslate"><span class="pre">sys.meta_path</span></code> is a list of importer objects that will be traversed before
  825. <code class="docutils literal notranslate"><span class="pre">sys.path</span></code> is checked. This list is initially empty, but user code can add
  826. objects to it. Additional built-in and frozen modules can be imported by an
  827. object added to this list.</p></li>
  828. </ul>
  829. <p>Importer objects must have a single method, <code class="docutils literal notranslate"><span class="pre">find_module(fullname,</span>
  830. <span class="pre">path=None)</span></code>. <em>fullname</em> will be a module or package name, e.g. <code class="docutils literal notranslate"><span class="pre">string</span></code> or
  831. <code class="docutils literal notranslate"><span class="pre">distutils.core</span></code>. <code class="xref py py-meth docutils literal notranslate"><span class="pre">find_module()</span></code> must return a loader object that has a
  832. single method, <code class="docutils literal notranslate"><span class="pre">load_module(fullname)</span></code>, that creates and returns the
  833. corresponding module object.</p>
  834. <p>Pseudo-code for Python’s new import logic, therefore, looks something like this
  835. (simplified a bit; see <span class="target" id="index-18"></span><a class="pep reference external" href="https://peps.python.org/pep-0302/"><strong>PEP 302</strong></a> for the full details):</p>
  836. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">mp</span> <span class="ow">in</span> <span class="n">sys</span><span class="o">.</span><span class="n">meta_path</span><span class="p">:</span>
  837. <span class="n">loader</span> <span class="o">=</span> <span class="n">mp</span><span class="p">(</span><span class="n">fullname</span><span class="p">)</span>
  838. <span class="k">if</span> <span class="n">loader</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
  839. <span class="o">&lt;</span><span class="n">module</span><span class="o">&gt;</span> <span class="o">=</span> <span class="n">loader</span><span class="o">.</span><span class="n">load_module</span><span class="p">(</span><span class="n">fullname</span><span class="p">)</span>
  840. <span class="k">for</span> <span class="n">path</span> <span class="ow">in</span> <span class="n">sys</span><span class="o">.</span><span class="n">path</span><span class="p">:</span>
  841. <span class="k">for</span> <span class="n">hook</span> <span class="ow">in</span> <span class="n">sys</span><span class="o">.</span><span class="n">path_hooks</span><span class="p">:</span>
  842. <span class="k">try</span><span class="p">:</span>
  843. <span class="n">importer</span> <span class="o">=</span> <span class="n">hook</span><span class="p">(</span><span class="n">path</span><span class="p">)</span>
  844. <span class="k">except</span> <span class="ne">ImportError</span><span class="p">:</span>
  845. <span class="c1"># ImportError, so try the other path hooks</span>
  846. <span class="k">pass</span>
  847. <span class="k">else</span><span class="p">:</span>
  848. <span class="n">loader</span> <span class="o">=</span> <span class="n">importer</span><span class="o">.</span><span class="n">find_module</span><span class="p">(</span><span class="n">fullname</span><span class="p">)</span>
  849. <span class="o">&lt;</span><span class="n">module</span><span class="o">&gt;</span> <span class="o">=</span> <span class="n">loader</span><span class="o">.</span><span class="n">load_module</span><span class="p">(</span><span class="n">fullname</span><span class="p">)</span>
  850. <span class="c1"># Not found!</span>
  851. <span class="k">raise</span> <span class="ne">ImportError</span>
  852. </pre></div>
  853. </div>
  854. <div class="admonition seealso">
  855. <p class="admonition-title">See also</p>
  856. <dl class="simple">
  857. <dt><span class="target" id="index-19"></span><a class="pep reference external" href="https://peps.python.org/pep-0302/"><strong>PEP 302</strong></a> - New Import Hooks</dt><dd><p>Written by Just van Rossum and Paul Moore. Implemented by Just van Rossum.</p>
  858. </dd>
  859. </dl>
  860. </div>
  861. </section>
  862. <section id="pep-305-comma-separated-files">
  863. <span id="section-pep305"></span><h2>PEP 305: Comma-separated Files<a class="headerlink" href="#pep-305-comma-separated-files" title="Link to this heading">¶</a></h2>
  864. <p>Comma-separated files are a format frequently used for exporting data from
  865. databases and spreadsheets. Python 2.3 adds a parser for comma-separated files.</p>
  866. <p>Comma-separated format is deceptively simple at first glance:</p>
  867. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">Costs</span><span class="p">,</span><span class="mi">150</span><span class="p">,</span><span class="mi">200</span><span class="p">,</span><span class="mf">3.95</span>
  868. </pre></div>
  869. </div>
  870. <p>Read a line and call <code class="docutils literal notranslate"><span class="pre">line.split(',')</span></code>: what could be simpler? But toss in
  871. string data that can contain commas, and things get more complicated:</p>
  872. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="s2">&quot;Costs&quot;</span><span class="p">,</span><span class="mi">150</span><span class="p">,</span><span class="mi">200</span><span class="p">,</span><span class="mf">3.95</span><span class="p">,</span><span class="s2">&quot;Includes taxes, shipping, and sundry items&quot;</span>
  873. </pre></div>
  874. </div>
  875. <p>A big ugly regular expression can parse this, but using the new <a class="reference internal" href="../library/csv.html#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a>
  876. package is much simpler:</p>
  877. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">csv</span>
  878. <span class="nb">input</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;datafile&#39;</span><span class="p">,</span> <span class="s1">&#39;rb&#39;</span><span class="p">)</span>
  879. <span class="n">reader</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">(</span><span class="nb">input</span><span class="p">)</span>
  880. <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">reader</span><span class="p">:</span>
  881. <span class="nb">print</span> <span class="n">line</span>
  882. </pre></div>
  883. </div>
  884. <p>The <a class="reference internal" href="../library/csv.html#csv.reader" title="csv.reader"><code class="xref py py-func docutils literal notranslate"><span class="pre">reader()</span></code></a> function takes a number of different options. The field
  885. separator isn’t limited to the comma and can be changed to any character, and so
  886. can the quoting and line-ending characters.</p>
  887. <p>Different dialects of comma-separated files can be defined and registered;
  888. currently there are two dialects, both used by Microsoft Excel. A separate
  889. <a class="reference internal" href="../library/csv.html#csv.writer" title="csv.writer"><code class="xref py py-class docutils literal notranslate"><span class="pre">csv.writer</span></code></a> class will generate comma-separated files from a succession
  890. of tuples or lists, quoting strings that contain the delimiter.</p>
  891. <div class="admonition seealso">
  892. <p class="admonition-title">See also</p>
  893. <dl class="simple">
  894. <dt><span class="target" id="index-20"></span><a class="pep reference external" href="https://peps.python.org/pep-0305/"><strong>PEP 305</strong></a> - CSV File API</dt><dd><p>Written and implemented by Kevin Altis, Dave Cole, Andrew McNamara, Skip
  895. Montanaro, Cliff Wells.</p>
  896. </dd>
  897. </dl>
  898. </div>
  899. </section>
  900. <section id="pep-307-pickle-enhancements">
  901. <span id="section-pep307"></span><h2>PEP 307: Pickle Enhancements<a class="headerlink" href="#pep-307-pickle-enhancements" title="Link to this heading">¶</a></h2>
  902. <p>The <a class="reference internal" href="../library/pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code> modules received some attention during the
  903. 2.3 development cycle. In 2.2, new-style classes could be pickled without
  904. difficulty, but they weren’t pickled very compactly; <span class="target" id="index-21"></span><a class="pep reference external" href="https://peps.python.org/pep-0307/"><strong>PEP 307</strong></a> quotes a trivial
  905. example where a new-style class results in a pickled string three times longer
  906. than that for a classic class.</p>
  907. <p>The solution was to invent a new pickle protocol. The <a class="reference internal" href="../library/pickle.html#pickle.dumps" title="pickle.dumps"><code class="xref py py-func docutils literal notranslate"><span class="pre">pickle.dumps()</span></code></a>
  908. function has supported a text-or-binary flag for a long time. In 2.3, this
  909. flag is redefined from a Boolean to an integer: 0 is the old text-mode pickle
  910. format, 1 is the old binary format, and now 2 is a new 2.3-specific format. A
  911. new constant, <a class="reference internal" href="../library/pickle.html#pickle.HIGHEST_PROTOCOL" title="pickle.HIGHEST_PROTOCOL"><code class="xref py py-const docutils literal notranslate"><span class="pre">pickle.HIGHEST_PROTOCOL</span></code></a>, can be used to select the
  912. fanciest protocol available.</p>
  913. <p>Unpickling is no longer considered a safe operation. 2.2’s <a class="reference internal" href="../library/pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a>
  914. provided hooks for trying to prevent unsafe classes from being unpickled
  915. (specifically, a <code class="xref py py-attr docutils literal notranslate"><span class="pre">__safe_for_unpickling__</span></code> attribute), but none of this
  916. code was ever audited and therefore it’s all been ripped out in 2.3. You should
  917. not unpickle untrusted data in any version of Python.</p>
  918. <p>To reduce the pickling overhead for new-style classes, a new interface for
  919. customizing pickling was added using three special methods:
  920. <a class="reference internal" href="../library/pickle.html#object.__getstate__" title="object.__getstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getstate__()</span></code></a>, <a class="reference internal" href="../library/pickle.html#object.__setstate__" title="object.__setstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setstate__()</span></code></a>, and <a class="reference internal" href="../library/pickle.html#object.__getnewargs__" title="object.__getnewargs__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getnewargs__()</span></code></a>. Consult
  921. <span class="target" id="index-22"></span><a class="pep reference external" href="https://peps.python.org/pep-0307/"><strong>PEP 307</strong></a> for the full semantics of these methods.</p>
  922. <p>As a way to compress pickles yet further, it’s now possible to use integer codes
  923. instead of long strings to identify pickled classes. The Python Software
  924. Foundation will maintain a list of standardized codes; there’s also a range of
  925. codes for private use. Currently no codes have been specified.</p>
  926. <div class="admonition seealso">
  927. <p class="admonition-title">See also</p>
  928. <dl class="simple">
  929. <dt><span class="target" id="index-23"></span><a class="pep reference external" href="https://peps.python.org/pep-0307/"><strong>PEP 307</strong></a> - Extensions to the pickle protocol</dt><dd><p>Written and implemented by Guido van Rossum and Tim Peters.</p>
  930. </dd>
  931. </dl>
  932. </div>
  933. </section>
  934. <section id="extended-slices">
  935. <span id="section-slices"></span><h2>Extended Slices<a class="headerlink" href="#extended-slices" title="Link to this heading">¶</a></h2>
  936. <p>Ever since Python 1.4, the slicing syntax has supported an optional third “step”
  937. or “stride” argument. For example, these are all legal Python syntax:
  938. <code class="docutils literal notranslate"><span class="pre">L[1:10:2]</span></code>, <code class="docutils literal notranslate"><span class="pre">L[:-1:1]</span></code>, <code class="docutils literal notranslate"><span class="pre">L[::-1]</span></code>. This was added to Python at the
  939. request of the developers of Numerical Python, which uses the third argument
  940. extensively. However, Python’s built-in list, tuple, and string sequence types
  941. have never supported this feature, raising a <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> if you tried it.
  942. Michael Hudson contributed a patch to fix this shortcoming.</p>
  943. <p>For example, you can now easily extract the elements of a list that have even
  944. indexes:</p>
  945. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">L</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
  946. <span class="gp">&gt;&gt;&gt; </span><span class="n">L</span><span class="p">[::</span><span class="mi">2</span><span class="p">]</span>
  947. <span class="go">[0, 2, 4, 6, 8]</span>
  948. </pre></div>
  949. </div>
  950. <p>Negative values also work to make a copy of the same list in reverse order:</p>
  951. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">L</span><span class="p">[::</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
  952. <span class="go">[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]</span>
  953. </pre></div>
  954. </div>
  955. <p>This also works for tuples, arrays, and strings:</p>
  956. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">=</span><span class="s1">&#39;abcd&#39;</span>
  957. <span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="p">[::</span><span class="mi">2</span><span class="p">]</span>
  958. <span class="go">&#39;ac&#39;</span>
  959. <span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="p">[::</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
  960. <span class="go">&#39;dcba&#39;</span>
  961. </pre></div>
  962. </div>
  963. <p>If you have a mutable sequence such as a list or an array you can assign to or
  964. delete an extended slice, but there are some differences between assignment to
  965. extended and regular slices. Assignment to a regular slice can be used to
  966. change the length of the sequence:</p>
  967. <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="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
  968. <span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
  969. <span class="go">[0, 1, 2]</span>
  970. <span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">3</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">]</span>
  971. <span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
  972. <span class="go">[0, 4, 5, 6]</span>
  973. </pre></div>
  974. </div>
  975. <p>Extended slices aren’t this flexible. When assigning to an extended slice, the
  976. list on the right hand side of the statement must contain the same number of
  977. items as the slice it is replacing:</p>
  978. <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="nb">range</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
  979. <span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
  980. <span class="go">[0, 1, 2, 3]</span>
  981. <span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">[::</span><span class="mi">2</span><span class="p">]</span>
  982. <span class="go">[0, 2]</span>
  983. <span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">[::</span><span class="mi">2</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">]</span>
  984. <span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
  985. <span class="go">[0, 1, -1, 3]</span>
  986. <span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">[::</span><span class="mi">2</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">]</span>
  987. <span class="gt">Traceback (most recent call last):</span>
  988. File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">?</span>
  989. <span class="gr">ValueError</span>: <span class="n">attempt to assign sequence of size 3 to extended slice of size 2</span>
  990. </pre></div>
  991. </div>
  992. <p>Deletion is more straightforward:</p>
  993. <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="nb">range</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
  994. <span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
  995. <span class="go">[0, 1, 2, 3]</span>
  996. <span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">[::</span><span class="mi">2</span><span class="p">]</span>
  997. <span class="go">[0, 2]</span>
  998. <span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">a</span><span class="p">[::</span><span class="mi">2</span><span class="p">]</span>
  999. <span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
  1000. <span class="go">[1, 3]</span>
  1001. </pre></div>
  1002. </div>
  1003. <p>One can also now pass slice objects to the <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> methods of the
  1004. built-in sequences:</p>
  1005. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span><span class="o">.</span><span class="fm">__getitem__</span><span class="p">(</span><span class="nb">slice</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span>
  1006. <span class="go">[0, 2, 4]</span>
  1007. </pre></div>
  1008. </div>
  1009. <p>Or use slice objects directly in subscripts:</p>
  1010. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)[</span><span class="nb">slice</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">2</span><span class="p">)]</span>
  1011. <span class="go">[0, 2, 4]</span>
  1012. </pre></div>
  1013. </div>
  1014. <p>To simplify implementing sequences that support extended slicing, slice objects
  1015. now have a method <code class="docutils literal notranslate"><span class="pre">indices(length)</span></code> which, given the length of a sequence,
  1016. returns a <code class="docutils literal notranslate"><span class="pre">(start,</span> <span class="pre">stop,</span> <span class="pre">step)</span></code> tuple that can be passed directly to
  1017. <a class="reference internal" href="../library/stdtypes.html#range" title="range"><code class="xref py py-func docutils literal notranslate"><span class="pre">range()</span></code></a>. <code class="xref py py-meth docutils literal notranslate"><span class="pre">indices()</span></code> handles omitted and out-of-bounds indices in a
  1018. manner consistent with regular slices (and this innocuous phrase hides a welter
  1019. of confusing details!). The method is intended to be used like this:</p>
  1020. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">FakeSeq</span><span class="p">:</span>
  1021. <span class="o">...</span>
  1022. <span class="k">def</span> <span class="nf">calc_item</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">i</span><span class="p">):</span>
  1023. <span class="o">...</span>
  1024. <span class="k">def</span> <span class="fm">__getitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">item</span><span class="p">):</span>
  1025. <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">item</span><span class="p">,</span> <span class="nb">slice</span><span class="p">):</span>
  1026. <span class="n">indices</span> <span class="o">=</span> <span class="n">item</span><span class="o">.</span><span class="n">indices</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="p">))</span>
  1027. <span class="k">return</span> <span class="n">FakeSeq</span><span class="p">([</span><span class="bp">self</span><span class="o">.</span><span class="n">calc_item</span><span class="p">(</span><span class="n">i</span><span class="p">)</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="o">*</span><span class="n">indices</span><span class="p">)])</span>
  1028. <span class="k">else</span><span class="p">:</span>
  1029. <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">calc_item</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
  1030. </pre></div>
  1031. </div>
  1032. <p>From this example you can also see that the built-in <a class="reference internal" href="../library/functions.html#slice" title="slice"><code class="xref py py-class docutils literal notranslate"><span class="pre">slice</span></code></a> object is
  1033. now the type object for the slice type, and is no longer a function. This is
  1034. consistent with Python 2.2, where <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#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>, etc., underwent
  1035. the same change.</p>
  1036. </section>
  1037. <section id="other-language-changes">
  1038. <h2>Other Language Changes<a class="headerlink" href="#other-language-changes" title="Link to this heading">¶</a></h2>
  1039. <p>Here are all of the changes that Python 2.3 makes to the core Python language.</p>
  1040. <ul>
  1041. <li><p>The <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement is now always a keyword, as described in
  1042. section <a class="reference internal" href="#section-generators"><span class="std std-ref">PEP 255: Simple Generators</span></a> of this document.</p></li>
  1043. <li><p>A new built-in function <a class="reference internal" href="../library/functions.html#enumerate" title="enumerate"><code class="xref py py-func docutils literal notranslate"><span class="pre">enumerate()</span></code></a> was added, as described in section
  1044. <a class="reference internal" href="#section-enumerate"><span class="std std-ref">PEP 279: enumerate()</span></a> of this document.</p></li>
  1045. <li><p>Two new constants, <a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> and <a class="reference internal" href="../library/constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> were added along with the
  1046. built-in <a class="reference internal" href="../library/functions.html#bool" title="bool"><code class="xref py py-class docutils literal notranslate"><span class="pre">bool</span></code></a> type, as described in section <a class="reference internal" href="#section-bool"><span class="std std-ref">PEP 285: A Boolean Type</span></a> of this
  1047. document.</p></li>
  1048. <li><p>The <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 will now return a long integer instead of
  1049. raising an <a class="reference internal" href="../library/exceptions.html#OverflowError" title="OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a> when a string or floating-point number is too
  1050. large to fit into an integer. This can lead to the paradoxical result that
  1051. <code class="docutils literal notranslate"><span class="pre">isinstance(int(expression),</span> <span class="pre">int)</span></code> is false, but that seems unlikely to cause
  1052. problems in practice.</p></li>
  1053. <li><p>Built-in types now support the extended slicing syntax, as described in
  1054. section <a class="reference internal" href="#section-slices"><span class="std std-ref">Extended Slices</span></a> of this document.</p></li>
  1055. <li><p>A new built-in function, <code class="docutils literal notranslate"><span class="pre">sum(iterable,</span> <span class="pre">start=0)</span></code>, adds up the numeric
  1056. items in the iterable object and returns their sum. <a class="reference internal" href="../library/functions.html#sum" title="sum"><code class="xref py py-func docutils literal notranslate"><span class="pre">sum()</span></code></a> only accepts
  1057. numbers, meaning that you can’t use it to concatenate a bunch of strings.
  1058. (Contributed by Alex Martelli.)</p></li>
  1059. <li><p><code class="docutils literal notranslate"><span class="pre">list.insert(pos,</span> <span class="pre">value)</span></code> used to insert <em>value</em> at the front of the list
  1060. when <em>pos</em> was negative. The behaviour has now been changed to be consistent
  1061. with slice indexing, so when <em>pos</em> is -1 the value will be inserted before the
  1062. last element, and so forth.</p></li>
  1063. <li><p><code class="docutils literal notranslate"><span class="pre">list.index(value)</span></code>, which searches for <em>value</em> within the list and returns
  1064. its index, now takes optional <em>start</em> and <em>stop</em> arguments to limit the search
  1065. to only part of the list.</p></li>
  1066. <li><p>Dictionaries have a new method, <code class="docutils literal notranslate"><span class="pre">pop(key[,</span> <span class="pre">*default*])</span></code>, that returns
  1067. the value corresponding to <em>key</em> and removes that key/value pair from the
  1068. dictionary. If the requested key isn’t present in the dictionary, <em>default</em> is
  1069. returned if it’s specified and <a class="reference internal" href="../library/exceptions.html#KeyError" title="KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> raised if it isn’t.</p>
  1070. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">d</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>
  1071. <span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
  1072. <span class="go">{1: 2}</span>
  1073. <span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
  1074. <span class="gt">Traceback (most recent call last):</span>
  1075. File <span class="nb">&quot;stdin&quot;</span>, line <span class="m">1</span>, in <span class="n">?</span>
  1076. <span class="gr">KeyError</span>: <span class="n">4</span>
  1077. <span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
  1078. <span class="go">2</span>
  1079. <span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
  1080. <span class="gt">Traceback (most recent call last):</span>
  1081. File <span class="nb">&quot;stdin&quot;</span>, line <span class="m">1</span>, in <span class="n">?</span>
  1082. <span class="gr">KeyError</span>: <span class="n">&#39;pop(): dictionary is empty&#39;</span>
  1083. <span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
  1084. <span class="go">{}</span>
  1085. <span class="gp">&gt;&gt;&gt;</span>
  1086. </pre></div>
  1087. </div>
  1088. <p>There’s also a new class method, <code class="docutils literal notranslate"><span class="pre">dict.fromkeys(iterable,</span> <span class="pre">value)</span></code>, that
  1089. creates a dictionary with keys taken from the supplied iterator <em>iterable</em> and
  1090. all values set to <em>value</em>, defaulting to <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
  1091. <p>(Patches contributed by Raymond Hettinger.)</p>
  1092. <p>Also, the <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-func docutils literal notranslate"><span class="pre">dict()</span></code></a> constructor now accepts keyword arguments to simplify
  1093. creating small dictionaries:</p>
  1094. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">dict</span><span class="p">(</span><span class="n">red</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">blue</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">green</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">black</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
  1095. <span class="go">{&#39;blue&#39;: 2, &#39;black&#39;: 4, &#39;green&#39;: 3, &#39;red&#39;: 1}</span>
  1096. </pre></div>
  1097. </div>
  1098. <p>(Contributed by Just van Rossum.)</p>
  1099. </li>
  1100. <li><p>The <a class="reference internal" href="../reference/simple_stmts.html#assert"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">assert</span></code></a> statement no longer checks the <code class="docutils literal notranslate"><span class="pre">__debug__</span></code> flag, so
  1101. you can no longer disable assertions by assigning to <code class="docutils literal notranslate"><span class="pre">__debug__</span></code>. Running
  1102. Python with the <a class="reference internal" href="../using/cmdline.html#cmdoption-O"><code class="xref std std-option docutils literal notranslate"><span class="pre">-O</span></code></a> switch will still generate code that doesn’t
  1103. execute any assertions.</p></li>
  1104. <li><p>Most type objects are now callable, so you can use them to create new objects
  1105. such as functions, classes, and modules. (This means that the <code class="xref py py-mod docutils literal notranslate"><span class="pre">new</span></code> module
  1106. can be deprecated in a future Python version, because you can now use the type
  1107. objects available in the <a class="reference internal" href="../library/types.html#module-types" title="types: Names for built-in types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">types</span></code></a> module.) For example, you can create a new
  1108. module object with the following code:</p>
  1109. <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">types</span>
  1110. <span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">types</span><span class="o">.</span><span class="n">ModuleType</span><span class="p">(</span><span class="s1">&#39;abc&#39;</span><span class="p">,</span><span class="s1">&#39;docstring&#39;</span><span class="p">)</span>
  1111. <span class="gp">&gt;&gt;&gt; </span><span class="n">m</span>
  1112. <span class="go">&lt;module &#39;abc&#39; (built-in)&gt;</span>
  1113. <span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="vm">__doc__</span>
  1114. <span class="go">&#39;docstring&#39;</span>
  1115. </pre></div>
  1116. </div>
  1117. </li>
  1118. <li><p>A new warning, <a class="reference internal" href="../library/exceptions.html#PendingDeprecationWarning" title="PendingDeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">PendingDeprecationWarning</span></code></a> was added to indicate features
  1119. which are in the process of being deprecated. The warning will <em>not</em> be printed
  1120. by default. To check for use of features that will be deprecated in the future,
  1121. supply <a class="reference internal" href="../using/cmdline.html#cmdoption-W"><code class="xref std std-option docutils literal notranslate"><span class="pre">-Walways::PendingDeprecationWarning::</span></code></a> on the command line or
  1122. use <a class="reference internal" href="../library/warnings.html#warnings.filterwarnings" title="warnings.filterwarnings"><code class="xref py py-func docutils literal notranslate"><span class="pre">warnings.filterwarnings()</span></code></a>.</p></li>
  1123. <li><p>The process of deprecating string-based exceptions, as in <code class="docutils literal notranslate"><span class="pre">raise</span> <span class="pre">&quot;Error</span>
  1124. <span class="pre">occurred&quot;</span></code>, has begun. Raising a string will now trigger
  1125. <a class="reference internal" href="../library/exceptions.html#PendingDeprecationWarning" title="PendingDeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">PendingDeprecationWarning</span></code></a>.</p></li>
  1126. <li><p>Using <code class="docutils literal notranslate"><span class="pre">None</span></code> as a variable name will now result in a <a class="reference internal" href="../library/exceptions.html#SyntaxWarning" title="SyntaxWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxWarning</span></code></a>
  1127. warning. In a future version of Python, <code class="docutils literal notranslate"><span class="pre">None</span></code> may finally become a keyword.</p></li>
  1128. <li><p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">xreadlines()</span></code> method of file objects, introduced in Python 2.1, is no
  1129. longer necessary because files now behave as their own iterator.
  1130. <code class="xref py py-meth docutils literal notranslate"><span class="pre">xreadlines()</span></code> was originally introduced as a faster way to loop over all
  1131. the lines in a file, but now you can simply write <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">line</span> <span class="pre">in</span> <span class="pre">file_obj</span></code>.
  1132. File objects also have a new read-only <code class="xref py py-attr docutils literal notranslate"><span class="pre">encoding</span></code> attribute that gives the
  1133. encoding used by the file; Unicode strings written to the file will be
  1134. automatically converted to bytes using the given encoding.</p></li>
  1135. <li><p>The method resolution order used by new-style classes has changed, though
  1136. you’ll only notice the difference if you have a really complicated inheritance
  1137. hierarchy. Classic classes are unaffected by this change. Python 2.2
  1138. originally used a topological sort of a class’s ancestors, but 2.3 now uses the
  1139. C3 algorithm as described in the paper <a class="reference external" href="https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.19.3910">“A Monotonic Superclass Linearization
  1140. for Dylan”</a>. To
  1141. understand the motivation for this change, read Michele Simionato’s article
  1142. <a class="reference external" href="http://www.phyast.pitt.edu/~micheles/mro.html">“Python 2.3 Method Resolution Order”</a>, or
  1143. read the thread on python-dev starting with the message at
  1144. <a class="reference external" href="https://mail.python.org/pipermail/python-dev/2002-October/029035.html">https://mail.python.org/pipermail/python-dev/2002-October/029035.html</a>. Samuele
  1145. Pedroni first pointed out the problem and also implemented the fix by coding the
  1146. C3 algorithm.</p></li>
  1147. <li><p>Python runs multithreaded programs by switching between threads after
  1148. executing N bytecodes. The default value for N has been increased from 10 to
  1149. 100 bytecodes, speeding up single-threaded applications by reducing the
  1150. switching overhead. Some multithreaded applications may suffer slower response
  1151. time, but that’s easily fixed by setting the limit back to a lower number using
  1152. <code class="docutils literal notranslate"><span class="pre">sys.setcheckinterval(N)</span></code>. The limit can be retrieved with the new
  1153. <code class="xref py py-func docutils literal notranslate"><span class="pre">sys.getcheckinterval()</span></code> function.</p></li>
  1154. <li><p>One minor but far-reaching change is that the names of extension types defined
  1155. by the modules included with Python now contain the module and a <code class="docutils literal notranslate"><span class="pre">'.'</span></code> in
  1156. front of the type name. For example, in Python 2.2, if you created a socket and
  1157. printed its <code class="xref py py-attr docutils literal notranslate"><span class="pre">__class__</span></code>, you’d get this output:</p>
  1158. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">()</span>
  1159. <span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="vm">__class__</span>
  1160. <span class="go">&lt;type &#39;socket&#39;&gt;</span>
  1161. </pre></div>
  1162. </div>
  1163. <p>In 2.3, you get this:</p>
  1164. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="vm">__class__</span>
  1165. <span class="go">&lt;type &#39;_socket.socket&#39;&gt;</span>
  1166. </pre></div>
  1167. </div>
  1168. </li>
  1169. <li><p>One of the noted incompatibilities between old- and new-style classes has been
  1170. removed: you can now assign to the <a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a> and <a class="reference internal" href="../library/stdtypes.html#class.__bases__" title="class.__bases__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__bases__</span></code></a>
  1171. attributes of new-style classes. There are some restrictions on what can be
  1172. assigned to <a class="reference internal" href="../library/stdtypes.html#class.__bases__" title="class.__bases__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__bases__</span></code></a> along the lines of those relating to assigning to
  1173. an instance’s <a class="reference internal" href="../library/stdtypes.html#instance.__class__" title="instance.__class__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__class__</span></code></a> attribute.</p></li>
  1174. </ul>
  1175. <section id="string-changes">
  1176. <h3>String Changes<a class="headerlink" href="#string-changes" title="Link to this heading">¶</a></h3>
  1177. <ul>
  1178. <li><p>The <a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> operator now works differently for strings. Previously, when
  1179. evaluating <code class="docutils literal notranslate"><span class="pre">X</span> <span class="pre">in</span> <span class="pre">Y</span></code> where <em>X</em> and <em>Y</em> are strings, <em>X</em> could only be a single
  1180. character. That’s now changed; <em>X</em> can be a string of any length, and <code class="docutils literal notranslate"><span class="pre">X</span> <span class="pre">in</span> <span class="pre">Y</span></code>
  1181. will return <a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if <em>X</em> is a substring of <em>Y</em>. If <em>X</em> is the empty
  1182. string, the result is always <a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>.</p>
  1183. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;ab&#39;</span> <span class="ow">in</span> <span class="s1">&#39;abcd&#39;</span>
  1184. <span class="go">True</span>
  1185. <span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;ad&#39;</span> <span class="ow">in</span> <span class="s1">&#39;abcd&#39;</span>
  1186. <span class="go">False</span>
  1187. <span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;&#39;</span> <span class="ow">in</span> <span class="s1">&#39;abcd&#39;</span>
  1188. <span class="go">True</span>
  1189. </pre></div>
  1190. </div>
  1191. <p>Note that this doesn’t tell you where the substring starts; if you need that
  1192. information, use the <a class="reference internal" href="../library/stdtypes.html#str.find" title="str.find"><code class="xref py py-meth docutils literal notranslate"><span class="pre">find()</span></code></a> string method.</p>
  1193. </li>
  1194. <li><p>The <a class="reference internal" href="../library/stdtypes.html#str.strip" title="str.strip"><code class="xref py py-meth docutils literal notranslate"><span class="pre">strip()</span></code></a>, <a class="reference internal" href="../library/stdtypes.html#str.lstrip" title="str.lstrip"><code class="xref py py-meth docutils literal notranslate"><span class="pre">lstrip()</span></code></a>, and <a class="reference internal" href="../library/stdtypes.html#str.rstrip" title="str.rstrip"><code class="xref py py-meth docutils literal notranslate"><span class="pre">rstrip()</span></code></a> string methods now have
  1195. an optional argument for specifying the characters to strip. The default is
  1196. still to remove all whitespace characters:</p>
  1197. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39; abc &#39;</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span>
  1198. <span class="go">&#39;abc&#39;</span>
  1199. <span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;&gt;&lt;&gt;&lt;abc&lt;&gt;&lt;&gt;&lt;&gt;&#39;</span><span class="o">.</span><span class="n">strip</span><span class="p">(</span><span class="s1">&#39;&lt;&gt;&#39;</span><span class="p">)</span>
  1200. <span class="go">&#39;abc&#39;</span>
  1201. <span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;&gt;&lt;&gt;&lt;abc&lt;&gt;&lt;&gt;&lt;&gt;</span><span class="se">\n</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">strip</span><span class="p">(</span><span class="s1">&#39;&lt;&gt;&#39;</span><span class="p">)</span>
  1202. <span class="go">&#39;abc&lt;&gt;&lt;&gt;&lt;&gt;\n&#39;</span>
  1203. <span class="gp">&gt;&gt;&gt; </span><span class="sa">u</span><span class="s1">&#39;</span><span class="se">\u4000\u4001</span><span class="s1">abc</span><span class="se">\u4000</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">strip</span><span class="p">(</span><span class="sa">u</span><span class="s1">&#39;</span><span class="se">\u4000</span><span class="s1">&#39;</span><span class="p">)</span>
  1204. <span class="go">u&#39;\u4001abc&#39;</span>
  1205. <span class="gp">&gt;&gt;&gt;</span>
  1206. </pre></div>
  1207. </div>
  1208. <p>(Suggested by Simon Brunning and implemented by Walter Dörwald.)</p>
  1209. </li>
  1210. <li><p>The <a class="reference internal" href="../library/stdtypes.html#str.startswith" title="str.startswith"><code class="xref py py-meth docutils literal notranslate"><span class="pre">startswith()</span></code></a> and <a class="reference internal" href="../library/stdtypes.html#str.endswith" title="str.endswith"><code class="xref py py-meth docutils literal notranslate"><span class="pre">endswith()</span></code></a> string methods now accept negative
  1211. numbers for the <em>start</em> and <em>end</em> parameters.</p></li>
  1212. <li><p>Another new string method is <a class="reference internal" href="../library/stdtypes.html#str.zfill" title="str.zfill"><code class="xref py py-meth docutils literal notranslate"><span class="pre">zfill()</span></code></a>, originally a function in the
  1213. <a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> module. <a class="reference internal" href="../library/stdtypes.html#str.zfill" title="str.zfill"><code class="xref py py-meth docutils literal notranslate"><span class="pre">zfill()</span></code></a> pads a numeric string with zeros on the
  1214. left until it’s the specified width. Note that the <code class="docutils literal notranslate"><span class="pre">%</span></code> operator is still more
  1215. flexible and powerful than <a class="reference internal" href="../library/stdtypes.html#str.zfill" title="str.zfill"><code class="xref py py-meth docutils literal notranslate"><span class="pre">zfill()</span></code></a>.</p>
  1216. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;45&#39;</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
  1217. <span class="go">&#39;0045&#39;</span>
  1218. <span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;12345&#39;</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
  1219. <span class="go">&#39;12345&#39;</span>
  1220. <span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;goofy&#39;</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">6</span><span class="p">)</span>
  1221. <span class="go">&#39;0goofy&#39;</span>
  1222. </pre></div>
  1223. </div>
  1224. <p>(Contributed by Walter Dörwald.)</p>
  1225. </li>
  1226. <li><p>A new type object, <code class="xref py py-class docutils literal notranslate"><span class="pre">basestring</span></code>, has been added. Both 8-bit strings and
  1227. Unicode strings inherit from this type, so <code class="docutils literal notranslate"><span class="pre">isinstance(obj,</span> <span class="pre">basestring)</span></code> will
  1228. return <a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> for either kind of string. It’s a completely abstract
  1229. type, so you can’t create <code class="xref py py-class docutils literal notranslate"><span class="pre">basestring</span></code> instances.</p></li>
  1230. <li><p>Interned strings are no longer immortal and will now be garbage-collected in
  1231. the usual way when the only reference to them is from the internal dictionary of
  1232. interned strings. (Implemented by Oren Tirosh.)</p></li>
  1233. </ul>
  1234. </section>
  1235. <section id="optimizations">
  1236. <h3>Optimizations<a class="headerlink" href="#optimizations" title="Link to this heading">¶</a></h3>
  1237. <ul class="simple">
  1238. <li><p>The creation of new-style class instances has been made much faster; they’re
  1239. now faster than classic classes!</p></li>
  1240. <li><p>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">sort()</span></code></a> method of list objects has been extensively rewritten by Tim
  1241. Peters, and the implementation is significantly faster.</p></li>
  1242. <li><p>Multiplication of large long integers is now much faster thanks to an
  1243. implementation of Karatsuba multiplication, an algorithm that scales better than
  1244. the <em>O</em>(<em>n</em><sup>2</sup>) required for the grade-school multiplication algorithm. (Original
  1245. patch by Christopher A. Craig, and significantly reworked by Tim Peters.)</p></li>
  1246. <li><p>The <code class="docutils literal notranslate"><span class="pre">SET_LINENO</span></code> opcode is now gone. This may provide a small speed
  1247. increase, depending on your compiler’s idiosyncrasies. See section
  1248. <a class="reference internal" href="#section-other"><span class="std std-ref">Other Changes and Fixes</span></a> for a longer explanation. (Removed by Michael Hudson.)</p></li>
  1249. <li><p><code class="xref py py-func docutils literal notranslate"><span class="pre">xrange()</span></code> objects now have their own iterator, making <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">i</span> <span class="pre">in</span>
  1250. <span class="pre">xrange(n)</span></code> slightly faster than <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">i</span> <span class="pre">in</span> <span class="pre">range(n)</span></code>. (Patch by Raymond
  1251. Hettinger.)</p></li>
  1252. <li><p>A number of small rearrangements have been made in various hotspots to improve
  1253. performance, such as inlining a function or removing some code. (Implemented
  1254. mostly by GvR, but lots of people have contributed single changes.)</p></li>
  1255. </ul>
  1256. <p>The net result of the 2.3 optimizations is that Python 2.3 runs the pystone
  1257. benchmark around 25% faster than Python 2.2.</p>
  1258. </section>
  1259. </section>
  1260. <section id="new-improved-and-deprecated-modules">
  1261. <h2>New, Improved, and Deprecated Modules<a class="headerlink" href="#new-improved-and-deprecated-modules" title="Link to this heading">¶</a></h2>
  1262. <p>As usual, Python’s standard library received a number of enhancements and bug
  1263. fixes. Here’s a partial list of the most notable changes, sorted alphabetically
  1264. by module name. Consult the <code class="file docutils literal notranslate"><span class="pre">Misc/NEWS</span></code> file in the source tree for a more
  1265. complete list of changes, or look through the CVS logs for all the details.</p>
  1266. <ul>
  1267. <li><p>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> module now supports arrays of Unicode characters using the
  1268. <code class="docutils literal notranslate"><span class="pre">'u'</span></code> format character. Arrays also now support using the <code class="docutils literal notranslate"><span class="pre">+=</span></code> assignment
  1269. operator to add another array’s contents, and the <code class="docutils literal notranslate"><span class="pre">*=</span></code> assignment operator to
  1270. repeat an array. (Contributed by Jason Orendorff.)</p></li>
  1271. <li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code> module has been replaced by version 4.1.6 of the <a class="reference external" href="https://pybsddb.sourceforge.net">PyBSDDB</a> package, providing a more complete interface
  1272. to the transactional features of the BerkeleyDB library.</p>
  1273. <p>The old version of the module has been renamed to <code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb185</span></code> and is no
  1274. longer built automatically; you’ll have to edit <code class="file docutils literal notranslate"><span class="pre">Modules/Setup</span></code> to enable
  1275. it. Note that the new <code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code> package is intended to be compatible with
  1276. the old module, so be sure to file bugs if you discover any incompatibilities.
  1277. When upgrading to Python 2.3, if the new interpreter is compiled with a new
  1278. version of the underlying BerkeleyDB library, you will almost certainly have to
  1279. convert your database files to the new version. You can do this fairly easily
  1280. with the new scripts <code class="file docutils literal notranslate"><span class="pre">db2pickle.py</span></code> and <code class="file docutils literal notranslate"><span class="pre">pickle2db.py</span></code> which you
  1281. will find in the distribution’s <code class="file docutils literal notranslate"><span class="pre">Tools/scripts</span></code> directory. If you’ve
  1282. already been using the PyBSDDB package and importing it as <code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb3</span></code>, you
  1283. will have to change your <code class="docutils literal notranslate"><span class="pre">import</span></code> statements to import it as <code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code>.</p>
  1284. </li>
  1285. <li><p>The new <a class="reference internal" href="../library/bz2.html#module-bz2" title="bz2: Interfaces for bzip2 compression and decompression."><code class="xref py py-mod docutils literal notranslate"><span class="pre">bz2</span></code></a> module is an interface to the bz2 data compression library.
  1286. bz2-compressed data is usually smaller than corresponding
  1287. <a class="reference internal" href="../library/zlib.html#module-zlib" title="zlib: Low-level interface to compression and decompression routines compatible with gzip."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zlib</span></code></a>-compressed data. (Contributed by Gustavo Niemeyer.)</p></li>
  1288. <li><p>A set of standard date/time types has been added in the new <a class="reference internal" href="../library/datetime.html#module-datetime" title="datetime: Basic date and time types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">datetime</span></code></a>
  1289. module. See the following section for more details.</p></li>
  1290. <li><p>The Distutils <code class="xref py py-class docutils literal notranslate"><span class="pre">Extension</span></code> class now supports an extra constructor
  1291. argument named <em>depends</em> for listing additional source files that an extension
  1292. depends on. This lets Distutils recompile the module if any of the dependency
  1293. files are modified. For example, if <code class="file docutils literal notranslate"><span class="pre">sampmodule.c</span></code> includes the header
  1294. file <code class="file docutils literal notranslate"><span class="pre">sample.h</span></code>, you would create the <code class="xref py py-class docutils literal notranslate"><span class="pre">Extension</span></code> object like
  1295. this:</p>
  1296. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">ext</span> <span class="o">=</span> <span class="n">Extension</span><span class="p">(</span><span class="s2">&quot;samp&quot;</span><span class="p">,</span>
  1297. <span class="n">sources</span><span class="o">=</span><span class="p">[</span><span class="s2">&quot;sampmodule.c&quot;</span><span class="p">],</span>
  1298. <span class="n">depends</span><span class="o">=</span><span class="p">[</span><span class="s2">&quot;sample.h&quot;</span><span class="p">])</span>
  1299. </pre></div>
  1300. </div>
  1301. <p>Modifying <code class="file docutils literal notranslate"><span class="pre">sample.h</span></code> would then cause the module to be recompiled.
  1302. (Contributed by Jeremy Hylton.)</p>
  1303. </li>
  1304. <li><p>Other minor changes to Distutils: it now checks for the <span class="target" id="index-24"></span><a class="reference internal" href="../using/configure.html#envvar-CC"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">CC</span></code></a>,
  1305. <span class="target" id="index-25"></span><a class="reference internal" href="../using/configure.html#envvar-CFLAGS"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">CFLAGS</span></code></a>, <code class="xref std std-envvar docutils literal notranslate"><span class="pre">CPP</span></code>, <span class="target" id="index-26"></span><a class="reference internal" href="../using/configure.html#envvar-LDFLAGS"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">LDFLAGS</span></code></a>, and <span class="target" id="index-27"></span><a class="reference internal" href="../using/configure.html#envvar-CPPFLAGS"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">CPPFLAGS</span></code></a>
  1306. environment variables, using them to override the settings in Python’s
  1307. configuration (contributed by Robert Weber).</p></li>
  1308. <li><p>Previously the <a class="reference internal" href="../library/doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> module would only search the docstrings of
  1309. public methods and functions for test cases, but it now also examines private
  1310. ones as well. The <a class="reference internal" href="../library/doctest.html#doctest.DocTestSuite" title="doctest.DocTestSuite"><code class="xref py py-func docutils literal notranslate"><span class="pre">DocTestSuite()</span></code></a> function creates a
  1311. <a class="reference internal" href="../library/unittest.html#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">unittest.TestSuite</span></code></a> object from a set of <a class="reference internal" href="../library/doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> tests.</p></li>
  1312. <li><p>The new <code class="docutils literal notranslate"><span class="pre">gc.get_referents(object)</span></code> function returns a list of all the
  1313. objects referenced by <em>object</em>.</p></li>
  1314. <li><p>The <a class="reference internal" href="../library/getopt.html#module-getopt" title="getopt: Portable parser for command line options; support both short and long option names."><code class="xref py py-mod docutils literal notranslate"><span class="pre">getopt</span></code></a> module gained a new function, <a class="reference internal" href="../library/getopt.html#getopt.gnu_getopt" title="getopt.gnu_getopt"><code class="xref py py-func docutils literal notranslate"><span class="pre">gnu_getopt()</span></code></a>, that
  1315. supports the same arguments as the existing <a class="reference internal" href="../library/getopt.html#getopt.getopt" title="getopt.getopt"><code class="xref py py-func docutils literal notranslate"><span class="pre">getopt()</span></code></a> function but uses
  1316. GNU-style scanning mode. The existing <a class="reference internal" href="../library/getopt.html#getopt.getopt" title="getopt.getopt"><code class="xref py py-func docutils literal notranslate"><span class="pre">getopt()</span></code></a> stops processing options as
  1317. soon as a non-option argument is encountered, but in GNU-style mode processing
  1318. continues, meaning that options and arguments can be mixed. For example:</p>
  1319. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">getopt</span><span class="o">.</span><span class="n">getopt</span><span class="p">([</span><span class="s1">&#39;-f&#39;</span><span class="p">,</span> <span class="s1">&#39;filename&#39;</span><span class="p">,</span> <span class="s1">&#39;output&#39;</span><span class="p">,</span> <span class="s1">&#39;-v&#39;</span><span class="p">],</span> <span class="s1">&#39;f:v&#39;</span><span class="p">)</span>
  1320. <span class="go">([(&#39;-f&#39;, &#39;filename&#39;)], [&#39;output&#39;, &#39;-v&#39;])</span>
  1321. <span class="gp">&gt;&gt;&gt; </span><span class="n">getopt</span><span class="o">.</span><span class="n">gnu_getopt</span><span class="p">([</span><span class="s1">&#39;-f&#39;</span><span class="p">,</span> <span class="s1">&#39;filename&#39;</span><span class="p">,</span> <span class="s1">&#39;output&#39;</span><span class="p">,</span> <span class="s1">&#39;-v&#39;</span><span class="p">],</span> <span class="s1">&#39;f:v&#39;</span><span class="p">)</span>
  1322. <span class="go">([(&#39;-f&#39;, &#39;filename&#39;), (&#39;-v&#39;, &#39;&#39;)], [&#39;output&#39;])</span>
  1323. </pre></div>
  1324. </div>
  1325. <p>(Contributed by Peter Åstrand.)</p>
  1326. </li>
  1327. <li><p>The <a class="reference internal" href="../library/grp.html#module-grp" title="grp: The group database (getgrnam() and friends). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">grp</span></code></a>, <a class="reference internal" href="../library/pwd.html#module-pwd" title="pwd: The password database (getpwnam() and friends). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pwd</span></code></a>, and <a class="reference internal" href="../library/resource.html#module-resource" title="resource: An interface to provide resource usage information on the current process. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">resource</span></code></a> modules now return enhanced
  1328. tuples:</p>
  1329. <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">grp</span>
  1330. <span class="gp">&gt;&gt;&gt; </span><span class="n">g</span> <span class="o">=</span> <span class="n">grp</span><span class="o">.</span><span class="n">getgrnam</span><span class="p">(</span><span class="s1">&#39;amk&#39;</span><span class="p">)</span>
  1331. <span class="gp">&gt;&gt;&gt; </span><span class="n">g</span><span class="o">.</span><span class="n">gr_name</span><span class="p">,</span> <span class="n">g</span><span class="o">.</span><span class="n">gr_gid</span>
  1332. <span class="go">(&#39;amk&#39;, 500)</span>
  1333. </pre></div>
  1334. </div>
  1335. </li>
  1336. <li><p>The <a class="reference internal" href="../library/gzip.html#module-gzip" title="gzip: Interfaces for gzip compression and decompression using file objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gzip</span></code></a> module can now handle files exceeding 2 GiB.</p></li>
  1337. <li><p>The new <a class="reference internal" href="../library/heapq.html#module-heapq" title="heapq: Heap queue algorithm (a.k.a. priority queue)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">heapq</span></code></a> module contains an implementation of a heap queue
  1338. algorithm. A heap is an array-like data structure that keeps items in a
  1339. partially sorted order such that, for every index <em>k</em>, <code class="docutils literal notranslate"><span class="pre">heap[k]</span> <span class="pre">&lt;=</span>
  1340. <span class="pre">heap[2*k+1]</span></code> and <code class="docutils literal notranslate"><span class="pre">heap[k]</span> <span class="pre">&lt;=</span> <span class="pre">heap[2*k+2]</span></code>. This makes it quick to remove the
  1341. smallest item, and inserting a new item while maintaining the heap property is
  1342. <em>O</em>(log <em>n</em>). (See <a class="reference external" href="https://xlinux.nist.gov/dads//HTML/priorityque.html">https://xlinux.nist.gov/dads//HTML/priorityque.html</a> for more
  1343. information about the priority queue data structure.)</p>
  1344. <p>The <a class="reference internal" href="../library/heapq.html#module-heapq" title="heapq: Heap queue algorithm (a.k.a. priority queue)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">heapq</span></code></a> module provides <a class="reference internal" href="../library/heapq.html#heapq.heappush" title="heapq.heappush"><code class="xref py py-func docutils literal notranslate"><span class="pre">heappush()</span></code></a> and <a class="reference internal" href="../library/heapq.html#heapq.heappop" title="heapq.heappop"><code class="xref py py-func docutils literal notranslate"><span class="pre">heappop()</span></code></a> functions
  1345. for adding and removing items while maintaining the heap property on top of some
  1346. other mutable Python sequence type. Here’s an example that uses a Python list:</p>
  1347. <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">heapq</span>
  1348. <span class="gp">&gt;&gt;&gt; </span><span class="n">heap</span> <span class="o">=</span> <span class="p">[]</span>
  1349. <span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">11</span><span class="p">,</span> <span class="mi">1</span><span class="p">]:</span>
  1350. <span class="gp">... </span> <span class="n">heapq</span><span class="o">.</span><span class="n">heappush</span><span class="p">(</span><span class="n">heap</span><span class="p">,</span> <span class="n">item</span><span class="p">)</span>
  1351. <span class="gp">...</span>
  1352. <span class="gp">&gt;&gt;&gt; </span><span class="n">heap</span>
  1353. <span class="go">[1, 3, 5, 11, 7]</span>
  1354. <span class="gp">&gt;&gt;&gt; </span><span class="n">heapq</span><span class="o">.</span><span class="n">heappop</span><span class="p">(</span><span class="n">heap</span><span class="p">)</span>
  1355. <span class="go">1</span>
  1356. <span class="gp">&gt;&gt;&gt; </span><span class="n">heapq</span><span class="o">.</span><span class="n">heappop</span><span class="p">(</span><span class="n">heap</span><span class="p">)</span>
  1357. <span class="go">3</span>
  1358. <span class="gp">&gt;&gt;&gt; </span><span class="n">heap</span>
  1359. <span class="go">[5, 7, 11]</span>
  1360. </pre></div>
  1361. </div>
  1362. <p>(Contributed by Kevin O’Connor.)</p>
  1363. </li>
  1364. <li><p>The IDLE integrated development environment has been updated using the code
  1365. from the IDLEfork project (<a class="reference external" href="https://idlefork.sourceforge.net">https://idlefork.sourceforge.net</a>). The most notable feature is
  1366. that the code being developed is now executed in a subprocess, meaning that
  1367. there’s no longer any need for manual <code class="docutils literal notranslate"><span class="pre">reload()</span></code> operations. IDLE’s core code
  1368. has been incorporated into the standard library as the <a class="reference internal" href="../library/idle.html#module-idlelib" title="idlelib: Implementation package for the IDLE shell/editor."><code class="xref py py-mod docutils literal notranslate"><span class="pre">idlelib</span></code></a> package.</p></li>
  1369. <li><p>The <a class="reference internal" href="../library/imaplib.html#module-imaplib" title="imaplib: IMAP4 protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">imaplib</span></code></a> module now supports IMAP over SSL. (Contributed by Piers
  1370. Lauder and Tino Lange.)</p></li>
  1371. <li><p>The <a class="reference internal" href="../library/itertools.html#module-itertools" title="itertools: Functions creating iterators for efficient looping."><code class="xref py py-mod docutils literal notranslate"><span class="pre">itertools</span></code></a> contains a number of useful functions for use with
  1372. iterators, inspired by various functions provided by the ML and Haskell
  1373. languages. For example, <code class="docutils literal notranslate"><span class="pre">itertools.ifilter(predicate,</span> <span class="pre">iterator)</span></code> returns all
  1374. elements in the iterator for which the function <code class="xref py py-func docutils literal notranslate"><span class="pre">predicate()</span></code> returns
  1375. <a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>, and <code class="docutils literal notranslate"><span class="pre">itertools.repeat(obj,</span> <span class="pre">N)</span></code> returns <code class="docutils literal notranslate"><span class="pre">obj</span></code> <em>N</em> times.
  1376. There are a number of other functions in the module; see the package’s reference
  1377. documentation for details.
  1378. (Contributed by Raymond Hettinger.)</p></li>
  1379. <li><p>Two new functions in the <a class="reference internal" href="../library/math.html#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">math</span></code></a> module, <code class="docutils literal notranslate"><span class="pre">degrees(rads)</span></code> and
  1380. <code class="docutils literal notranslate"><span class="pre">radians(degs)</span></code>, convert between radians and degrees. Other functions in
  1381. the <a class="reference internal" href="../library/math.html#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">math</span></code></a> module such as <a class="reference internal" href="../library/math.html#math.sin" title="math.sin"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.sin()</span></code></a> and <a class="reference internal" href="../library/math.html#math.cos" title="math.cos"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.cos()</span></code></a> have always
  1382. required input values measured in radians. Also, an optional <em>base</em> argument
  1383. was added to <a class="reference internal" href="../library/math.html#math.log" title="math.log"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.log()</span></code></a> to make it easier to compute logarithms for bases
  1384. other than <code class="docutils literal notranslate"><span class="pre">e</span></code> and <code class="docutils literal notranslate"><span class="pre">10</span></code>. (Contributed by Raymond Hettinger.)</p></li>
  1385. <li><p>Several new POSIX functions (<code class="xref py py-func docutils literal notranslate"><span class="pre">getpgid()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">killpg()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">lchown()</span></code>,
  1386. <code class="xref py py-func docutils literal notranslate"><span class="pre">loadavg()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">major()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">makedev()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">minor()</span></code>, and
  1387. <code class="xref py py-func docutils literal notranslate"><span class="pre">mknod()</span></code>) were added to the <a class="reference internal" href="../library/posix.html#module-posix" title="posix: The most common POSIX system calls (normally used via module os). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">posix</span></code></a> module that underlies the
  1388. <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> module. (Contributed by Gustavo Niemeyer, Geert Jansen, and Denis S.
  1389. Otkidach.)</p></li>
  1390. <li><p>In the <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> module, the <code class="xref py py-func docutils literal notranslate"><span class="pre">*stat()</span></code> family of functions can now report
  1391. fractions of a second in a timestamp. Such time stamps are represented as
  1392. floats, similar to the value returned by <a class="reference internal" href="../library/time.html#time.time" title="time.time"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.time()</span></code></a>.</p>
  1393. <p>During testing, it was found that some applications will break if time stamps
  1394. are floats. For compatibility, when using the tuple interface of the
  1395. <a class="reference internal" href="../library/os.html#os.stat_result" title="os.stat_result"><code class="xref py py-class docutils literal notranslate"><span class="pre">stat_result</span></code></a> time stamps will be represented as integers. When using
  1396. named fields (a feature first introduced in Python 2.2), time stamps are still
  1397. represented as integers, unless <code class="xref py py-func docutils literal notranslate"><span class="pre">os.stat_float_times()</span></code> is invoked to enable
  1398. float return values:</p>
  1399. <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">stat</span><span class="p">(</span><span class="s2">&quot;/tmp&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">st_mtime</span>
  1400. <span class="go">1034791200</span>
  1401. <span class="gp">&gt;&gt;&gt; </span><span class="n">os</span><span class="o">.</span><span class="n">stat_float_times</span><span class="p">(</span><span class="kc">True</span><span class="p">)</span>
  1402. <span class="gp">&gt;&gt;&gt; </span><span class="n">os</span><span class="o">.</span><span class="n">stat</span><span class="p">(</span><span class="s2">&quot;/tmp&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">st_mtime</span>
  1403. <span class="go">1034791200.6335014</span>
  1404. </pre></div>
  1405. </div>
  1406. <p>In Python 2.4, the default will change to always returning floats.</p>
  1407. <p>Application developers should enable this feature only if all their libraries
  1408. work properly when confronted with floating point time stamps, or if they use
  1409. the tuple API. If used, the feature should be activated on an application level
  1410. instead of trying to enable it on a per-use basis.</p>
  1411. </li>
  1412. <li><p>The <a class="reference internal" href="../library/optparse.html#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> module contains a new parser for command-line arguments
  1413. that can convert option values to a particular Python type and will
  1414. automatically generate a usage message. See the following section for more
  1415. details.</p></li>
  1416. <li><p>The old and never-documented <code class="xref py py-mod docutils literal notranslate"><span class="pre">linuxaudiodev</span></code> module has been deprecated,
  1417. and a new version named <a class="reference internal" href="../library/ossaudiodev.html#module-ossaudiodev" title="ossaudiodev: Access to OSS-compatible audio devices. (deprecated) (Linux, FreeBSD)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ossaudiodev</span></code></a> has been added. The module was
  1418. renamed because the OSS sound drivers can be used on platforms other than Linux,
  1419. and the interface has also been tidied and brought up to date in various ways.
  1420. (Contributed by Greg Ward and Nicholas FitzRoy-Dale.)</p></li>
  1421. <li><p>The new <a class="reference internal" href="../library/platform.html#module-platform" title="platform: Retrieves as much platform identifying data as possible."><code class="xref py py-mod docutils literal notranslate"><span class="pre">platform</span></code></a> module contains a number of functions that try to
  1422. determine various properties of the platform you’re running on. There are
  1423. functions for getting the architecture, CPU type, the Windows OS version, and
  1424. even the Linux distribution version. (Contributed by Marc-André Lemburg.)</p></li>
  1425. <li><p>The parser objects provided by the <a class="reference internal" href="../library/pyexpat.html#module-xml.parsers.expat" title="xml.parsers.expat: An interface to the Expat non-validating XML parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pyexpat</span></code></a> module can now optionally
  1426. buffer character data, resulting in fewer calls to your character data handler
  1427. and therefore faster performance. Setting the parser object’s
  1428. <a class="reference internal" href="../library/pyexpat.html#xml.parsers.expat.xmlparser.buffer_text" title="xml.parsers.expat.xmlparser.buffer_text"><code class="xref py py-attr docutils literal notranslate"><span class="pre">buffer_text</span></code></a> attribute to <a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> will enable buffering.</p></li>
  1429. <li><p>The <code class="docutils literal notranslate"><span class="pre">sample(population,</span> <span class="pre">k)</span></code> function was added to the <a class="reference internal" href="../library/random.html#module-random" title="random: Generate pseudo-random numbers with various common distributions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">random</span></code></a>
  1430. module. <em>population</em> is a sequence or <code class="xref py py-class docutils literal notranslate"><span class="pre">xrange</span></code> object containing the
  1431. elements of a population, and <a class="reference internal" href="../library/random.html#random.sample" title="random.sample"><code class="xref py py-func docutils literal notranslate"><span class="pre">sample()</span></code></a> chooses <em>k</em> elements from the
  1432. population without replacing chosen elements. <em>k</em> can be any value up to
  1433. <code class="docutils literal notranslate"><span class="pre">len(population)</span></code>. For example:</p>
  1434. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">days</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;Mo&#39;</span><span class="p">,</span> <span class="s1">&#39;Tu&#39;</span><span class="p">,</span> <span class="s1">&#39;We&#39;</span><span class="p">,</span> <span class="s1">&#39;Th&#39;</span><span class="p">,</span> <span class="s1">&#39;Fr&#39;</span><span class="p">,</span> <span class="s1">&#39;St&#39;</span><span class="p">,</span> <span class="s1">&#39;Sn&#39;</span><span class="p">]</span>
  1435. <span class="gp">&gt;&gt;&gt; </span><span class="n">random</span><span class="o">.</span><span class="n">sample</span><span class="p">(</span><span class="n">days</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="c1"># Choose 3 elements</span>
  1436. <span class="go">[&#39;St&#39;, &#39;Sn&#39;, &#39;Th&#39;]</span>
  1437. <span class="gp">&gt;&gt;&gt; </span><span class="n">random</span><span class="o">.</span><span class="n">sample</span><span class="p">(</span><span class="n">days</span><span class="p">,</span> <span class="mi">7</span><span class="p">)</span> <span class="c1"># Choose 7 elements</span>
  1438. <span class="go">[&#39;Tu&#39;, &#39;Th&#39;, &#39;Mo&#39;, &#39;We&#39;, &#39;St&#39;, &#39;Fr&#39;, &#39;Sn&#39;]</span>
  1439. <span class="gp">&gt;&gt;&gt; </span><span class="n">random</span><span class="o">.</span><span class="n">sample</span><span class="p">(</span><span class="n">days</span><span class="p">,</span> <span class="mi">7</span><span class="p">)</span> <span class="c1"># Choose 7 again</span>
  1440. <span class="go">[&#39;We&#39;, &#39;Mo&#39;, &#39;Sn&#39;, &#39;Fr&#39;, &#39;Tu&#39;, &#39;St&#39;, &#39;Th&#39;]</span>
  1441. <span class="gp">&gt;&gt;&gt; </span><span class="n">random</span><span class="o">.</span><span class="n">sample</span><span class="p">(</span><span class="n">days</span><span class="p">,</span> <span class="mi">8</span><span class="p">)</span> <span class="c1"># Can&#39;t choose eight</span>
  1442. <span class="gt">Traceback (most recent call last):</span>
  1443. File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">?</span>
  1444. File <span class="nb">&quot;random.py&quot;</span>, line <span class="m">414</span>, in <span class="n">sample</span>
  1445. <span class="w"> </span> <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">,</span> <span class="s2">&quot;sample larger than population&quot;</span>
  1446. <span class="gr">ValueError</span>: <span class="n">sample larger than population</span>
  1447. <span class="gp">&gt;&gt;&gt; </span><span class="n">random</span><span class="o">.</span><span class="n">sample</span><span class="p">(</span><span class="n">xrange</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">10000</span><span class="p">,</span><span class="mi">2</span><span class="p">),</span> <span class="mi">10</span><span class="p">)</span> <span class="c1"># Choose ten odd nos. under 10000</span>
  1448. <span class="go">[3407, 3805, 1505, 7023, 2401, 2267, 9733, 3151, 8083, 9195]</span>
  1449. </pre></div>
  1450. </div>
  1451. <p>The <a class="reference internal" href="../library/random.html#module-random" title="random: Generate pseudo-random numbers with various common distributions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">random</span></code></a> module now uses a new algorithm, the Mersenne Twister,
  1452. implemented in C. It’s faster and more extensively studied than the previous
  1453. algorithm.</p>
  1454. <p>(All changes contributed by Raymond Hettinger.)</p>
  1455. </li>
  1456. <li><p>The <a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">readline</span></code></a> module also gained a number of new functions:
  1457. <a class="reference internal" href="../library/readline.html#readline.get_history_item" title="readline.get_history_item"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_history_item()</span></code></a>, <a class="reference internal" href="../library/readline.html#readline.get_current_history_length" title="readline.get_current_history_length"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_current_history_length()</span></code></a>, and
  1458. <a class="reference internal" href="../library/readline.html#readline.redisplay" title="readline.redisplay"><code class="xref py py-func docutils literal notranslate"><span class="pre">redisplay()</span></code></a>.</p></li>
  1459. <li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">rexec</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">Bastion</span></code> modules have been declared dead, and
  1460. attempts to import them will fail with a <a class="reference internal" href="../library/exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>. New-style classes
  1461. provide new ways to break out of the restricted execution environment provided
  1462. by <code class="xref py py-mod docutils literal notranslate"><span class="pre">rexec</span></code>, and no one has interest in fixing them or time to do so. If
  1463. you have applications using <code class="xref py py-mod docutils literal notranslate"><span class="pre">rexec</span></code>, rewrite them to use something else.</p>
  1464. <p>(Sticking with Python 2.2 or 2.1 will not make your applications any safer
  1465. because there are known bugs in the <code class="xref py py-mod docutils literal notranslate"><span class="pre">rexec</span></code> module in those versions. To
  1466. repeat: if you’re using <code class="xref py py-mod docutils literal notranslate"><span class="pre">rexec</span></code>, stop using it immediately.)</p>
  1467. </li>
  1468. <li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">rotor</span></code> module has been deprecated because the algorithm it uses for
  1469. encryption is not believed to be secure. If you need encryption, use one of the
  1470. several AES Python modules that are available separately.</p></li>
  1471. <li><p>The <a class="reference internal" href="../library/shutil.html#module-shutil" title="shutil: High-level file operations, including copying."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shutil</span></code></a> module gained a <code class="docutils literal notranslate"><span class="pre">move(src,</span> <span class="pre">dest)</span></code> function that
  1472. recursively moves a file or directory to a new location.</p></li>
  1473. <li><p>Support for more advanced POSIX signal handling was added to the <a class="reference internal" href="../library/signal.html#module-signal" title="signal: Set handlers for asynchronous events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">signal</span></code></a>
  1474. but then removed again as it proved impossible to make it work reliably across
  1475. platforms.</p></li>
  1476. <li><p>The <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module now supports timeouts. You can call the
  1477. <code class="docutils literal notranslate"><span class="pre">settimeout(t)</span></code> method on a socket object to set a timeout of <em>t</em> seconds.
  1478. Subsequent socket operations that take longer than <em>t</em> seconds to complete will
  1479. abort and raise a <a class="reference internal" href="../library/socket.html#socket.timeout" title="socket.timeout"><code class="xref py py-exc docutils literal notranslate"><span class="pre">socket.timeout</span></code></a> exception.</p>
  1480. <p>The original timeout implementation was by Tim O’Malley. Michael Gilfix
  1481. integrated it into the Python <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module and shepherded it through a
  1482. lengthy review. After the code was checked in, Guido van Rossum rewrote parts
  1483. of it. (This is a good example of a collaborative development process in
  1484. action.)</p>
  1485. </li>
  1486. <li><p>On Windows, the <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module now ships with Secure Sockets Layer
  1487. (SSL) support.</p></li>
  1488. <li><p>The value of the C <code class="xref c c-macro docutils literal notranslate"><span class="pre">PYTHON_API_VERSION</span></code> macro is now exposed at the
  1489. Python level as <code class="docutils literal notranslate"><span class="pre">sys.api_version</span></code>. The current exception can be cleared by
  1490. calling the new <code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_clear()</span></code> function.</p></li>
  1491. <li><p>The new <a class="reference internal" href="../library/tarfile.html#module-tarfile" title="tarfile: Read and write tar-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tarfile</span></code></a> module allows reading from and writing to
  1492. <strong class="program">tar</strong>-format archive files. (Contributed by Lars Gustäbel.)</p></li>
  1493. <li><p>The new <a class="reference internal" href="../library/textwrap.html#module-textwrap" title="textwrap: Text wrapping and filling"><code class="xref py py-mod docutils literal notranslate"><span class="pre">textwrap</span></code></a> module contains functions for wrapping strings
  1494. containing paragraphs of text. The <code class="docutils literal notranslate"><span class="pre">wrap(text,</span> <span class="pre">width)</span></code> function takes a
  1495. string and returns a list containing the text split into lines of no more than
  1496. the chosen width. The <code class="docutils literal notranslate"><span class="pre">fill(text,</span> <span class="pre">width)</span></code> function returns a single
  1497. string, reformatted to fit into lines no longer than the chosen width. (As you
  1498. can guess, <a class="reference internal" href="../library/textwrap.html#textwrap.fill" title="textwrap.fill"><code class="xref py py-func docutils literal notranslate"><span class="pre">fill()</span></code></a> is built on top of <a class="reference internal" href="../library/textwrap.html#textwrap.wrap" title="textwrap.wrap"><code class="xref py py-func docutils literal notranslate"><span class="pre">wrap()</span></code></a>. For example:</p>
  1499. <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">textwrap</span>
  1500. <span class="gp">&gt;&gt;&gt; </span><span class="n">paragraph</span> <span class="o">=</span> <span class="s2">&quot;Not a whit, we defy augury: ... more text ...&quot;</span>
  1501. <span class="gp">&gt;&gt;&gt; </span><span class="n">textwrap</span><span class="o">.</span><span class="n">wrap</span><span class="p">(</span><span class="n">paragraph</span><span class="p">,</span> <span class="mi">60</span><span class="p">)</span>
  1502. <span class="go">[&quot;Not a whit, we defy augury: there&#39;s a special providence in&quot;,</span>
  1503. <span class="go"> &quot;the fall of a sparrow. If it be now, &#39;tis not to come; if it&quot;,</span>
  1504. <span class="go"> ...]</span>
  1505. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">textwrap</span><span class="o">.</span><span class="n">fill</span><span class="p">(</span><span class="n">paragraph</span><span class="p">,</span> <span class="mi">35</span><span class="p">)</span>
  1506. <span class="go">Not a whit, we defy augury: there&#39;s</span>
  1507. <span class="go">a special providence in the fall of</span>
  1508. <span class="go">a sparrow. If it be now, &#39;tis not</span>
  1509. <span class="go">to come; if it be not to come, it</span>
  1510. <span class="go">will be now; if it be not now, yet</span>
  1511. <span class="go">it will come: the readiness is all.</span>
  1512. <span class="gp">&gt;&gt;&gt;</span>
  1513. </pre></div>
  1514. </div>
  1515. <p>The module also contains a <a class="reference internal" href="../library/textwrap.html#textwrap.TextWrapper" title="textwrap.TextWrapper"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextWrapper</span></code></a> class that actually implements
  1516. the text wrapping strategy. Both the <a class="reference internal" href="../library/textwrap.html#textwrap.TextWrapper" title="textwrap.TextWrapper"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextWrapper</span></code></a> class and the
  1517. <a class="reference internal" href="../library/textwrap.html#textwrap.wrap" title="textwrap.wrap"><code class="xref py py-func docutils literal notranslate"><span class="pre">wrap()</span></code></a> and <a class="reference internal" href="../library/textwrap.html#textwrap.fill" title="textwrap.fill"><code class="xref py py-func docutils literal notranslate"><span class="pre">fill()</span></code></a> functions support a number of additional keyword
  1518. arguments for fine-tuning the formatting; consult the module’s documentation
  1519. for details. (Contributed by Greg Ward.)</p>
  1520. </li>
  1521. <li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">thread</span></code> and <a class="reference internal" href="../library/threading.html#module-threading" title="threading: Thread-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> modules now have companion modules,
  1522. <code class="xref py py-mod docutils literal notranslate"><span class="pre">dummy_thread</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">dummy_threading</span></code>, that provide a do-nothing
  1523. implementation of the <code class="xref py py-mod docutils literal notranslate"><span class="pre">thread</span></code> module’s interface for platforms where
  1524. threads are not supported. The intention is to simplify thread-aware modules
  1525. (ones that <em>don’t</em> rely on threads to run) by putting the following code at the
  1526. top:</p>
  1527. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
  1528. <span class="kn">import</span> <span class="nn">threading</span> <span class="k">as</span> <span class="nn">_threading</span>
  1529. <span class="k">except</span> <span class="ne">ImportError</span><span class="p">:</span>
  1530. <span class="kn">import</span> <span class="nn">dummy_threading</span> <span class="k">as</span> <span class="nn">_threading</span>
  1531. </pre></div>
  1532. </div>
  1533. <p>In this example, <code class="xref py py-mod docutils literal notranslate"><span class="pre">_threading</span></code> is used as the module name to make it clear
  1534. that the module being used is not necessarily the actual <a class="reference internal" href="../library/threading.html#module-threading" title="threading: Thread-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a>
  1535. module. Code can call functions and use classes in <code class="xref py py-mod docutils literal notranslate"><span class="pre">_threading</span></code> whether or
  1536. not threads are supported, avoiding an <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement and making the
  1537. code slightly clearer. This module will not magically make multithreaded code
  1538. run without threads; code that waits for another thread to return or to do
  1539. something will simply hang forever.</p>
  1540. </li>
  1541. <li><p>The <a class="reference internal" href="../library/time.html#module-time" title="time: Time access and conversions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">time</span></code></a> module’s <a class="reference internal" href="../library/time.html#time.strptime" title="time.strptime"><code class="xref py py-func docutils literal notranslate"><span class="pre">strptime()</span></code></a> function has long been an annoyance
  1542. because it uses the platform C library’s <a class="reference internal" href="../library/time.html#time.strptime" title="time.strptime"><code class="xref py py-func docutils literal notranslate"><span class="pre">strptime()</span></code></a> implementation, and
  1543. different platforms sometimes have odd bugs. Brett Cannon contributed a
  1544. portable implementation that’s written in pure Python and should behave
  1545. identically on all platforms.</p></li>
  1546. <li><p>The new <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 helps measure how long snippets of Python code
  1547. take to execute. The <code class="file docutils literal notranslate"><span class="pre">timeit.py</span></code> file can be run directly from the
  1548. command line, or the module’s <a class="reference internal" href="../library/timeit.html#timeit.Timer" title="timeit.Timer"><code class="xref py py-class docutils literal notranslate"><span class="pre">Timer</span></code></a> class can be imported and used
  1549. directly. Here’s a short example that figures out whether it’s faster to
  1550. convert an 8-bit string to Unicode by appending an empty Unicode string to it or
  1551. by using the <code class="xref py py-func docutils literal notranslate"><span class="pre">unicode()</span></code> function:</p>
  1552. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">timeit</span>
  1553. <span class="n">timer1</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">Timer</span><span class="p">(</span><span class="s1">&#39;unicode(&quot;abc&quot;)&#39;</span><span class="p">)</span>
  1554. <span class="n">timer2</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">Timer</span><span class="p">(</span><span class="s1">&#39;&quot;abc&quot; + u&quot;&quot;&#39;</span><span class="p">)</span>
  1555. <span class="c1"># Run three trials</span>
  1556. <span class="nb">print</span> <span class="n">timer1</span><span class="o">.</span><span class="n">repeat</span><span class="p">(</span><span class="n">repeat</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">number</span><span class="o">=</span><span class="mi">100000</span><span class="p">)</span>
  1557. <span class="nb">print</span> <span class="n">timer2</span><span class="o">.</span><span class="n">repeat</span><span class="p">(</span><span class="n">repeat</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">number</span><span class="o">=</span><span class="mi">100000</span><span class="p">)</span>
  1558. <span class="c1"># On my laptop this outputs:</span>
  1559. <span class="c1"># [0.36831796169281006, 0.37441694736480713, 0.35304892063140869]</span>
  1560. <span class="c1"># [0.17574405670166016, 0.18193507194519043, 0.17565798759460449]</span>
  1561. </pre></div>
  1562. </div>
  1563. </li>
  1564. <li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">Tix</span></code> module has received various bug fixes and updates for the
  1565. current version of the Tix package.</p></li>
  1566. <li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code> module now works with a thread-enabled version of Tcl.
  1567. Tcl’s threading model requires that widgets only be accessed from the thread in
  1568. which they’re created; accesses from another thread can cause Tcl to panic. For
  1569. certain Tcl interfaces, <code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code> will now automatically avoid this when a
  1570. widget is accessed from a different thread by marshalling a command, passing it
  1571. to the correct thread, and waiting for the results. Other interfaces can’t be
  1572. handled automatically but <code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code> will now raise an exception on such an
  1573. access so that you can at least find out about the problem. See
  1574. <a class="reference external" href="https://mail.python.org/pipermail/python-dev/2002-December/031107.html">https://mail.python.org/pipermail/python-dev/2002-December/031107.html</a> for a more
  1575. detailed explanation of this change. (Implemented by Martin von Löwis.)</p></li>
  1576. <li><p>Calling Tcl methods through <code class="xref py py-mod docutils literal notranslate"><span class="pre">_tkinter</span></code> no longer returns only strings.
  1577. Instead, if Tcl returns other objects those objects are converted to their
  1578. Python equivalent, if one exists, or wrapped with a <code class="xref py py-class docutils literal notranslate"><span class="pre">_tkinter.Tcl_Obj</span></code>
  1579. object if no Python equivalent exists. This behavior can be controlled through
  1580. the <code class="xref py py-meth docutils literal notranslate"><span class="pre">wantobjects()</span></code> method of <code class="xref py py-class docutils literal notranslate"><span class="pre">tkapp</span></code> objects.</p>
  1581. <p>When using <code class="xref py py-mod docutils literal notranslate"><span class="pre">_tkinter</span></code> through the <code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code> module (as most Tkinter
  1582. applications will), this feature is always activated. It should not cause
  1583. compatibility problems, since Tkinter would always convert string results to
  1584. Python types where possible.</p>
  1585. <p>If any incompatibilities are found, the old behavior can be restored by setting
  1586. the <code class="xref py py-attr docutils literal notranslate"><span class="pre">wantobjects</span></code> variable in the <code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code> module to false before
  1587. creating the first <code class="xref py py-class docutils literal notranslate"><span class="pre">tkapp</span></code> object.</p>
  1588. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">Tkinter</span>
  1589. <span class="n">Tkinter</span><span class="o">.</span><span class="n">wantobjects</span> <span class="o">=</span> <span class="mi">0</span>
  1590. </pre></div>
  1591. </div>
  1592. <p>Any breakage caused by this change should be reported as a bug.</p>
  1593. </li>
  1594. <li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">UserDict</span></code> module has a new <code class="xref py py-class docutils literal notranslate"><span class="pre">DictMixin</span></code> class which defines
  1595. all dictionary methods for classes that already have a minimum mapping
  1596. interface. This greatly simplifies writing classes that need to be
  1597. substitutable for dictionaries, such as the classes in the <a class="reference internal" href="../library/shelve.html#module-shelve" title="shelve: Python object persistence."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shelve</span></code></a>
  1598. module.</p>
  1599. <p>Adding the mix-in as a superclass provides the full dictionary interface
  1600. whenever the class defines <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>, <a class="reference internal" href="../reference/datamodel.html#object.__setitem__" title="object.__setitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setitem__()</span></code></a>,
  1601. <a class="reference internal" href="../reference/datamodel.html#object.__delitem__" title="object.__delitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delitem__()</span></code></a>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code>. For example:</p>
  1602. <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">UserDict</span>
  1603. <span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">SeqDict</span><span class="p">(</span><span class="n">UserDict</span><span class="o">.</span><span class="n">DictMixin</span><span class="p">):</span>
  1604. <span class="gp">... </span><span class="w"> </span><span class="sd">&quot;&quot;&quot;Dictionary lookalike implemented with lists.&quot;&quot;&quot;</span>
  1605. <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>
  1606. <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">keylist</span> <span class="o">=</span> <span class="p">[]</span>
  1607. <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">valuelist</span> <span class="o">=</span> <span class="p">[]</span>
  1608. <span class="gp">... </span> <span class="k">def</span> <span class="fm">__getitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">):</span>
  1609. <span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
  1610. <span class="gp">... </span> <span class="n">i</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">keylist</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
  1611. <span class="gp">... </span> <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
  1612. <span class="gp">... </span> <span class="k">raise</span> <span class="ne">KeyError</span>
  1613. <span class="gp">... </span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">valuelist</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
  1614. <span class="gp">... </span> <span class="k">def</span> <span class="fm">__setitem__</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>
  1615. <span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
  1616. <span class="gp">... </span> <span class="n">i</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">keylist</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
  1617. <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">valuelist</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="n">value</span>
  1618. <span class="gp">... </span> <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
  1619. <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">keylist</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
  1620. <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">valuelist</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
  1621. <span class="gp">... </span> <span class="k">def</span> <span class="fm">__delitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">):</span>
  1622. <span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
  1623. <span class="gp">... </span> <span class="n">i</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">keylist</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
  1624. <span class="gp">... </span> <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
  1625. <span class="gp">... </span> <span class="k">raise</span> <span class="ne">KeyError</span>
  1626. <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">keylist</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
  1627. <span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">valuelist</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
  1628. <span class="gp">... </span> <span class="k">def</span> <span class="nf">keys</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  1629. <span class="gp">... </span> <span class="k">return</span> <span class="nb">list</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">keylist</span><span class="p">)</span>
  1630. <span class="gp">...</span>
  1631. <span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">SeqDict</span><span class="p">()</span>
  1632. <span class="gp">&gt;&gt;&gt; </span><span class="nb">dir</span><span class="p">(</span><span class="n">s</span><span class="p">)</span> <span class="c1"># See that other dictionary methods are implemented</span>
  1633. <span class="go">[&#39;__cmp__&#39;, &#39;__contains__&#39;, &#39;__delitem__&#39;, &#39;__doc__&#39;, &#39;__getitem__&#39;,</span>
  1634. <span class="go"> &#39;__init__&#39;, &#39;__iter__&#39;, &#39;__len__&#39;, &#39;__module__&#39;, &#39;__repr__&#39;,</span>
  1635. <span class="go"> &#39;__setitem__&#39;, &#39;clear&#39;, &#39;get&#39;, &#39;has_key&#39;, &#39;items&#39;, &#39;iteritems&#39;,</span>
  1636. <span class="go"> &#39;iterkeys&#39;, &#39;itervalues&#39;, &#39;keylist&#39;, &#39;keys&#39;, &#39;pop&#39;, &#39;popitem&#39;,</span>
  1637. <span class="go"> &#39;setdefault&#39;, &#39;update&#39;, &#39;valuelist&#39;, &#39;values&#39;]</span>
  1638. </pre></div>
  1639. </div>
  1640. <p>(Contributed by Raymond Hettinger.)</p>
  1641. </li>
  1642. <li><p>The DOM implementation in <a class="reference internal" href="../library/xml.dom.minidom.html#module-xml.dom.minidom" title="xml.dom.minidom: Minimal Document Object Model (DOM) implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code></a> can now generate XML output
  1643. in a particular encoding by providing an optional encoding argument to the
  1644. <a class="reference internal" href="../library/xml.dom.minidom.html#xml.dom.minidom.Node.toxml" title="xml.dom.minidom.Node.toxml"><code class="xref py py-meth docutils literal notranslate"><span class="pre">toxml()</span></code></a> and <a class="reference internal" href="../library/xml.dom.minidom.html#xml.dom.minidom.Node.toprettyxml" title="xml.dom.minidom.Node.toprettyxml"><code class="xref py py-meth docutils literal notranslate"><span class="pre">toprettyxml()</span></code></a> methods of DOM nodes.</p></li>
  1645. <li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code> module now supports an XML-RPC extension for handling nil
  1646. data values such as Python’s <code class="docutils literal notranslate"><span class="pre">None</span></code>. Nil values are always supported on
  1647. unmarshalling an XML-RPC response. To generate requests containing <code class="docutils literal notranslate"><span class="pre">None</span></code>,
  1648. you must supply a true value for the <em>allow_none</em> parameter when creating a
  1649. <code class="xref py py-class docutils literal notranslate"><span class="pre">Marshaller</span></code> instance.</p></li>
  1650. <li><p>The new <code class="xref py py-mod docutils literal notranslate"><span class="pre">DocXMLRPCServer</span></code> module allows writing self-documenting XML-RPC
  1651. servers. Run it in demo mode (as a program) to see it in action. Pointing the
  1652. web browser to the RPC server produces pydoc-style documentation; pointing
  1653. xmlrpclib to the server allows invoking the actual methods. (Contributed by
  1654. Brian Quinlan.)</p></li>
  1655. <li><p>Support for internationalized domain names (RFCs 3454, 3490, 3491, and 3492)
  1656. has been added. The “idna” encoding can be used to convert between a Unicode
  1657. domain name and the ASCII-compatible encoding (ACE) of that name.</p>
  1658. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="o">&gt;</span><span class="p">{}</span><span class="o">&gt;</span><span class="p">{}</span><span class="o">&gt;</span> <span class="sa">u</span><span class="s2">&quot;www.Alliancefrançaise.nu&quot;</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s2">&quot;idna&quot;</span><span class="p">)</span>
  1659. <span class="s1">&#39;www.xn--alliancefranaise-npb.nu&#39;</span>
  1660. </pre></div>
  1661. </div>
  1662. <p>The <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module has also been extended to transparently convert
  1663. Unicode hostnames to the ACE version before passing them to the C library.
  1664. Modules that deal with hostnames such as <code class="xref py py-mod docutils literal notranslate"><span class="pre">httplib</span></code> and <a class="reference internal" href="../library/ftplib.html#module-ftplib" title="ftplib: FTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ftplib</span></code></a>)
  1665. also support Unicode host names; <code class="xref py py-mod docutils literal notranslate"><span class="pre">httplib</span></code> also sends HTTP <code class="docutils literal notranslate"><span class="pre">Host</span></code>
  1666. headers using the ACE version of the domain name. <a class="reference internal" href="../library/urllib.html#module-urllib" title="urllib"><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib</span></code></a> supports
  1667. Unicode URLs with non-ASCII host names as long as the <code class="docutils literal notranslate"><span class="pre">path</span></code> part of the URL
  1668. is ASCII only.</p>
  1669. <p>To implement this change, the <a class="reference internal" href="../library/stringprep.html#module-stringprep" title="stringprep: String preparation, as per RFC 3453"><code class="xref py py-mod docutils literal notranslate"><span class="pre">stringprep</span></code></a> module, the <code class="docutils literal notranslate"><span class="pre">mkstringprep</span></code>
  1670. tool and the <code class="docutils literal notranslate"><span class="pre">punycode</span></code> encoding have been added.</p>
  1671. </li>
  1672. </ul>
  1673. <section id="date-time-type">
  1674. <h3>Date/Time Type<a class="headerlink" href="#date-time-type" title="Link to this heading">¶</a></h3>
  1675. <p>Date and time types suitable for expressing timestamps were added as the
  1676. <a class="reference internal" href="../library/datetime.html#module-datetime" title="datetime: Basic date and time types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">datetime</span></code></a> module. The types don’t support different calendars or many
  1677. fancy features, and just stick to the basics of representing time.</p>
  1678. <p>The three primary types are: <a class="reference internal" href="../library/datetime.html#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a>, representing a day, month, and year;
  1679. <a class="reference internal" href="../library/datetime.html#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a>, consisting of hour, minute, and second; and <a class="reference internal" href="../library/datetime.html#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a>,
  1680. which contains all the attributes of both <a class="reference internal" href="../library/datetime.html#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a> and <a class="reference internal" href="../library/datetime.html#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a>.
  1681. There’s also a <a class="reference internal" href="../library/datetime.html#datetime.timedelta" title="datetime.timedelta"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a> class representing differences between two
  1682. points in time, and time zone logic is implemented by classes inheriting from
  1683. the abstract <a class="reference internal" href="../library/datetime.html#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> class.</p>
  1684. <p>You can create instances of <a class="reference internal" href="../library/datetime.html#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a> and <a class="reference internal" href="../library/datetime.html#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a> by either supplying
  1685. keyword arguments to the appropriate constructor, e.g.
  1686. <code class="docutils literal notranslate"><span class="pre">datetime.date(year=1972,</span> <span class="pre">month=10,</span> <span class="pre">day=15)</span></code>, or by using one of a number of
  1687. class methods. For example, the <a class="reference internal" href="../library/datetime.html#datetime.date.today" title="datetime.date.today"><code class="xref py py-meth docutils literal notranslate"><span class="pre">today()</span></code></a> class method returns the
  1688. current local date.</p>
  1689. <p>Once created, instances of the date/time classes are all immutable. There are a
  1690. number of methods for producing formatted strings from objects:</p>
  1691. <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">datetime</span>
  1692. <span class="gp">&gt;&gt;&gt; </span><span class="n">now</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">()</span>
  1693. <span class="gp">&gt;&gt;&gt; </span><span class="n">now</span><span class="o">.</span><span class="n">isoformat</span><span class="p">()</span>
  1694. <span class="go">&#39;2002-12-30T21:27:03.994956&#39;</span>
  1695. <span class="gp">&gt;&gt;&gt; </span><span class="n">now</span><span class="o">.</span><span class="n">ctime</span><span class="p">()</span> <span class="c1"># Only available on date, datetime</span>
  1696. <span class="go">&#39;Mon Dec 30 21:27:03 2002&#39;</span>
  1697. <span class="gp">&gt;&gt;&gt; </span><span class="n">now</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s1">&#39;%Y </span><span class="si">%d</span><span class="s1"> %b&#39;</span><span class="p">)</span>
  1698. <span class="go">&#39;2002 30 Dec&#39;</span>
  1699. </pre></div>
  1700. </div>
  1701. <p>The <a class="reference internal" href="../library/datetime.html#datetime.datetime.replace" title="datetime.datetime.replace"><code class="xref py py-meth docutils literal notranslate"><span class="pre">replace()</span></code></a> method allows modifying one or more fields of a
  1702. <a class="reference internal" href="../library/datetime.html#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a> or <a class="reference internal" href="../library/datetime.html#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> instance, returning a new instance:</p>
  1703. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">()</span>
  1704. <span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
  1705. <span class="go">datetime.datetime(2002, 12, 30, 22, 15, 38, 827738)</span>
  1706. <span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="n">year</span><span class="o">=</span><span class="mi">2001</span><span class="p">,</span> <span class="n">hour</span> <span class="o">=</span> <span class="mi">12</span><span class="p">)</span>
  1707. <span class="go">datetime.datetime(2001, 12, 30, 12, 15, 38, 827738)</span>
  1708. <span class="gp">&gt;&gt;&gt;</span>
  1709. </pre></div>
  1710. </div>
  1711. <p>Instances can be compared, hashed, and converted to strings (the result is the
  1712. same as that of <a class="reference internal" href="../library/datetime.html#datetime.datetime.isoformat" title="datetime.datetime.isoformat"><code class="xref py py-meth docutils literal notranslate"><span class="pre">isoformat()</span></code></a>). <a class="reference internal" href="../library/datetime.html#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a> and <a class="reference internal" href="../library/datetime.html#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a>
  1713. instances can be subtracted from each other, and added to <a class="reference internal" href="../library/datetime.html#datetime.timedelta" title="datetime.timedelta"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a>
  1714. instances. The largest missing feature is that there’s no standard library
  1715. support for parsing strings and getting back a <a class="reference internal" href="../library/datetime.html#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a> or
  1716. <a class="reference internal" href="../library/datetime.html#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a>.</p>
  1717. <p>For more information, refer to the module’s reference documentation.
  1718. (Contributed by Tim Peters.)</p>
  1719. </section>
  1720. <section id="the-optparse-module">
  1721. <h3>The optparse Module<a class="headerlink" href="#the-optparse-module" title="Link to this heading">¶</a></h3>
  1722. <p>The <a class="reference internal" href="../library/getopt.html#module-getopt" title="getopt: Portable parser for command line options; support both short and long option names."><code class="xref py py-mod docutils literal notranslate"><span class="pre">getopt</span></code></a> module provides simple parsing of command-line arguments. The
  1723. new <a class="reference internal" href="../library/optparse.html#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> module (originally named Optik) provides more elaborate
  1724. command-line parsing that follows the Unix conventions, automatically creates
  1725. the output for <code class="xref std std-option docutils literal notranslate"><span class="pre">--help</span></code>, and can perform different actions for different
  1726. options.</p>
  1727. <p>You start by creating an instance of <a class="reference internal" href="../library/optparse.html#optparse.OptionParser" title="optparse.OptionParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">OptionParser</span></code></a> and telling it what
  1728. your program’s options are.</p>
  1729. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sys</span>
  1730. <span class="kn">from</span> <span class="nn">optparse</span> <span class="kn">import</span> <span class="n">OptionParser</span>
  1731. <span class="n">op</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">()</span>
  1732. <span class="n">op</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s1">&#39;-i&#39;</span><span class="p">,</span> <span class="s1">&#39;--input&#39;</span><span class="p">,</span>
  1733. <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s1">&#39;string&#39;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s1">&#39;input&#39;</span><span class="p">,</span>
  1734. <span class="n">help</span><span class="o">=</span><span class="s1">&#39;set input filename&#39;</span><span class="p">)</span>
  1735. <span class="n">op</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s1">&#39;-l&#39;</span><span class="p">,</span> <span class="s1">&#39;--length&#39;</span><span class="p">,</span>
  1736. <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s1">&#39;int&#39;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s1">&#39;length&#39;</span><span class="p">,</span>
  1737. <span class="n">help</span><span class="o">=</span><span class="s1">&#39;set maximum length of output&#39;</span><span class="p">)</span>
  1738. </pre></div>
  1739. </div>
  1740. <p>Parsing a command line is then done by calling the <a class="reference internal" href="../library/optparse.html#optparse.OptionParser.parse_args" title="optparse.OptionParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> method.</p>
  1741. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">options</span><span class="p">,</span> <span class="n">args</span> <span class="o">=</span> <span class="n">op</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">:])</span>
  1742. <span class="nb">print</span> <span class="n">options</span>
  1743. <span class="nb">print</span> <span class="n">args</span>
  1744. </pre></div>
  1745. </div>
  1746. <p>This returns an object containing all of the option values, and a list of
  1747. strings containing the remaining arguments.</p>
  1748. <p>Invoking the script with the various arguments now works as you’d expect it to.
  1749. Note that the length argument is automatically converted to an integer.</p>
  1750. <div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>./python<span class="w"> </span>opt.py<span class="w"> </span>-i<span class="w"> </span>data<span class="w"> </span>arg1
  1751. <span class="go">&lt;Values at 0x400cad4c: {&#39;input&#39;: &#39;data&#39;, &#39;length&#39;: None}&gt;</span>
  1752. <span class="go">[&#39;arg1&#39;]</span>
  1753. <span class="gp">$ </span>./python<span class="w"> </span>opt.py<span class="w"> </span>--input<span class="o">=</span>data<span class="w"> </span>--length<span class="o">=</span><span class="m">4</span>
  1754. <span class="go">&lt;Values at 0x400cad2c: {&#39;input&#39;: &#39;data&#39;, &#39;length&#39;: 4}&gt;</span>
  1755. <span class="go">[]</span>
  1756. <span class="gp">$</span>
  1757. </pre></div>
  1758. </div>
  1759. <p>The help message is automatically generated for you:</p>
  1760. <div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>./python<span class="w"> </span>opt.py<span class="w"> </span>--help
  1761. <span class="go">usage: opt.py [options]</span>
  1762. <span class="go">options:</span>
  1763. <span class="go"> -h, --help show this help message and exit</span>
  1764. <span class="go"> -iINPUT, --input=INPUT</span>
  1765. <span class="go"> set input filename</span>
  1766. <span class="go"> -lLENGTH, --length=LENGTH</span>
  1767. <span class="go"> set maximum length of output</span>
  1768. <span class="gp">$</span>
  1769. </pre></div>
  1770. </div>
  1771. <p>See the module’s documentation for more details.</p>
  1772. <p>Optik was written by Greg Ward, with suggestions from the readers of the Getopt
  1773. SIG.</p>
  1774. </section>
  1775. </section>
  1776. <section id="pymalloc-a-specialized-object-allocator">
  1777. <span id="section-pymalloc"></span><h2>Pymalloc: A Specialized Object Allocator<a class="headerlink" href="#pymalloc-a-specialized-object-allocator" title="Link to this heading">¶</a></h2>
  1778. <p>Pymalloc, a specialized object allocator written by Vladimir Marangozov, was a
  1779. feature added to Python 2.1. Pymalloc is intended to be faster than the system
  1780. <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> and to have less memory overhead for allocation patterns typical
  1781. of Python programs. The allocator uses C’s <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> function to get large
  1782. pools of memory and then fulfills smaller memory requests from these pools.</p>
  1783. <p>In 2.1 and 2.2, pymalloc was an experimental feature and wasn’t enabled by
  1784. default; you had to explicitly enable it when compiling Python by providing the
  1785. <code class="xref std std-option docutils literal notranslate"><span class="pre">--with-pymalloc</span></code> option to the <strong class="program">configure</strong> script. In 2.3,
  1786. pymalloc has had further enhancements and is now enabled by default; you’ll have
  1787. to supply <code class="xref std std-option docutils literal notranslate"><span class="pre">--without-pymalloc</span></code> to disable it.</p>
  1788. <p>This change is transparent to code written in Python; however, pymalloc may
  1789. expose bugs in C extensions. Authors of C extension modules should test their
  1790. code with pymalloc enabled, because some incorrect code may cause core dumps at
  1791. runtime.</p>
  1792. <p>There’s one particularly common error that causes problems. There are a number
  1793. of memory allocation functions in Python’s C API that have previously just been
  1794. aliases for the C library’s <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code>, meaning that if
  1795. you accidentally called mismatched functions the error wouldn’t be noticeable.
  1796. When the object allocator is enabled, these functions aren’t aliases of
  1797. <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code> any more, and calling the wrong function to
  1798. free memory may get you a core dump. For example, if memory was allocated using
  1799. <a class="reference internal" href="../c-api/memory.html#c.PyObject_Malloc" title="PyObject_Malloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Malloc()</span></code></a>, it has to be freed using <a class="reference internal" href="../c-api/memory.html#c.PyObject_Free" title="PyObject_Free"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Free()</span></code></a>, not
  1800. <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code>. A few modules included with Python fell afoul of this and had to
  1801. be fixed; doubtless there are more third-party modules that will have the same
  1802. problem.</p>
  1803. <p>As part of this change, the confusing multiple interfaces for allocating memory
  1804. have been consolidated down into two API families. Memory allocated with one
  1805. family must not be manipulated with functions from the other family. There is
  1806. one family for allocating chunks of memory and another family of functions
  1807. specifically for allocating Python objects.</p>
  1808. <ul class="simple">
  1809. <li><p>To allocate and free an undistinguished chunk of memory use the “raw memory”
  1810. family: <a class="reference internal" href="../c-api/memory.html#c.PyMem_Malloc" title="PyMem_Malloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_Malloc()</span></code></a>, <a class="reference internal" href="../c-api/memory.html#c.PyMem_Realloc" title="PyMem_Realloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_Realloc()</span></code></a>, and <a class="reference internal" href="../c-api/memory.html#c.PyMem_Free" title="PyMem_Free"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_Free()</span></code></a>.</p></li>
  1811. <li><p>The “object memory” family is the interface to the pymalloc facility described
  1812. above and is biased towards a large number of “small” allocations:
  1813. <a class="reference internal" href="../c-api/memory.html#c.PyObject_Malloc" title="PyObject_Malloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Malloc()</span></code></a>, <a class="reference internal" href="../c-api/memory.html#c.PyObject_Realloc" title="PyObject_Realloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Realloc()</span></code></a>, and <a class="reference internal" href="../c-api/memory.html#c.PyObject_Free" title="PyObject_Free"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Free()</span></code></a>.</p></li>
  1814. <li><p>To allocate and free Python objects, use the “object” family
  1815. <a class="reference internal" href="../c-api/allocation.html#c.PyObject_New" title="PyObject_New"><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyObject_New</span></code></a>, <a class="reference internal" href="../c-api/allocation.html#c.PyObject_NewVar" title="PyObject_NewVar"><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyObject_NewVar</span></code></a>, and <a class="reference internal" href="../c-api/allocation.html#c.PyObject_Del" title="PyObject_Del"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Del()</span></code></a>.</p></li>
  1816. </ul>
  1817. <p>Thanks to lots of work by Tim Peters, pymalloc in 2.3 also provides debugging
  1818. features to catch memory overwrites and doubled frees in both extension modules
  1819. and in the interpreter itself. To enable this support, compile a debugging
  1820. version of the Python interpreter by running <strong class="program">configure</strong> with
  1821. <code class="xref std std-option docutils literal notranslate"><span class="pre">--with-pydebug</span></code>.</p>
  1822. <p>To aid extension writers, a header file <code class="file docutils literal notranslate"><span class="pre">Misc/pymemcompat.h</span></code> is
  1823. distributed with the source to Python 2.3 that allows Python extensions to use
  1824. the 2.3 interfaces to memory allocation while compiling against any version of
  1825. Python since 1.5.2. You would copy the file from Python’s source distribution
  1826. and bundle it with the source of your extension.</p>
  1827. <div class="admonition seealso">
  1828. <p class="admonition-title">See also</p>
  1829. <dl class="simple">
  1830. <dt><a class="reference external" href="https://hg.python.org/cpython/file/default/Objects/obmalloc.c">https://hg.python.org/cpython/file/default/Objects/obmalloc.c</a></dt><dd><p>For the full details of the pymalloc implementation, see the comments at
  1831. the top of the file <code class="file docutils literal notranslate"><span class="pre">Objects/obmalloc.c</span></code> in the Python source code.
  1832. The above link points to the file within the python.org SVN browser.</p>
  1833. </dd>
  1834. </dl>
  1835. </div>
  1836. </section>
  1837. <section id="build-and-c-api-changes">
  1838. <h2>Build and C API Changes<a class="headerlink" href="#build-and-c-api-changes" title="Link to this heading">¶</a></h2>
  1839. <p>Changes to Python’s build process and to the C API include:</p>
  1840. <ul class="simple">
  1841. <li><p>The cycle detection implementation used by the garbage collection has proven
  1842. to be stable, so it’s now been made mandatory. You can no longer compile Python
  1843. without it, and the <code class="xref std std-option docutils literal notranslate"><span class="pre">--with-cycle-gc</span></code> switch to <strong class="program">configure</strong> has
  1844. been removed.</p></li>
  1845. <li><p>Python can now optionally be built as a shared library
  1846. (<code class="file docutils literal notranslate"><span class="pre">libpython2.3.so</span></code>) by supplying <code class="xref std std-option docutils literal notranslate"><span class="pre">--enable-shared</span></code> when running
  1847. Python’s <strong class="program">configure</strong> script. (Contributed by Ondrej Palkovsky.)</p></li>
  1848. <li><p>The <code class="xref c c-macro docutils literal notranslate"><span class="pre">DL_EXPORT</span></code> and <code class="xref c c-macro docutils literal notranslate"><span class="pre">DL_IMPORT</span></code> macros are now deprecated.
  1849. Initialization functions for Python extension modules should now be declared
  1850. using the new macro <a class="reference internal" href="../c-api/intro.html#c.PyMODINIT_FUNC" title="PyMODINIT_FUNC"><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyMODINIT_FUNC</span></code></a>, while the Python core will
  1851. generally use the <code class="xref c c-macro docutils literal notranslate"><span class="pre">PyAPI_FUNC</span></code> and <code class="xref c c-macro docutils literal notranslate"><span class="pre">PyAPI_DATA</span></code> macros.</p></li>
  1852. <li><p>The interpreter can be compiled without any docstrings for the built-in
  1853. functions and modules by supplying <code class="xref std std-option docutils literal notranslate"><span class="pre">--without-doc-strings</span></code> to the
  1854. <strong class="program">configure</strong> script. This makes the Python executable about 10% smaller,
  1855. but will also mean that you can’t get help for Python’s built-ins. (Contributed
  1856. by Gustavo Niemeyer.)</p></li>
  1857. <li><p>The <code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_NoArgs()</span></code> macro is now deprecated, and code that uses it
  1858. should be changed. For Python 2.2 and later, the method definition table can
  1859. specify the <a class="reference internal" href="../c-api/structures.html#c.METH_NOARGS" title="METH_NOARGS"><code class="xref c c-macro docutils literal notranslate"><span class="pre">METH_NOARGS</span></code></a> flag, signalling that there are no arguments,
  1860. and the argument checking can then be removed. If compatibility with pre-2.2
  1861. versions of Python is important, the code could use <code class="docutils literal notranslate"><span class="pre">PyArg_ParseTuple(args,</span>
  1862. <span class="pre">&quot;&quot;)</span></code> instead, but this will be slower than using <a class="reference internal" href="../c-api/structures.html#c.METH_NOARGS" title="METH_NOARGS"><code class="xref c c-macro docutils literal notranslate"><span class="pre">METH_NOARGS</span></code></a>.</p></li>
  1863. <li><p><a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> accepts new format characters for various sizes of
  1864. unsigned integers: <code class="docutils literal notranslate"><span class="pre">B</span></code> for <span class="c-expr sig sig-inline c"><span class="kt">unsigned</span><span class="w"> </span><span class="kt">char</span></span>, <code class="docutils literal notranslate"><span class="pre">H</span></code> for <span class="c-expr sig sig-inline c"><span class="kt">unsigned</span><span class="w"> </span><span class="kt">short</span><span class="w"> </span><span class="kt">int</span></span>, <code class="docutils literal notranslate"><span class="pre">I</span></code> for <span class="c-expr sig sig-inline c"><span class="kt">unsigned</span><span class="w"> </span><span class="kt">int</span></span>, and <code class="docutils literal notranslate"><span class="pre">K</span></code> for <span class="c-expr sig sig-inline c"><span class="kt">unsigned</span><span class="w"> </span><span class="kt">long</span><span class="w"> </span><span class="kt">long</span></span>.</p></li>
  1865. <li><p>A new function, <code class="docutils literal notranslate"><span class="pre">PyObject_DelItemString(mapping,</span> <span class="pre">char</span> <span class="pre">*key)</span></code> was added
  1866. as shorthand for <code class="docutils literal notranslate"><span class="pre">PyObject_DelItem(mapping,</span> <span class="pre">PyString_New(key))</span></code>.</p></li>
  1867. <li><p>File objects now manage their internal string buffer differently, increasing
  1868. it exponentially when needed. This results in the benchmark tests in
  1869. <code class="file docutils literal notranslate"><span class="pre">Lib/test/test_bufio.py</span></code> speeding up considerably (from 57 seconds to 1.7
  1870. seconds, according to one measurement).</p></li>
  1871. <li><p>It’s now possible to define class and static methods for a C extension type by
  1872. setting either the <a class="reference internal" href="../c-api/structures.html#c.METH_CLASS" title="METH_CLASS"><code class="xref c c-macro docutils literal notranslate"><span class="pre">METH_CLASS</span></code></a> or <a class="reference internal" href="../c-api/structures.html#c.METH_STATIC" title="METH_STATIC"><code class="xref c c-macro docutils literal notranslate"><span class="pre">METH_STATIC</span></code></a> flags in a
  1873. method’s <a class="reference internal" href="../c-api/structures.html#c.PyMethodDef" title="PyMethodDef"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyMethodDef</span></code></a> structure.</p></li>
  1874. <li><p>Python now includes a copy of the Expat XML parser’s source code, removing any
  1875. dependence on a system version or local installation of Expat.</p></li>
  1876. <li><p>If you dynamically allocate type objects in your extension, you should be
  1877. aware of a change in the rules relating to the <code class="xref py py-attr docutils literal notranslate"><span class="pre">__module__</span></code> and
  1878. <a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a> attributes. In summary, you will want to ensure the type’s
  1879. dictionary contains a <code class="docutils literal notranslate"><span class="pre">'__module__'</span></code> key; making the module name the part of
  1880. the type name leading up to the final period will no longer have the desired
  1881. effect. For more detail, read the API reference documentation or the source.</p></li>
  1882. </ul>
  1883. <section id="port-specific-changes">
  1884. <h3>Port-Specific Changes<a class="headerlink" href="#port-specific-changes" title="Link to this heading">¶</a></h3>
  1885. <p>Support for a port to IBM’s OS/2 using the EMX runtime environment was merged
  1886. into the main Python source tree. EMX is a POSIX emulation layer over the OS/2
  1887. system APIs. The Python port for EMX tries to support all the POSIX-like
  1888. capability exposed by the EMX runtime, and mostly succeeds; <code class="xref py py-func docutils literal notranslate"><span class="pre">fork()</span></code> and
  1889. <a class="reference internal" href="../library/fcntl.html#module-fcntl" title="fcntl: The fcntl() and ioctl() system calls. (Unix)"><code class="xref py py-func docutils literal notranslate"><span class="pre">fcntl()</span></code></a> are restricted by the limitations of the underlying emulation
  1890. layer. The standard OS/2 port, which uses IBM’s Visual Age compiler, also
  1891. gained support for case-sensitive import semantics as part of the integration of
  1892. the EMX port into CVS. (Contributed by Andrew MacIntyre.)</p>
  1893. <p>On MacOS, most toolbox modules have been weaklinked to improve backward
  1894. compatibility. This means that modules will no longer fail to load if a single
  1895. routine is missing on the current OS version. Instead calling the missing
  1896. routine will raise an exception. (Contributed by Jack Jansen.)</p>
  1897. <p>The RPM spec files, found in the <code class="file docutils literal notranslate"><span class="pre">Misc/RPM/</span></code> directory in the Python
  1898. source distribution, were updated for 2.3. (Contributed by Sean Reifschneider.)</p>
  1899. <p>Other new platforms now supported by Python include AtheOS
  1900. (<a class="reference external" href="http://www.atheos.cx/">http://www.atheos.cx/</a>), GNU/Hurd, and OpenVMS.</p>
  1901. </section>
  1902. </section>
  1903. <section id="other-changes-and-fixes">
  1904. <span id="section-other"></span><h2>Other Changes and Fixes<a class="headerlink" href="#other-changes-and-fixes" title="Link to this heading">¶</a></h2>
  1905. <p>As usual, there were a bunch of other improvements and bugfixes scattered
  1906. throughout the source tree. A search through the CVS change logs finds there
  1907. were 523 patches applied and 514 bugs fixed between Python 2.2 and 2.3. Both
  1908. figures are likely to be underestimates.</p>
  1909. <p>Some of the more notable changes are:</p>
  1910. <ul>
  1911. <li><p>If the <span class="target" id="index-28"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONINSPECT"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONINSPECT</span></code></a> environment variable is set, the Python
  1912. interpreter will enter the interactive prompt after running a Python program, as
  1913. if Python had been invoked with the <a class="reference internal" href="../using/cmdline.html#cmdoption-i"><code class="xref std std-option docutils literal notranslate"><span class="pre">-i</span></code></a> option. The environment
  1914. variable can be set before running the Python interpreter, or it can be set by
  1915. the Python program as part of its execution.</p></li>
  1916. <li><p>The <code class="file docutils literal notranslate"><span class="pre">regrtest.py</span></code> script now provides a way to allow “all resources
  1917. except <em>foo</em>.” A resource name passed to the <code class="xref std std-option docutils literal notranslate"><span class="pre">-u</span></code> option can now be
  1918. prefixed with a hyphen (<code class="docutils literal notranslate"><span class="pre">'-'</span></code>) to mean “remove this resource.” For example,
  1919. the option ‘<code class="docutils literal notranslate"><span class="pre">-uall,-bsddb</span></code>’ could be used to enable the use of all resources
  1920. except <code class="docutils literal notranslate"><span class="pre">bsddb</span></code>.</p></li>
  1921. <li><p>The tools used to build the documentation now work under Cygwin as well as
  1922. Unix.</p></li>
  1923. <li><p>The <code class="docutils literal notranslate"><span class="pre">SET_LINENO</span></code> opcode has been removed. Back in the mists of time, this
  1924. opcode was needed to produce line numbers in tracebacks and support trace
  1925. functions (for, e.g., <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">pdb</span></code></a>). Since Python 1.5, the line numbers in
  1926. tracebacks have been computed using a different mechanism that works with
  1927. “python -O”. For Python 2.3 Michael Hudson implemented a similar scheme to
  1928. determine when to call the trace function, removing the need for <code class="docutils literal notranslate"><span class="pre">SET_LINENO</span></code>
  1929. entirely.</p>
  1930. <p>It would be difficult to detect any resulting difference from Python code, apart
  1931. from a slight speed up when Python is run without <a class="reference internal" href="../using/cmdline.html#cmdoption-O"><code class="xref std std-option docutils literal notranslate"><span class="pre">-O</span></code></a>.</p>
  1932. <p>C extensions that access the <a class="reference internal" href="../reference/datamodel.html#frame.f_lineno" title="frame.f_lineno"><code class="xref py py-attr docutils literal notranslate"><span class="pre">f_lineno</span></code></a> field of frame objects should
  1933. instead call <code class="docutils literal notranslate"><span class="pre">PyCode_Addr2Line(f-&gt;f_code,</span> <span class="pre">f-&gt;f_lasti)</span></code>. This will have the
  1934. added effect of making the code work as desired under “python -O” in earlier
  1935. versions of Python.</p>
  1936. <p>A nifty new feature is that trace functions can now assign to the
  1937. <a class="reference internal" href="../reference/datamodel.html#frame.f_lineno" title="frame.f_lineno"><code class="xref py py-attr docutils literal notranslate"><span class="pre">f_lineno</span></code></a> attribute of frame objects, changing the line that will be
  1938. executed next. A <code class="docutils literal notranslate"><span class="pre">jump</span></code> command has been added to the <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">pdb</span></code></a> debugger
  1939. taking advantage of this new feature. (Implemented by Richie Hindle.)</p>
  1940. </li>
  1941. </ul>
  1942. </section>
  1943. <section id="porting-to-python-2-3">
  1944. <h2>Porting to Python 2.3<a class="headerlink" href="#porting-to-python-2-3" title="Link to this heading">¶</a></h2>
  1945. <p>This section lists previously described changes that may require changes to your
  1946. code:</p>
  1947. <ul>
  1948. <li><p><a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> is now always a keyword; if it’s used as a variable name in
  1949. your code, a different name must be chosen.</p></li>
  1950. <li><p>For strings <em>X</em> and <em>Y</em>, <code class="docutils literal notranslate"><span class="pre">X</span> <span class="pre">in</span> <span class="pre">Y</span></code> now works if <em>X</em> is more than one
  1951. character long.</p></li>
  1952. <li><p>The <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 will now return a long integer instead of
  1953. raising an <a class="reference internal" href="../library/exceptions.html#OverflowError" title="OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a> when a string or floating-point number is too
  1954. large to fit into an integer.</p></li>
  1955. <li><p>If you have Unicode strings that contain 8-bit characters, you must declare
  1956. the file’s encoding (UTF-8, Latin-1, or whatever) by adding a comment to the top
  1957. of the file. See section <a class="reference internal" href="#section-encodings"><span class="std std-ref">PEP 263: Source Code Encodings</span></a> for more information.</p></li>
  1958. <li><p>Calling Tcl methods through <code class="xref py py-mod docutils literal notranslate"><span class="pre">_tkinter</span></code> no longer returns only strings.
  1959. Instead, if Tcl returns other objects those objects are converted to their
  1960. Python equivalent, if one exists, or wrapped with a <code class="xref py py-class docutils literal notranslate"><span class="pre">_tkinter.Tcl_Obj</span></code>
  1961. object if no Python equivalent exists.</p></li>
  1962. <li><p>Large octal and hex literals such as <code class="docutils literal notranslate"><span class="pre">0xffffffff</span></code> now trigger a
  1963. <a class="reference internal" href="../library/exceptions.html#FutureWarning" title="FutureWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">FutureWarning</span></code></a>. Currently they’re stored as 32-bit numbers and result in a
  1964. negative value, but in Python 2.4 they’ll become positive long integers.</p>
  1965. <p>There are a few ways to fix this warning. If you really need a positive number,
  1966. just add an <code class="docutils literal notranslate"><span class="pre">L</span></code> to the end of the literal. If you’re trying to get a 32-bit
  1967. integer with low bits set and have previously used an expression such as <code class="docutils literal notranslate"><span class="pre">~(1</span>
  1968. <span class="pre">&lt;&lt;</span> <span class="pre">31)</span></code>, it’s probably clearest to start with all bits set and clear the
  1969. desired upper bits. For example, to clear just the top bit (bit 31), you could
  1970. write <code class="docutils literal notranslate"><span class="pre">0xffffffffL</span> <span class="pre">&amp;~(1L&lt;&lt;31)</span></code>.</p>
  1971. </li>
  1972. <li><p>You can no longer disable assertions by assigning to <code class="docutils literal notranslate"><span class="pre">__debug__</span></code>.</p></li>
  1973. <li><p>The Distutils <code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code> function has gained various new keyword arguments
  1974. such as <em>depends</em>. Old versions of the Distutils will abort if passed unknown
  1975. keywords. A solution is to check for the presence of the new
  1976. <code class="xref py py-func docutils literal notranslate"><span class="pre">get_distutil_options()</span></code> function in your <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code> and only uses the
  1977. new keywords with a version of the Distutils that supports them:</p>
  1978. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">distutils</span> <span class="kn">import</span> <span class="n">core</span>
  1979. <span class="n">kw</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;sources&#39;</span><span class="p">:</span> <span class="s1">&#39;foo.c&#39;</span><span class="p">,</span> <span class="o">...</span><span class="p">}</span>
  1980. <span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">core</span><span class="p">,</span> <span class="s1">&#39;get_distutil_options&#39;</span><span class="p">):</span>
  1981. <span class="n">kw</span><span class="p">[</span><span class="s1">&#39;depends&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;foo.h&#39;</span><span class="p">]</span>
  1982. <span class="n">ext</span> <span class="o">=</span> <span class="n">Extension</span><span class="p">(</span><span class="o">**</span><span class="n">kw</span><span class="p">)</span>
  1983. </pre></div>
  1984. </div>
  1985. </li>
  1986. <li><p>Using <code class="docutils literal notranslate"><span class="pre">None</span></code> as a variable name will now result in a <a class="reference internal" href="../library/exceptions.html#SyntaxWarning" title="SyntaxWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxWarning</span></code></a>
  1987. warning.</p></li>
  1988. <li><p>Names of extension types defined by the modules included with Python now
  1989. contain the module and a <code class="docutils literal notranslate"><span class="pre">'.'</span></code> in front of the type name.</p></li>
  1990. </ul>
  1991. </section>
  1992. <section id="acknowledgements">
  1993. <span id="acks"></span><h2>Acknowledgements<a class="headerlink" href="#acknowledgements" title="Link to this heading">¶</a></h2>
  1994. <p>The author would like to thank the following people for offering suggestions,
  1995. corrections and assistance with various drafts of this article: Jeff Bauer,
  1996. Simon Brunning, Brett Cannon, Michael Chermside, Andrew Dalke, Scott David
  1997. Daniels, Fred L. Drake, Jr., David Fraser, Kelly Gerber, Raymond Hettinger,
  1998. Michael Hudson, Chris Lambert, Detlef Lannert, Martin von Löwis, Andrew
  1999. MacIntyre, Lalo Martins, Chad Netzer, Gustavo Niemeyer, Neal Norwitz, Hans
  2000. Nowak, Chris Reedy, Francesco Ricciardi, Vinay Sajip, Neil Schemenauer, Roman
  2001. Suzi, Jason Tishler, Just van Rossum.</p>
  2002. </section>
  2003. </section>
  2004. <div class="clearer"></div>
  2005. </div>
  2006. </div>
  2007. </div>
  2008. <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
  2009. <div class="sphinxsidebarwrapper">
  2010. <div>
  2011. <h3><a href="../contents.html">Table of Contents</a></h3>
  2012. <ul>
  2013. <li><a class="reference internal" href="#">What’s New in Python 2.3</a><ul>
  2014. <li><a class="reference internal" href="#pep-218-a-standard-set-datatype">PEP 218: A Standard Set Datatype</a></li>
  2015. <li><a class="reference internal" href="#pep-255-simple-generators">PEP 255: Simple Generators</a></li>
  2016. <li><a class="reference internal" href="#pep-263-source-code-encodings">PEP 263: Source Code Encodings</a></li>
  2017. <li><a class="reference internal" href="#pep-273-importing-modules-from-zip-archives">PEP 273: Importing Modules from ZIP Archives</a></li>
  2018. <li><a class="reference internal" href="#pep-277-unicode-file-name-support-for-windows-nt">PEP 277: Unicode file name support for Windows NT</a></li>
  2019. <li><a class="reference internal" href="#pep-278-universal-newline-support">PEP 278: Universal Newline Support</a></li>
  2020. <li><a class="reference internal" href="#pep-279-enumerate">PEP 279: enumerate()</a></li>
  2021. <li><a class="reference internal" href="#pep-282-the-logging-package">PEP 282: The logging Package</a></li>
  2022. <li><a class="reference internal" href="#pep-285-a-boolean-type">PEP 285: A Boolean Type</a></li>
  2023. <li><a class="reference internal" href="#pep-293-codec-error-handling-callbacks">PEP 293: Codec Error Handling Callbacks</a></li>
  2024. <li><a class="reference internal" href="#pep-301-package-index-and-metadata-for-distutils">PEP 301: Package Index and Metadata for Distutils</a></li>
  2025. <li><a class="reference internal" href="#pep-302-new-import-hooks">PEP 302: New Import Hooks</a></li>
  2026. <li><a class="reference internal" href="#pep-305-comma-separated-files">PEP 305: Comma-separated Files</a></li>
  2027. <li><a class="reference internal" href="#pep-307-pickle-enhancements">PEP 307: Pickle Enhancements</a></li>
  2028. <li><a class="reference internal" href="#extended-slices">Extended Slices</a></li>
  2029. <li><a class="reference internal" href="#other-language-changes">Other Language Changes</a><ul>
  2030. <li><a class="reference internal" href="#string-changes">String Changes</a></li>
  2031. <li><a class="reference internal" href="#optimizations">Optimizations</a></li>
  2032. </ul>
  2033. </li>
  2034. <li><a class="reference internal" href="#new-improved-and-deprecated-modules">New, Improved, and Deprecated Modules</a><ul>
  2035. <li><a class="reference internal" href="#date-time-type">Date/Time Type</a></li>
  2036. <li><a class="reference internal" href="#the-optparse-module">The optparse Module</a></li>
  2037. </ul>
  2038. </li>
  2039. <li><a class="reference internal" href="#pymalloc-a-specialized-object-allocator">Pymalloc: A Specialized Object Allocator</a></li>
  2040. <li><a class="reference internal" href="#build-and-c-api-changes">Build and C API Changes</a><ul>
  2041. <li><a class="reference internal" href="#port-specific-changes">Port-Specific Changes</a></li>
  2042. </ul>
  2043. </li>
  2044. <li><a class="reference internal" href="#other-changes-and-fixes">Other Changes and Fixes</a></li>
  2045. <li><a class="reference internal" href="#porting-to-python-2-3">Porting to Python 2.3</a></li>
  2046. <li><a class="reference internal" href="#acknowledgements">Acknowledgements</a></li>
  2047. </ul>
  2048. </li>
  2049. </ul>
  2050. </div>
  2051. <div>
  2052. <h4>Previous topic</h4>
  2053. <p class="topless"><a href="2.4.html"
  2054. title="previous chapter">What’s New in Python 2.4</a></p>
  2055. </div>
  2056. <div>
  2057. <h4>Next topic</h4>
  2058. <p class="topless"><a href="2.2.html"
  2059. title="next chapter">What’s New in Python 2.2</a></p>
  2060. </div>
  2061. <div role="note" aria-label="source link">
  2062. <h3>This Page</h3>
  2063. <ul class="this-page-menu">
  2064. <li><a href="../bugs.html">Report a Bug</a></li>
  2065. <li>
  2066. <a href="https://github.com/python/cpython/blob/main/Doc/whatsnew/2.3.rst"
  2067. rel="nofollow">Show Source
  2068. </a>
  2069. </li>
  2070. </ul>
  2071. </div>
  2072. </div>
  2073. <div id="sidebarbutton" title="Collapse sidebar">
  2074. <span>«</span>
  2075. </div>
  2076. </div>
  2077. <div class="clearer"></div>
  2078. </div>
  2079. <div class="related" role="navigation" aria-label="related navigation">
  2080. <h3>Navigation</h3>
  2081. <ul>
  2082. <li class="right" style="margin-right: 10px">
  2083. <a href="../genindex.html" title="General Index"
  2084. >index</a></li>
  2085. <li class="right" >
  2086. <a href="../py-modindex.html" title="Python Module Index"
  2087. >modules</a> |</li>
  2088. <li class="right" >
  2089. <a href="2.2.html" title="What’s New in Python 2.2"
  2090. >next</a> |</li>
  2091. <li class="right" >
  2092. <a href="2.4.html" title="What’s New in Python 2.4"
  2093. >previous</a> |</li>
  2094. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  2095. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  2096. <li class="switchers">
  2097. <div class="language_switcher_placeholder"></div>
  2098. <div class="version_switcher_placeholder"></div>
  2099. </li>
  2100. <li>
  2101. </li>
  2102. <li id="cpython-language-and-version">
  2103. <a href="../index.html">3.12.3 Documentation</a> &#187;
  2104. </li>
  2105. <li class="nav-item nav-item-1"><a href="index.html" >What’s New in Python</a> &#187;</li>
  2106. <li class="nav-item nav-item-this"><a href="">What’s New in Python 2.3</a></li>
  2107. <li class="right">
  2108. <div class="inline-search" role="search">
  2109. <form class="inline-search" action="../search.html" method="get">
  2110. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  2111. <input type="submit" value="Go" />
  2112. </form>
  2113. </div>
  2114. |
  2115. </li>
  2116. <li class="right">
  2117. <label class="theme-selector-label">
  2118. Theme
  2119. <select class="theme-selector" oninput="activateTheme(this.value)">
  2120. <option value="auto" selected>Auto</option>
  2121. <option value="light">Light</option>
  2122. <option value="dark">Dark</option>
  2123. </select>
  2124. </label> |</li>
  2125. </ul>
  2126. </div>
  2127. <div class="footer">
  2128. &copy;
  2129. <a href="../copyright.html">
  2130. Copyright
  2131. </a>
  2132. 2001-2024, Python Software Foundation.
  2133. <br />
  2134. This page is licensed under the Python Software Foundation License Version 2.
  2135. <br />
  2136. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  2137. <br />
  2138. See <a href="/license.html">History and License</a> for more information.<br />
  2139. <br />
  2140. The Python Software Foundation is a non-profit corporation.
  2141. <a href="https://www.python.org/psf/donations/">Please donate.</a>
  2142. <br />
  2143. <br />
  2144. Last updated on Apr 09, 2024 (13:47 UTC).
  2145. <a href="/bugs.html">Found a bug</a>?
  2146. <br />
  2147. Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 7.2.6.
  2148. </div>
  2149. </body>
  2150. </html>
上海开阖软件有限公司 沪ICP备12045867号-1