gooderp18绿色标准版
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

3380 行
360KB

  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.6" />
  7. <meta property="og:type" content="website" />
  8. <meta property="og:url" content="https://docs.python.org/3/whatsnew/2.6.html" />
  9. <meta property="og:site_name" content="Python documentation" />
  10. <meta property="og:description" content="Author, A.M. Kuchling (amk at amk.ca),. This article explains the new features in Python 2.6, released on October 1, 2008. The release schedule is described in PEP 361. The major theme of Python 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 (amk at amk.ca),. This article explains the new features in Python 2.6, released on October 1, 2008. The release schedule is described in PEP 361. The major theme of Python 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.6 &#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.5" href="2.5.html" />
  33. <link rel="prev" title="What’s New in Python 2.7" href="2.7.html" />
  34. <link rel="canonical" href="https://docs.python.org/3/whatsnew/2.6.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.6</a><ul>
  86. <li><a class="reference internal" href="#python-3-0">Python 3.0</a></li>
  87. <li><a class="reference internal" href="#changes-to-the-development-process">Changes to the Development Process</a><ul>
  88. <li><a class="reference internal" href="#new-issue-tracker-roundup">New Issue Tracker: Roundup</a></li>
  89. <li><a class="reference internal" href="#new-documentation-format-restructuredtext-using-sphinx">New Documentation Format: reStructuredText Using Sphinx</a></li>
  90. </ul>
  91. </li>
  92. <li><a class="reference internal" href="#pep-343-the-with-statement">PEP 343: The ‘with’ statement</a><ul>
  93. <li><a class="reference internal" href="#writing-context-managers">Writing Context Managers</a></li>
  94. <li><a class="reference internal" href="#the-contextlib-module">The contextlib module</a></li>
  95. </ul>
  96. </li>
  97. <li><a class="reference internal" href="#pep-366-explicit-relative-imports-from-a-main-module">PEP 366: Explicit Relative Imports From a Main Module</a></li>
  98. <li><a class="reference internal" href="#pep-370-per-user-site-packages-directory">PEP 370: Per-user <code class="docutils literal notranslate"><span class="pre">site-packages</span></code> Directory</a></li>
  99. <li><a class="reference internal" href="#pep-371-the-multiprocessing-package">PEP 371: The <code class="docutils literal notranslate"><span class="pre">multiprocessing</span></code> Package</a></li>
  100. <li><a class="reference internal" href="#pep-3101-advanced-string-formatting">PEP 3101: Advanced String Formatting</a></li>
  101. <li><a class="reference internal" href="#pep-3105-print-as-a-function">PEP 3105: <code class="docutils literal notranslate"><span class="pre">print</span></code> As a Function</a></li>
  102. <li><a class="reference internal" href="#pep-3110-exception-handling-changes">PEP 3110: Exception-Handling Changes</a></li>
  103. <li><a class="reference internal" href="#pep-3112-byte-literals">PEP 3112: Byte Literals</a></li>
  104. <li><a class="reference internal" href="#pep-3116-new-i-o-library">PEP 3116: New I/O Library</a></li>
  105. <li><a class="reference internal" href="#pep-3118-revised-buffer-protocol">PEP 3118: Revised Buffer Protocol</a></li>
  106. <li><a class="reference internal" href="#pep-3119-abstract-base-classes">PEP 3119: Abstract Base Classes</a></li>
  107. <li><a class="reference internal" href="#pep-3127-integer-literal-support-and-syntax">PEP 3127: Integer Literal Support and Syntax</a></li>
  108. <li><a class="reference internal" href="#pep-3129-class-decorators">PEP 3129: Class Decorators</a></li>
  109. <li><a class="reference internal" href="#pep-3141-a-type-hierarchy-for-numbers">PEP 3141: A Type Hierarchy for Numbers</a><ul>
  110. <li><a class="reference internal" href="#the-fractions-module">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">fractions</span></code> Module</a></li>
  111. </ul>
  112. </li>
  113. <li><a class="reference internal" href="#other-language-changes">Other Language Changes</a><ul>
  114. <li><a class="reference internal" href="#optimizations">Optimizations</a></li>
  115. <li><a class="reference internal" href="#interpreter-changes">Interpreter Changes</a></li>
  116. </ul>
  117. </li>
  118. <li><a class="reference internal" href="#new-and-improved-modules">New and Improved Modules</a><ul>
  119. <li><a class="reference internal" href="#the-ast-module">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">ast</span></code> module</a></li>
  120. <li><a class="reference internal" href="#the-future-builtins-module">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">future_builtins</span></code> module</a></li>
  121. <li><a class="reference internal" href="#the-json-module-javascript-object-notation">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code> module: JavaScript Object Notation</a></li>
  122. <li><a class="reference internal" href="#the-plistlib-module-a-property-list-parser">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">plistlib</span></code> module: A Property-List Parser</a></li>
  123. <li><a class="reference internal" href="#ctypes-enhancements">ctypes Enhancements</a></li>
  124. <li><a class="reference internal" href="#improved-ssl-support">Improved SSL Support</a></li>
  125. </ul>
  126. </li>
  127. <li><a class="reference internal" href="#deprecations-and-removals">Deprecations and Removals</a></li>
  128. <li><a class="reference internal" href="#build-and-c-api-changes">Build and C API Changes</a><ul>
  129. <li><a class="reference internal" href="#port-specific-changes-windows">Port-Specific Changes: Windows</a></li>
  130. <li><a class="reference internal" href="#port-specific-changes-mac-os-x">Port-Specific Changes: Mac OS X</a></li>
  131. <li><a class="reference internal" href="#port-specific-changes-irix">Port-Specific Changes: IRIX</a></li>
  132. </ul>
  133. </li>
  134. <li><a class="reference internal" href="#porting-to-python-2-6">Porting to Python 2.6</a></li>
  135. <li><a class="reference internal" href="#acknowledgements">Acknowledgements</a></li>
  136. </ul>
  137. </li>
  138. </ul>
  139. </div>
  140. <div>
  141. <h4>Previous topic</h4>
  142. <p class="topless"><a href="2.7.html"
  143. title="previous chapter">What’s New in Python 2.7</a></p>
  144. </div>
  145. <div>
  146. <h4>Next topic</h4>
  147. <p class="topless"><a href="2.5.html"
  148. title="next chapter">What’s New in Python 2.5</a></p>
  149. </div>
  150. <div role="note" aria-label="source link">
  151. <h3>This Page</h3>
  152. <ul class="this-page-menu">
  153. <li><a href="../bugs.html">Report a Bug</a></li>
  154. <li>
  155. <a href="https://github.com/python/cpython/blob/main/Doc/whatsnew/2.6.rst"
  156. rel="nofollow">Show Source
  157. </a>
  158. </li>
  159. </ul>
  160. </div>
  161. </nav>
  162. </div>
  163. </div>
  164. <div class="related" role="navigation" aria-label="related navigation">
  165. <h3>Navigation</h3>
  166. <ul>
  167. <li class="right" style="margin-right: 10px">
  168. <a href="../genindex.html" title="General Index"
  169. accesskey="I">index</a></li>
  170. <li class="right" >
  171. <a href="../py-modindex.html" title="Python Module Index"
  172. >modules</a> |</li>
  173. <li class="right" >
  174. <a href="2.5.html" title="What’s New in Python 2.5"
  175. accesskey="N">next</a> |</li>
  176. <li class="right" >
  177. <a href="2.7.html" title="What’s New in Python 2.7"
  178. accesskey="P">previous</a> |</li>
  179. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  180. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  181. <li class="switchers">
  182. <div class="language_switcher_placeholder"></div>
  183. <div class="version_switcher_placeholder"></div>
  184. </li>
  185. <li>
  186. </li>
  187. <li id="cpython-language-and-version">
  188. <a href="../index.html">3.12.3 Documentation</a> &#187;
  189. </li>
  190. <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">What’s New in Python</a> &#187;</li>
  191. <li class="nav-item nav-item-this"><a href="">What’s New in Python 2.6</a></li>
  192. <li class="right">
  193. <div class="inline-search" role="search">
  194. <form class="inline-search" action="../search.html" method="get">
  195. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  196. <input type="submit" value="Go" />
  197. </form>
  198. </div>
  199. |
  200. </li>
  201. <li class="right">
  202. <label class="theme-selector-label">
  203. Theme
  204. <select class="theme-selector" oninput="activateTheme(this.value)">
  205. <option value="auto" selected>Auto</option>
  206. <option value="light">Light</option>
  207. <option value="dark">Dark</option>
  208. </select>
  209. </label> |</li>
  210. </ul>
  211. </div>
  212. <div class="document">
  213. <div class="documentwrapper">
  214. <div class="bodywrapper">
  215. <div class="body" role="main">
  216. <section id="what-s-new-in-python-2-6">
  217. <span id="whats-new-in-2-6"></span><h1>What’s New in Python 2.6<a class="headerlink" href="#what-s-new-in-python-2-6" title="Link to this heading">¶</a></h1>
  218. <dl class="field-list simple">
  219. <dt class="field-odd">Author<span class="colon">:</span></dt>
  220. <dd class="field-odd"><p>A.M. Kuchling (amk at amk.ca)</p>
  221. </dd>
  222. </dl>
  223. <p>This article explains the new features in Python 2.6, released on October 1,
  224. 2008. The release schedule is described in <span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0361/"><strong>PEP 361</strong></a>.</p>
  225. <p>The major theme of Python 2.6 is preparing the migration path to
  226. Python 3.0, a major redesign of the language. Whenever possible,
  227. Python 2.6 incorporates new features and syntax from 3.0 while
  228. remaining compatible with existing code by not removing older features
  229. or syntax. When it’s not possible to do that, Python 2.6 tries to do
  230. what it can, adding compatibility functions in a
  231. <code class="xref py py-mod docutils literal notranslate"><span class="pre">future_builtins</span></code> module and a <code class="xref std std-option docutils literal notranslate"><span class="pre">-3</span></code> switch to warn about
  232. usages that will become unsupported in 3.0.</p>
  233. <p>Some significant new packages have been added to the standard library,
  234. such as the <a class="reference internal" href="../library/multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> and <a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> modules, but
  235. there aren’t many new features that aren’t related to Python 3.0 in
  236. some way.</p>
  237. <p>Python 2.6 also sees a number of improvements and bugfixes throughout
  238. the source. A search through the change logs finds there were 259
  239. patches applied and 612 bugs fixed between Python 2.5 and 2.6. Both
  240. figures are likely to be underestimates.</p>
  241. <p>This article doesn’t attempt to provide a complete specification of
  242. the new features, but instead provides a convenient overview. For
  243. full details, you should refer to the documentation for Python 2.6. If
  244. you want to understand the rationale for the design and
  245. implementation, refer to the PEP for a particular new feature.
  246. Whenever possible, “What’s New in Python” links to the bug/patch item
  247. for each change.</p>
  248. <section id="python-3-0">
  249. <h2>Python 3.0<a class="headerlink" href="#python-3-0" title="Link to this heading">¶</a></h2>
  250. <p>The development cycle for Python versions 2.6 and 3.0 was
  251. synchronized, with the alpha and beta releases for both versions being
  252. made on the same days. The development of 3.0 has influenced many
  253. features in 2.6.</p>
  254. <p>Python 3.0 is a far-ranging redesign of Python that breaks
  255. compatibility with the 2.x series. This means that existing Python
  256. code will need some conversion in order to run on
  257. Python 3.0. However, not all the changes in 3.0 necessarily break
  258. compatibility. In cases where new features won’t cause existing code
  259. to break, they’ve been backported to 2.6 and are described in this
  260. document in the appropriate place. Some of the 3.0-derived features
  261. are:</p>
  262. <ul class="simple">
  263. <li><p>A <code class="xref py py-meth docutils literal notranslate"><span class="pre">__complex__()</span></code> method for converting objects to a complex number.</p></li>
  264. <li><p>Alternate syntax for catching exceptions: <code class="docutils literal notranslate"><span class="pre">except</span> <span class="pre">TypeError</span> <span class="pre">as</span> <span class="pre">exc</span></code>.</p></li>
  265. <li><p>The addition of <a class="reference internal" href="../library/functools.html#functools.reduce" title="functools.reduce"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.reduce()</span></code></a> as a synonym for the built-in
  266. <code class="xref py py-func docutils literal notranslate"><span class="pre">reduce()</span></code> function.</p></li>
  267. </ul>
  268. <p>Python 3.0 adds several new built-in functions and changes the
  269. semantics of some existing builtins. Functions that are new in 3.0
  270. such as <a class="reference internal" href="../library/functions.html#bin" title="bin"><code class="xref py py-func docutils literal notranslate"><span class="pre">bin()</span></code></a> have simply been added to Python 2.6, but existing
  271. builtins haven’t been changed; instead, the <code class="xref py py-mod docutils literal notranslate"><span class="pre">future_builtins</span></code>
  272. module has versions with the new 3.0 semantics. Code written to be
  273. compatible with 3.0 can do <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">future_builtins</span> <span class="pre">import</span> <span class="pre">hex,</span> <span class="pre">map</span></code> as
  274. necessary.</p>
  275. <p>A new command-line switch, <code class="xref std std-option docutils literal notranslate"><span class="pre">-3</span></code>, enables warnings
  276. about features that will be removed in Python 3.0. You can run code
  277. with this switch to see how much work will be necessary to port
  278. code to 3.0. The value of this switch is available
  279. to Python code as the boolean variable <code class="xref py py-data docutils literal notranslate"><span class="pre">sys.py3kwarning</span></code>,
  280. and to C extension code as <code class="xref c c-data docutils literal notranslate"><span class="pre">Py_Py3kWarningFlag</span></code>.</p>
  281. <div class="admonition seealso">
  282. <p class="admonition-title">See also</p>
  283. <p>The 3<em>xxx</em> series of PEPs, which contains proposals for Python 3.0.
  284. <span class="target" id="index-1"></span><a class="pep reference external" href="https://peps.python.org/pep-3000/"><strong>PEP 3000</strong></a> describes the development process for Python 3.0.
  285. Start with <span class="target" id="index-2"></span><a class="pep reference external" href="https://peps.python.org/pep-3100/"><strong>PEP 3100</strong></a> that describes the general goals for Python
  286. 3.0, and then explore the higher-numbered PEPs that propose
  287. specific features.</p>
  288. </div>
  289. </section>
  290. <section id="changes-to-the-development-process">
  291. <h2>Changes to the Development Process<a class="headerlink" href="#changes-to-the-development-process" title="Link to this heading">¶</a></h2>
  292. <p>While 2.6 was being developed, the Python development process
  293. underwent two significant changes: we switched from SourceForge’s
  294. issue tracker to a customized Roundup installation, and the
  295. documentation was converted from LaTeX to reStructuredText.</p>
  296. <section id="new-issue-tracker-roundup">
  297. <h3>New Issue Tracker: Roundup<a class="headerlink" href="#new-issue-tracker-roundup" title="Link to this heading">¶</a></h3>
  298. <p>For a long time, the Python developers had been growing increasingly
  299. annoyed by SourceForge’s bug tracker. SourceForge’s hosted solution
  300. doesn’t permit much customization; for example, it wasn’t possible to
  301. customize the life cycle of issues.</p>
  302. <p>The infrastructure committee of the Python Software Foundation
  303. therefore posted a call for issue trackers, asking volunteers to set
  304. up different products and import some of the bugs and patches from
  305. SourceForge. Four different trackers were examined: <a class="reference external" href="https://www.atlassian.com/software/jira/">Jira</a>,
  306. <a class="reference external" href="https://launchpad.net/">Launchpad</a>,
  307. <a class="reference external" href="https://roundup.sourceforge.io/">Roundup</a>, and
  308. <a class="reference external" href="https://trac.edgewall.org/">Trac</a>.
  309. The committee eventually settled on Jira
  310. and Roundup as the two candidates. Jira is a commercial product that
  311. offers no-cost hosted instances to free-software projects; Roundup
  312. is an open-source project that requires volunteers
  313. to administer it and a server to host it.</p>
  314. <p>After posting a call for volunteers, a new Roundup installation was
  315. set up at <a class="reference external" href="https://bugs.python.org">https://bugs.python.org</a>. One installation of Roundup can
  316. host multiple trackers, and this server now also hosts issue trackers
  317. for Jython and for the Python web site. It will surely find
  318. other uses in the future. Where possible,
  319. this edition of “What’s New in Python” links to the bug/patch
  320. item for each change.</p>
  321. <p>Hosting of the Python bug tracker is kindly provided by
  322. <a class="reference external" href="https://upfrontsoftware.co.za">Upfront Systems</a>
  323. of Stellenbosch, South Africa. Martin von Löwis put a
  324. lot of effort into importing existing bugs and patches from
  325. SourceForge; his scripts for this import operation are at
  326. <code class="docutils literal notranslate"><span class="pre">https://svn.python.org/view/tracker/importer/</span></code> and may be useful to
  327. other projects wishing to move from SourceForge to Roundup.</p>
  328. <div class="admonition seealso">
  329. <p class="admonition-title">See also</p>
  330. <dl class="simple">
  331. <dt><a class="reference external" href="https://bugs.python.org">https://bugs.python.org</a></dt><dd><p>The Python bug tracker.</p>
  332. </dd>
  333. <dt><a class="reference external" href="https://bugs.jython.org">https://bugs.jython.org</a>:</dt><dd><p>The Jython bug tracker.</p>
  334. </dd>
  335. <dt><a class="reference external" href="https://roundup.sourceforge.io/">https://roundup.sourceforge.io/</a></dt><dd><p>Roundup downloads and documentation.</p>
  336. </dd>
  337. <dt><a class="reference external" href="https://svn.python.org/view/tracker/importer/">https://svn.python.org/view/tracker/importer/</a></dt><dd><p>Martin von Löwis’s conversion scripts.</p>
  338. </dd>
  339. </dl>
  340. </div>
  341. </section>
  342. <section id="new-documentation-format-restructuredtext-using-sphinx">
  343. <h3>New Documentation Format: reStructuredText Using Sphinx<a class="headerlink" href="#new-documentation-format-restructuredtext-using-sphinx" title="Link to this heading">¶</a></h3>
  344. <p>The Python documentation was written using LaTeX since the project
  345. started around 1989. In the 1980s and early 1990s, most documentation
  346. was printed out for later study, not viewed online. LaTeX was widely
  347. used because it provided attractive printed output while remaining
  348. straightforward to write once the basic rules of the markup were
  349. learned.</p>
  350. <p>Today LaTeX is still used for writing publications destined for
  351. printing, but the landscape for programming tools has shifted. We no
  352. longer print out reams of documentation; instead, we browse through it
  353. online and HTML has become the most important format to support.
  354. Unfortunately, converting LaTeX to HTML is fairly complicated and Fred
  355. L. Drake Jr., the long-time Python documentation editor, spent a lot
  356. of time maintaining the conversion process. Occasionally people would
  357. suggest converting the documentation into SGML and later XML, but
  358. performing a good conversion is a major task and no one ever committed
  359. the time required to finish the job.</p>
  360. <p>During the 2.6 development cycle, Georg Brandl put a lot of effort
  361. into building a new toolchain for processing the documentation. The
  362. resulting package is called Sphinx, and is available from
  363. <a class="reference external" href="https://www.sphinx-doc.org/">https://www.sphinx-doc.org/</a>.</p>
  364. <p>Sphinx concentrates on HTML output, producing attractively styled and
  365. modern HTML; printed output is still supported through conversion to
  366. LaTeX. The input format is reStructuredText, a markup syntax
  367. supporting custom extensions and directives that is commonly used in
  368. the Python community.</p>
  369. <p>Sphinx is a standalone package that can be used for writing, and
  370. almost two dozen other projects
  371. (<a class="reference external" href="https://www.sphinx-doc.org/en/master/examples.html">listed on the Sphinx web site</a>)
  372. have adopted Sphinx as their documentation tool.</p>
  373. <div class="admonition seealso">
  374. <p class="admonition-title">See also</p>
  375. <dl class="simple">
  376. <dt><a class="reference external" href="https://devguide.python.org/documenting/">Documenting Python</a></dt><dd><p>Describes how to write for Python’s documentation.</p>
  377. </dd>
  378. <dt><a class="reference external" href="https://www.sphinx-doc.org/">Sphinx</a></dt><dd><p>Documentation and code for the Sphinx toolchain.</p>
  379. </dd>
  380. <dt><a class="reference external" href="https://docutils.sourceforge.io">Docutils</a></dt><dd><p>The underlying reStructuredText parser and toolset.</p>
  381. </dd>
  382. </dl>
  383. </div>
  384. </section>
  385. </section>
  386. <section id="pep-343-the-with-statement">
  387. <span id="pep-0343"></span><h2>PEP 343: The ‘with’ statement<a class="headerlink" href="#pep-343-the-with-statement" title="Link to this heading">¶</a></h2>
  388. <p>The previous version, Python 2.5, added the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’
  389. statement as an optional feature, to be enabled by a <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span>
  390. <span class="pre">import</span> <span class="pre">with_statement</span></code> directive. In 2.6 the statement no longer needs to
  391. be specially enabled; this means that <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> is now always a
  392. keyword. The rest of this section is a copy of the corresponding
  393. section from the “What’s New in Python 2.5” document; if you’re
  394. familiar with the ‘<code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code>’ statement
  395. from Python 2.5, you can skip this section.</p>
  396. <p>The ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement clarifies code that previously would use
  397. <code class="docutils literal notranslate"><span class="pre">try...finally</span></code> blocks to ensure that clean-up code is executed. In this
  398. section, I’ll discuss the statement as it will commonly be used. In the next
  399. section, I’ll examine the implementation details and show how to write objects
  400. for use with this statement.</p>
  401. <p>The ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement is a control-flow structure whose basic
  402. structure is:</p>
  403. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">expression</span> <span class="p">[</span><span class="k">as</span> <span class="n">variable</span><span class="p">]:</span>
  404. <span class="k">with</span><span class="o">-</span><span class="n">block</span>
  405. </pre></div>
  406. </div>
  407. <p>The expression is evaluated, and it should result in an object that supports the
  408. context management protocol (that is, has <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a>
  409. methods).</p>
  410. <p>The object’s <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> is called before <em>with-block</em> is executed and
  411. therefore can run set-up code. It also may return a value that is bound to the
  412. name <em>variable</em>, if given. (Note carefully that <em>variable</em> is <em>not</em> assigned
  413. the result of <em>expression</em>.)</p>
  414. <p>After execution of the <em>with-block</em> is finished, the object’s <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a>
  415. method is called, even if the block raised an exception, and can therefore run
  416. clean-up code.</p>
  417. <p>Some standard Python objects now support the context management protocol and can
  418. be used with the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement. File objects are one example:</p>
  419. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/etc/passwd&#39;</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
  420. <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
  421. <span class="nb">print</span> <span class="n">line</span>
  422. <span class="o">...</span> <span class="n">more</span> <span class="n">processing</span> <span class="n">code</span> <span class="o">...</span>
  423. </pre></div>
  424. </div>
  425. <p>After this statement has executed, the file object in <em>f</em> will have been
  426. automatically closed, even if the <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loop raised an exception
  427. part-way through the block.</p>
  428. <div class="admonition note">
  429. <p class="admonition-title">Note</p>
  430. <p>In this case, <em>f</em> is the same object created by <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>, because
  431. <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> returns <em>self</em>.</p>
  432. </div>
  433. <p>The <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> module’s locks and condition variables also support the
  434. ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement:</p>
  435. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">lock</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">Lock</span><span class="p">()</span>
  436. <span class="k">with</span> <span class="n">lock</span><span class="p">:</span>
  437. <span class="c1"># Critical section of code</span>
  438. <span class="o">...</span>
  439. </pre></div>
  440. </div>
  441. <p>The lock is acquired before the block is executed and always released once the
  442. block is complete.</p>
  443. <p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">localcontext()</span></code> function in the <a class="reference internal" href="../library/decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> module makes it easy
  444. to save and restore the current decimal context, which encapsulates the desired
  445. precision and rounding characteristics for computations:</p>
  446. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">decimal</span> <span class="kn">import</span> <span class="n">Decimal</span><span class="p">,</span> <span class="n">Context</span><span class="p">,</span> <span class="n">localcontext</span>
  447. <span class="c1"># Displays with default precision of 28 digits</span>
  448. <span class="n">v</span> <span class="o">=</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;578&#39;</span><span class="p">)</span>
  449. <span class="nb">print</span> <span class="n">v</span><span class="o">.</span><span class="n">sqrt</span><span class="p">()</span>
  450. <span class="k">with</span> <span class="n">localcontext</span><span class="p">(</span><span class="n">Context</span><span class="p">(</span><span class="n">prec</span><span class="o">=</span><span class="mi">16</span><span class="p">)):</span>
  451. <span class="c1"># All code in this block uses a precision of 16 digits.</span>
  452. <span class="c1"># The original context is restored on exiting the block.</span>
  453. <span class="nb">print</span> <span class="n">v</span><span class="o">.</span><span class="n">sqrt</span><span class="p">()</span>
  454. </pre></div>
  455. </div>
  456. <section id="writing-context-managers">
  457. <span id="new-26-context-managers"></span><h3>Writing Context Managers<a class="headerlink" href="#writing-context-managers" title="Link to this heading">¶</a></h3>
  458. <p>Under the hood, the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement is fairly complicated. Most
  459. people will only use ‘<code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code>’ in company with existing objects and
  460. don’t need to know these details, so you can skip the rest of this section if
  461. you like. Authors of new objects will need to understand the details of the
  462. underlying implementation and should keep reading.</p>
  463. <p>A high-level explanation of the context management protocol is:</p>
  464. <ul class="simple">
  465. <li><p>The expression is evaluated and should result in an object called a “context
  466. manager”. The context manager must have <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a>
  467. methods.</p></li>
  468. <li><p>The context manager’s <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> method is called. The value returned
  469. is assigned to <em>VAR</em>. If no <code class="docutils literal notranslate"><span class="pre">as</span> <span class="pre">VAR</span></code> clause is present, the value is simply
  470. discarded.</p></li>
  471. <li><p>The code in <em>BLOCK</em> is executed.</p></li>
  472. <li><p>If <em>BLOCK</em> raises an exception, the context manager’s <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method
  473. is called with three arguments, the exception details (<code class="docutils literal notranslate"><span class="pre">type,</span> <span class="pre">value,</span> <span class="pre">traceback</span></code>,
  474. the same values returned by <a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>, which can also be <code class="docutils literal notranslate"><span class="pre">None</span></code>
  475. if no exception occurred). The method’s return value controls whether an exception
  476. is re-raised: any false value re-raises the exception, and <code class="docutils literal notranslate"><span class="pre">True</span></code> will result
  477. in suppressing it. You’ll only rarely want to suppress the exception, because
  478. if you do the author of the code containing the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement will
  479. never realize anything went wrong.</p></li>
  480. <li><p>If <em>BLOCK</em> didn’t raise an exception, the <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method is still
  481. called, but <em>type</em>, <em>value</em>, and <em>traceback</em> are all <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p></li>
  482. </ul>
  483. <p>Let’s think through an example. I won’t present detailed code but will only
  484. sketch the methods necessary for a database that supports transactions.</p>
  485. <p>(For people unfamiliar with database terminology: a set of changes to the
  486. database are grouped into a transaction. Transactions can be either committed,
  487. meaning that all the changes are written into the database, or rolled back,
  488. meaning that the changes are all discarded and the database is unchanged. See
  489. any database textbook for more information.)</p>
  490. <p>Let’s assume there’s an object representing a database connection. Our goal will
  491. be to let the user write code like this:</p>
  492. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">db_connection</span> <span class="o">=</span> <span class="n">DatabaseConnection</span><span class="p">()</span>
  493. <span class="k">with</span> <span class="n">db_connection</span> <span class="k">as</span> <span class="n">cursor</span><span class="p">:</span>
  494. <span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">&#39;insert into ...&#39;</span><span class="p">)</span>
  495. <span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">&#39;delete from ...&#39;</span><span class="p">)</span>
  496. <span class="c1"># ... more operations ...</span>
  497. </pre></div>
  498. </div>
  499. <p>The transaction should be committed if the code in the block runs flawlessly or
  500. rolled back if there’s an exception. Here’s the basic interface for
  501. <code class="xref py py-class docutils literal notranslate"><span class="pre">DatabaseConnection</span></code> that I’ll assume:</p>
  502. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">DatabaseConnection</span><span class="p">:</span>
  503. <span class="c1"># Database interface</span>
  504. <span class="k">def</span> <span class="nf">cursor</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  505. <span class="s2">&quot;Returns a cursor object and starts a new transaction&quot;</span>
  506. <span class="k">def</span> <span class="nf">commit</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  507. <span class="s2">&quot;Commits current transaction&quot;</span>
  508. <span class="k">def</span> <span class="nf">rollback</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  509. <span class="s2">&quot;Rolls back current transaction&quot;</span>
  510. </pre></div>
  511. </div>
  512. <p>The <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> method is pretty easy, having only to start a new
  513. transaction. For this application the resulting cursor object would be a useful
  514. result, so the method will return it. The user can then add <code class="docutils literal notranslate"><span class="pre">as</span> <span class="pre">cursor</span></code> to
  515. their ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement to bind the cursor to a variable name.</p>
  516. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">DatabaseConnection</span><span class="p">:</span>
  517. <span class="o">...</span>
  518. <span class="k">def</span> <span class="fm">__enter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  519. <span class="c1"># Code to start a new transaction</span>
  520. <span class="n">cursor</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
  521. <span class="k">return</span> <span class="n">cursor</span>
  522. </pre></div>
  523. </div>
  524. <p>The <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method is the most complicated because it’s where most of
  525. the work has to be done. The method has to check if an exception occurred. If
  526. there was no exception, the transaction is committed. The transaction is rolled
  527. back if there was an exception.</p>
  528. <p>In the code below, execution will just fall off the end of the function,
  529. returning the default value of <code class="docutils literal notranslate"><span class="pre">None</span></code>. <code class="docutils literal notranslate"><span class="pre">None</span></code> is false, so the exception
  530. will be re-raised automatically. If you wished, you could be more explicit and
  531. add 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 at the marked location.</p>
  532. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">DatabaseConnection</span><span class="p">:</span>
  533. <span class="o">...</span>
  534. <span class="k">def</span> <span class="fm">__exit__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="nb">type</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">tb</span><span class="p">):</span>
  535. <span class="k">if</span> <span class="n">tb</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
  536. <span class="c1"># No exception, so commit</span>
  537. <span class="bp">self</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
  538. <span class="k">else</span><span class="p">:</span>
  539. <span class="c1"># Exception occurred, so rollback.</span>
  540. <span class="bp">self</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
  541. <span class="c1"># return False</span>
  542. </pre></div>
  543. </div>
  544. </section>
  545. <section id="the-contextlib-module">
  546. <span id="new-module-contextlib"></span><h3>The contextlib module<a class="headerlink" href="#the-contextlib-module" title="Link to this heading">¶</a></h3>
  547. <p>The <a class="reference internal" href="../library/contextlib.html#module-contextlib" title="contextlib: Utilities for with-statement contexts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextlib</span></code></a> module provides some functions and a decorator that
  548. are useful when writing objects for use with the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement.</p>
  549. <p>The decorator is called <code class="xref py py-func docutils literal notranslate"><span class="pre">contextmanager()</span></code>, and lets you write a single
  550. generator function instead of defining a new class. The generator should yield
  551. exactly one value. The code up to 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> will be executed as the
  552. <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> method, and the value yielded will be the method’s return
  553. value that will get bound to the variable in the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement’s
  554. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code> clause, if any. The code after the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code> will be
  555. executed in the <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method. Any exception raised in the block will
  556. be raised by the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code> statement.</p>
  557. <p>Using this decorator, our database example from the previous section
  558. could be written as:</p>
  559. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">contextmanager</span>
  560. <span class="nd">@contextmanager</span>
  561. <span class="k">def</span> <span class="nf">db_transaction</span><span class="p">(</span><span class="n">connection</span><span class="p">):</span>
  562. <span class="n">cursor</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
  563. <span class="k">try</span><span class="p">:</span>
  564. <span class="k">yield</span> <span class="n">cursor</span>
  565. <span class="k">except</span><span class="p">:</span>
  566. <span class="n">connection</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
  567. <span class="k">raise</span>
  568. <span class="k">else</span><span class="p">:</span>
  569. <span class="n">connection</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
  570. <span class="n">db</span> <span class="o">=</span> <span class="n">DatabaseConnection</span><span class="p">()</span>
  571. <span class="k">with</span> <span class="n">db_transaction</span><span class="p">(</span><span class="n">db</span><span class="p">)</span> <span class="k">as</span> <span class="n">cursor</span><span class="p">:</span>
  572. <span class="o">...</span>
  573. </pre></div>
  574. </div>
  575. <p>The <a class="reference internal" href="../library/contextlib.html#module-contextlib" title="contextlib: Utilities for with-statement contexts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextlib</span></code></a> module also has a <code class="docutils literal notranslate"><span class="pre">nested(mgr1,</span> <span class="pre">mgr2,</span> <span class="pre">...)</span></code> function
  576. that combines a number of context managers so you don’t need to write nested
  577. ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statements. In this example, the single ‘<code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code>’
  578. statement both starts a database transaction and acquires a thread lock:</p>
  579. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">lock</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">Lock</span><span class="p">()</span>
  580. <span class="k">with</span> <span class="n">nested</span> <span class="p">(</span><span class="n">db_transaction</span><span class="p">(</span><span class="n">db</span><span class="p">),</span> <span class="n">lock</span><span class="p">)</span> <span class="k">as</span> <span class="p">(</span><span class="n">cursor</span><span class="p">,</span> <span class="n">locked</span><span class="p">):</span>
  581. <span class="o">...</span>
  582. </pre></div>
  583. </div>
  584. <p>Finally, the <code class="xref py py-func docutils literal notranslate"><span class="pre">closing()</span></code> function returns its argument so that it can be
  585. bound to a variable, and calls the argument’s <code class="docutils literal notranslate"><span class="pre">.close()</span></code> method at the end
  586. of the block.</p>
  587. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">urllib</span><span class="o">,</span> <span class="nn">sys</span>
  588. <span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">closing</span>
  589. <span class="k">with</span> <span class="n">closing</span><span class="p">(</span><span class="n">urllib</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="s1">&#39;http://www.yahoo.com&#39;</span><span class="p">))</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
  590. <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
  591. <span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">line</span><span class="p">)</span>
  592. </pre></div>
  593. </div>
  594. <div class="admonition seealso">
  595. <p class="admonition-title">See also</p>
  596. <dl class="simple">
  597. <dt><span class="target" id="index-3"></span><a class="pep reference external" href="https://peps.python.org/pep-0343/"><strong>PEP 343</strong></a> - The “with” statement</dt><dd><p>PEP written by Guido van Rossum and Nick Coghlan; implemented by Mike Bland,
  598. Guido van Rossum, and Neal Norwitz. The PEP shows the code generated for a
  599. ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement, which can be helpful in learning how the statement
  600. works.</p>
  601. </dd>
  602. </dl>
  603. <p>The documentation for the <a class="reference internal" href="../library/contextlib.html#module-contextlib" title="contextlib: Utilities for with-statement contexts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextlib</span></code></a> module.</p>
  604. </div>
  605. </section>
  606. </section>
  607. <section id="pep-366-explicit-relative-imports-from-a-main-module">
  608. <span id="pep-0366"></span><h2>PEP 366: Explicit Relative Imports From a Main Module<a class="headerlink" href="#pep-366-explicit-relative-imports-from-a-main-module" title="Link to this heading">¶</a></h2>
  609. <p>Python’s <a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal notranslate"><span class="pre">-m</span></code></a> switch allows running a module as a script.
  610. When you ran a module that was located inside a package, relative
  611. imports didn’t work correctly.</p>
  612. <p>The fix for Python 2.6 adds a <a class="reference internal" href="../reference/import.html#package__" title="__package__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__package__</span></code></a> attribute to
  613. modules. When this attribute is present, relative imports will be
  614. relative to the value of this attribute instead of the
  615. <a class="reference internal" href="../reference/import.html#name__" title="__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a> attribute.</p>
  616. <p>PEP 302-style importers can then set <a class="reference internal" href="../reference/import.html#package__" title="__package__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__package__</span></code></a> as necessary.
  617. The <a class="reference internal" href="../library/runpy.html#module-runpy" title="runpy: Locate and run Python modules without importing them first."><code class="xref py py-mod docutils literal notranslate"><span class="pre">runpy</span></code></a> module that implements the <a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal notranslate"><span class="pre">-m</span></code></a> switch now
  618. does this, so relative imports will now work correctly in scripts
  619. running from inside a package.</p>
  620. </section>
  621. <section id="pep-370-per-user-site-packages-directory">
  622. <span id="pep-0370"></span><h2>PEP 370: Per-user <code class="docutils literal notranslate"><span class="pre">site-packages</span></code> Directory<a class="headerlink" href="#pep-370-per-user-site-packages-directory" title="Link to this heading">¶</a></h2>
  623. <p>When you run Python, the module search path <code class="docutils literal notranslate"><span class="pre">sys.path</span></code> usually
  624. includes a directory whose path ends in <code class="docutils literal notranslate"><span class="pre">&quot;site-packages&quot;</span></code>. This
  625. directory is intended to hold locally installed packages available to
  626. all users using a machine or a particular site installation.</p>
  627. <p>Python 2.6 introduces a convention for user-specific site directories.
  628. The directory varies depending on the platform:</p>
  629. <ul class="simple">
  630. <li><p>Unix and Mac OS X: <code class="file docutils literal notranslate"><span class="pre">~/.local/</span></code></p></li>
  631. <li><p>Windows: <code class="file docutils literal notranslate"><span class="pre">%APPDATA%/Python</span></code></p></li>
  632. </ul>
  633. <p>Within this directory, there will be version-specific subdirectories,
  634. such as <code class="file docutils literal notranslate"><span class="pre">lib/python2.6/site-packages</span></code> on Unix/Mac OS and
  635. <code class="file docutils literal notranslate"><span class="pre">Python26/site-packages</span></code> on Windows.</p>
  636. <p>If you don’t like the default directory, it can be overridden by an
  637. environment variable. <span class="target" id="index-4"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONUSERBASE"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONUSERBASE</span></code></a> sets the root
  638. directory used for all Python versions supporting this feature. On
  639. Windows, the directory for application-specific data can be changed by
  640. setting the <span class="target" id="index-5"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">APPDATA</span></code> environment variable. You can also
  641. modify the <code class="file docutils literal notranslate"><span class="pre">site.py</span></code> file for your Python installation.</p>
  642. <p>The feature can be disabled entirely by running Python with the
  643. <a class="reference internal" href="../using/cmdline.html#cmdoption-s"><code class="xref std std-option docutils literal notranslate"><span class="pre">-s</span></code></a> option or setting the <span class="target" id="index-6"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONNOUSERSITE"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONNOUSERSITE</span></code></a>
  644. environment variable.</p>
  645. <div class="admonition seealso">
  646. <p class="admonition-title">See also</p>
  647. <dl class="simple">
  648. <dt><span class="target" id="index-7"></span><a class="pep reference external" href="https://peps.python.org/pep-0370/"><strong>PEP 370</strong></a> - Per-user <code class="docutils literal notranslate"><span class="pre">site-packages</span></code> Directory</dt><dd><p>PEP written and implemented by Christian Heimes.</p>
  649. </dd>
  650. </dl>
  651. </div>
  652. </section>
  653. <section id="pep-371-the-multiprocessing-package">
  654. <span id="pep-0371"></span><h2>PEP 371: The <code class="docutils literal notranslate"><span class="pre">multiprocessing</span></code> Package<a class="headerlink" href="#pep-371-the-multiprocessing-package" title="Link to this heading">¶</a></h2>
  655. <p>The new <a class="reference internal" href="../library/multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> package lets Python programs create new
  656. processes that will perform a computation and return a result to the
  657. parent. The parent and child processes can communicate using queues
  658. and pipes, synchronize their operations using locks and semaphores,
  659. and can share simple arrays of data.</p>
  660. <p>The <a class="reference internal" href="../library/multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> module started out as an exact emulation of
  661. the <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> module using processes instead of threads. That
  662. goal was discarded along the path to Python 2.6, but the general
  663. approach of the module is still similar. The fundamental class
  664. is the <code class="xref py py-class docutils literal notranslate"><span class="pre">Process</span></code>, which is passed a callable object and
  665. a collection of arguments. The <code class="xref py py-meth docutils literal notranslate"><span class="pre">start()</span></code> method
  666. sets the callable running in a subprocess, after which you can call
  667. the <code class="xref py py-meth docutils literal notranslate"><span class="pre">is_alive()</span></code> method to check whether the subprocess is still running
  668. and the <code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code> method to wait for the process to exit.</p>
  669. <p>Here’s a simple example where the subprocess will calculate a
  670. factorial. The function doing the calculation is written strangely so
  671. that it takes significantly longer when the input argument is a
  672. multiple of 4.</p>
  673. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">time</span>
  674. <span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="kn">import</span> <span class="n">Process</span><span class="p">,</span> <span class="n">Queue</span>
  675. <span class="k">def</span> <span class="nf">factorial</span><span class="p">(</span><span class="n">queue</span><span class="p">,</span> <span class="n">N</span><span class="p">):</span>
  676. <span class="s2">&quot;Compute a factorial.&quot;</span>
  677. <span class="c1"># If N is a multiple of 4, this function will take much longer.</span>
  678. <span class="k">if</span> <span class="p">(</span><span class="n">N</span> <span class="o">%</span> <span class="mi">4</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
  679. <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">.05</span> <span class="o">*</span> <span class="n">N</span><span class="o">/</span><span class="mi">4</span><span class="p">)</span>
  680. <span class="c1"># Calculate the result</span>
  681. <span class="n">fact</span> <span class="o">=</span> <span class="mi">1</span><span class="n">L</span>
  682. <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">N</span><span class="o">+</span><span class="mi">1</span><span class="p">):</span>
  683. <span class="n">fact</span> <span class="o">=</span> <span class="n">fact</span> <span class="o">*</span> <span class="n">i</span>
  684. <span class="c1"># Put the result on the queue</span>
  685. <span class="n">queue</span><span class="o">.</span><span class="n">put</span><span class="p">(</span><span class="n">fact</span><span class="p">)</span>
  686. <span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
  687. <span class="n">queue</span> <span class="o">=</span> <span class="n">Queue</span><span class="p">()</span>
  688. <span class="n">N</span> <span class="o">=</span> <span class="mi">5</span>
  689. <span class="n">p</span> <span class="o">=</span> <span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">factorial</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">queue</span><span class="p">,</span> <span class="n">N</span><span class="p">))</span>
  690. <span class="n">p</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
  691. <span class="n">p</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>
  692. <span class="n">result</span> <span class="o">=</span> <span class="n">queue</span><span class="o">.</span><span class="n">get</span><span class="p">()</span>
  693. <span class="nb">print</span> <span class="s1">&#39;Factorial&#39;</span><span class="p">,</span> <span class="n">N</span><span class="p">,</span> <span class="s1">&#39;=&#39;</span><span class="p">,</span> <span class="n">result</span>
  694. </pre></div>
  695. </div>
  696. <p>A <a class="reference internal" href="../library/queue.html#queue.Queue" title="queue.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a> is used to communicate the result of the factorial.
  697. The <a class="reference internal" href="../library/queue.html#queue.Queue" title="queue.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a> object is stored in a global variable.
  698. The child process will use the value of the variable when the child
  699. was created; because it’s a <a class="reference internal" href="../library/queue.html#queue.Queue" title="queue.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a>, parent and child can use
  700. the object to communicate. (If the parent were to change the value of
  701. the global variable, the child’s value would be unaffected, and vice
  702. versa.)</p>
  703. <p>Two other classes, <code class="xref py py-class docutils literal notranslate"><span class="pre">Pool</span></code> and <code class="xref py py-class docutils literal notranslate"><span class="pre">Manager</span></code>, provide
  704. higher-level interfaces. <code class="xref py py-class docutils literal notranslate"><span class="pre">Pool</span></code> will create a fixed number of
  705. worker processes, and requests can then be distributed to the workers
  706. by calling <code class="xref py py-meth docutils literal notranslate"><span class="pre">apply()</span></code> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">apply_async()</span></code> to add a single request,
  707. and <a class="reference internal" href="../library/functions.html#map" title="map"><code class="xref py py-meth docutils literal notranslate"><span class="pre">map()</span></code></a> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">map_async()</span></code> to add a number of
  708. requests. The following code uses a <code class="xref py py-class docutils literal notranslate"><span class="pre">Pool</span></code> to spread requests
  709. across 5 worker processes and retrieve a list of results:</p>
  710. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="kn">import</span> <span class="n">Pool</span>
  711. <span class="k">def</span> <span class="nf">factorial</span><span class="p">(</span><span class="n">N</span><span class="p">,</span> <span class="n">dictionary</span><span class="p">):</span>
  712. <span class="s2">&quot;Compute a factorial.&quot;</span>
  713. <span class="o">...</span>
  714. <span class="n">p</span> <span class="o">=</span> <span class="n">Pool</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
  715. <span class="n">result</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="n">factorial</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1000</span><span class="p">,</span> <span class="mi">10</span><span class="p">))</span>
  716. <span class="k">for</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">result</span><span class="p">:</span>
  717. <span class="nb">print</span> <span class="n">v</span>
  718. </pre></div>
  719. </div>
  720. <p>This produces the following output:</p>
  721. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="mi">1</span>
  722. <span class="mi">39916800</span>
  723. <span class="mi">51090942171709440000</span>
  724. <span class="mi">8222838654177922817725562880000000</span>
  725. <span class="mi">33452526613163807108170062053440751665152000000000</span>
  726. <span class="o">...</span>
  727. </pre></div>
  728. </div>
  729. <p>The other high-level interface, the <code class="xref py py-class docutils literal notranslate"><span class="pre">Manager</span></code> class, creates a
  730. separate server process that can hold master copies of Python data
  731. structures. Other processes can then access and modify these data
  732. structures using proxy objects. The following example creates a
  733. shared dictionary by calling the <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict()</span></code></a> method; the worker
  734. processes then insert values into the dictionary. (Locking is not
  735. done for you automatically, which doesn’t matter in this example.
  736. <code class="xref py py-class docutils literal notranslate"><span class="pre">Manager</span></code>’s methods also include <code class="xref py py-meth docutils literal notranslate"><span class="pre">Lock()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">RLock()</span></code>,
  737. and <code class="xref py py-meth docutils literal notranslate"><span class="pre">Semaphore()</span></code> to create shared locks.)</p>
  738. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">time</span>
  739. <span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="kn">import</span> <span class="n">Pool</span><span class="p">,</span> <span class="n">Manager</span>
  740. <span class="k">def</span> <span class="nf">factorial</span><span class="p">(</span><span class="n">N</span><span class="p">,</span> <span class="n">dictionary</span><span class="p">):</span>
  741. <span class="s2">&quot;Compute a factorial.&quot;</span>
  742. <span class="c1"># Calculate the result</span>
  743. <span class="n">fact</span> <span class="o">=</span> <span class="mi">1</span><span class="n">L</span>
  744. <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">N</span><span class="o">+</span><span class="mi">1</span><span class="p">):</span>
  745. <span class="n">fact</span> <span class="o">=</span> <span class="n">fact</span> <span class="o">*</span> <span class="n">i</span>
  746. <span class="c1"># Store result in dictionary</span>
  747. <span class="n">dictionary</span><span class="p">[</span><span class="n">N</span><span class="p">]</span> <span class="o">=</span> <span class="n">fact</span>
  748. <span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
  749. <span class="n">p</span> <span class="o">=</span> <span class="n">Pool</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
  750. <span class="n">mgr</span> <span class="o">=</span> <span class="n">Manager</span><span class="p">()</span>
  751. <span class="n">d</span> <span class="o">=</span> <span class="n">mgr</span><span class="o">.</span><span class="n">dict</span><span class="p">()</span> <span class="c1"># Create shared dictionary</span>
  752. <span class="c1"># Run tasks using the pool</span>
  753. <span class="k">for</span> <span class="n">N</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1000</span><span class="p">,</span> <span class="mi">10</span><span class="p">):</span>
  754. <span class="n">p</span><span class="o">.</span><span class="n">apply_async</span><span class="p">(</span><span class="n">factorial</span><span class="p">,</span> <span class="p">(</span><span class="n">N</span><span class="p">,</span> <span class="n">d</span><span class="p">))</span>
  755. <span class="c1"># Mark pool as closed -- no more tasks can be added.</span>
  756. <span class="n">p</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
  757. <span class="c1"># Wait for tasks to exit</span>
  758. <span class="n">p</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>
  759. <span class="c1"># Output results</span>
  760. <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()):</span>
  761. <span class="nb">print</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span>
  762. </pre></div>
  763. </div>
  764. <p>This will produce the output:</p>
  765. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="mi">1</span> <span class="mi">1</span>
  766. <span class="mi">11</span> <span class="mi">39916800</span>
  767. <span class="mi">21</span> <span class="mi">51090942171709440000</span>
  768. <span class="mi">31</span> <span class="mi">8222838654177922817725562880000000</span>
  769. <span class="mi">41</span> <span class="mi">33452526613163807108170062053440751665152000000000</span>
  770. <span class="mi">51</span> <span class="mf">15511187532873822802242430164693032110632597200169861120000.</span><span class="o">..</span>
  771. </pre></div>
  772. </div>
  773. <div class="admonition seealso">
  774. <p class="admonition-title">See also</p>
  775. <p>The documentation for the <a class="reference internal" href="../library/multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> module.</p>
  776. <dl class="simple">
  777. <dt><span class="target" id="index-8"></span><a class="pep reference external" href="https://peps.python.org/pep-0371/"><strong>PEP 371</strong></a> - Addition of the multiprocessing package</dt><dd><p>PEP written by Jesse Noller and Richard Oudkerk;
  778. implemented by Richard Oudkerk and Jesse Noller.</p>
  779. </dd>
  780. </dl>
  781. </div>
  782. </section>
  783. <section id="pep-3101-advanced-string-formatting">
  784. <span id="pep-3101"></span><h2>PEP 3101: Advanced String Formatting<a class="headerlink" href="#pep-3101-advanced-string-formatting" title="Link to this heading">¶</a></h2>
  785. <p>In Python 3.0, the <code class="docutils literal notranslate"><span class="pre">%</span></code> operator is supplemented by a more powerful string
  786. formatting method, <a class="reference internal" href="../library/functions.html#format" title="format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">format()</span></code></a>. Support for the <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method
  787. has been backported to Python 2.6.</p>
  788. <p>In 2.6, both 8-bit and Unicode strings have a <code class="docutils literal notranslate"><span class="pre">.format()</span></code> method that
  789. treats the string as a template and takes the arguments to be formatted.
  790. The formatting template uses curly brackets (<code class="docutils literal notranslate"><span class="pre">{</span></code>, <code class="docutils literal notranslate"><span class="pre">}</span></code>) as special characters:</p>
  791. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Substitute positional argument 0 into the string.</span>
  792. <span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;User ID: </span><span class="si">{0}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s2">&quot;root&quot;</span><span class="p">)</span>
  793. <span class="go">&#39;User ID: root&#39;</span>
  794. <span class="gp">&gt;&gt;&gt; </span><span class="c1"># Use the named keyword arguments</span>
  795. <span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;User ID: </span><span class="si">{uid}</span><span class="s2"> Last seen: </span><span class="si">{last_login}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
  796. <span class="gp">... </span> <span class="n">uid</span><span class="o">=</span><span class="s2">&quot;root&quot;</span><span class="p">,</span>
  797. <span class="gp">... </span> <span class="n">last_login</span> <span class="o">=</span> <span class="s2">&quot;5 Mar 2008 07:20&quot;</span><span class="p">)</span>
  798. <span class="go">&#39;User ID: root Last seen: 5 Mar 2008 07:20&#39;</span>
  799. </pre></div>
  800. </div>
  801. <p>Curly brackets can be escaped by doubling them:</p>
  802. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;Empty dict: {{}}&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">()</span>
  803. <span class="go">&quot;Empty dict: {}&quot;</span>
  804. </pre></div>
  805. </div>
  806. <p>Field names can be integers indicating positional arguments, such as
  807. <code class="docutils literal notranslate"><span class="pre">{0}</span></code>, <code class="docutils literal notranslate"><span class="pre">{1}</span></code>, etc. or names of keyword arguments. You can also
  808. supply compound field names that read attributes or access dictionary keys:</p>
  809. <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">sys</span>
  810. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s1">&#39;Platform: </span><span class="si">{0.platform}</span><span class="se">\n</span><span class="s1">Python version: </span><span class="si">{0.version}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">sys</span><span class="p">)</span>
  811. <span class="go">Platform: darwin</span>
  812. <span class="go">Python version: 2.6a1+ (trunk:61261M, Mar 5 2008, 20:29:41)</span>
  813. <span class="go">[GCC 4.0.1 (Apple Computer, Inc. build 5367)]&#39;</span>
  814. <span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">mimetypes</span>
  815. <span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;Content-type: </span><span class="si">{0[.mp4]}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">mimetypes</span><span class="o">.</span><span class="n">types_map</span><span class="p">)</span>
  816. <span class="go">&#39;Content-type: video/mp4&#39;</span>
  817. </pre></div>
  818. </div>
  819. <p>Note that when using dictionary-style notation such as <code class="docutils literal notranslate"><span class="pre">[.mp4]</span></code>, you
  820. don’t need to put any quotation marks around the string; it will look
  821. up the value using <code class="docutils literal notranslate"><span class="pre">.mp4</span></code> as the key. Strings beginning with a
  822. number will be converted to an integer. You can’t write more
  823. complicated expressions inside a format string.</p>
  824. <p>So far we’ve shown how to specify which field to substitute into the
  825. resulting string. The precise formatting used is also controllable by
  826. adding a colon followed by a format specifier. For example:</p>
  827. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Field 0: left justify, pad to 15 characters</span>
  828. <span class="gp">&gt;&gt;&gt; </span><span class="c1"># Field 1: right justify, pad to 6 characters</span>
  829. <span class="gp">&gt;&gt;&gt; </span><span class="n">fmt</span> <span class="o">=</span> <span class="s1">&#39;</span><span class="si">{0:15}</span><span class="s1"> $</span><span class="si">{1:&gt;6}</span><span class="s1">&#39;</span>
  830. <span class="gp">&gt;&gt;&gt; </span><span class="n">fmt</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;Registration&#39;</span><span class="p">,</span> <span class="mi">35</span><span class="p">)</span>
  831. <span class="go">&#39;Registration $ 35&#39;</span>
  832. <span class="gp">&gt;&gt;&gt; </span><span class="n">fmt</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;Tutorial&#39;</span><span class="p">,</span> <span class="mi">50</span><span class="p">)</span>
  833. <span class="go">&#39;Tutorial $ 50&#39;</span>
  834. <span class="gp">&gt;&gt;&gt; </span><span class="n">fmt</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;Banquet&#39;</span><span class="p">,</span> <span class="mi">125</span><span class="p">)</span>
  835. <span class="go">&#39;Banquet $ 125&#39;</span>
  836. </pre></div>
  837. </div>
  838. <p>Format specifiers can reference other fields through nesting:</p>
  839. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">fmt</span> <span class="o">=</span> <span class="s1">&#39;{0:</span><span class="si">{1}</span><span class="s1">}&#39;</span>
  840. <span class="gp">&gt;&gt;&gt; </span><span class="n">width</span> <span class="o">=</span> <span class="mi">15</span>
  841. <span class="gp">&gt;&gt;&gt; </span><span class="n">fmt</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;Invoice #1234&#39;</span><span class="p">,</span> <span class="n">width</span><span class="p">)</span>
  842. <span class="go">&#39;Invoice #1234 &#39;</span>
  843. <span class="gp">&gt;&gt;&gt; </span><span class="n">width</span> <span class="o">=</span> <span class="mi">35</span>
  844. <span class="gp">&gt;&gt;&gt; </span><span class="n">fmt</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;Invoice #1234&#39;</span><span class="p">,</span> <span class="n">width</span><span class="p">)</span>
  845. <span class="go">&#39;Invoice #1234 &#39;</span>
  846. </pre></div>
  847. </div>
  848. <p>The alignment of a field within the desired width can be specified:</p>
  849. <table class="docutils align-default">
  850. <thead>
  851. <tr class="row-odd"><th class="head"><p>Character</p></th>
  852. <th class="head"><p>Effect</p></th>
  853. </tr>
  854. </thead>
  855. <tbody>
  856. <tr class="row-even"><td><p>&lt; (default)</p></td>
  857. <td><p>Left-align</p></td>
  858. </tr>
  859. <tr class="row-odd"><td><p>&gt;</p></td>
  860. <td><p>Right-align</p></td>
  861. </tr>
  862. <tr class="row-even"><td><p>^</p></td>
  863. <td><p>Center</p></td>
  864. </tr>
  865. <tr class="row-odd"><td><p>=</p></td>
  866. <td><p>(For numeric types only) Pad after the sign.</p></td>
  867. </tr>
  868. </tbody>
  869. </table>
  870. <p>Format specifiers can also include a presentation type, which
  871. controls how the value is formatted. For example, floating-point numbers
  872. can be formatted as a general number or in exponential notation:</p>
  873. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">{0:g}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="mf">3.75</span><span class="p">)</span>
  874. <span class="go">&#39;3.75&#39;</span>
  875. <span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">{0:e}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="mf">3.75</span><span class="p">)</span>
  876. <span class="go">&#39;3.750000e+00&#39;</span>
  877. </pre></div>
  878. </div>
  879. <p>A variety of presentation types are available. Consult the 2.6
  880. documentation for a <a class="reference internal" href="../library/string.html#formatstrings"><span class="std std-ref">complete list</span></a>; here’s a sample:</p>
  881. <table class="docutils align-default">
  882. <tbody>
  883. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">b</span></code></p></td>
  884. <td><p>Binary. Outputs the number in base 2.</p></td>
  885. </tr>
  886. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">c</span></code></p></td>
  887. <td><p>Character. Converts the integer to the corresponding Unicode character
  888. before printing.</p></td>
  889. </tr>
  890. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">d</span></code></p></td>
  891. <td><p>Decimal Integer. Outputs the number in base 10.</p></td>
  892. </tr>
  893. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">o</span></code></p></td>
  894. <td><p>Octal format. Outputs the number in base 8.</p></td>
  895. </tr>
  896. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">x</span></code></p></td>
  897. <td><p>Hex format. Outputs the number in base 16, using lower-case letters for
  898. the digits above 9.</p></td>
  899. </tr>
  900. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">e</span></code></p></td>
  901. <td><p>Exponent notation. Prints the number in scientific notation using the
  902. letter ‘e’ to indicate the exponent.</p></td>
  903. </tr>
  904. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">g</span></code></p></td>
  905. <td><p>General format. This prints the number as a fixed-point number, unless
  906. the number is too large, in which case it switches to ‘e’ exponent
  907. notation.</p></td>
  908. </tr>
  909. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">n</span></code></p></td>
  910. <td><p>Number. This is the same as ‘g’ (for floats) or ‘d’ (for integers),
  911. except that it uses the current locale setting to insert the appropriate
  912. number separator characters.</p></td>
  913. </tr>
  914. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">%</span></code></p></td>
  915. <td><p>Percentage. Multiplies the number by 100 and displays in fixed (‘f’)
  916. format, followed by a percent sign.</p></td>
  917. </tr>
  918. </tbody>
  919. </table>
  920. <p>Classes and types can define a <code class="xref py py-meth docutils literal notranslate"><span class="pre">__format__()</span></code> method to control how they’re
  921. formatted. It receives a single argument, the format specifier:</p>
  922. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="fm">__format__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">format_spec</span><span class="p">):</span>
  923. <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">format_spec</span><span class="p">,</span> <span class="n">unicode</span><span class="p">):</span>
  924. <span class="k">return</span> <span class="n">unicode</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="bp">self</span><span class="p">))</span>
  925. <span class="k">else</span><span class="p">:</span>
  926. <span class="k">return</span> <span class="nb">str</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
  927. </pre></div>
  928. </div>
  929. <p>There’s also a <a class="reference internal" href="../library/functions.html#format" title="format"><code class="xref py py-func docutils literal notranslate"><span class="pre">format()</span></code></a> builtin that will format a single
  930. value. It calls the type’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">__format__()</span></code> method with the
  931. provided specifier:</p>
  932. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">format</span><span class="p">(</span><span class="mf">75.6564</span><span class="p">,</span> <span class="s1">&#39;.2f&#39;</span><span class="p">)</span>
  933. <span class="go">&#39;75.66&#39;</span>
  934. </pre></div>
  935. </div>
  936. <div class="admonition seealso">
  937. <p class="admonition-title">See also</p>
  938. <dl class="simple">
  939. <dt><a class="reference internal" href="../library/string.html#formatstrings"><span class="std std-ref">Format String Syntax</span></a></dt><dd><p>The reference documentation for format fields.</p>
  940. </dd>
  941. <dt><span class="target" id="index-9"></span><a class="pep reference external" href="https://peps.python.org/pep-3101/"><strong>PEP 3101</strong></a> - Advanced String Formatting</dt><dd><p>PEP written by Talin. Implemented by Eric Smith.</p>
  942. </dd>
  943. </dl>
  944. </div>
  945. </section>
  946. <section id="pep-3105-print-as-a-function">
  947. <span id="pep-3105"></span><h2>PEP 3105: <code class="docutils literal notranslate"><span class="pre">print</span></code> As a Function<a class="headerlink" href="#pep-3105-print-as-a-function" title="Link to this heading">¶</a></h2>
  948. <p>The <code class="docutils literal notranslate"><span class="pre">print</span></code> statement becomes the <a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> function in Python 3.0.
  949. Making <a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> a function makes it possible to replace the function
  950. by doing <code class="docutils literal notranslate"><span class="pre">def</span> <span class="pre">print(...)</span></code> or importing a new function from somewhere else.</p>
  951. <p>Python 2.6 has a <code class="docutils literal notranslate"><span class="pre">__future__</span></code> import that removes <code class="docutils literal notranslate"><span class="pre">print</span></code> as language
  952. syntax, letting you use the functional form instead. For example:</p>
  953. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">__future__</span> <span class="kn">import</span> <span class="n">print_function</span>
  954. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;# of entries&#39;</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">dictionary</span><span class="p">),</span> <span class="n">file</span><span class="o">=</span><span class="n">sys</span><span class="o">.</span><span class="n">stderr</span><span class="p">)</span>
  955. </pre></div>
  956. </div>
  957. <p>The signature of the new function is:</p>
  958. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">print</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="n">sep</span><span class="o">=</span><span class="s1">&#39; &#39;</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s1">&#39;</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">file</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span>
  959. </pre></div>
  960. </div>
  961. <p>The parameters are:</p>
  962. <ul class="simple">
  963. <li><p><em>args</em>: positional arguments whose values will be printed out.</p></li>
  964. <li><p><em>sep</em>: the separator, which will be printed between arguments.</p></li>
  965. <li><p><em>end</em>: the ending text, which will be printed after all of the
  966. arguments have been output.</p></li>
  967. <li><p><em>file</em>: the file object to which the output will be sent.</p></li>
  968. </ul>
  969. <div class="admonition seealso">
  970. <p class="admonition-title">See also</p>
  971. <dl class="simple">
  972. <dt><span class="target" id="index-10"></span><a class="pep reference external" href="https://peps.python.org/pep-3105/"><strong>PEP 3105</strong></a> - Make print a function</dt><dd><p>PEP written by Georg Brandl.</p>
  973. </dd>
  974. </dl>
  975. </div>
  976. </section>
  977. <section id="pep-3110-exception-handling-changes">
  978. <span id="pep-3110"></span><h2>PEP 3110: Exception-Handling Changes<a class="headerlink" href="#pep-3110-exception-handling-changes" title="Link to this heading">¶</a></h2>
  979. <p>One error that Python programmers occasionally make
  980. is writing the following code:</p>
  981. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
  982. <span class="o">...</span>
  983. <span class="k">except</span> <span class="ne">TypeError</span><span class="p">,</span> <span class="ne">ValueError</span><span class="p">:</span> <span class="c1"># Wrong!</span>
  984. <span class="o">...</span>
  985. </pre></div>
  986. </div>
  987. <p>The author is probably trying to catch both <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> and
  988. <a class="reference internal" href="../library/exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> exceptions, but this code actually does something
  989. different: it will catch <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> and bind the resulting
  990. exception object to the local name <code class="docutils literal notranslate"><span class="pre">&quot;ValueError&quot;</span></code>. The
  991. <a class="reference internal" href="../library/exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> exception will not be caught at all. The correct
  992. code specifies a tuple of exceptions:</p>
  993. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
  994. <span class="o">...</span>
  995. <span class="k">except</span> <span class="p">(</span><span class="ne">TypeError</span><span class="p">,</span> <span class="ne">ValueError</span><span class="p">):</span>
  996. <span class="o">...</span>
  997. </pre></div>
  998. </div>
  999. <p>This error happens because the use of the comma here is ambiguous:
  1000. does it indicate two different nodes in the parse tree, or a single
  1001. node that’s a tuple?</p>
  1002. <p>Python 3.0 makes this unambiguous by replacing the comma with the word
  1003. “as”. To catch an exception and store the exception object in the
  1004. variable <code class="docutils literal notranslate"><span class="pre">exc</span></code>, you must write:</p>
  1005. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
  1006. <span class="o">...</span>
  1007. <span class="k">except</span> <span class="ne">TypeError</span> <span class="k">as</span> <span class="n">exc</span><span class="p">:</span>
  1008. <span class="o">...</span>
  1009. </pre></div>
  1010. </div>
  1011. <p>Python 3.0 will only support the use of “as”, and therefore interprets
  1012. the first example as catching two different exceptions. Python 2.6
  1013. supports both the comma and “as”, so existing code will continue to
  1014. work. We therefore suggest using “as” when writing new Python code
  1015. that will only be executed with 2.6.</p>
  1016. <div class="admonition seealso">
  1017. <p class="admonition-title">See also</p>
  1018. <dl class="simple">
  1019. <dt><span class="target" id="index-11"></span><a class="pep reference external" href="https://peps.python.org/pep-3110/"><strong>PEP 3110</strong></a> - Catching Exceptions in Python 3000</dt><dd><p>PEP written and implemented by Collin Winter.</p>
  1020. </dd>
  1021. </dl>
  1022. </div>
  1023. </section>
  1024. <section id="pep-3112-byte-literals">
  1025. <span id="pep-3112"></span><h2>PEP 3112: Byte Literals<a class="headerlink" href="#pep-3112-byte-literals" title="Link to this heading">¶</a></h2>
  1026. <p>Python 3.0 adopts Unicode as the language’s fundamental string type and
  1027. denotes 8-bit literals differently, either as <code class="docutils literal notranslate"><span class="pre">b'string'</span></code>
  1028. or using a <a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> constructor. For future compatibility,
  1029. Python 2.6 adds <a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> as a synonym for the <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> type,
  1030. and it also supports the <code class="docutils literal notranslate"><span class="pre">b''</span></code> notation.</p>
  1031. <p>The 2.6 <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> differs from 3.0’s <a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> type in various
  1032. ways; most notably, the constructor is completely different. In 3.0,
  1033. <code class="docutils literal notranslate"><span class="pre">bytes([65,</span> <span class="pre">66,</span> <span class="pre">67])</span></code> is 3 elements long, containing the bytes
  1034. representing <code class="docutils literal notranslate"><span class="pre">ABC</span></code>; in 2.6, <code class="docutils literal notranslate"><span class="pre">bytes([65,</span> <span class="pre">66,</span> <span class="pre">67])</span></code> returns the
  1035. 12-byte string representing the <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> of the list.</p>
  1036. <p>The primary use of <a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> in 2.6 will be to write tests of
  1037. object type such as <code class="docutils literal notranslate"><span class="pre">isinstance(x,</span> <span class="pre">bytes)</span></code>. This will help the 2to3
  1038. converter, which can’t tell whether 2.x code intends strings to
  1039. contain either characters or 8-bit bytes; you can now
  1040. use either <a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> or <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> to represent your intention
  1041. exactly, and the resulting code will also be correct in Python 3.0.</p>
  1042. <p>There’s also a <code class="docutils literal notranslate"><span class="pre">__future__</span></code> import that causes all string literals
  1043. to become Unicode strings. This means that <code class="docutils literal notranslate"><span class="pre">\u</span></code> escape sequences
  1044. can be used to include Unicode characters:</p>
  1045. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">__future__</span> <span class="kn">import</span> <span class="n">unicode_literals</span>
  1046. <span class="n">s</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;</span><span class="se">\u751f\u3080\u304e\u3000\u751f\u3054</span><span class="s1">&#39;</span>
  1047. <span class="s1">&#39;</span><span class="se">\u3081\u3000\u751f\u305f\u307e\u3054</span><span class="s1">&#39;</span><span class="p">)</span>
  1048. <span class="nb">print</span> <span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span> <span class="c1"># 12 Unicode characters</span>
  1049. </pre></div>
  1050. </div>
  1051. <p>At the C level, Python 3.0 will rename the existing 8-bit
  1052. string type, called <code class="xref c c-type docutils literal notranslate"><span class="pre">PyStringObject</span></code> in Python 2.x,
  1053. to <a class="reference internal" href="../c-api/bytes.html#c.PyBytesObject" title="PyBytesObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyBytesObject</span></code></a>. Python 2.6 uses <code class="docutils literal notranslate"><span class="pre">#define</span></code>
  1054. to support using the names <a class="reference internal" href="../c-api/bytes.html#c.PyBytesObject" title="PyBytesObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyBytesObject()</span></code></a>,
  1055. <a class="reference internal" href="../c-api/bytes.html#c.PyBytes_Check" title="PyBytes_Check"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyBytes_Check()</span></code></a>, <a class="reference internal" href="../c-api/bytes.html#c.PyBytes_FromStringAndSize" title="PyBytes_FromStringAndSize"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyBytes_FromStringAndSize()</span></code></a>,
  1056. and all the other functions and macros used with strings.</p>
  1057. <p>Instances of the <a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> type are immutable just
  1058. as strings are. A new <a class="reference internal" href="../library/stdtypes.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> type stores a mutable
  1059. sequence of bytes:</p>
  1060. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">bytearray</span><span class="p">([</span><span class="mi">65</span><span class="p">,</span> <span class="mi">66</span><span class="p">,</span> <span class="mi">67</span><span class="p">])</span>
  1061. <span class="go">bytearray(b&#39;ABC&#39;)</span>
  1062. <span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="nb">bytearray</span><span class="p">(</span><span class="sa">u</span><span class="s1">&#39;</span><span class="se">\u21ef\u3244</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;utf-8&#39;</span><span class="p">)</span>
  1063. <span class="gp">&gt;&gt;&gt; </span><span class="n">b</span>
  1064. <span class="go">bytearray(b&#39;\xe2\x87\xaf\xe3\x89\x84&#39;)</span>
  1065. <span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;</span><span class="se">\xe3</span><span class="s1">&#39;</span>
  1066. <span class="gp">&gt;&gt;&gt; </span><span class="n">b</span>
  1067. <span class="go">bytearray(b&#39;\xe3\x87\xaf\xe3\x89\x84&#39;)</span>
  1068. <span class="gp">&gt;&gt;&gt; </span><span class="n">unicode</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">b</span><span class="p">),</span> <span class="s1">&#39;utf-8&#39;</span><span class="p">)</span>
  1069. <span class="go">u&#39;\u31ef \u3244&#39;</span>
  1070. </pre></div>
  1071. </div>
  1072. <p>Byte arrays support most of the methods of string types, such as
  1073. <code class="xref py py-meth docutils literal notranslate"><span class="pre">startswith()</span></code>/<code class="xref py py-meth docutils literal notranslate"><span class="pre">endswith()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">find()</span></code>/<code class="xref py py-meth docutils literal notranslate"><span class="pre">rfind()</span></code>,
  1074. and some of the methods of lists, such as <code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code>,
  1075. <code class="xref py py-meth docutils literal notranslate"><span class="pre">pop()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">reverse()</span></code>.</p>
  1076. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="nb">bytearray</span><span class="p">(</span><span class="s1">&#39;ABC&#39;</span><span class="p">)</span>
  1077. <span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s1">&#39;d&#39;</span><span class="p">)</span>
  1078. <span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="nb">ord</span><span class="p">(</span><span class="s1">&#39;e&#39;</span><span class="p">))</span>
  1079. <span class="gp">&gt;&gt;&gt; </span><span class="n">b</span>
  1080. <span class="go">bytearray(b&#39;ABCde&#39;)</span>
  1081. </pre></div>
  1082. </div>
  1083. <p>There’s also a corresponding C API, with
  1084. <a class="reference internal" href="../c-api/bytearray.html#c.PyByteArray_FromObject" title="PyByteArray_FromObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyByteArray_FromObject()</span></code></a>,
  1085. <a class="reference internal" href="../c-api/bytearray.html#c.PyByteArray_FromStringAndSize" title="PyByteArray_FromStringAndSize"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyByteArray_FromStringAndSize()</span></code></a>,
  1086. and various other functions.</p>
  1087. <div class="admonition seealso">
  1088. <p class="admonition-title">See also</p>
  1089. <dl class="simple">
  1090. <dt><span class="target" id="index-12"></span><a class="pep reference external" href="https://peps.python.org/pep-3112/"><strong>PEP 3112</strong></a> - Bytes literals in Python 3000</dt><dd><p>PEP written by Jason Orendorff; backported to 2.6 by Christian Heimes.</p>
  1091. </dd>
  1092. </dl>
  1093. </div>
  1094. </section>
  1095. <section id="pep-3116-new-i-o-library">
  1096. <span id="pep-3116"></span><h2>PEP 3116: New I/O Library<a class="headerlink" href="#pep-3116-new-i-o-library" title="Link to this heading">¶</a></h2>
  1097. <p>Python’s built-in file objects support a number of methods, but
  1098. file-like objects don’t necessarily support all of them. Objects that
  1099. imitate files usually support <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">write()</span></code>, but they
  1100. may not support <a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a>, for example. Python 3.0 introduces
  1101. a layered I/O library in the <a class="reference internal" href="../library/io.html#module-io" title="io: Core tools for working with streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">io</span></code></a> module that separates buffering
  1102. and text-handling features from the fundamental read and write
  1103. operations.</p>
  1104. <p>There are three levels of abstract base classes provided by
  1105. the <a class="reference internal" href="../library/io.html#module-io" title="io: Core tools for working with streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">io</span></code></a> module:</p>
  1106. <ul>
  1107. <li><p><code class="xref py py-class docutils literal notranslate"><span class="pre">RawIOBase</span></code> defines raw I/O operations: <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code>,
  1108. <code class="xref py py-meth docutils literal notranslate"><span class="pre">readinto()</span></code>,
  1109. <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">seek()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">tell()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">truncate()</span></code>,
  1110. and <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code>.
  1111. Most of the methods of this class will often map to a single system call.
  1112. There are also <code class="xref py py-meth docutils literal notranslate"><span class="pre">readable()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">writable()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">seekable()</span></code>
  1113. methods for determining what operations a given object will allow.</p>
  1114. <p>Python 3.0 has concrete implementations of this class for files and
  1115. sockets, but Python 2.6 hasn’t restructured its file and socket objects
  1116. in this way.</p>
  1117. </li>
  1118. <li><p><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedIOBase</span></code> is an abstract base class that
  1119. buffers data in memory to reduce the number of
  1120. system calls used, making I/O processing more efficient.
  1121. It supports all of the methods of <code class="xref py py-class docutils literal notranslate"><span class="pre">RawIOBase</span></code>,
  1122. and adds a <code class="xref py py-attr docutils literal notranslate"><span class="pre">raw</span></code> attribute holding the underlying raw object.</p>
  1123. <p>There are five concrete classes implementing this ABC.
  1124. <code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedWriter</span></code> and <code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedReader</span></code> are for objects
  1125. that support write-only or read-only usage that have a <code class="xref py py-meth docutils literal notranslate"><span class="pre">seek()</span></code>
  1126. method for random access. <code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedRandom</span></code> objects support
  1127. read and write access upon the same underlying stream, and
  1128. <code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedRWPair</span></code> is for objects such as TTYs that have both
  1129. read and write operations acting upon unconnected streams of data.
  1130. The <code class="xref py py-class docutils literal notranslate"><span class="pre">BytesIO</span></code> class supports reading, writing, and seeking
  1131. over an in-memory buffer.</p>
  1132. </li>
  1133. <li id="index-13"><p><code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOBase</span></code>: Provides functions for reading and writing
  1134. strings (remember, strings will be Unicode in Python 3.0),
  1135. and supporting <a class="reference internal" href="../glossary.html#term-universal-newlines"><span class="xref std std-term">universal newlines</span></a>. <code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOBase</span></code> defines
  1136. the <a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> method and supports iteration upon
  1137. objects.</p>
  1138. <p>There are two concrete implementations. <code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOWrapper</span></code>
  1139. wraps a buffered I/O object, supporting all of the methods for
  1140. text I/O and adding a <code class="xref py py-attr docutils literal notranslate"><span class="pre">buffer</span></code> attribute for access
  1141. to the underlying object. <code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO</span></code> simply buffers
  1142. everything in memory without ever writing anything to disk.</p>
  1143. <p>(In Python 2.6, <a class="reference internal" href="../library/io.html#io.StringIO" title="io.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.StringIO</span></code></a> is implemented in
  1144. pure Python, so it’s pretty slow. You should therefore stick with the
  1145. existing <code class="xref py py-mod docutils literal notranslate"><span class="pre">StringIO</span></code> module or <code class="xref py py-mod docutils literal notranslate"><span class="pre">cStringIO</span></code> for now. At some
  1146. point Python 3.0’s <a class="reference internal" href="../library/io.html#module-io" title="io: Core tools for working with streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">io</span></code></a> module will be rewritten into C for speed,
  1147. and perhaps the C implementation will be backported to the 2.x releases.)</p>
  1148. </li>
  1149. </ul>
  1150. <p>In Python 2.6, the underlying implementations haven’t been
  1151. restructured to build on top of the <a class="reference internal" href="../library/io.html#module-io" title="io: Core tools for working with streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">io</span></code></a> module’s classes. The
  1152. module is being provided to make it easier to write code that’s
  1153. forward-compatible with 3.0, and to save developers the effort of writing
  1154. their own implementations of buffering and text I/O.</p>
  1155. <div class="admonition seealso">
  1156. <p class="admonition-title">See also</p>
  1157. <dl class="simple">
  1158. <dt><span class="target" id="index-14"></span><a class="pep reference external" href="https://peps.python.org/pep-3116/"><strong>PEP 3116</strong></a> - New I/O</dt><dd><p>PEP written by Daniel Stutzbach, Mike Verdone, and Guido van Rossum.
  1159. Code by Guido van Rossum, Georg Brandl, Walter Doerwald,
  1160. Jeremy Hylton, Martin von Löwis, Tony Lownds, and others.</p>
  1161. </dd>
  1162. </dl>
  1163. </div>
  1164. </section>
  1165. <section id="pep-3118-revised-buffer-protocol">
  1166. <span id="pep-3118"></span><h2>PEP 3118: Revised Buffer Protocol<a class="headerlink" href="#pep-3118-revised-buffer-protocol" title="Link to this heading">¶</a></h2>
  1167. <p>The buffer protocol is a C-level API that lets Python types
  1168. exchange pointers into their internal representations. A
  1169. memory-mapped file can be viewed as a buffer of characters, for
  1170. example, and this lets another module such as <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a>
  1171. treat memory-mapped files as a string of characters to be searched.</p>
  1172. <p>The primary users of the buffer protocol are numeric-processing
  1173. packages such as NumPy, which expose the internal representation
  1174. of arrays so that callers can write data directly into an array instead
  1175. of going through a slower API. This PEP updates the buffer protocol in light of experience
  1176. from NumPy development, adding a number of new features
  1177. such as indicating the shape of an array or locking a memory region.</p>
  1178. <p>The most important new C API function is
  1179. <code class="docutils literal notranslate"><span class="pre">PyObject_GetBuffer(PyObject</span> <span class="pre">*obj,</span> <span class="pre">Py_buffer</span> <span class="pre">*view,</span> <span class="pre">int</span> <span class="pre">flags)</span></code>, which
  1180. takes an object and a set of flags, and fills in the
  1181. <code class="docutils literal notranslate"><span class="pre">Py_buffer</span></code> structure with information
  1182. about the object’s memory representation. Objects
  1183. can use this operation to lock memory in place
  1184. while an external caller could be modifying the contents,
  1185. so there’s a corresponding <code class="docutils literal notranslate"><span class="pre">PyBuffer_Release(Py_buffer</span> <span class="pre">*view)</span></code> to
  1186. indicate that the external caller is done.</p>
  1187. <p>The <em>flags</em> argument to <a class="reference internal" href="../c-api/buffer.html#c.PyObject_GetBuffer" title="PyObject_GetBuffer"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GetBuffer()</span></code></a> specifies
  1188. constraints upon the memory returned. Some examples are:</p>
  1189. <ul class="simple">
  1190. <li><p><a class="reference internal" href="../c-api/buffer.html#c.PyBUF_WRITABLE" title="PyBUF_WRITABLE"><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyBUF_WRITABLE</span></code></a> indicates that the memory must be writable.</p></li>
  1191. <li><p><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyBUF_LOCK</span></code> requests a read-only or exclusive lock on the memory.</p></li>
  1192. <li><p><a class="reference internal" href="../c-api/buffer.html#c.PyBUF_C_CONTIGUOUS" title="PyBUF_C_CONTIGUOUS"><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyBUF_C_CONTIGUOUS</span></code></a> and <a class="reference internal" href="../c-api/buffer.html#c.PyBUF_F_CONTIGUOUS" title="PyBUF_F_CONTIGUOUS"><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyBUF_F_CONTIGUOUS</span></code></a>
  1193. requests a C-contiguous (last dimension varies the fastest) or
  1194. Fortran-contiguous (first dimension varies the fastest) array layout.</p></li>
  1195. </ul>
  1196. <p>Two new argument codes for <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>,
  1197. <code class="docutils literal notranslate"><span class="pre">s*</span></code> and <code class="docutils literal notranslate"><span class="pre">z*</span></code>, return locked buffer objects for a parameter.</p>
  1198. <div class="admonition seealso">
  1199. <p class="admonition-title">See also</p>
  1200. <dl class="simple">
  1201. <dt><span class="target" id="index-15"></span><a class="pep reference external" href="https://peps.python.org/pep-3118/"><strong>PEP 3118</strong></a> - Revising the buffer protocol</dt><dd><p>PEP written by Travis Oliphant and Carl Banks; implemented by
  1202. Travis Oliphant.</p>
  1203. </dd>
  1204. </dl>
  1205. </div>
  1206. </section>
  1207. <section id="pep-3119-abstract-base-classes">
  1208. <span id="pep-3119"></span><h2>PEP 3119: Abstract Base Classes<a class="headerlink" href="#pep-3119-abstract-base-classes" title="Link to this heading">¶</a></h2>
  1209. <p>Some object-oriented languages such as Java support interfaces,
  1210. declaring that a class has a given set of methods or supports a given
  1211. access protocol. Abstract Base Classes (or ABCs) are an equivalent
  1212. feature for Python. The ABC support consists of an <a class="reference internal" href="../library/abc.html#module-abc" title="abc: Abstract base classes according to :pep:`3119`."><code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code></a> module
  1213. containing a metaclass called <code class="xref py py-class docutils literal notranslate"><span class="pre">ABCMeta</span></code>, special handling of
  1214. this metaclass by the <a class="reference internal" href="../library/functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a> and <a class="reference internal" href="../library/functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal notranslate"><span class="pre">issubclass()</span></code></a>
  1215. builtins, and a collection of basic ABCs that the Python developers
  1216. think will be widely useful. Future versions of Python will probably
  1217. add more ABCs.</p>
  1218. <p>Let’s say you have a particular class and wish to know whether it supports
  1219. dictionary-style access. The phrase “dictionary-style” is vague, however.
  1220. It probably means that accessing items with <code class="docutils literal notranslate"><span class="pre">obj[1]</span></code> works.
  1221. Does it imply that setting items with <code class="docutils literal notranslate"><span class="pre">obj[2]</span> <span class="pre">=</span> <span class="pre">value</span></code> works?
  1222. Or that the object will have <code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">values()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">items()</span></code>
  1223. methods? What about the iterative variants such as <code class="xref py py-meth docutils literal notranslate"><span class="pre">iterkeys()</span></code>? <a class="reference internal" href="../library/copy.html#module-copy" title="copy: Shallow and deep copy operations."><code class="xref py py-meth docutils literal notranslate"><span class="pre">copy()</span></code></a>
  1224. and <code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code>? Iterating over the object with <a class="reference internal" href="../library/functions.html#iter" title="iter"><code class="xref py py-func docutils literal notranslate"><span class="pre">iter()</span></code></a>?</p>
  1225. <p>The Python 2.6 <a class="reference internal" href="../library/collections.html#module-collections" title="collections: Container datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> module includes a number of
  1226. different ABCs that represent these distinctions. <code class="xref py py-class docutils literal notranslate"><span class="pre">Iterable</span></code>
  1227. indicates that a class defines <code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code>, and
  1228. <code class="xref py py-class docutils literal notranslate"><span class="pre">Container</span></code> means the class defines a <code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code>
  1229. method and therefore supports <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">y</span></code> expressions. The basic
  1230. dictionary interface of getting items, setting items, and
  1231. <code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">values()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">items()</span></code>, is defined by the
  1232. <code class="xref py py-class docutils literal notranslate"><span class="pre">MutableMapping</span></code> ABC.</p>
  1233. <p>You can derive your own classes from a particular ABC
  1234. to indicate they support that ABC’s interface:</p>
  1235. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">collections</span>
  1236. <span class="k">class</span> <span class="nc">Storage</span><span class="p">(</span><span class="n">collections</span><span class="o">.</span><span class="n">MutableMapping</span><span class="p">):</span>
  1237. <span class="o">...</span>
  1238. </pre></div>
  1239. </div>
  1240. <p>Alternatively, you could write the class without deriving from
  1241. the desired ABC and instead register the class by
  1242. calling the ABC’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">register()</span></code> method:</p>
  1243. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">collections</span>
  1244. <span class="k">class</span> <span class="nc">Storage</span><span class="p">:</span>
  1245. <span class="o">...</span>
  1246. <span class="n">collections</span><span class="o">.</span><span class="n">MutableMapping</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">Storage</span><span class="p">)</span>
  1247. </pre></div>
  1248. </div>
  1249. <p>For classes that you write, deriving from the ABC is probably clearer.
  1250. The <code class="xref py py-meth docutils literal notranslate"><span class="pre">register()</span></code> method is useful when you’ve written a new
  1251. ABC that can describe an existing type or class, or if you want
  1252. to declare that some third-party class implements an ABC.
  1253. For example, if you defined a <code class="xref py py-class docutils literal notranslate"><span class="pre">PrintableType</span></code> ABC,
  1254. it’s legal to do:</p>
  1255. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Register Python&#39;s types</span>
  1256. <span class="n">PrintableType</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span>
  1257. <span class="n">PrintableType</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="nb">float</span><span class="p">)</span>
  1258. <span class="n">PrintableType</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="nb">str</span><span class="p">)</span>
  1259. </pre></div>
  1260. </div>
  1261. <p>Classes should obey the semantics specified by an ABC, but
  1262. Python can’t check this; it’s up to the class author to
  1263. understand the ABC’s requirements and to implement the code accordingly.</p>
  1264. <p>To check whether an object supports a particular interface, you can
  1265. now write:</p>
  1266. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">func</span><span class="p">(</span><span class="n">d</span><span class="p">):</span>
  1267. <span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">d</span><span class="p">,</span> <span class="n">collections</span><span class="o">.</span><span class="n">MutableMapping</span><span class="p">):</span>
  1268. <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">&quot;Mapping object expected, not </span><span class="si">%r</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="n">d</span><span class="p">)</span>
  1269. </pre></div>
  1270. </div>
  1271. <p>Don’t feel that you must now begin writing lots of checks as in the
  1272. above example. Python has a strong tradition of duck-typing, where
  1273. explicit type-checking is never done and code simply calls methods on
  1274. an object, trusting that those methods will be there and raising an
  1275. exception if they aren’t. Be judicious in checking for ABCs and only
  1276. do it where it’s absolutely necessary.</p>
  1277. <p>You can write your own ABCs by using <code class="docutils literal notranslate"><span class="pre">abc.ABCMeta</span></code> as the
  1278. metaclass in a class definition:</p>
  1279. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">abc</span> <span class="kn">import</span> <span class="n">ABCMeta</span><span class="p">,</span> <span class="n">abstractmethod</span>
  1280. <span class="k">class</span> <span class="nc">Drawable</span><span class="p">():</span>
  1281. <span class="n">__metaclass__</span> <span class="o">=</span> <span class="n">ABCMeta</span>
  1282. <span class="nd">@abstractmethod</span>
  1283. <span class="k">def</span> <span class="nf">draw</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">scale</span><span class="o">=</span><span class="mf">1.0</span><span class="p">):</span>
  1284. <span class="k">pass</span>
  1285. <span class="k">def</span> <span class="nf">draw_doubled</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
  1286. <span class="bp">self</span><span class="o">.</span><span class="n">draw</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">scale</span><span class="o">=</span><span class="mf">2.0</span><span class="p">)</span>
  1287. <span class="k">class</span> <span class="nc">Square</span><span class="p">(</span><span class="n">Drawable</span><span class="p">):</span>
  1288. <span class="k">def</span> <span class="nf">draw</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">scale</span><span class="p">):</span>
  1289. <span class="o">...</span>
  1290. </pre></div>
  1291. </div>
  1292. <p>In the <code class="xref py py-class docutils literal notranslate"><span class="pre">Drawable</span></code> ABC above, the <code class="xref py py-meth docutils literal notranslate"><span class="pre">draw_doubled()</span></code> method
  1293. renders the object at twice its size and can be implemented in terms
  1294. of other methods described in <code class="xref py py-class docutils literal notranslate"><span class="pre">Drawable</span></code>. Classes implementing
  1295. this ABC therefore don’t need to provide their own implementation
  1296. of <code class="xref py py-meth docutils literal notranslate"><span class="pre">draw_doubled()</span></code>, though they can do so. An implementation
  1297. of <code class="xref py py-meth docutils literal notranslate"><span class="pre">draw()</span></code> is necessary, though; the ABC can’t provide
  1298. a useful generic implementation.</p>
  1299. <p>You can apply the <code class="docutils literal notranslate"><span class="pre">&#64;abstractmethod</span></code> decorator to methods such as
  1300. <code class="xref py py-meth docutils literal notranslate"><span class="pre">draw()</span></code> that must be implemented; Python will then raise an
  1301. exception for classes that don’t define the method.
  1302. Note that the exception is only raised when you actually
  1303. try to create an instance of a subclass lacking the method:</p>
  1304. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Circle</span><span class="p">(</span><span class="n">Drawable</span><span class="p">):</span>
  1305. <span class="gp">... </span> <span class="k">pass</span>
  1306. <span class="gp">...</span>
  1307. <span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Circle</span><span class="p">()</span>
  1308. <span class="gt">Traceback (most recent call last):</span>
  1309. File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
  1310. <span class="gr">TypeError</span>: <span class="n">Can&#39;t instantiate abstract class Circle with abstract methods draw</span>
  1311. <span class="gp">&gt;&gt;&gt;</span>
  1312. </pre></div>
  1313. </div>
  1314. <p>Abstract data attributes can be declared using the
  1315. <code class="docutils literal notranslate"><span class="pre">&#64;abstractproperty</span></code> decorator:</p>
  1316. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">abc</span> <span class="kn">import</span> <span class="n">abstractproperty</span>
  1317. <span class="o">...</span>
  1318. <span class="nd">@abstractproperty</span>
  1319. <span class="k">def</span> <span class="nf">readonly</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  1320. <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_x</span>
  1321. </pre></div>
  1322. </div>
  1323. <p>Subclasses must then define a <code class="xref py py-meth docutils literal notranslate"><span class="pre">readonly()</span></code> property.</p>
  1324. <div class="admonition seealso">
  1325. <p class="admonition-title">See also</p>
  1326. <dl class="simple">
  1327. <dt><span class="target" id="index-16"></span><a class="pep reference external" href="https://peps.python.org/pep-3119/"><strong>PEP 3119</strong></a> - Introducing Abstract Base Classes</dt><dd><p>PEP written by Guido van Rossum and Talin.
  1328. Implemented by Guido van Rossum.
  1329. Backported to 2.6 by Benjamin Aranguren, with Alex Martelli.</p>
  1330. </dd>
  1331. </dl>
  1332. </div>
  1333. </section>
  1334. <section id="pep-3127-integer-literal-support-and-syntax">
  1335. <span id="pep-3127"></span><h2>PEP 3127: Integer Literal Support and Syntax<a class="headerlink" href="#pep-3127-integer-literal-support-and-syntax" title="Link to this heading">¶</a></h2>
  1336. <p>Python 3.0 changes the syntax for octal (base-8) integer literals,
  1337. prefixing them with “0o” or “0O” instead of a leading zero, and adds
  1338. support for binary (base-2) integer literals, signalled by a “0b” or
  1339. “0B” prefix.</p>
  1340. <p>Python 2.6 doesn’t drop support for a leading 0 signalling
  1341. an octal number, but it does add support for “0o” and “0b”:</p>
  1342. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mo">0o21</span><span class="p">,</span> <span class="mi">2</span><span class="o">*</span><span class="mi">8</span> <span class="o">+</span> <span class="mi">1</span>
  1343. <span class="go">(17, 17)</span>
  1344. <span class="gp">&gt;&gt;&gt; </span><span class="mb">0b101111</span>
  1345. <span class="go">47</span>
  1346. </pre></div>
  1347. </div>
  1348. <p>The <a class="reference internal" href="../library/functions.html#oct" title="oct"><code class="xref py py-func docutils literal notranslate"><span class="pre">oct()</span></code></a> builtin still returns numbers
  1349. prefixed with a leading zero, and a new <a class="reference internal" href="../library/functions.html#bin" title="bin"><code class="xref py py-func docutils literal notranslate"><span class="pre">bin()</span></code></a>
  1350. builtin returns the binary representation for a number:</p>
  1351. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">oct</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
  1352. <span class="go">&#39;052&#39;</span>
  1353. <span class="gp">&gt;&gt;&gt; </span><span class="n">future_builtins</span><span class="o">.</span><span class="n">oct</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
  1354. <span class="go">&#39;0o52&#39;</span>
  1355. <span class="gp">&gt;&gt;&gt; </span><span class="nb">bin</span><span class="p">(</span><span class="mi">173</span><span class="p">)</span>
  1356. <span class="go">&#39;0b10101101&#39;</span>
  1357. </pre></div>
  1358. </div>
  1359. <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> and <code class="xref py py-func docutils literal notranslate"><span class="pre">long()</span></code> builtins will now accept the “0o”
  1360. and “0b” prefixes when base-8 or base-2 are requested, or when the
  1361. <em>base</em> argument is zero (signalling that the base used should be
  1362. determined from the string):</p>
  1363. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span> <span class="p">(</span><span class="s1">&#39;0o52&#39;</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
  1364. <span class="go">42</span>
  1365. <span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="p">(</span><span class="s1">&#39;1101&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
  1366. <span class="go">13</span>
  1367. <span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="p">(</span><span class="s1">&#39;0b1101&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
  1368. <span class="go">13</span>
  1369. <span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="p">(</span><span class="s1">&#39;0b1101&#39;</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
  1370. <span class="go">13</span>
  1371. </pre></div>
  1372. </div>
  1373. <div class="admonition seealso">
  1374. <p class="admonition-title">See also</p>
  1375. <dl class="simple">
  1376. <dt><span class="target" id="index-17"></span><a class="pep reference external" href="https://peps.python.org/pep-3127/"><strong>PEP 3127</strong></a> - Integer Literal Support and Syntax</dt><dd><p>PEP written by Patrick Maupin; backported to 2.6 by
  1377. Eric Smith.</p>
  1378. </dd>
  1379. </dl>
  1380. </div>
  1381. </section>
  1382. <section id="pep-3129-class-decorators">
  1383. <span id="pep-3129"></span><h2>PEP 3129: Class Decorators<a class="headerlink" href="#pep-3129-class-decorators" title="Link to this heading">¶</a></h2>
  1384. <p>Decorators have been extended from functions to classes. It’s now legal to
  1385. write:</p>
  1386. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nd">@foo</span>
  1387. <span class="nd">@bar</span>
  1388. <span class="k">class</span> <span class="nc">A</span><span class="p">:</span>
  1389. <span class="k">pass</span>
  1390. </pre></div>
  1391. </div>
  1392. <p>This is equivalent to:</p>
  1393. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">A</span><span class="p">:</span>
  1394. <span class="k">pass</span>
  1395. <span class="n">A</span> <span class="o">=</span> <span class="n">foo</span><span class="p">(</span><span class="n">bar</span><span class="p">(</span><span class="n">A</span><span class="p">))</span>
  1396. </pre></div>
  1397. </div>
  1398. <div class="admonition seealso">
  1399. <p class="admonition-title">See also</p>
  1400. <dl class="simple">
  1401. <dt><span class="target" id="index-18"></span><a class="pep reference external" href="https://peps.python.org/pep-3129/"><strong>PEP 3129</strong></a> - Class Decorators</dt><dd><p>PEP written by Collin Winter.</p>
  1402. </dd>
  1403. </dl>
  1404. </div>
  1405. </section>
  1406. <section id="pep-3141-a-type-hierarchy-for-numbers">
  1407. <span id="pep-3141"></span><h2>PEP 3141: A Type Hierarchy for Numbers<a class="headerlink" href="#pep-3141-a-type-hierarchy-for-numbers" title="Link to this heading">¶</a></h2>
  1408. <p>Python 3.0 adds several abstract base classes for numeric types
  1409. inspired by Scheme’s numeric tower. These classes were backported to
  1410. 2.6 as the <a class="reference internal" href="../library/numbers.html#module-numbers" title="numbers: Numeric abstract base classes (Complex, Real, Integral, etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">numbers</span></code></a> module.</p>
  1411. <p>The most general ABC is <code class="xref py py-class docutils literal notranslate"><span class="pre">Number</span></code>. It defines no operations at
  1412. all, and only exists to allow checking if an object is a number by
  1413. doing <code class="docutils literal notranslate"><span class="pre">isinstance(obj,</span> <span class="pre">Number)</span></code>.</p>
  1414. <p><code class="xref py py-class docutils literal notranslate"><span class="pre">Complex</span></code> is a subclass of <code class="xref py py-class docutils literal notranslate"><span class="pre">Number</span></code>. Complex numbers
  1415. can undergo the basic operations of addition, subtraction,
  1416. multiplication, division, and exponentiation, and you can retrieve the
  1417. real and imaginary parts and obtain a number’s conjugate. Python’s built-in
  1418. complex type is an implementation of <code class="xref py py-class docutils literal notranslate"><span class="pre">Complex</span></code>.</p>
  1419. <p><code class="xref py py-class docutils literal notranslate"><span class="pre">Real</span></code> further derives from <code class="xref py py-class docutils literal notranslate"><span class="pre">Complex</span></code>, and adds
  1420. operations that only work on real numbers: <code class="xref py py-func docutils literal notranslate"><span class="pre">floor()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">trunc()</span></code>,
  1421. rounding, taking the remainder mod N, floor division,
  1422. and comparisons.</p>
  1423. <p><code class="xref py py-class docutils literal notranslate"><span class="pre">Rational</span></code> numbers derive from <code class="xref py py-class docutils literal notranslate"><span class="pre">Real</span></code>, have
  1424. <code class="xref py py-attr docutils literal notranslate"><span class="pre">numerator</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">denominator</span></code> properties, and can be
  1425. converted to floats. Python 2.6 adds a simple rational-number class,
  1426. <code class="xref py py-class docutils literal notranslate"><span class="pre">Fraction</span></code>, in the <a class="reference internal" href="../library/fractions.html#module-fractions" title="fractions: Rational numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fractions</span></code></a> module. (It’s called
  1427. <code class="xref py py-class docutils literal notranslate"><span class="pre">Fraction</span></code> instead of <code class="xref py py-class docutils literal notranslate"><span class="pre">Rational</span></code> to avoid
  1428. a name clash with <a class="reference internal" href="../library/numbers.html#numbers.Rational" title="numbers.Rational"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Rational</span></code></a>.)</p>
  1429. <p><code class="xref py py-class docutils literal notranslate"><span class="pre">Integral</span></code> numbers derive from <code class="xref py py-class docutils literal notranslate"><span class="pre">Rational</span></code>, and
  1430. can be shifted left and right with <code class="docutils literal notranslate"><span class="pre">&lt;&lt;</span></code> and <code class="docutils literal notranslate"><span class="pre">&gt;&gt;</span></code>,
  1431. combined using bitwise operations such as <code class="docutils literal notranslate"><span class="pre">&amp;</span></code> and <code class="docutils literal notranslate"><span class="pre">|</span></code>,
  1432. and can be used as array indexes and slice boundaries.</p>
  1433. <p>In Python 3.0, the PEP slightly redefines the existing builtins
  1434. <a class="reference internal" href="../library/functions.html#round" title="round"><code class="xref py py-func docutils literal notranslate"><span class="pre">round()</span></code></a>, <a class="reference internal" href="../library/math.html#math.floor" title="math.floor"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.floor()</span></code></a>, <a class="reference internal" href="../library/math.html#math.ceil" title="math.ceil"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.ceil()</span></code></a>, and adds a new
  1435. one, <a class="reference internal" href="../library/math.html#math.trunc" title="math.trunc"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.trunc()</span></code></a>, that’s been backported to Python 2.6.
  1436. <a class="reference internal" href="../library/math.html#math.trunc" title="math.trunc"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.trunc()</span></code></a> rounds toward zero, returning the closest
  1437. <code class="xref py py-class docutils literal notranslate"><span class="pre">Integral</span></code> that’s between the function’s argument and zero.</p>
  1438. <div class="admonition seealso">
  1439. <p class="admonition-title">See also</p>
  1440. <dl class="simple">
  1441. <dt><span class="target" id="index-19"></span><a class="pep reference external" href="https://peps.python.org/pep-3141/"><strong>PEP 3141</strong></a> - A Type Hierarchy for Numbers</dt><dd><p>PEP written by Jeffrey Yasskin.</p>
  1442. </dd>
  1443. </dl>
  1444. <p><a class="reference external" href="https://www.gnu.org/software/guile/manual/html_node/Numerical-Tower.html#Numerical-Tower">Scheme’s numerical tower</a>, from the Guile manual.</p>
  1445. <p><a class="reference external" href="https://conservatory.scheme.org/schemers/Documents/Standards/R5RS/HTML/r5rs-Z-H-9.html#%_sec_6.2">Scheme’s number datatypes</a> from the R5RS Scheme specification.</p>
  1446. </div>
  1447. <section id="the-fractions-module">
  1448. <h3>The <a class="reference internal" href="../library/fractions.html#module-fractions" title="fractions: Rational numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fractions</span></code></a> Module<a class="headerlink" href="#the-fractions-module" title="Link to this heading">¶</a></h3>
  1449. <p>To fill out the hierarchy of numeric types, the <a class="reference internal" href="../library/fractions.html#module-fractions" title="fractions: Rational numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fractions</span></code></a>
  1450. module provides a rational-number class. Rational numbers store their
  1451. values as a numerator and denominator forming a fraction, and can
  1452. exactly represent numbers such as <code class="docutils literal notranslate"><span class="pre">2/3</span></code> that floating-point numbers
  1453. can only approximate.</p>
  1454. <p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">Fraction</span></code> constructor takes two <code class="xref py py-class docutils literal notranslate"><span class="pre">Integral</span></code> values
  1455. that will be the numerator and denominator of the resulting fraction.</p>
  1456. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">fractions</span> <span class="kn">import</span> <span class="n">Fraction</span>
  1457. <span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">Fraction</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
  1458. <span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">Fraction</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">5</span><span class="p">)</span>
  1459. <span class="gp">&gt;&gt;&gt; </span><span class="nb">float</span><span class="p">(</span><span class="n">a</span><span class="p">),</span> <span class="nb">float</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
  1460. <span class="go">(0.66666666666666663, 0.40000000000000002)</span>
  1461. <span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">+</span><span class="n">b</span>
  1462. <span class="go">Fraction(16, 15)</span>
  1463. <span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">/</span><span class="n">b</span>
  1464. <span class="go">Fraction(5, 3)</span>
  1465. </pre></div>
  1466. </div>
  1467. <p>For converting floating-point numbers to rationals,
  1468. the float type now has an <code class="xref py py-meth docutils literal notranslate"><span class="pre">as_integer_ratio()</span></code> method that returns
  1469. the numerator and denominator for a fraction that evaluates to the same
  1470. floating-point value:</p>
  1471. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="mf">2.5</span><span class="p">)</span> <span class="o">.</span><span class="n">as_integer_ratio</span><span class="p">()</span>
  1472. <span class="go">(5, 2)</span>
  1473. <span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="mf">3.1415</span><span class="p">)</span> <span class="o">.</span><span class="n">as_integer_ratio</span><span class="p">()</span>
  1474. <span class="go">(7074029114692207L, 2251799813685248L)</span>
  1475. <span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="mf">1.</span><span class="o">/</span><span class="mi">3</span><span class="p">)</span> <span class="o">.</span><span class="n">as_integer_ratio</span><span class="p">()</span>
  1476. <span class="go">(6004799503160661L, 18014398509481984L)</span>
  1477. </pre></div>
  1478. </div>
  1479. <p>Note that values that can only be approximated by floating-point
  1480. numbers, such as 1./3, are not simplified to the number being
  1481. approximated; the fraction attempts to match the floating-point value
  1482. <strong>exactly</strong>.</p>
  1483. <p>The <a class="reference internal" href="../library/fractions.html#module-fractions" title="fractions: Rational numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fractions</span></code></a> module is based upon an implementation by Sjoerd
  1484. Mullender that was in Python’s <code class="file docutils literal notranslate"><span class="pre">Demo/classes/</span></code> directory for a
  1485. long time. This implementation was significantly updated by Jeffrey
  1486. Yasskin.</p>
  1487. </section>
  1488. </section>
  1489. <section id="other-language-changes">
  1490. <h2>Other Language Changes<a class="headerlink" href="#other-language-changes" title="Link to this heading">¶</a></h2>
  1491. <p>Some smaller changes made to the core Python language are:</p>
  1492. <ul>
  1493. <li><p>Directories and zip archives containing a <code class="file docutils literal notranslate"><span class="pre">__main__.py</span></code> file
  1494. can now be executed directly by passing their name to the
  1495. interpreter. The directory or zip archive is automatically inserted
  1496. as the first entry in sys.path. (Suggestion and initial patch by
  1497. Andy Chu, subsequently revised by Phillip J. Eby and Nick Coghlan;
  1498. <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1739468">bpo-1739468</a>.)</p></li>
  1499. <li><p>The <a class="reference internal" href="../library/functions.html#hasattr" title="hasattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">hasattr()</span></code></a> function was catching and ignoring all errors,
  1500. under the assumption that they meant a <code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code> method
  1501. was failing somehow and the return value of <a class="reference internal" href="../library/functions.html#hasattr" title="hasattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">hasattr()</span></code></a> would
  1502. therefore be <code class="docutils literal notranslate"><span class="pre">False</span></code>. This logic shouldn’t be applied to
  1503. <a class="reference internal" href="../library/exceptions.html#KeyboardInterrupt" title="KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> and <a class="reference internal" href="../library/exceptions.html#SystemExit" title="SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a>, however; Python 2.6
  1504. will no longer discard such exceptions when <a class="reference internal" href="../library/functions.html#hasattr" title="hasattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">hasattr()</span></code></a>
  1505. encounters them. (Fixed by Benjamin Peterson; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2196">bpo-2196</a>.)</p></li>
  1506. <li><p>When calling a function using the <code class="docutils literal notranslate"><span class="pre">**</span></code> syntax to provide keyword
  1507. arguments, you are no longer required to use a Python dictionary;
  1508. any mapping will now work:</p>
  1509. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="o">**</span><span class="n">kw</span><span class="p">):</span>
  1510. <span class="gp">... </span> <span class="nb">print</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">kw</span><span class="p">)</span>
  1511. <span class="gp">...</span>
  1512. <span class="gp">&gt;&gt;&gt; </span><span class="n">ud</span><span class="o">=</span><span class="n">UserDict</span><span class="o">.</span><span class="n">UserDict</span><span class="p">()</span>
  1513. <span class="gp">&gt;&gt;&gt; </span><span class="n">ud</span><span class="p">[</span><span class="s1">&#39;a&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1</span>
  1514. <span class="gp">&gt;&gt;&gt; </span><span class="n">ud</span><span class="p">[</span><span class="s1">&#39;b&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;string&#39;</span>
  1515. <span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">(</span><span class="o">**</span><span class="n">ud</span><span class="p">)</span>
  1516. <span class="go">[&#39;a&#39;, &#39;b&#39;]</span>
  1517. </pre></div>
  1518. </div>
  1519. <p>(Contributed by Alexander Belopolsky; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1686487">bpo-1686487</a>.)</p>
  1520. <p>It’s also become legal to provide keyword arguments after a <code class="docutils literal notranslate"><span class="pre">*args</span></code> argument
  1521. to a function call.</p>
  1522. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">):</span>
  1523. <span class="gp">... </span> <span class="nb">print</span> <span class="n">args</span><span class="p">,</span> <span class="n">kw</span>
  1524. <span class="gp">...</span>
  1525. <span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</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> <span class="n">keyword</span><span class="o">=</span><span class="mi">13</span><span class="p">)</span>
  1526. <span class="go">(1, 2, 3, 4, 5, 6) {&#39;keyword&#39;: 13}</span>
  1527. </pre></div>
  1528. </div>
  1529. <p>Previously this would have been a syntax error.
  1530. (Contributed by Amaury Forgeot d’Arc; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=3473">bpo-3473</a>.)</p>
  1531. </li>
  1532. <li><p>A new builtin, <code class="docutils literal notranslate"><span class="pre">next(iterator,</span> <span class="pre">[default])</span></code> returns the next item
  1533. from the specified iterator. If the <em>default</em> argument is supplied,
  1534. it will be returned if <em>iterator</em> has been exhausted; otherwise,
  1535. the <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> exception will be raised. (Backported
  1536. in <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2719">bpo-2719</a>.)</p></li>
  1537. <li><p>Tuples now have <code class="xref py py-meth docutils literal notranslate"><span class="pre">index()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">count()</span></code> methods matching the
  1538. list type’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">index()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">count()</span></code> methods:</p>
  1539. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">t</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><span class="mi">3</span><span class="p">,</span><span class="mi">4</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>
  1540. <span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
  1541. <span class="go">3</span>
  1542. <span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">count</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
  1543. <span class="go">2</span>
  1544. </pre></div>
  1545. </div>
  1546. <p>(Contributed by Raymond Hettinger)</p>
  1547. </li>
  1548. <li><p>The built-in types now have improved support for extended slicing syntax,
  1549. accepting various combinations of <code class="docutils literal notranslate"><span class="pre">(start,</span> <span class="pre">stop,</span> <span class="pre">step)</span></code>.
  1550. Previously, the support was partial and certain corner cases wouldn’t work.
  1551. (Implemented by Thomas Wouters.)</p>
  1552. </li>
  1553. <li><p>Properties now have three attributes, <code class="xref py py-attr docutils literal notranslate"><span class="pre">getter</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">setter</span></code>
  1554. and <code class="xref py py-attr docutils literal notranslate"><span class="pre">deleter</span></code>, that are decorators providing useful shortcuts
  1555. for adding a getter, setter or deleter function to an existing
  1556. property. You would use them like this:</p>
  1557. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
  1558. <span class="nd">@property</span>
  1559. <span class="k">def</span> <span class="nf">x</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  1560. <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_x</span>
  1561. <span class="nd">@x</span><span class="o">.</span><span class="n">setter</span>
  1562. <span class="k">def</span> <span class="nf">x</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
  1563. <span class="bp">self</span><span class="o">.</span><span class="n">_x</span> <span class="o">=</span> <span class="n">value</span>
  1564. <span class="nd">@x</span><span class="o">.</span><span class="n">deleter</span>
  1565. <span class="k">def</span> <span class="nf">x</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  1566. <span class="k">del</span> <span class="bp">self</span><span class="o">.</span><span class="n">_x</span>
  1567. <span class="k">class</span> <span class="nc">D</span><span class="p">(</span><span class="n">C</span><span class="p">):</span>
  1568. <span class="nd">@C</span><span class="o">.</span><span class="n">x</span><span class="o">.</span><span class="n">getter</span>
  1569. <span class="k">def</span> <span class="nf">x</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  1570. <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_x</span> <span class="o">*</span> <span class="mi">2</span>
  1571. <span class="nd">@x</span><span class="o">.</span><span class="n">setter</span>
  1572. <span class="k">def</span> <span class="nf">x</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
  1573. <span class="bp">self</span><span class="o">.</span><span class="n">_x</span> <span class="o">=</span> <span class="n">value</span> <span class="o">/</span> <span class="mi">2</span>
  1574. </pre></div>
  1575. </div>
  1576. </li>
  1577. <li><p>Several methods of the built-in set types now accept multiple iterables:
  1578. <code class="xref py py-meth docutils literal notranslate"><span class="pre">intersection()</span></code>,
  1579. <code class="xref py py-meth docutils literal notranslate"><span class="pre">intersection_update()</span></code>,
  1580. <code class="xref py py-meth docutils literal notranslate"><span class="pre">union()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code>,
  1581. <code class="xref py py-meth docutils literal notranslate"><span class="pre">difference()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">difference_update()</span></code>.</p>
  1582. <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="nb">set</span><span class="p">(</span><span class="s1">&#39;1234567890&#39;</span><span class="p">)</span>
  1583. <span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">intersection</span><span class="p">(</span><span class="s1">&#39;abc123&#39;</span><span class="p">,</span> <span class="s1">&#39;cdf246&#39;</span><span class="p">)</span> <span class="c1"># Intersection between all inputs</span>
  1584. <span class="go">set([&#39;2&#39;])</span>
  1585. <span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">difference</span><span class="p">(</span><span class="s1">&#39;246&#39;</span><span class="p">,</span> <span class="s1">&#39;789&#39;</span><span class="p">)</span>
  1586. <span class="go">set([&#39;1&#39;, &#39;0&#39;, &#39;3&#39;, &#39;5&#39;])</span>
  1587. </pre></div>
  1588. </div>
  1589. <p>(Contributed by Raymond Hettinger.)</p>
  1590. </li>
  1591. <li><p>Many floating-point features were added. The <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-func docutils literal notranslate"><span class="pre">float()</span></code></a> function
  1592. will now turn the string <code class="docutils literal notranslate"><span class="pre">nan</span></code> into an
  1593. IEEE 754 Not A Number value, and <code class="docutils literal notranslate"><span class="pre">+inf</span></code> and <code class="docutils literal notranslate"><span class="pre">-inf</span></code> into
  1594. positive or negative infinity. This works on any platform with
  1595. IEEE 754 semantics. (Contributed by Christian Heimes; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1635">bpo-1635</a>.)</p>
  1596. <p>Other 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="xref py py-func docutils literal notranslate"><span class="pre">isinf()</span></code> and
  1597. <code class="xref py py-func docutils literal notranslate"><span class="pre">isnan()</span></code>, return true if their floating-point argument is
  1598. infinite or Not A Number. (<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1640">bpo-1640</a>)</p>
  1599. <p>Conversion functions were added to convert floating-point numbers
  1600. into hexadecimal strings (<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=3008">bpo-3008</a>). These functions
  1601. convert floats to and from a string representation without
  1602. introducing rounding errors from the conversion between decimal and
  1603. binary. Floats have a <a class="reference internal" href="../library/functions.html#hex" title="hex"><code class="xref py py-meth docutils literal notranslate"><span class="pre">hex()</span></code></a> method that returns a string
  1604. representation, and the <code class="docutils literal notranslate"><span class="pre">float.fromhex()</span></code> method converts a string
  1605. back into a number:</p>
  1606. <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="mf">3.75</span>
  1607. <span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">.</span><span class="n">hex</span><span class="p">()</span>
  1608. <span class="go">&#39;0x1.e000000000000p+1&#39;</span>
  1609. <span class="gp">&gt;&gt;&gt; </span><span class="nb">float</span><span class="o">.</span><span class="n">fromhex</span><span class="p">(</span><span class="s1">&#39;0x1.e000000000000p+1&#39;</span><span class="p">)</span>
  1610. <span class="go">3.75</span>
  1611. <span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">=</span><span class="mf">1.</span><span class="o">/</span><span class="mi">3</span>
  1612. <span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">hex</span><span class="p">()</span>
  1613. <span class="go">&#39;0x1.5555555555555p-2&#39;</span>
  1614. </pre></div>
  1615. </div>
  1616. </li>
  1617. <li><p>A numerical nicety: when creating a complex number from two floats
  1618. on systems that support signed zeros (-0 and +0), the
  1619. <a class="reference internal" href="../library/functions.html#complex" title="complex"><code class="xref py py-func docutils literal notranslate"><span class="pre">complex()</span></code></a> constructor will now preserve the sign
  1620. of the zero. (Fixed by Mark T. Dickinson; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1507">bpo-1507</a>.)</p></li>
  1621. <li><p>Classes that inherit a <code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code> method from a parent class
  1622. can set <code class="docutils literal notranslate"><span class="pre">__hash__</span> <span class="pre">=</span> <span class="pre">None</span></code> to indicate that the class isn’t
  1623. hashable. This will make <code class="docutils literal notranslate"><span class="pre">hash(obj)</span></code> raise 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>
  1624. and the class will not be indicated as implementing the
  1625. <code class="xref py py-class docutils literal notranslate"><span class="pre">Hashable</span></code> ABC.</p>
  1626. <p>You should do this when you’ve defined a <code class="xref py py-meth docutils literal notranslate"><span class="pre">__cmp__()</span></code> or
  1627. <code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code> method that compares objects by their value rather
  1628. than by identity. All objects have a default hash method that uses
  1629. <code class="docutils literal notranslate"><span class="pre">id(obj)</span></code> as the hash value. There’s no tidy way to remove the
  1630. <code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code> method inherited from a parent class, so
  1631. assigning <code class="docutils literal notranslate"><span class="pre">None</span></code> was implemented as an override. At the
  1632. C level, extensions can set <code class="docutils literal notranslate"><span class="pre">tp_hash</span></code> to
  1633. <a class="reference internal" href="../c-api/object.html#c.PyObject_HashNotImplemented" title="PyObject_HashNotImplemented"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_HashNotImplemented()</span></code></a>.
  1634. (Fixed by Nick Coghlan and Amaury Forgeot d’Arc; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2235">bpo-2235</a>.)</p>
  1635. </li>
  1636. <li><p>The <a class="reference internal" href="../library/exceptions.html#GeneratorExit" title="GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> exception now subclasses
  1637. <a class="reference internal" href="../library/exceptions.html#BaseException" title="BaseException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BaseException</span></code></a> instead of <a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a>. This means
  1638. that an exception handler that does <code class="docutils literal notranslate"><span class="pre">except</span> <span class="pre">Exception:</span></code>
  1639. will not inadvertently catch <a class="reference internal" href="../library/exceptions.html#GeneratorExit" title="GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a>.
  1640. (Contributed by Chad Austin; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1537">bpo-1537</a>.)</p></li>
  1641. <li><p>Generator objects now have a <code class="xref py py-attr docutils literal notranslate"><span class="pre">gi_code</span></code> attribute that refers to
  1642. the original code object backing the generator.
  1643. (Contributed by Collin Winter; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1473257">bpo-1473257</a>.)</p></li>
  1644. <li><p>The <a class="reference internal" href="../library/functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a> built-in function now accepts keyword arguments
  1645. as well as positional parameters. (Contributed by Thomas Wouters;
  1646. <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1444529">bpo-1444529</a>.)</p></li>
  1647. <li><p>The <a class="reference internal" href="../library/functions.html#complex" title="complex"><code class="xref py py-func docutils literal notranslate"><span class="pre">complex()</span></code></a> constructor now accepts strings containing
  1648. parenthesized complex numbers, meaning that <code class="docutils literal notranslate"><span class="pre">complex(repr(cplx))</span></code>
  1649. will now round-trip values. For example, <code class="docutils literal notranslate"><span class="pre">complex('(3+4j)')</span></code>
  1650. now returns the value (3+4j). (<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1491866">bpo-1491866</a>)</p></li>
  1651. <li><p>The string <code class="xref py py-meth docutils literal notranslate"><span class="pre">translate()</span></code> method now accepts <code class="docutils literal notranslate"><span class="pre">None</span></code> as the
  1652. translation table parameter, which is treated as the identity
  1653. transformation. This makes it easier to carry out operations
  1654. that only delete characters. (Contributed by Bengt Richter and
  1655. implemented by Raymond Hettinger; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1193128">bpo-1193128</a>.)</p></li>
  1656. <li><p>The built-in <a class="reference internal" href="../library/functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> function now checks for a <code class="xref py py-meth docutils literal notranslate"><span class="pre">__dir__()</span></code>
  1657. method on the objects it receives. This method must return a list
  1658. of strings containing the names of valid attributes for the object,
  1659. and lets the object control the value that <a class="reference internal" href="../library/functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> produces.
  1660. Objects that have <code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code>
  1661. methods can use this to advertise pseudo-attributes they will honor.
  1662. (<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1591665">bpo-1591665</a>)</p></li>
  1663. <li><p>Instance method objects have new attributes for the object and function
  1664. comprising the method; the new synonym for <code class="xref py py-attr docutils literal notranslate"><span class="pre">im_self</span></code> is
  1665. <a class="reference internal" href="../reference/datamodel.html#method.__self__" title="method.__self__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code></a>, and <code class="xref py py-attr docutils literal notranslate"><span class="pre">im_func</span></code> is also available as
  1666. <a class="reference internal" href="../reference/datamodel.html#method.__func__" title="method.__func__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__func__</span></code></a>.
  1667. The old names are still supported in Python 2.6, but are gone in 3.0.</p></li>
  1668. <li><p>An obscure change: when you use the <a class="reference internal" href="../library/functions.html#locals" title="locals"><code class="xref py py-func docutils literal notranslate"><span class="pre">locals()</span></code></a> function inside a
  1669. <a class="reference internal" href="../reference/compound_stmts.html#class"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">class</span></code></a> statement, the resulting dictionary no longer returns free
  1670. variables. (Free variables, in this case, are variables referenced in the
  1671. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">class</span></code> statement that aren’t attributes of the class.)</p></li>
  1672. </ul>
  1673. <section id="optimizations">
  1674. <h3>Optimizations<a class="headerlink" href="#optimizations" title="Link to this heading">¶</a></h3>
  1675. <ul>
  1676. <li><p>The <a class="reference internal" href="../library/warnings.html#module-warnings" title="warnings: Issue warning messages and control their disposition."><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code></a> module has been rewritten in C. This makes
  1677. it possible to invoke warnings from the parser, and may also
  1678. make the interpreter’s startup faster.
  1679. (Contributed by Neal Norwitz and Brett Cannon; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1631171">bpo-1631171</a>.)</p></li>
  1680. <li><p>Type objects now have a cache of methods that can reduce
  1681. the work required to find the correct method implementation
  1682. for a particular class; once cached, the interpreter doesn’t need to
  1683. traverse base classes to figure out the right method to call.
  1684. The cache is cleared if a base class or the class itself is modified,
  1685. so the cache should remain correct even in the face of Python’s dynamic
  1686. nature.
  1687. (Original optimization implemented by Armin Rigo, updated for
  1688. Python 2.6 by Kevin Jacobs; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1700288">bpo-1700288</a>.)</p>
  1689. <p>By default, this change is only applied to types that are included with
  1690. the Python core. Extension modules may not necessarily be compatible with
  1691. this cache,
  1692. so they must explicitly add <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_VERSION_TAG</span></code>
  1693. to the module’s <code class="docutils literal notranslate"><span class="pre">tp_flags</span></code> field to enable the method cache.
  1694. (To be compatible with the method cache, the extension module’s code
  1695. must not directly access and modify the <code class="docutils literal notranslate"><span class="pre">tp_dict</span></code> member of
  1696. any of the types it implements. Most modules don’t do this,
  1697. but it’s impossible for the Python interpreter to determine that.
  1698. See <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1878">bpo-1878</a> for some discussion.)</p>
  1699. </li>
  1700. <li><p>Function calls that use keyword arguments are significantly faster
  1701. by doing a quick pointer comparison, usually saving the time of a
  1702. full string comparison. (Contributed by Raymond Hettinger, after an
  1703. initial implementation by Antoine Pitrou; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1819">bpo-1819</a>.)</p></li>
  1704. <li><p>All of the functions in the <a class="reference internal" href="../library/struct.html#module-struct" title="struct: Interpret bytes as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> module have been rewritten in
  1705. C, thanks to work at the Need For Speed sprint.
  1706. (Contributed by Raymond Hettinger.)</p></li>
  1707. <li><p>Some of the standard built-in types now set a bit in their type
  1708. objects. This speeds up checking whether an object is a subclass of
  1709. one of these types. (Contributed by Neal Norwitz.)</p></li>
  1710. <li><p>Unicode strings now use faster code for detecting
  1711. whitespace and line breaks; this speeds up the <code class="xref py py-meth docutils literal notranslate"><span class="pre">split()</span></code> method
  1712. by about 25% and <code class="xref py py-meth docutils literal notranslate"><span class="pre">splitlines()</span></code> by 35%.
  1713. (Contributed by Antoine Pitrou.) Memory usage is reduced
  1714. by using pymalloc for the Unicode string’s data.</p></li>
  1715. <li><p>The <code class="docutils literal notranslate"><span class="pre">with</span></code> statement now stores the <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method on the stack,
  1716. producing a small speedup. (Implemented by Jeffrey Yasskin.)</p></li>
  1717. <li><p>To reduce memory usage, the garbage collector will now clear internal
  1718. free lists when garbage-collecting the highest generation of objects.
  1719. This may return memory to the operating system sooner.</p></li>
  1720. </ul>
  1721. </section>
  1722. <section id="interpreter-changes">
  1723. <span id="new-26-interpreter"></span><h3>Interpreter Changes<a class="headerlink" href="#interpreter-changes" title="Link to this heading">¶</a></h3>
  1724. <p>Two command-line options have been reserved for use by other Python
  1725. implementations. The <a class="reference internal" href="../using/cmdline.html#cmdoption-J"><code class="xref std std-option docutils literal notranslate"><span class="pre">-J</span></code></a> switch has been reserved for use by
  1726. Jython for Jython-specific options, such as switches that are passed to
  1727. the underlying JVM. <a class="reference internal" href="../using/cmdline.html#cmdoption-X"><code class="xref std std-option docutils literal notranslate"><span class="pre">-X</span></code></a> has been reserved for options
  1728. specific to a particular implementation of Python such as CPython,
  1729. Jython, or IronPython. If either option is used with Python 2.6, the
  1730. interpreter will report that the option isn’t currently used.</p>
  1731. <p>Python can now be prevented from writing <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>
  1732. files by supplying the <a class="reference internal" href="../using/cmdline.html#cmdoption-B"><code class="xref std std-option docutils literal notranslate"><span class="pre">-B</span></code></a> switch to the Python interpreter,
  1733. or by setting the <span class="target" id="index-20"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONDONTWRITEBYTECODE</span></code></a> environment
  1734. variable before running the interpreter. This setting is available to
  1735. Python programs as the <code class="docutils literal notranslate"><span class="pre">sys.dont_write_bytecode</span></code> variable, and
  1736. Python code can change the value to modify the interpreter’s
  1737. behaviour. (Contributed by Neal Norwitz and Georg Brandl.)</p>
  1738. <p>The encoding used for standard input, output, and standard error can
  1739. be specified by setting the <span class="target" id="index-21"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONIOENCODING"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONIOENCODING</span></code></a> environment
  1740. variable before running the interpreter. The value should be a string
  1741. in the form <code class="docutils literal notranslate"><span class="pre">&lt;encoding&gt;</span></code> or <code class="docutils literal notranslate"><span class="pre">&lt;encoding&gt;:&lt;errorhandler&gt;</span></code>.
  1742. The <em>encoding</em> part specifies the encoding’s name, e.g. <code class="docutils literal notranslate"><span class="pre">utf-8</span></code> or
  1743. <code class="docutils literal notranslate"><span class="pre">latin-1</span></code>; the optional <em>errorhandler</em> part specifies
  1744. what to do with characters that can’t be handled by the encoding,
  1745. and should be one of “error”, “ignore”, or “replace”. (Contributed
  1746. by Martin von Löwis.)</p>
  1747. </section>
  1748. </section>
  1749. <section id="new-and-improved-modules">
  1750. <h2>New and Improved Modules<a class="headerlink" href="#new-and-improved-modules" title="Link to this heading">¶</a></h2>
  1751. <p>As in every release, Python’s standard library received a number of
  1752. enhancements and bug fixes. Here’s a partial list of the most notable
  1753. changes, sorted alphabetically by module name. Consult the
  1754. <code class="file docutils literal notranslate"><span class="pre">Misc/NEWS</span></code> file in the source tree for a more complete list of
  1755. changes, or look through the Subversion logs for all the details.</p>
  1756. <ul>
  1757. <li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncore</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">asynchat</span></code> modules are
  1758. being actively maintained again, and a number of patches and bugfixes
  1759. were applied. (Maintained by Josiah Carlson; see <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1736190">bpo-1736190</a> for
  1760. one patch.)</p></li>
  1761. <li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code> module also has a new maintainer, Jesús Cea Avión, and the package
  1762. is now available as a standalone package. The web page for the package is
  1763. <a class="reference external" href="https://www.jcea.es/programacion/pybsddb.htm">www.jcea.es/programacion/pybsddb.htm</a>.
  1764. The plan is to remove the package from the standard library
  1765. in Python 3.0, because its pace of releases is much more frequent than
  1766. Python’s.</p>
  1767. <p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb.dbshelve</span></code> module now uses the highest pickling protocol
  1768. available, instead of restricting itself to protocol 1.
  1769. (Contributed by W. Barnes.)</p>
  1770. </li>
  1771. <li><p>The <a class="reference internal" href="../library/cgi.html#module-cgi" title="cgi: Helpers for running Python scripts via the Common Gateway Interface. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cgi</span></code></a> module will now read variables from the query string
  1772. of an HTTP POST request. This makes it possible to use form actions
  1773. with URLs that include query strings such as
  1774. “/cgi-bin/add.py?category=1”. (Contributed by Alexandre Fiori and
  1775. Nubis; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1817">bpo-1817</a>.)</p>
  1776. <p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">parse_qs()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">parse_qsl()</span></code> functions have been
  1777. relocated from the <a class="reference internal" href="../library/cgi.html#module-cgi" title="cgi: Helpers for running Python scripts via the Common Gateway Interface. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cgi</span></code></a> module to the <a class="reference internal" href="../library/urllib.parse.html#module-urllib.parse" title="urllib.parse: Parse URLs into or assemble them from components."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urlparse</span></code></a> module.
  1778. The versions still available in the <code class="xref py py-mod docutils literal notranslate"><span class="pre">cgi</span></code> module will
  1779. trigger <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> messages in 2.6
  1780. (<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=600362">bpo-600362</a>).</p>
  1781. </li>
  1782. <li><p>The <a class="reference internal" href="../library/cmath.html#module-cmath" title="cmath: Mathematical functions for complex numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cmath</span></code></a> module underwent extensive revision,
  1783. contributed by Mark Dickinson and Christian Heimes.
  1784. Five new functions were added:</p>
  1785. <ul class="simple">
  1786. <li><p><code class="xref py py-func docutils literal notranslate"><span class="pre">polar()</span></code> converts a complex number to polar form, returning
  1787. the modulus and argument of the complex number.</p></li>
  1788. <li><p><code class="xref py py-func docutils literal notranslate"><span class="pre">rect()</span></code> does the opposite, turning a modulus, argument pair
  1789. back into the corresponding complex number.</p></li>
  1790. <li><p><code class="xref py py-func docutils literal notranslate"><span class="pre">phase()</span></code> returns the argument (also called the angle) of a complex
  1791. number.</p></li>
  1792. <li><p><code class="xref py py-func docutils literal notranslate"><span class="pre">isnan()</span></code> returns True if either
  1793. the real or imaginary part of its argument is a NaN.</p></li>
  1794. <li><p><code class="xref py py-func docutils literal notranslate"><span class="pre">isinf()</span></code> returns True if either the real or imaginary part of
  1795. its argument is infinite.</p></li>
  1796. </ul>
  1797. <p>The revisions also improved the numerical soundness of the
  1798. <a class="reference internal" href="../library/cmath.html#module-cmath" title="cmath: Mathematical functions for complex numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cmath</span></code></a> module. For all functions, the real and imaginary
  1799. parts of the results are accurate to within a few units of least
  1800. precision (ulps) whenever possible. See <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1381">bpo-1381</a> for the
  1801. details. The branch cuts for <code class="xref py py-func docutils literal notranslate"><span class="pre">asinh()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">atanh()</span></code>: and
  1802. <code class="xref py py-func docutils literal notranslate"><span class="pre">atan()</span></code> have also been corrected.</p>
  1803. <p>The tests for the module have been greatly expanded; nearly 2000 new
  1804. test cases exercise the algebraic functions.</p>
  1805. <p>On IEEE 754 platforms, the <a class="reference internal" href="../library/cmath.html#module-cmath" title="cmath: Mathematical functions for complex numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cmath</span></code></a> module now handles IEEE 754
  1806. special values and floating-point exceptions in a manner consistent
  1807. with Annex ‘G’ of the C99 standard.</p>
  1808. </li>
  1809. <li><p>A new data type in the <a class="reference internal" href="../library/collections.html#module-collections" title="collections: Container datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> module: <code class="docutils literal notranslate"><span class="pre">namedtuple(typename,</span> <span class="pre">fieldnames)</span></code>
  1810. is a factory function that creates subclasses of the standard tuple
  1811. whose fields are accessible by name as well as index. For example:</p>
  1812. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">var_type</span> <span class="o">=</span> <span class="n">collections</span><span class="o">.</span><span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;variable&#39;</span><span class="p">,</span>
  1813. <span class="gp">... </span> <span class="s1">&#39;id name type size&#39;</span><span class="p">)</span>
  1814. <span class="gp">&gt;&gt;&gt; </span><span class="c1"># Names are separated by spaces or commas.</span>
  1815. <span class="gp">&gt;&gt;&gt; </span><span class="c1"># &#39;id, name, type, size&#39; would also work.</span>
  1816. <span class="gp">&gt;&gt;&gt; </span><span class="n">var_type</span><span class="o">.</span><span class="n">_fields</span>
  1817. <span class="go">(&#39;id&#39;, &#39;name&#39;, &#39;type&#39;, &#39;size&#39;)</span>
  1818. <span class="gp">&gt;&gt;&gt; </span><span class="n">var</span> <span class="o">=</span> <span class="n">var_type</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;frequency&#39;</span><span class="p">,</span> <span class="s1">&#39;int&#39;</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span>
  1819. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">var</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">var</span><span class="o">.</span><span class="n">id</span> <span class="c1"># Equivalent</span>
  1820. <span class="go">1 1</span>
  1821. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">var</span><span class="p">[</span><span class="mi">2</span><span class="p">],</span> <span class="n">var</span><span class="o">.</span><span class="n">type</span> <span class="c1"># Equivalent</span>
  1822. <span class="go">int int</span>
  1823. <span class="gp">&gt;&gt;&gt; </span><span class="n">var</span><span class="o">.</span><span class="n">_asdict</span><span class="p">()</span>
  1824. <span class="go">{&#39;size&#39;: 4, &#39;type&#39;: &#39;int&#39;, &#39;id&#39;: 1, &#39;name&#39;: &#39;frequency&#39;}</span>
  1825. <span class="gp">&gt;&gt;&gt; </span><span class="n">v2</span> <span class="o">=</span> <span class="n">var</span><span class="o">.</span><span class="n">_replace</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;amplitude&#39;</span><span class="p">)</span>
  1826. <span class="gp">&gt;&gt;&gt; </span><span class="n">v2</span>
  1827. <span class="go">variable(id=1, name=&#39;amplitude&#39;, type=&#39;int&#39;, size=4)</span>
  1828. </pre></div>
  1829. </div>
  1830. <p>Several places in the standard library that returned tuples have
  1831. been modified to return <code class="xref py py-func docutils literal notranslate"><span class="pre">namedtuple()</span></code> instances. For example,
  1832. the <code class="xref py py-meth docutils literal notranslate"><span class="pre">Decimal.as_tuple()</span></code> method now returns a named tuple with
  1833. <code class="xref py py-attr docutils literal notranslate"><span class="pre">sign</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">digits</span></code>, and <code class="xref py py-attr docutils literal notranslate"><span class="pre">exponent</span></code> fields.</p>
  1834. <p>(Contributed by Raymond Hettinger.)</p>
  1835. </li>
  1836. <li><p>Another change to the <a class="reference internal" href="../library/collections.html#module-collections" title="collections: Container datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> module is that the
  1837. <code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code> type now supports an optional <em>maxlen</em> parameter;
  1838. if supplied, the deque’s size will be restricted to no more
  1839. than <em>maxlen</em> items. Adding more items to a full deque causes
  1840. old items to be discarded.</p>
  1841. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">collections</span> <span class="kn">import</span> <span class="n">deque</span>
  1842. <span class="gp">&gt;&gt;&gt; </span><span class="n">dq</span><span class="o">=</span><span class="n">deque</span><span class="p">(</span><span class="n">maxlen</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>
  1843. <span class="gp">&gt;&gt;&gt; </span><span class="n">dq</span>
  1844. <span class="go">deque([], maxlen=3)</span>
  1845. <span class="gp">&gt;&gt;&gt; </span><span class="n">dq</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span> <span class="n">dq</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">2</span><span class="p">);</span> <span class="n">dq</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
  1846. <span class="gp">&gt;&gt;&gt; </span><span class="n">dq</span>
  1847. <span class="go">deque([1, 2, 3], maxlen=3)</span>
  1848. <span class="gp">&gt;&gt;&gt; </span><span class="n">dq</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
  1849. <span class="gp">&gt;&gt;&gt; </span><span class="n">dq</span>
  1850. <span class="go">deque([2, 3, 4], maxlen=3)</span>
  1851. </pre></div>
  1852. </div>
  1853. <p>(Contributed by Raymond Hettinger.)</p>
  1854. </li>
  1855. <li><p>The <a class="reference internal" href="../library/http.cookies.html#module-http.cookies" title="http.cookies: Support for HTTP state management (cookies)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">Cookie</span></code></a> module’s <a class="reference internal" href="../library/http.cookies.html#http.cookies.Morsel" title="http.cookies.Morsel"><code class="xref py py-class docutils literal notranslate"><span class="pre">Morsel</span></code></a> objects now support an
  1856. <a class="reference internal" href="../library/http.cookies.html#http.cookies.Morsel.httponly" title="http.cookies.Morsel.httponly"><code class="xref py py-attr docutils literal notranslate"><span class="pre">httponly</span></code></a> attribute. In some browsers. cookies with this attribute
  1857. set cannot be accessed or manipulated by JavaScript code.
  1858. (Contributed by Arvin Schnell; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1638033">bpo-1638033</a>.)</p></li>
  1859. <li><p>A new window method in the <a class="reference internal" href="../library/curses.html#module-curses" title="curses: An interface to the curses library, providing portable terminal handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses</span></code></a> module,
  1860. <code class="xref py py-meth docutils literal notranslate"><span class="pre">chgat()</span></code>, changes the display attributes for a certain number of
  1861. characters on a single line. (Contributed by Fabian Kreutz.)</p>
  1862. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Boldface text starting at y=0,x=21</span>
  1863. <span class="c1"># and affecting the rest of the line.</span>
  1864. <span class="n">stdscr</span><span class="o">.</span><span class="n">chgat</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">21</span><span class="p">,</span> <span class="n">curses</span><span class="o">.</span><span class="n">A_BOLD</span><span class="p">)</span>
  1865. </pre></div>
  1866. </div>
  1867. <p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">Textbox</span></code> class in the <a class="reference internal" href="../library/curses.html#module-curses.textpad" title="curses.textpad: Emacs-like input editing in a curses window."><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses.textpad</span></code></a> module
  1868. now supports editing in insert mode as well as overwrite mode.
  1869. Insert mode is enabled by supplying a true value for the <em>insert_mode</em>
  1870. parameter when creating the <code class="xref py py-class docutils literal notranslate"><span class="pre">Textbox</span></code> instance.</p>
  1871. </li>
  1872. <li><p>The <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’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">strftime()</span></code> methods now support a
  1873. <code class="docutils literal notranslate"><span class="pre">%f</span></code> format code that expands to the number of microseconds in the
  1874. object, zero-padded on
  1875. the left to six places. (Contributed by Skip Montanaro; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1158">bpo-1158</a>.)</p></li>
  1876. <li><p>The <a class="reference internal" href="../library/decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> module was updated to version 1.66 of
  1877. <a class="reference external" href="https://speleotrove.com/decimal/decarith.html">the General Decimal Specification</a>. New features
  1878. include some methods for some basic mathematical functions such as
  1879. <code class="xref py py-meth docutils literal notranslate"><span class="pre">exp()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">log10()</span></code>:</p>
  1880. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="n">exp</span><span class="p">()</span>
  1881. <span class="go">Decimal(&quot;2.718281828459045235360287471&quot;)</span>
  1882. <span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="s2">&quot;2.7182818&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">ln</span><span class="p">()</span>
  1883. <span class="go">Decimal(&quot;0.9999999895305022877376682436&quot;)</span>
  1884. <span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1000</span><span class="p">)</span><span class="o">.</span><span class="n">log10</span><span class="p">()</span>
  1885. <span class="go">Decimal(&quot;3&quot;)</span>
  1886. </pre></div>
  1887. </div>
  1888. <p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">as_tuple()</span></code> method of <code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code> objects now returns a
  1889. named tuple with <code class="xref py py-attr docutils literal notranslate"><span class="pre">sign</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">digits</span></code>, and <code class="xref py py-attr docutils literal notranslate"><span class="pre">exponent</span></code> fields.</p>
  1890. <p>(Implemented by Facundo Batista and Mark Dickinson. Named tuple
  1891. support added by Raymond Hettinger.)</p>
  1892. </li>
  1893. <li><p>The <a class="reference internal" href="../library/difflib.html#module-difflib" title="difflib: Helpers for computing differences between objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">difflib</span></code></a> module’s <code class="xref py py-class docutils literal notranslate"><span class="pre">SequenceMatcher</span></code> class
  1894. now returns named tuples representing matches,
  1895. with <code class="xref py py-attr docutils literal notranslate"><span class="pre">a</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">b</span></code>, and <code class="xref py py-attr docutils literal notranslate"><span class="pre">size</span></code> attributes.
  1896. (Contributed by Raymond Hettinger.)</p></li>
  1897. <li><p>An optional <code class="docutils literal notranslate"><span class="pre">timeout</span></code> parameter, specifying a timeout measured in
  1898. seconds, was added to the <a class="reference internal" href="../library/ftplib.html#ftplib.FTP" title="ftplib.FTP"><code class="xref py py-class docutils literal notranslate"><span class="pre">ftplib.FTP</span></code></a> class constructor as
  1899. well as the <code class="xref py py-meth docutils literal notranslate"><span class="pre">connect()</span></code> method. (Added by Facundo Batista.)
  1900. Also, the <code class="xref py py-class docutils literal notranslate"><span class="pre">FTP</span></code> class’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">storbinary()</span></code> and
  1901. <code class="xref py py-meth docutils literal notranslate"><span class="pre">storlines()</span></code> now take an optional <em>callback</em> parameter that
  1902. will be called with each block of data after the data has been sent.
  1903. (Contributed by Phil Schwartz; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1221598">bpo-1221598</a>.)</p></li>
  1904. <li><p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">reduce()</span></code> built-in function is also available in the
  1905. <a class="reference internal" href="../library/functools.html#module-functools" title="functools: Higher-order functions and operations on callable objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">functools</span></code></a> module. In Python 3.0, the builtin has been
  1906. dropped and <code class="xref py py-func docutils literal notranslate"><span class="pre">reduce()</span></code> is only available from <a class="reference internal" href="../library/functools.html#module-functools" title="functools: Higher-order functions and operations on callable objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">functools</span></code></a>;
  1907. currently there are no plans to drop the builtin in the 2.x series.
  1908. (Patched by Christian Heimes; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1739906">bpo-1739906</a>.)</p></li>
  1909. <li><p>When possible, the <a class="reference internal" href="../library/getpass.html#module-getpass" title="getpass: Portable reading of passwords and retrieval of the userid."><code class="xref py py-mod docutils literal notranslate"><span class="pre">getpass</span></code></a> module will now use
  1910. <code class="file docutils literal notranslate"><span class="pre">/dev/tty</span></code> to print a prompt message and read the password,
  1911. falling back to standard error and standard input. If the
  1912. password may be echoed to the terminal, a warning is printed before
  1913. the prompt is displayed. (Contributed by Gregory P. Smith.)</p></li>
  1914. <li><p>The <a class="reference internal" href="../library/glob.html#glob.glob" title="glob.glob"><code class="xref py py-func docutils literal notranslate"><span class="pre">glob.glob()</span></code></a> function can now return Unicode filenames if
  1915. a Unicode path was used and Unicode filenames are matched within the
  1916. directory. (<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1001604">bpo-1001604</a>)</p></li>
  1917. <li><p>A new function in 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, <code class="docutils literal notranslate"><span class="pre">merge(iter1,</span> <span class="pre">iter2,</span> <span class="pre">...)</span></code>,
  1918. takes any number of iterables returning data in sorted
  1919. order, and returns a new generator that returns the contents of all
  1920. the iterators, also in sorted order. For example:</p>
  1921. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">heapq</span><span class="o">.</span><span class="n">merge</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="mi">5</span><span class="p">,</span> <span class="mi">9</span><span class="p">],</span> <span class="p">[</span><span class="mi">2</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">16</span><span class="p">]))</span>
  1922. <span class="go">[1, 2, 3, 5, 8, 9, 16]</span>
  1923. </pre></div>
  1924. </div>
  1925. <p>Another new function, <code class="docutils literal notranslate"><span class="pre">heappushpop(heap,</span> <span class="pre">item)</span></code>,
  1926. pushes <em>item</em> onto <em>heap</em>, then pops off and returns the smallest item.
  1927. This is more efficient than making a call to <code class="xref py py-func docutils literal notranslate"><span class="pre">heappush()</span></code> and then
  1928. <code class="xref py py-func docutils literal notranslate"><span class="pre">heappop()</span></code>.</p>
  1929. <p><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> is now implemented to only use less-than comparison,
  1930. instead of the less-than-or-equal comparison it previously used.
  1931. This makes <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>’s usage of a type match the
  1932. <a class="reference internal" href="../library/stdtypes.html#list.sort" title="list.sort"><code class="xref py py-meth docutils literal notranslate"><span class="pre">list.sort()</span></code></a> method.
  1933. (Contributed by Raymond Hettinger.)</p>
  1934. </li>
  1935. <li><p>An optional <code class="docutils literal notranslate"><span class="pre">timeout</span></code> parameter, specifying a timeout measured in
  1936. seconds, was added to the <a class="reference internal" href="../library/http.client.html#http.client.HTTPConnection" title="http.client.HTTPConnection"><code class="xref py py-class docutils literal notranslate"><span class="pre">httplib.HTTPConnection</span></code></a> and
  1937. <a class="reference internal" href="../library/http.client.html#http.client.HTTPSConnection" title="http.client.HTTPSConnection"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPSConnection</span></code></a> class constructors. (Added by Facundo
  1938. Batista.)</p></li>
  1939. <li><p>Most of the <a class="reference internal" href="../library/inspect.html#module-inspect" title="inspect: Extract information and source code from live objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">inspect</span></code></a> module’s functions, such as
  1940. <code class="xref py py-func docutils literal notranslate"><span class="pre">getmoduleinfo()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">getargs()</span></code>, now return named tuples.
  1941. In addition to behaving like tuples, the elements of the return value
  1942. can also be accessed as attributes.
  1943. (Contributed by Raymond Hettinger.)</p>
  1944. <p>Some new functions in the module include
  1945. <code class="xref py py-func docutils literal notranslate"><span class="pre">isgenerator()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">isgeneratorfunction()</span></code>,
  1946. and <code class="xref py py-func docutils literal notranslate"><span class="pre">isabstract()</span></code>.</p>
  1947. </li>
  1948. <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> module gained several new functions.</p>
  1949. <p><code class="docutils literal notranslate"><span class="pre">izip_longest(iter1,</span> <span class="pre">iter2,</span> <span class="pre">...[,</span> <span class="pre">fillvalue])</span></code> makes tuples from
  1950. each of the elements; if some of the iterables are shorter than
  1951. others, the missing values are set to <em>fillvalue</em>. For example:</p>
  1952. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">tuple</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">izip_longest</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="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><span class="mi">5</span><span class="p">]))</span>
  1953. <span class="go">((1, 1), (2, 2), (3, 3), (None, 4), (None, 5))</span>
  1954. </pre></div>
  1955. </div>
  1956. <p><code class="docutils literal notranslate"><span class="pre">product(iter1,</span> <span class="pre">iter2,</span> <span class="pre">...,</span> <span class="pre">[repeat=N])</span></code> returns the Cartesian product
  1957. of the supplied iterables, a set of tuples containing
  1958. every possible combination of the elements returned from each iterable.</p>
  1959. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">product</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="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>
  1960. <span class="go">[(1, 4), (1, 5), (1, 6),</span>
  1961. <span class="go"> (2, 4), (2, 5), (2, 6),</span>
  1962. <span class="go"> (3, 4), (3, 5), (3, 6)]</span>
  1963. </pre></div>
  1964. </div>
  1965. <p>The optional <em>repeat</em> keyword argument is used for taking the
  1966. product of an iterable or a set of iterables with themselves,
  1967. repeated <em>N</em> times. With a single iterable argument, <em>N</em>-tuples
  1968. are returned:</p>
  1969. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">product</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="n">repeat</span><span class="o">=</span><span class="mi">3</span><span class="p">))</span>
  1970. <span class="go">[(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),</span>
  1971. <span class="go"> (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]</span>
  1972. </pre></div>
  1973. </div>
  1974. <p>With two iterables, <em>2N</em>-tuples are returned.</p>
  1975. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">product</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="p">[</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">],</span> <span class="n">repeat</span><span class="o">=</span><span class="mi">2</span><span class="p">))</span>
  1976. <span class="go">[(1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4),</span>
  1977. <span class="go"> (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4),</span>
  1978. <span class="go"> (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4),</span>
  1979. <span class="go"> (2, 4, 1, 3), (2, 4, 1, 4), (2, 4, 2, 3), (2, 4, 2, 4)]</span>
  1980. </pre></div>
  1981. </div>
  1982. <p><code class="docutils literal notranslate"><span class="pre">combinations(iterable,</span> <span class="pre">r)</span></code> returns sub-sequences of length <em>r</em> from
  1983. the elements of <em>iterable</em>.</p>
  1984. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">combinations</span><span class="p">(</span><span class="s1">&#39;123&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span>
  1985. <span class="go">[(&#39;1&#39;, &#39;2&#39;), (&#39;1&#39;, &#39;3&#39;), (&#39;2&#39;, &#39;3&#39;)]</span>
  1986. <span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">combinations</span><span class="p">(</span><span class="s1">&#39;123&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">))</span>
  1987. <span class="go">[(&#39;1&#39;, &#39;2&#39;, &#39;3&#39;)]</span>
  1988. <span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">combinations</span><span class="p">(</span><span class="s1">&#39;1234&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">))</span>
  1989. <span class="go">[(&#39;1&#39;, &#39;2&#39;, &#39;3&#39;), (&#39;1&#39;, &#39;2&#39;, &#39;4&#39;),</span>
  1990. <span class="go"> (&#39;1&#39;, &#39;3&#39;, &#39;4&#39;), (&#39;2&#39;, &#39;3&#39;, &#39;4&#39;)]</span>
  1991. </pre></div>
  1992. </div>
  1993. <p><code class="docutils literal notranslate"><span class="pre">permutations(iter[,</span> <span class="pre">r])</span></code> returns all the permutations of length <em>r</em> of
  1994. the iterable’s elements. If <em>r</em> is not specified, it will default to the
  1995. number of elements produced by the iterable.</p>
  1996. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">permutations</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> <span class="mi">2</span><span class="p">))</span>
  1997. <span class="go">[(1, 2), (1, 3), (1, 4),</span>
  1998. <span class="go"> (2, 1), (2, 3), (2, 4),</span>
  1999. <span class="go"> (3, 1), (3, 2), (3, 4),</span>
  2000. <span class="go"> (4, 1), (4, 2), (4, 3)]</span>
  2001. </pre></div>
  2002. </div>
  2003. <p><code class="docutils literal notranslate"><span class="pre">itertools.chain(*iterables)</span></code> is an existing function in
  2004. <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> that gained a new constructor in Python 2.6.
  2005. <code class="docutils literal notranslate"><span class="pre">itertools.chain.from_iterable(iterable)</span></code> takes a single
  2006. iterable that should return other iterables. <code class="xref py py-func docutils literal notranslate"><span class="pre">chain()</span></code> will
  2007. then return all the elements of the first iterable, then
  2008. all the elements of the second, and so on.</p>
  2009. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">chain</span><span class="o">.</span><span class="n">from_iterable</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="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>
  2010. <span class="go">[1, 2, 3, 4, 5, 6]</span>
  2011. </pre></div>
  2012. </div>
  2013. <p>(All contributed by Raymond Hettinger.)</p>
  2014. </li>
  2015. <li><p>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> module’s <code class="xref py py-class docutils literal notranslate"><span class="pre">FileHandler</span></code> class
  2016. and its subclasses <code class="xref py py-class docutils literal notranslate"><span class="pre">WatchedFileHandler</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">RotatingFileHandler</span></code>,
  2017. and <code class="xref py py-class docutils literal notranslate"><span class="pre">TimedRotatingFileHandler</span></code> now
  2018. have an optional <em>delay</em> parameter to their constructors. If <em>delay</em>
  2019. is true, opening of the log file is deferred until the first
  2020. <code class="xref py py-meth docutils literal notranslate"><span class="pre">emit()</span></code> call is made. (Contributed by Vinay Sajip.)</p>
  2021. <p><code class="xref py py-class docutils literal notranslate"><span class="pre">TimedRotatingFileHandler</span></code> also has a <em>utc</em> constructor
  2022. parameter. If the argument is true, UTC time will be used
  2023. in determining when midnight occurs and in generating filenames;
  2024. otherwise local time will be used.</p>
  2025. </li>
  2026. <li><p>Several new functions were added to 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:</p>
  2027. <ul class="simple">
  2028. <li><p><a class="reference internal" href="../library/math.html#math.isinf" title="math.isinf"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinf()</span></code></a> and <a class="reference internal" href="../library/math.html#math.isnan" title="math.isnan"><code class="xref py py-func docutils literal notranslate"><span class="pre">isnan()</span></code></a> determine whether a given float
  2029. is a (positive or negative) infinity or a NaN (Not a Number), respectively.</p></li>
  2030. <li><p><a class="reference internal" href="../library/math.html#math.copysign" title="math.copysign"><code class="xref py py-func docutils literal notranslate"><span class="pre">copysign()</span></code></a> copies the sign bit of an IEEE 754 number,
  2031. returning the absolute value of <em>x</em> combined with the sign bit of
  2032. <em>y</em>. For example, <code class="docutils literal notranslate"><span class="pre">math.copysign(1,</span> <span class="pre">-0.0)</span></code> returns -1.0.
  2033. (Contributed by Christian Heimes.)</p></li>
  2034. <li><p><a class="reference internal" href="../library/math.html#math.factorial" title="math.factorial"><code class="xref py py-func docutils literal notranslate"><span class="pre">factorial()</span></code></a> computes the factorial of a number.
  2035. (Contributed by Raymond Hettinger; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2138">bpo-2138</a>.)</p></li>
  2036. <li><p><a class="reference internal" href="../library/math.html#math.fsum" title="math.fsum"><code class="xref py py-func docutils literal notranslate"><span class="pre">fsum()</span></code></a> adds up the stream of numbers from an iterable,
  2037. and is careful to avoid loss of precision through using partial sums.
  2038. (Contributed by Jean Brouwers, Raymond Hettinger, and Mark Dickinson;
  2039. <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2819">bpo-2819</a>.)</p></li>
  2040. <li><p><a class="reference internal" href="../library/math.html#math.acosh" title="math.acosh"><code class="xref py py-func docutils literal notranslate"><span class="pre">acosh()</span></code></a>, <a class="reference internal" href="../library/math.html#math.asinh" title="math.asinh"><code class="xref py py-func docutils literal notranslate"><span class="pre">asinh()</span></code></a>
  2041. and <a class="reference internal" href="../library/math.html#math.atanh" title="math.atanh"><code class="xref py py-func docutils literal notranslate"><span class="pre">atanh()</span></code></a> compute the inverse hyperbolic functions.</p></li>
  2042. <li><p><a class="reference internal" href="../library/math.html#math.log1p" title="math.log1p"><code class="xref py py-func docutils literal notranslate"><span class="pre">log1p()</span></code></a> returns the natural logarithm of <em>1+x</em>
  2043. (base <em>e</em>).</p></li>
  2044. <li><p><code class="xref py py-func docutils literal notranslate"><span class="pre">trunc()</span></code> rounds a number toward zero, returning the closest
  2045. <code class="xref py py-class docutils literal notranslate"><span class="pre">Integral</span></code> that’s between the function’s argument and zero.
  2046. Added as part of the backport of
  2047. <a class="reference external" href="#pep-3141">PEP 3141’s type hierarchy for numbers</a>.</p></li>
  2048. </ul>
  2049. </li>
  2050. <li><p>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 has been improved to give more consistent
  2051. behaviour across platforms, especially with respect to handling of
  2052. floating-point exceptions and IEEE 754 special values.</p>
  2053. <p>Whenever possible, the module follows the recommendations of the C99
  2054. standard about 754’s special values. For example, <code class="docutils literal notranslate"><span class="pre">sqrt(-1.)</span></code>
  2055. should now give a <a class="reference internal" href="../library/exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> across almost all platforms,
  2056. while <code class="docutils literal notranslate"><span class="pre">sqrt(float('NaN'))</span></code> should return a NaN on all IEEE 754
  2057. platforms. Where Annex ‘F’ of the C99 standard recommends signaling
  2058. ‘divide-by-zero’ or ‘invalid’, Python will raise <a class="reference internal" href="../library/exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>.
  2059. Where Annex ‘F’ of the C99 standard recommends signaling ‘overflow’,
  2060. Python will raise <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>. (See <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=711019">bpo-711019</a> and
  2061. <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1640">bpo-1640</a>.)</p>
  2062. <p>(Contributed by Christian Heimes and Mark Dickinson.)</p>
  2063. </li>
  2064. <li><p><a class="reference internal" href="../library/mmap.html#mmap.mmap" title="mmap.mmap"><code class="xref py py-class docutils literal notranslate"><span class="pre">mmap</span></code></a> objects now have a <code class="xref py py-meth docutils literal notranslate"><span class="pre">rfind()</span></code> method that searches for a
  2065. substring beginning at the end of the string and searching
  2066. backwards. The <code class="xref py py-meth docutils literal notranslate"><span class="pre">find()</span></code> method also gained an <em>end</em> parameter
  2067. giving an index at which to stop searching.
  2068. (Contributed by John Lenton.)</p></li>
  2069. <li><p>The <a class="reference internal" href="../library/operator.html#module-operator" title="operator: Functions corresponding to the standard operators."><code class="xref py py-mod docutils literal notranslate"><span class="pre">operator</span></code></a> module gained a
  2070. <code class="xref py py-func docutils literal notranslate"><span class="pre">methodcaller()</span></code> function that takes a name and an optional
  2071. set of arguments, returning a callable that will call
  2072. the named function on any arguments passed to it. For example:</p>
  2073. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Equivalent to lambda s: s.replace(&#39;old&#39;, &#39;new&#39;)</span>
  2074. <span class="gp">&gt;&gt;&gt; </span><span class="n">replacer</span> <span class="o">=</span> <span class="n">operator</span><span class="o">.</span><span class="n">methodcaller</span><span class="p">(</span><span class="s1">&#39;replace&#39;</span><span class="p">,</span> <span class="s1">&#39;old&#39;</span><span class="p">,</span> <span class="s1">&#39;new&#39;</span><span class="p">)</span>
  2075. <span class="gp">&gt;&gt;&gt; </span><span class="n">replacer</span><span class="p">(</span><span class="s1">&#39;old wine in old bottles&#39;</span><span class="p">)</span>
  2076. <span class="go">&#39;new wine in new bottles&#39;</span>
  2077. </pre></div>
  2078. </div>
  2079. <p>(Contributed by Georg Brandl, after a suggestion by Gregory Petrosyan.)</p>
  2080. <p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">attrgetter()</span></code> function now accepts dotted names and performs
  2081. the corresponding attribute lookups:</p>
  2082. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">inst_name</span> <span class="o">=</span> <span class="n">operator</span><span class="o">.</span><span class="n">attrgetter</span><span class="p">(</span>
  2083. <span class="gp">... </span> <span class="s1">&#39;__class__.__name__&#39;</span><span class="p">)</span>
  2084. <span class="gp">&gt;&gt;&gt; </span><span class="n">inst_name</span><span class="p">(</span><span class="s1">&#39;&#39;</span><span class="p">)</span>
  2085. <span class="go">&#39;str&#39;</span>
  2086. <span class="gp">&gt;&gt;&gt; </span><span class="n">inst_name</span><span class="p">(</span><span class="n">help</span><span class="p">)</span>
  2087. <span class="go">&#39;_Helper&#39;</span>
  2088. </pre></div>
  2089. </div>
  2090. <p>(Contributed by Georg Brandl, after a suggestion by Barry Warsaw.)</p>
  2091. </li>
  2092. <li><p>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 now wraps several new system calls.
  2093. <code class="docutils literal notranslate"><span class="pre">fchmod(fd,</span> <span class="pre">mode)</span></code> and <code class="docutils literal notranslate"><span class="pre">fchown(fd,</span> <span class="pre">uid,</span> <span class="pre">gid)</span></code> change the mode
  2094. and ownership of an opened file, and <code class="docutils literal notranslate"><span class="pre">lchmod(path,</span> <span class="pre">mode)</span></code> changes
  2095. the mode of a symlink. (Contributed by Georg Brandl and Christian
  2096. Heimes.)</p>
  2097. <p><code class="xref py py-func docutils literal notranslate"><span class="pre">chflags()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">lchflags()</span></code> are wrappers for the
  2098. corresponding system calls (where they’re available), changing the
  2099. flags set on a file. Constants for the flag values are defined in
  2100. the <a class="reference internal" href="../library/stat.html#module-stat" title="stat: Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat()."><code class="xref py py-mod docutils literal notranslate"><span class="pre">stat</span></code></a> module; some possible values include
  2101. <code class="xref py py-const docutils literal notranslate"><span class="pre">UF_IMMUTABLE</span></code> to signal the file may not be changed and
  2102. <code class="xref py py-const docutils literal notranslate"><span class="pre">UF_APPEND</span></code> to indicate that data can only be appended to the
  2103. file. (Contributed by M. Levinson.)</p>
  2104. <p><code class="docutils literal notranslate"><span class="pre">os.closerange(low,</span> <span class="pre">high)</span></code> efficiently closes all file descriptors
  2105. from <em>low</em> to <em>high</em>, ignoring any errors and not including <em>high</em> itself.
  2106. This function is now used by the <a class="reference internal" href="../library/subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module to make starting
  2107. processes faster. (Contributed by Georg Brandl; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1663329">bpo-1663329</a>.)</p>
  2108. </li>
  2109. <li><p>The <code class="docutils literal notranslate"><span class="pre">os.environ</span></code> object’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">clear()</span></code> method will now unset the
  2110. environment variables using <a class="reference internal" href="../library/os.html#os.unsetenv" title="os.unsetenv"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.unsetenv()</span></code></a> in addition to clearing
  2111. the object’s keys. (Contributed by Martin Horcicka; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1181">bpo-1181</a>.)</p></li>
  2112. <li><p>The <a class="reference internal" href="../library/os.html#os.walk" title="os.walk"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.walk()</span></code></a> function now has a <code class="docutils literal notranslate"><span class="pre">followlinks</span></code> parameter. If
  2113. set to True, it will follow symlinks pointing to directories and
  2114. visit the directory’s contents. For backward compatibility, the
  2115. parameter’s default value is false. Note that the function can fall
  2116. into an infinite recursion if there’s a symlink that points to a
  2117. parent directory. (<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1273829">bpo-1273829</a>)</p></li>
  2118. <li><p>In the <a class="reference internal" href="../library/os.path.html#module-os.path" title="os.path: Operations on pathnames."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.path</span></code></a> module, the <code class="xref py py-func docutils literal notranslate"><span class="pre">splitext()</span></code> function
  2119. has been changed to not split on leading period characters.
  2120. This produces better results when operating on Unix’s dot-files.
  2121. For example, <code class="docutils literal notranslate"><span class="pre">os.path.splitext('.ipython')</span></code>
  2122. now returns <code class="docutils literal notranslate"><span class="pre">('.ipython',</span> <span class="pre">'')</span></code> instead of <code class="docutils literal notranslate"><span class="pre">('',</span> <span class="pre">'.ipython')</span></code>.
  2123. (<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1115886">bpo-1115886</a>)</p>
  2124. <p>A new function, <code class="docutils literal notranslate"><span class="pre">os.path.relpath(path,</span> <span class="pre">start='.')</span></code>, returns a relative path
  2125. from the <code class="docutils literal notranslate"><span class="pre">start</span></code> path, if it’s supplied, or from the current
  2126. working directory to the destination <code class="docutils literal notranslate"><span class="pre">path</span></code>. (Contributed by
  2127. Richard Barran; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1339796">bpo-1339796</a>.)</p>
  2128. <p>On Windows, <a class="reference internal" href="../library/os.path.html#os.path.expandvars" title="os.path.expandvars"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.path.expandvars()</span></code></a> will now expand environment variables
  2129. given in the form “%var%”, and “~user” will be expanded into the
  2130. user’s home directory path. (Contributed by Josiah Carlson;
  2131. <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=957650">bpo-957650</a>.)</p>
  2132. </li>
  2133. <li><p>The Python debugger provided by 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> module
  2134. gained a new command: “run” restarts the Python program being debugged
  2135. and can optionally take new command-line arguments for the program.
  2136. (Contributed by Rocky Bernstein; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1393667">bpo-1393667</a>.)</p></li>
  2137. <li><p>The <a class="reference internal" href="../library/pdb.html#pdb.post_mortem" title="pdb.post_mortem"><code class="xref py py-func docutils literal notranslate"><span class="pre">pdb.post_mortem()</span></code></a> function, used to begin debugging a
  2138. traceback, will now use the traceback returned by <a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>
  2139. if no traceback is supplied. (Contributed by Facundo Batista;
  2140. <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1106316">bpo-1106316</a>.)</p></li>
  2141. <li><p>The <a class="reference internal" href="../library/pickletools.html#module-pickletools" title="pickletools: Contains extensive comments about the pickle protocols and pickle-machine opcodes, as well as some useful functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickletools</span></code></a> module now has an <code class="xref py py-func docutils literal notranslate"><span class="pre">optimize()</span></code> function
  2142. that takes a string containing a pickle and removes some unused
  2143. opcodes, returning a shorter pickle that contains the same data structure.
  2144. (Contributed by Raymond Hettinger.)</p></li>
  2145. <li><p>A <code class="xref py py-func docutils literal notranslate"><span class="pre">get_data()</span></code> function was added to the <a class="reference internal" href="../library/pkgutil.html#module-pkgutil" title="pkgutil: Utilities for the import system."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pkgutil</span></code></a>
  2146. module that returns the contents of resource files included
  2147. with an installed Python package. For example:</p>
  2148. <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">pkgutil</span>
  2149. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">pkgutil</span><span class="o">.</span><span class="n">get_data</span><span class="p">(</span><span class="s1">&#39;test&#39;</span><span class="p">,</span> <span class="s1">&#39;exception_hierarchy.txt&#39;</span><span class="p">)</span>
  2150. <span class="go">BaseException</span>
  2151. <span class="go"> +-- SystemExit</span>
  2152. <span class="go"> +-- KeyboardInterrupt</span>
  2153. <span class="go"> +-- GeneratorExit</span>
  2154. <span class="go"> +-- Exception</span>
  2155. <span class="go"> +-- StopIteration</span>
  2156. <span class="go"> +-- StandardError</span>
  2157. <span class="go"> ...</span>
  2158. </pre></div>
  2159. </div>
  2160. <p>(Contributed by Paul Moore; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2439">bpo-2439</a>.)</p>
  2161. </li>
  2162. <li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">pyexpat</span></code> module’s <code class="xref py py-class docutils literal notranslate"><span class="pre">Parser</span></code> objects now allow setting
  2163. their <code class="xref py py-attr docutils literal notranslate"><span class="pre">buffer_size</span></code> attribute to change the size of the buffer
  2164. used to hold character data.
  2165. (Contributed by Achim Gaedke; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1137">bpo-1137</a>.)</p></li>
  2166. <li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">Queue</span></code> module now provides queue variants that retrieve entries
  2167. in different orders. The <code class="xref py py-class docutils literal notranslate"><span class="pre">PriorityQueue</span></code> class stores
  2168. queued items in a heap and retrieves them in priority order,
  2169. and <code class="xref py py-class docutils literal notranslate"><span class="pre">LifoQueue</span></code> retrieves the most recently added entries first,
  2170. meaning that it behaves like a stack.
  2171. (Contributed by Raymond Hettinger.)</p></li>
  2172. <li><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’s <code class="xref py py-class docutils literal notranslate"><span class="pre">Random</span></code> objects can
  2173. now be pickled on a 32-bit system and unpickled on a 64-bit
  2174. system, and vice versa. Unfortunately, this change also means
  2175. that Python 2.6’s <code class="xref py py-class docutils literal notranslate"><span class="pre">Random</span></code> objects can’t be unpickled correctly
  2176. on earlier versions of Python.
  2177. (Contributed by Shawn Ligocki; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1727780">bpo-1727780</a>.)</p>
  2178. <p>The new <code class="docutils literal notranslate"><span class="pre">triangular(low,</span> <span class="pre">high,</span> <span class="pre">mode)</span></code> function returns random
  2179. numbers following a triangular distribution. The returned values
  2180. are between <em>low</em> and <em>high</em>, not including <em>high</em> itself, and
  2181. with <em>mode</em> as the most frequently occurring value
  2182. in the distribution. (Contributed by Wladmir van der Laan and
  2183. Raymond Hettinger; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1681432">bpo-1681432</a>.)</p>
  2184. </li>
  2185. <li><p>Long regular expression searches carried out by the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a>
  2186. module will check for signals being delivered, so
  2187. time-consuming searches can now be interrupted.
  2188. (Contributed by Josh Hoyt and Ralf Schmitt; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=846388">bpo-846388</a>.)</p>
  2189. <p>The regular expression module is implemented by compiling bytecodes
  2190. for a tiny regex-specific virtual machine. Untrusted code
  2191. could create malicious strings of bytecode directly and cause crashes,
  2192. so Python 2.6 includes a verifier for the regex bytecode.
  2193. (Contributed by Guido van Rossum from work for Google App Engine;
  2194. <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=3487">bpo-3487</a>.)</p>
  2195. </li>
  2196. <li><p>The <a class="reference internal" href="../library/rlcompleter.html#module-rlcompleter" title="rlcompleter: Python identifier completion, suitable for the GNU readline library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">rlcompleter</span></code></a> module’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">Completer.complete()</span></code> method
  2197. will now ignore exceptions triggered while evaluating a name.
  2198. (Fixed by Lorenz Quack; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2250">bpo-2250</a>.)</p></li>
  2199. <li><p>The <a class="reference internal" href="../library/sched.html#module-sched" title="sched: General purpose event scheduler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sched</span></code></a> module’s <code class="xref py py-class docutils literal notranslate"><span class="pre">scheduler</span></code> instances now
  2200. have a read-only <a class="reference internal" href="../library/queue.html#module-queue" title="queue: A synchronized queue class."><code class="xref py py-attr docutils literal notranslate"><span class="pre">queue</span></code></a> attribute that returns the
  2201. contents of the scheduler’s queue, represented as a list of
  2202. named tuples with the fields <code class="docutils literal notranslate"><span class="pre">(time,</span> <span class="pre">priority,</span> <span class="pre">action,</span> <span class="pre">argument)</span></code>.
  2203. (Contributed by Raymond Hettinger; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1861">bpo-1861</a>.)</p></li>
  2204. <li><p>The <a class="reference internal" href="../library/select.html#module-select" title="select: Wait for I/O completion on multiple streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">select</span></code></a> module now has wrapper functions
  2205. for the Linux <code class="xref c c-func docutils literal notranslate"><span class="pre">epoll()</span></code> and BSD <code class="xref c c-func docutils literal notranslate"><span class="pre">kqueue()</span></code> system calls.
  2206. <code class="xref py py-meth docutils literal notranslate"><span class="pre">modify()</span></code> method was added to the existing <code class="xref py py-class docutils literal notranslate"><span class="pre">poll</span></code>
  2207. objects; <code class="docutils literal notranslate"><span class="pre">pollobj.modify(fd,</span> <span class="pre">eventmask)</span></code> takes a file descriptor
  2208. or file object and an event mask, modifying the recorded event mask
  2209. for that file.
  2210. (Contributed by Christian Heimes; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1657">bpo-1657</a>.)</p></li>
  2211. <li><p>The <a class="reference internal" href="../library/shutil.html#shutil.copytree" title="shutil.copytree"><code class="xref py py-func docutils literal notranslate"><span class="pre">shutil.copytree()</span></code></a> function now has an optional <em>ignore</em> argument
  2212. that takes a callable object. This callable will receive each directory path
  2213. and a list of the directory’s contents, and returns a list of names that
  2214. will be ignored, not copied.</p>
  2215. <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 also provides an <code class="xref py py-func docutils literal notranslate"><span class="pre">ignore_patterns()</span></code>
  2216. function for use with this new parameter. <code class="xref py py-func docutils literal notranslate"><span class="pre">ignore_patterns()</span></code>
  2217. takes an arbitrary number of glob-style patterns and returns a
  2218. callable that will ignore any files and directories that match any
  2219. of these patterns. The following example copies a directory tree,
  2220. but skips both <code class="file docutils literal notranslate"><span class="pre">.svn</span></code> directories and Emacs backup files,
  2221. which have names ending with ‘~’:</p>
  2222. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">shutil</span><span class="o">.</span><span class="n">copytree</span><span class="p">(</span><span class="s1">&#39;Doc/library&#39;</span><span class="p">,</span> <span class="s1">&#39;/tmp/library&#39;</span><span class="p">,</span>
  2223. <span class="n">ignore</span><span class="o">=</span><span class="n">shutil</span><span class="o">.</span><span class="n">ignore_patterns</span><span class="p">(</span><span class="s1">&#39;*~&#39;</span><span class="p">,</span> <span class="s1">&#39;.svn&#39;</span><span class="p">))</span>
  2224. </pre></div>
  2225. </div>
  2226. <p>(Contributed by Tarek Ziadé; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2663">bpo-2663</a>.)</p>
  2227. </li>
  2228. <li><p>Integrating signal handling with GUI handling event loops
  2229. like those used by Tkinter or GTk+ has long been a problem; most
  2230. software ends up polling, waking up every fraction of a second to check
  2231. if any GUI events have occurred.
  2232. 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> module can now make this more efficient.
  2233. Calling <code class="docutils literal notranslate"><span class="pre">signal.set_wakeup_fd(fd)</span></code> sets a file descriptor
  2234. to be used; when a signal is received, a byte is written to that
  2235. file descriptor. There’s also a C-level function,
  2236. <a class="reference internal" href="../c-api/exceptions.html#c.PySignal_SetWakeupFd" title="PySignal_SetWakeupFd"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySignal_SetWakeupFd()</span></code></a>, for setting the descriptor.</p>
  2237. <p>Event loops will use this by opening a pipe to create two descriptors,
  2238. one for reading and one for writing. The writable descriptor
  2239. will be passed to <code class="xref py py-func docutils literal notranslate"><span class="pre">set_wakeup_fd()</span></code>, and the readable descriptor
  2240. will be added to the list of descriptors monitored by the event loop via
  2241. <code class="xref c c-func docutils literal notranslate"><span class="pre">select()</span></code> or <code class="xref c c-func docutils literal notranslate"><span class="pre">poll()</span></code>.
  2242. On receiving a signal, a byte will be written and the main event loop
  2243. will be woken up, avoiding the need to poll.</p>
  2244. <p>(Contributed by Adam Olsen; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1583">bpo-1583</a>.)</p>
  2245. <p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">siginterrupt()</span></code> function is now available from Python code,
  2246. and allows changing whether signals can interrupt system calls or not.
  2247. (Contributed by Ralf Schmitt.)</p>
  2248. <p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">setitimer()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">getitimer()</span></code> functions have also been
  2249. added (where they’re available). <code class="xref py py-func docutils literal notranslate"><span class="pre">setitimer()</span></code>
  2250. allows setting interval timers that will cause a signal to be
  2251. delivered to the process after a specified time, measured in
  2252. wall-clock time, consumed process time, or combined process+system
  2253. time. (Contributed by Guilherme Polo; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2240">bpo-2240</a>.)</p>
  2254. </li>
  2255. <li><p>The <a class="reference internal" href="../library/smtplib.html#module-smtplib" title="smtplib: SMTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">smtplib</span></code></a> module now supports SMTP over SSL thanks to the
  2256. addition of the <code class="xref py py-class docutils literal notranslate"><span class="pre">SMTP_SSL</span></code> class. This class supports an
  2257. interface identical to the existing <code class="xref py py-class docutils literal notranslate"><span class="pre">SMTP</span></code> class.
  2258. (Contributed by Monty Taylor.) Both class constructors also have an
  2259. optional <code class="docutils literal notranslate"><span class="pre">timeout</span></code> parameter that specifies a timeout for the
  2260. initial connection attempt, measured in seconds. (Contributed by
  2261. Facundo Batista.)</p>
  2262. <p>An implementation of the LMTP protocol (<span class="target" id="index-22"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc2033.html"><strong>RFC 2033</strong></a>) was also added
  2263. to the module. LMTP is used in place of SMTP when transferring
  2264. e-mail between agents that don’t manage a mail queue. (LMTP
  2265. implemented by Leif Hedstrom; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=957003">bpo-957003</a>.)</p>
  2266. <p><code class="xref py py-meth docutils literal notranslate"><span class="pre">SMTP.starttls()</span></code> now complies with <span class="target" id="index-23"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc3207.html"><strong>RFC 3207</strong></a> and forgets any
  2267. knowledge obtained from the server not obtained from the TLS
  2268. negotiation itself. (Patch contributed by Bill Fenner;
  2269. <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=829951">bpo-829951</a>.)</p>
  2270. </li>
  2271. <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 TIPC (<a class="reference external" href="https://tipc.sourceforge.net/">https://tipc.sourceforge.net/</a>),
  2272. a high-performance non-IP-based protocol designed for use in clustered
  2273. environments. TIPC addresses are 4- or 5-tuples.
  2274. (Contributed by Alberto Bertogli; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1646">bpo-1646</a>.)</p>
  2275. <p>A new function, <code class="xref py py-func docutils literal notranslate"><span class="pre">create_connection()</span></code>, takes an address and
  2276. connects to it using an optional timeout value, returning the
  2277. connected socket object. This function also looks up the address’s
  2278. type and connects to it using IPv4 or IPv6 as appropriate. Changing
  2279. your code to use <code class="xref py py-func docutils literal notranslate"><span class="pre">create_connection()</span></code> instead of
  2280. <code class="docutils literal notranslate"><span class="pre">socket(socket.AF_INET,</span> <span class="pre">...)</span></code> may be all that’s required to make
  2281. your code work with IPv6.</p>
  2282. </li>
  2283. <li><p>The base classes in the <a class="reference internal" href="../library/socketserver.html#module-socketserver" title="socketserver: A framework for network servers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">SocketServer</span></code></a> module now support
  2284. calling a <a class="reference internal" href="../library/socketserver.html#socketserver.BaseServer.handle_timeout" title="socketserver.BaseServer.handle_timeout"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_timeout()</span></code></a> method after a span of inactivity
  2285. specified by the server’s <a class="reference internal" href="../library/socketserver.html#socketserver.BaseServer.timeout" title="socketserver.BaseServer.timeout"><code class="xref py py-attr docutils literal notranslate"><span class="pre">timeout</span></code></a> attribute. (Contributed
  2286. by Michael Pomraning.) The <a class="reference internal" href="../library/socketserver.html#socketserver.BaseServer.serve_forever" title="socketserver.BaseServer.serve_forever"><code class="xref py py-meth docutils literal notranslate"><span class="pre">serve_forever()</span></code></a> method
  2287. now takes an optional poll interval measured in seconds,
  2288. controlling how often the server will check for a shutdown request.
  2289. (Contributed by Pedro Werneck and Jeffrey Yasskin;
  2290. <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=742598">bpo-742598</a>, <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1193577">bpo-1193577</a>.)</p></li>
  2291. <li><p>The <a class="reference internal" href="../library/sqlite3.html#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> module, maintained by Gerhard Häring,
  2292. has been updated from version 2.3.2 in Python 2.5 to
  2293. version 2.4.1.</p></li>
  2294. <li><p>The <a class="reference internal" href="../library/struct.html#module-struct" title="struct: Interpret bytes as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> module now supports the C99 <span class="c-expr sig sig-inline c"><span class="kt">_Bool</span></span> type,
  2295. using the format character <code class="docutils literal notranslate"><span class="pre">'?'</span></code>.
  2296. (Contributed by David Remahl.)</p></li>
  2297. <li><p>The <a class="reference internal" href="../library/subprocess.html#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code></a> objects provided by the <a class="reference internal" href="../library/subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module
  2298. now have <a class="reference internal" href="../library/subprocess.html#subprocess.Popen.terminate" title="subprocess.Popen.terminate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">terminate()</span></code></a>, <a class="reference internal" href="../library/subprocess.html#subprocess.Popen.kill" title="subprocess.Popen.kill"><code class="xref py py-meth docutils literal notranslate"><span class="pre">kill()</span></code></a>, and <a class="reference internal" href="../library/subprocess.html#subprocess.Popen.send_signal" title="subprocess.Popen.send_signal"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send_signal()</span></code></a> methods.
  2299. On Windows, <code class="xref py py-meth docutils literal notranslate"><span class="pre">send_signal()</span></code> only supports the <a class="reference internal" href="../library/signal.html#signal.SIGTERM" title="signal.SIGTERM"><code class="xref py py-const docutils literal notranslate"><span class="pre">SIGTERM</span></code></a>
  2300. signal, and all these methods are aliases for the Win32 API function
  2301. <code class="xref c c-func docutils literal notranslate"><span class="pre">TerminateProcess()</span></code>.
  2302. (Contributed by Christian Heimes.)</p></li>
  2303. <li><p>A new variable in the <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> module, <code class="xref py py-attr docutils literal notranslate"><span class="pre">float_info</span></code>, is an
  2304. object containing information derived from the <code class="file docutils literal notranslate"><span class="pre">float.h</span></code> file
  2305. about the platform’s floating-point support. Attributes of this
  2306. object include <code class="xref py py-attr docutils literal notranslate"><span class="pre">mant_dig</span></code> (number of digits in the mantissa),
  2307. <code class="xref py py-attr docutils literal notranslate"><span class="pre">epsilon</span></code> (smallest difference between 1.0 and the next
  2308. largest value representable), and several others. (Contributed by
  2309. Christian Heimes; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1534">bpo-1534</a>.)</p>
  2310. <p>Another new variable, <code class="xref py py-attr docutils literal notranslate"><span class="pre">dont_write_bytecode</span></code>, controls whether Python
  2311. writes any <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> files on importing a module.
  2312. If this variable is true, the compiled files are not written. The
  2313. variable is initially set on start-up by supplying the <a class="reference internal" href="../using/cmdline.html#cmdoption-B"><code class="xref std std-option docutils literal notranslate"><span class="pre">-B</span></code></a>
  2314. switch to the Python interpreter, or by setting the
  2315. <span class="target" id="index-24"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONDONTWRITEBYTECODE</span></code></a> environment variable before
  2316. running the interpreter. Python code can subsequently
  2317. change the value of this variable to control whether bytecode files
  2318. are written or not.
  2319. (Contributed by Neal Norwitz and Georg Brandl.)</p>
  2320. <p>Information about the command-line arguments supplied to the Python
  2321. interpreter is available by reading attributes of a named
  2322. tuple available as <code class="docutils literal notranslate"><span class="pre">sys.flags</span></code>. For example, the <code class="xref py py-attr docutils literal notranslate"><span class="pre">verbose</span></code>
  2323. attribute is true if Python
  2324. was executed in verbose mode, <code class="xref py py-attr docutils literal notranslate"><span class="pre">debug</span></code> is true in debugging mode, etc.
  2325. These attributes are all read-only.
  2326. (Contributed by Christian Heimes.)</p>
  2327. <p>A new function, <code class="xref py py-func docutils literal notranslate"><span class="pre">getsizeof()</span></code>, takes a Python object and returns
  2328. the amount of memory used by the object, measured in bytes. Built-in
  2329. objects return correct results; third-party extensions may not,
  2330. but can define a <code class="xref py py-meth docutils literal notranslate"><span class="pre">__sizeof__()</span></code> method to return the
  2331. object’s size.
  2332. (Contributed by Robert Schuppenies; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2898">bpo-2898</a>.)</p>
  2333. <p>It’s now possible to determine the current profiler and tracer functions
  2334. by calling <a class="reference internal" href="../library/sys.html#sys.getprofile" title="sys.getprofile"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.getprofile()</span></code></a> and <a class="reference internal" href="../library/sys.html#sys.gettrace" title="sys.gettrace"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.gettrace()</span></code></a>.
  2335. (Contributed by Georg Brandl; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1648">bpo-1648</a>.)</p>
  2336. </li>
  2337. <li><p>The <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 now supports POSIX.1-2001 (pax) tarfiles in
  2338. addition to the POSIX.1-1988 (ustar) and GNU tar formats that were
  2339. already supported. The default format is GNU tar; specify the
  2340. <code class="docutils literal notranslate"><span class="pre">format</span></code> parameter to open a file using a different format:</p>
  2341. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">tar</span> <span class="o">=</span> <span class="n">tarfile</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s2">&quot;output.tar&quot;</span><span class="p">,</span> <span class="s2">&quot;w&quot;</span><span class="p">,</span>
  2342. <span class="nb">format</span><span class="o">=</span><span class="n">tarfile</span><span class="o">.</span><span class="n">PAX_FORMAT</span><span class="p">)</span>
  2343. </pre></div>
  2344. </div>
  2345. <p>The new <code class="docutils literal notranslate"><span class="pre">encoding</span></code> and <code class="docutils literal notranslate"><span class="pre">errors</span></code> parameters specify an encoding and
  2346. an error handling scheme for character conversions. <code class="docutils literal notranslate"><span class="pre">'strict'</span></code>,
  2347. <code class="docutils literal notranslate"><span class="pre">'ignore'</span></code>, and <code class="docutils literal notranslate"><span class="pre">'replace'</span></code> are the three standard ways Python can
  2348. handle errors,;
  2349. <code class="docutils literal notranslate"><span class="pre">'utf-8'</span></code> is a special value that replaces bad characters with
  2350. their UTF-8 representation. (Character conversions occur because the
  2351. PAX format supports Unicode filenames, defaulting to UTF-8 encoding.)</p>
  2352. <p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">TarFile.add()</span></code> method now accepts an <code class="docutils literal notranslate"><span class="pre">exclude</span></code> argument that’s
  2353. a function that can be used to exclude certain filenames from
  2354. an archive.
  2355. The function must take a filename and return true if the file
  2356. should be excluded or false if it should be archived.
  2357. The function is applied to both the name initially passed to <code class="xref py py-meth docutils literal notranslate"><span class="pre">add()</span></code>
  2358. and to the names of files in recursively added directories.</p>
  2359. <p>(All changes contributed by Lars Gustäbel).</p>
  2360. </li>
  2361. <li><p>An optional <code class="docutils literal notranslate"><span class="pre">timeout</span></code> parameter was added to the
  2362. <a class="reference internal" href="../library/telnetlib.html#telnetlib.Telnet" title="telnetlib.Telnet"><code class="xref py py-class docutils literal notranslate"><span class="pre">telnetlib.Telnet</span></code></a> class constructor, specifying a timeout
  2363. measured in seconds. (Added by Facundo Batista.)</p></li>
  2364. <li><p>The <a class="reference internal" href="../library/tempfile.html#tempfile.NamedTemporaryFile" title="tempfile.NamedTemporaryFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">tempfile.NamedTemporaryFile</span></code></a> class usually deletes
  2365. the temporary file it created when the file is closed. This
  2366. behaviour can now be changed by passing <code class="docutils literal notranslate"><span class="pre">delete=False</span></code> to the
  2367. constructor. (Contributed by Damien Miller; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1537850">bpo-1537850</a>.)</p>
  2368. <p>A new class, <code class="xref py py-class docutils literal notranslate"><span class="pre">SpooledTemporaryFile</span></code>, behaves like
  2369. a temporary file but stores its data in memory until a maximum size is
  2370. exceeded. On reaching that limit, the contents will be written to
  2371. an on-disk temporary file. (Contributed by Dustin J. Mitchell.)</p>
  2372. <p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">NamedTemporaryFile</span></code> and <code class="xref py py-class docutils literal notranslate"><span class="pre">SpooledTemporaryFile</span></code> classes
  2373. both work as context managers, so you can write
  2374. <code class="docutils literal notranslate"><span class="pre">with</span> <span class="pre">tempfile.NamedTemporaryFile()</span> <span class="pre">as</span> <span class="pre">tmp:</span> <span class="pre">...</span></code>.
  2375. (Contributed by Alexander Belopolsky; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2021">bpo-2021</a>.)</p>
  2376. </li>
  2377. <li><p>The <a class="reference internal" href="../library/test.html#module-test.support" title="test.support: Support for Python's regression test suite."><code class="xref py py-mod docutils literal notranslate"><span class="pre">test.test_support</span></code></a> module gained a number
  2378. of context managers useful for writing tests.
  2379. <a class="reference internal" href="../library/test.html#test.support.os_helper.EnvironmentVarGuard" title="test.support.os_helper.EnvironmentVarGuard"><code class="xref py py-func docutils literal notranslate"><span class="pre">EnvironmentVarGuard()</span></code></a> is a
  2380. context manager that temporarily changes environment variables and
  2381. automatically restores them to their old values.</p>
  2382. <p>Another context manager, <code class="xref py py-class docutils literal notranslate"><span class="pre">TransientResource</span></code>, can surround calls
  2383. to resources that may or may not be available; it will catch and
  2384. ignore a specified list of exceptions. For example,
  2385. a network test may ignore certain failures when connecting to an
  2386. external web site:</p>
  2387. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">test_support</span><span class="o">.</span><span class="n">TransientResource</span><span class="p">(</span><span class="ne">IOError</span><span class="p">,</span>
  2388. <span class="n">errno</span><span class="o">=</span><span class="n">errno</span><span class="o">.</span><span class="n">ETIMEDOUT</span><span class="p">):</span>
  2389. <span class="n">f</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="s1">&#39;https://sf.net&#39;</span><span class="p">)</span>
  2390. <span class="o">...</span>
  2391. </pre></div>
  2392. </div>
  2393. <p>Finally, <code class="xref py py-func docutils literal notranslate"><span class="pre">check_warnings()</span></code> resets the <code class="xref py py-mod docutils literal notranslate"><span class="pre">warning</span></code> module’s
  2394. warning filters and returns an object that will record all warning
  2395. messages triggered (<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=3781">bpo-3781</a>):</p>
  2396. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">test_support</span><span class="o">.</span><span class="n">check_warnings</span><span class="p">()</span> <span class="k">as</span> <span class="n">wrec</span><span class="p">:</span>
  2397. <span class="n">warnings</span><span class="o">.</span><span class="n">simplefilter</span><span class="p">(</span><span class="s2">&quot;always&quot;</span><span class="p">)</span>
  2398. <span class="c1"># ... code that triggers a warning ...</span>
  2399. <span class="k">assert</span> <span class="nb">str</span><span class="p">(</span><span class="n">wrec</span><span class="o">.</span><span class="n">message</span><span class="p">)</span> <span class="o">==</span> <span class="s2">&quot;function is outdated&quot;</span>
  2400. <span class="k">assert</span> <span class="nb">len</span><span class="p">(</span><span class="n">wrec</span><span class="o">.</span><span class="n">warnings</span><span class="p">)</span> <span class="o">==</span> <span class="mi">1</span><span class="p">,</span> <span class="s2">&quot;Multiple warnings raised&quot;</span>
  2401. </pre></div>
  2402. </div>
  2403. <p>(Contributed by Brett Cannon.)</p>
  2404. </li>
  2405. <li><p>The <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 can now preserve existing whitespace
  2406. at the beginnings and ends of the newly created lines
  2407. by specifying <code class="docutils literal notranslate"><span class="pre">drop_whitespace=False</span></code>
  2408. as an argument:</p>
  2409. <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="s2">&quot;&quot;&quot;This sentence has a bunch of</span>
  2410. <span class="gp">... </span><span class="s2"> extra whitespace.&quot;&quot;&quot;</span>
  2411. <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">S</span><span class="p">,</span> <span class="n">width</span><span class="o">=</span><span class="mi">15</span><span class="p">)</span>
  2412. <span class="go">This sentence</span>
  2413. <span class="go">has a bunch</span>
  2414. <span class="go">of extra</span>
  2415. <span class="go">whitespace.</span>
  2416. <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">S</span><span class="p">,</span> <span class="n">drop_whitespace</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">width</span><span class="o">=</span><span class="mi">15</span><span class="p">)</span>
  2417. <span class="go">This sentence</span>
  2418. <span class="go"> has a bunch</span>
  2419. <span class="go"> of extra</span>
  2420. <span class="go"> whitespace.</span>
  2421. <span class="gp">&gt;&gt;&gt;</span>
  2422. </pre></div>
  2423. </div>
  2424. <p>(Contributed by Dwayne Bailey; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1581073">bpo-1581073</a>.)</p>
  2425. </li>
  2426. <li><p>The <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> module API is being changed to use properties
  2427. such as <code class="xref py py-attr docutils literal notranslate"><span class="pre">daemon</span></code> instead of <code class="xref py py-meth docutils literal notranslate"><span class="pre">setDaemon()</span></code> and
  2428. <code class="xref py py-meth docutils literal notranslate"><span class="pre">isDaemon()</span></code> methods, and some methods have been renamed to use
  2429. underscores instead of camel-case; for example, the
  2430. <code class="xref py py-meth docutils literal notranslate"><span class="pre">activeCount()</span></code> method is renamed to <code class="xref py py-meth docutils literal notranslate"><span class="pre">active_count()</span></code>. Both
  2431. the 2.6 and 3.0 versions of the module support the same properties
  2432. and renamed methods, but don’t remove the old methods. No date has been set
  2433. for the deprecation of the old APIs in Python 3.x; the old APIs won’t
  2434. be removed in any 2.x version.
  2435. (Carried out by several people, most notably Benjamin Peterson.)</p>
  2436. <p>The <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> module’s <code class="xref py py-class docutils literal notranslate"><span class="pre">Thread</span></code> objects
  2437. gained an <code class="xref py py-attr docutils literal notranslate"><span class="pre">ident</span></code> property that returns the thread’s
  2438. identifier, a nonzero integer. (Contributed by Gregory P. Smith;
  2439. <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2871">bpo-2871</a>.)</p>
  2440. </li>
  2441. <li><p>The <a class="reference internal" href="../library/timeit.html#module-timeit" title="timeit: Measure the execution time of small code snippets."><code class="xref py py-mod docutils literal notranslate"><span class="pre">timeit</span></code></a> module now accepts callables as well as strings
  2442. for the statement being timed and for the setup code.
  2443. Two convenience functions were added for creating
  2444. <code class="xref py py-class docutils literal notranslate"><span class="pre">Timer</span></code> instances:
  2445. <code class="docutils literal notranslate"><span class="pre">repeat(stmt,</span> <span class="pre">setup,</span> <span class="pre">time,</span> <span class="pre">repeat,</span> <span class="pre">number)</span></code> and
  2446. <code class="docutils literal notranslate"><span class="pre">timeit(stmt,</span> <span class="pre">setup,</span> <span class="pre">time,</span> <span class="pre">number)</span></code> create an instance and call
  2447. the corresponding method. (Contributed by Erik Demaine;
  2448. <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1533909">bpo-1533909</a>.)</p></li>
  2449. <li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code> module now accepts lists and tuples for options,
  2450. separating the elements by spaces before passing the resulting value to
  2451. Tcl/Tk.
  2452. (Contributed by Guilherme Polo; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2906">bpo-2906</a>.)</p></li>
  2453. <li><p>The <a class="reference internal" href="../library/turtle.html#module-turtle" title="turtle: An educational framework for simple graphics applications"><code class="xref py py-mod docutils literal notranslate"><span class="pre">turtle</span></code></a> module for turtle graphics was greatly enhanced by
  2454. Gregor Lingl. New features in the module include:</p>
  2455. <ul class="simple">
  2456. <li><p>Better animation of turtle movement and rotation.</p></li>
  2457. <li><p>Control over turtle movement using the new <code class="xref py py-meth docutils literal notranslate"><span class="pre">delay()</span></code>,
  2458. <code class="xref py py-meth docutils literal notranslate"><span class="pre">tracer()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">speed()</span></code> methods.</p></li>
  2459. <li><p>The ability to set new shapes for the turtle, and to
  2460. define a new coordinate system.</p></li>
  2461. <li><p>Turtles now have an <code class="xref py py-meth docutils literal notranslate"><span class="pre">undo()</span></code> method that can roll back actions.</p></li>
  2462. <li><p>Simple support for reacting to input events such as mouse and keyboard
  2463. activity, making it possible to write simple games.</p></li>
  2464. <li><p>A <code class="file docutils literal notranslate"><span class="pre">turtle.cfg</span></code> file can be used to customize the starting appearance
  2465. of the turtle’s screen.</p></li>
  2466. <li><p>The module’s docstrings can be replaced by new docstrings that have been
  2467. translated into another language.</p></li>
  2468. </ul>
  2469. <p>(<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1513695">bpo-1513695</a>)</p>
  2470. </li>
  2471. <li><p>An optional <code class="docutils literal notranslate"><span class="pre">timeout</span></code> parameter was added to the
  2472. <a class="reference internal" href="../library/urllib.request.html#urllib.request.urlopen" title="urllib.request.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urllib.urlopen</span></code></a> function and the
  2473. <code class="xref py py-class docutils literal notranslate"><span class="pre">urllib.ftpwrapper</span></code> class constructor, as well as the
  2474. <a class="reference internal" href="../library/urllib.request.html#urllib.request.urlopen" title="urllib.request.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urllib2.urlopen</span></code></a> function. The parameter specifies a timeout
  2475. measured in seconds. For example:</p>
  2476. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">u</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="s2">&quot;http://slow.example.com&quot;</span><span class="p">,</span>
  2477. <span class="go"> timeout=3)</span>
  2478. <span class="gt">Traceback (most recent call last):</span>
  2479. <span class="w"> </span><span class="c">...</span>
  2480. <span class="gr">urllib2.URLError</span>: <span class="n">&lt;urlopen error timed out&gt;</span>
  2481. <span class="gp">&gt;&gt;&gt;</span>
  2482. </pre></div>
  2483. </div>
  2484. <p>(Added by Facundo Batista.)</p>
  2485. </li>
  2486. <li><p>The Unicode database provided by the <a class="reference internal" href="../library/unicodedata.html#module-unicodedata" title="unicodedata: Access the Unicode Database."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unicodedata</span></code></a> module
  2487. has been updated to version 5.1.0. (Updated by
  2488. Martin von Löwis; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=3811">bpo-3811</a>.)</p></li>
  2489. <li><p>The <a class="reference internal" href="../library/warnings.html#module-warnings" title="warnings: Issue warning messages and control their disposition."><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code></a> module’s <code class="xref py py-func docutils literal notranslate"><span class="pre">formatwarning()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">showwarning()</span></code>
  2490. gained an optional <em>line</em> argument that can be used to supply the
  2491. line of source code. (Added as part of <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1631171">bpo-1631171</a>, which re-implemented
  2492. part of the <a class="reference internal" href="../library/warnings.html#module-warnings" title="warnings: Issue warning messages and control their disposition."><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code></a> module in C code.)</p>
  2493. <p>A new function, <code class="xref py py-func docutils literal notranslate"><span class="pre">catch_warnings()</span></code>, is a context manager
  2494. intended for testing purposes that lets you temporarily modify the
  2495. warning filters and then restore their original values (<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=3781">bpo-3781</a>).</p>
  2496. </li>
  2497. <li><p>The XML-RPC <a class="reference internal" href="../library/xmlrpc.server.html#module-xmlrpc.server" title="xmlrpc.server: Basic XML-RPC server implementations."><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleXMLRPCServer</span></code></a> and <a class="reference internal" href="../library/xmlrpc.server.html#module-xmlrpc.server" title="xmlrpc.server: Basic XML-RPC server implementations."><code class="xref py py-class docutils literal notranslate"><span class="pre">DocXMLRPCServer</span></code></a>
  2498. classes can now be prevented from immediately opening and binding to
  2499. their socket by passing <code class="docutils literal notranslate"><span class="pre">False</span></code> as the <em>bind_and_activate</em>
  2500. constructor parameter. This can be used to modify the instance’s
  2501. <code class="xref py py-attr docutils literal notranslate"><span class="pre">allow_reuse_address</span></code> attribute before calling the
  2502. <code class="xref py py-meth docutils literal notranslate"><span class="pre">server_bind()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">server_activate()</span></code> methods to
  2503. open the socket and begin listening for connections.
  2504. (Contributed by Peter Parente; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1599845">bpo-1599845</a>.)</p>
  2505. <p><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleXMLRPCServer</span></code> also has a <code class="xref py py-attr docutils literal notranslate"><span class="pre">_send_traceback_header</span></code>
  2506. attribute; if true, the exception and formatted traceback are returned
  2507. as HTTP headers “X-Exception” and “X-Traceback”. This feature is
  2508. for debugging purposes only and should not be used on production servers
  2509. because the tracebacks might reveal passwords or other sensitive
  2510. information. (Contributed by Alan McIntyre as part of his
  2511. project for Google’s Summer of Code 2007.)</p>
  2512. </li>
  2513. <li><p>The <a class="reference internal" href="../library/xmlrpc.client.html#module-xmlrpc.client" title="xmlrpc.client: XML-RPC client access."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code></a> module no longer automatically converts
  2514. <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">datetime.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">datetime.time</span></code></a> to the
  2515. <a class="reference internal" href="../library/xmlrpc.client.html#xmlrpc.client.DateTime" title="xmlrpc.client.DateTime"><code class="xref py py-class docutils literal notranslate"><span class="pre">xmlrpclib.DateTime</span></code></a> type; the conversion semantics were
  2516. not necessarily correct for all applications. Code using
  2517. <code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code> should convert <code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code> 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>
  2518. instances. (<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1330538">bpo-1330538</a>) The code can also handle
  2519. dates before 1900 (contributed by Ralf Schmitt; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2014">bpo-2014</a>)
  2520. and 64-bit integers represented by using <code class="docutils literal notranslate"><span class="pre">&lt;i8&gt;</span></code> in XML-RPC responses
  2521. (contributed by Riku Lindblad; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2985">bpo-2985</a>).</p></li>
  2522. <li><p>The <a class="reference internal" href="../library/zipfile.html#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a> module’s <code class="xref py py-class docutils literal notranslate"><span class="pre">ZipFile</span></code> class now has
  2523. <code class="xref py py-meth docutils literal notranslate"><span class="pre">extract()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">extractall()</span></code> methods that will unpack
  2524. a single file or all the files in the archive to the current directory, or
  2525. to a specified directory:</p>
  2526. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">z</span> <span class="o">=</span> <span class="n">zipfile</span><span class="o">.</span><span class="n">ZipFile</span><span class="p">(</span><span class="s1">&#39;python-251.zip&#39;</span><span class="p">)</span>
  2527. <span class="c1"># Unpack a single file, writing it relative</span>
  2528. <span class="c1"># to the /tmp directory.</span>
  2529. <span class="n">z</span><span class="o">.</span><span class="n">extract</span><span class="p">(</span><span class="s1">&#39;Python/sysmodule.c&#39;</span><span class="p">,</span> <span class="s1">&#39;/tmp&#39;</span><span class="p">)</span>
  2530. <span class="c1"># Unpack all the files in the archive.</span>
  2531. <span class="n">z</span><span class="o">.</span><span class="n">extractall</span><span class="p">()</span>
  2532. </pre></div>
  2533. </div>
  2534. <p>(Contributed by Alan McIntyre; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=467924">bpo-467924</a>.)</p>
  2535. <p>The <a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-meth docutils literal notranslate"><span class="pre">open()</span></code></a>, <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">extract()</span></code> methods can now
  2536. take either a filename or a <code class="xref py py-class docutils literal notranslate"><span class="pre">ZipInfo</span></code> object. This is useful when an
  2537. archive accidentally contains a duplicated filename.
  2538. (Contributed by Graham Horler; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1775025">bpo-1775025</a>.)</p>
  2539. <p>Finally, <a class="reference internal" href="../library/zipfile.html#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a> now supports using Unicode filenames
  2540. for archived files. (Contributed by Alexey Borzenkov; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1734346">bpo-1734346</a>.)</p>
  2541. </li>
  2542. </ul>
  2543. <section id="the-ast-module">
  2544. <h3>The <a class="reference internal" href="../library/ast.html#module-ast" title="ast: Abstract Syntax Tree classes and manipulation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ast</span></code></a> module<a class="headerlink" href="#the-ast-module" title="Link to this heading">¶</a></h3>
  2545. <p>The <a class="reference internal" href="../library/ast.html#module-ast" title="ast: Abstract Syntax Tree classes and manipulation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ast</span></code></a> module provides an Abstract Syntax Tree
  2546. representation of Python code, and Armin Ronacher
  2547. contributed a set of helper functions that perform a variety of
  2548. common tasks. These will be useful for HTML templating
  2549. packages, code analyzers, and similar tools that process
  2550. Python code.</p>
  2551. <p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">parse()</span></code> function takes an expression and returns an AST.
  2552. The <code class="xref py py-func docutils literal notranslate"><span class="pre">dump()</span></code> function outputs a representation of a tree, suitable
  2553. for debugging:</p>
  2554. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">ast</span>
  2555. <span class="n">t</span> <span class="o">=</span> <span class="n">ast</span><span class="o">.</span><span class="n">parse</span><span class="p">(</span><span class="s2">&quot;&quot;&quot;</span>
  2556. <span class="s2">d = </span><span class="si">{}</span>
  2557. <span class="s2">for i in &#39;abcdefghijklm&#39;:</span>
  2558. <span class="s2"> d[i + i] = ord(i) - ord(&#39;a&#39;) + 1</span>
  2559. <span class="s2">print d</span>
  2560. <span class="s2">&quot;&quot;&quot;</span><span class="p">)</span>
  2561. <span class="nb">print</span> <span class="n">ast</span><span class="o">.</span><span class="n">dump</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>
  2562. </pre></div>
  2563. </div>
  2564. <p>This outputs a deeply nested tree:</p>
  2565. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">Module</span><span class="p">(</span><span class="n">body</span><span class="o">=</span><span class="p">[</span>
  2566. <span class="n">Assign</span><span class="p">(</span><span class="n">targets</span><span class="o">=</span><span class="p">[</span>
  2567. <span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;d&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Store</span><span class="p">())</span>
  2568. <span class="p">],</span> <span class="n">value</span><span class="o">=</span><span class="n">Dict</span><span class="p">(</span><span class="n">keys</span><span class="o">=</span><span class="p">[],</span> <span class="n">values</span><span class="o">=</span><span class="p">[]))</span>
  2569. <span class="n">For</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;i&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Store</span><span class="p">()),</span>
  2570. <span class="nb">iter</span><span class="o">=</span><span class="n">Str</span><span class="p">(</span><span class="n">s</span><span class="o">=</span><span class="s1">&#39;abcdefghijklm&#39;</span><span class="p">),</span> <span class="n">body</span><span class="o">=</span><span class="p">[</span>
  2571. <span class="n">Assign</span><span class="p">(</span><span class="n">targets</span><span class="o">=</span><span class="p">[</span>
  2572. <span class="n">Subscript</span><span class="p">(</span><span class="n">value</span><span class="o">=</span>
  2573. <span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;d&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Load</span><span class="p">()),</span>
  2574. <span class="nb">slice</span><span class="o">=</span>
  2575. <span class="n">Index</span><span class="p">(</span><span class="n">value</span><span class="o">=</span>
  2576. <span class="n">BinOp</span><span class="p">(</span><span class="n">left</span><span class="o">=</span><span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;i&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Load</span><span class="p">()),</span> <span class="n">op</span><span class="o">=</span><span class="n">Add</span><span class="p">(),</span>
  2577. <span class="n">right</span><span class="o">=</span><span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;i&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Load</span><span class="p">()))),</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Store</span><span class="p">())</span>
  2578. <span class="p">],</span> <span class="n">value</span><span class="o">=</span>
  2579. <span class="n">BinOp</span><span class="p">(</span><span class="n">left</span><span class="o">=</span>
  2580. <span class="n">BinOp</span><span class="p">(</span><span class="n">left</span><span class="o">=</span>
  2581. <span class="n">Call</span><span class="p">(</span><span class="n">func</span><span class="o">=</span>
  2582. <span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;ord&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Load</span><span class="p">()),</span> <span class="n">args</span><span class="o">=</span><span class="p">[</span>
  2583. <span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;i&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Load</span><span class="p">())</span>
  2584. <span class="p">],</span> <span class="n">keywords</span><span class="o">=</span><span class="p">[],</span> <span class="n">starargs</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">kwargs</span><span class="o">=</span><span class="kc">None</span><span class="p">),</span>
  2585. <span class="n">op</span><span class="o">=</span><span class="n">Sub</span><span class="p">(),</span> <span class="n">right</span><span class="o">=</span><span class="n">Call</span><span class="p">(</span><span class="n">func</span><span class="o">=</span>
  2586. <span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;ord&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Load</span><span class="p">()),</span> <span class="n">args</span><span class="o">=</span><span class="p">[</span>
  2587. <span class="n">Str</span><span class="p">(</span><span class="n">s</span><span class="o">=</span><span class="s1">&#39;a&#39;</span><span class="p">)</span>
  2588. <span class="p">],</span> <span class="n">keywords</span><span class="o">=</span><span class="p">[],</span> <span class="n">starargs</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">kwargs</span><span class="o">=</span><span class="kc">None</span><span class="p">)),</span>
  2589. <span class="n">op</span><span class="o">=</span><span class="n">Add</span><span class="p">(),</span> <span class="n">right</span><span class="o">=</span><span class="n">Num</span><span class="p">(</span><span class="n">n</span><span class="o">=</span><span class="mi">1</span><span class="p">)))</span>
  2590. <span class="p">],</span> <span class="n">orelse</span><span class="o">=</span><span class="p">[])</span>
  2591. <span class="n">Print</span><span class="p">(</span><span class="n">dest</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">values</span><span class="o">=</span><span class="p">[</span>
  2592. <span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;d&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Load</span><span class="p">())</span>
  2593. <span class="p">],</span> <span class="n">nl</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
  2594. <span class="p">])</span>
  2595. </pre></div>
  2596. </div>
  2597. <p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">literal_eval()</span></code> method takes a string or an AST
  2598. representing a literal expression, parses and evaluates it, and
  2599. returns the resulting value. A literal expression is a Python
  2600. expression containing only strings, numbers, dictionaries,
  2601. etc. but no statements or function calls. If you need to
  2602. evaluate an expression but cannot accept the security risk of using an
  2603. <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> call, <code class="xref py py-func docutils literal notranslate"><span class="pre">literal_eval()</span></code> will handle it safely:</p>
  2604. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">literal</span> <span class="o">=</span> <span class="s1">&#39;(&quot;a&quot;, &quot;b&quot;, {2:4, 3:8, 1:2})&#39;</span>
  2605. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">ast</span><span class="o">.</span><span class="n">literal_eval</span><span class="p">(</span><span class="n">literal</span><span class="p">)</span>
  2606. <span class="go">(&#39;a&#39;, &#39;b&#39;, {1: 2, 2: 4, 3: 8})</span>
  2607. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">ast</span><span class="o">.</span><span class="n">literal_eval</span><span class="p">(</span><span class="s1">&#39;&quot;a&quot; + &quot;b&quot;&#39;</span><span class="p">)</span>
  2608. <span class="gt">Traceback (most recent call last):</span>
  2609. <span class="w"> </span><span class="c">...</span>
  2610. <span class="gr">ValueError</span>: <span class="n">malformed string</span>
  2611. </pre></div>
  2612. </div>
  2613. <p>The module also includes <code class="xref py py-class docutils literal notranslate"><span class="pre">NodeVisitor</span></code> and
  2614. <code class="xref py py-class docutils literal notranslate"><span class="pre">NodeTransformer</span></code> classes for traversing and modifying an AST,
  2615. and functions for common transformations such as changing line
  2616. numbers.</p>
  2617. </section>
  2618. <section id="the-future-builtins-module">
  2619. <h3>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">future_builtins</span></code> module<a class="headerlink" href="#the-future-builtins-module" title="Link to this heading">¶</a></h3>
  2620. <p>Python 3.0 makes many changes to the repertoire of built-in
  2621. functions, and most of the changes can’t be introduced in the Python
  2622. 2.x series because they would break compatibility.
  2623. The <code class="xref py py-mod docutils literal notranslate"><span class="pre">future_builtins</span></code> module provides versions
  2624. of these built-in functions that can be imported when writing
  2625. 3.0-compatible code.</p>
  2626. <p>The functions in this module currently include:</p>
  2627. <ul class="simple">
  2628. <li><p><code class="docutils literal notranslate"><span class="pre">ascii(obj)</span></code>: equivalent to <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>. In Python 3.0,
  2629. <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> will return a Unicode string, while <a class="reference internal" href="../library/functions.html#ascii" title="ascii"><code class="xref py py-func docutils literal notranslate"><span class="pre">ascii()</span></code></a> will
  2630. return a pure ASCII bytestring.</p></li>
  2631. <li><p><code class="docutils literal notranslate"><span class="pre">filter(predicate,</span> <span class="pre">iterable)</span></code>,
  2632. <code class="docutils literal notranslate"><span class="pre">map(func,</span> <span class="pre">iterable1,</span> <span class="pre">...)</span></code>: the 3.0 versions
  2633. return iterators, unlike the 2.x builtins which return lists.</p></li>
  2634. <li><p><code class="docutils literal notranslate"><span class="pre">hex(value)</span></code>, <code class="docutils literal notranslate"><span class="pre">oct(value)</span></code>: instead of calling the
  2635. <code class="xref py py-meth docutils literal notranslate"><span class="pre">__hex__()</span></code> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">__oct__()</span></code> methods, these versions will
  2636. call the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__index__()</span></code> method and convert the result to hexadecimal
  2637. or octal. <a class="reference internal" href="../library/functions.html#oct" title="oct"><code class="xref py py-func docutils literal notranslate"><span class="pre">oct()</span></code></a> will use the new <code class="docutils literal notranslate"><span class="pre">0o</span></code> notation for its
  2638. result.</p></li>
  2639. </ul>
  2640. </section>
  2641. <section id="the-json-module-javascript-object-notation">
  2642. <h3>The <a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> module: JavaScript Object Notation<a class="headerlink" href="#the-json-module-javascript-object-notation" title="Link to this heading">¶</a></h3>
  2643. <p>The new <a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> module supports the encoding and decoding of Python types in
  2644. JSON (Javascript Object Notation). JSON is a lightweight interchange format
  2645. often used in web applications. For more information about JSON, see
  2646. <a class="reference external" href="http://www.json.org">http://www.json.org</a>.</p>
  2647. <p><a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> comes with support for decoding and encoding most built-in Python
  2648. types. The following example encodes and decodes a dictionary:</p>
  2649. <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">json</span>
  2650. <span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">=</span> <span class="p">{</span><span class="s2">&quot;spam&quot;</span><span class="p">:</span> <span class="s2">&quot;foo&quot;</span><span class="p">,</span> <span class="s2">&quot;parrot&quot;</span><span class="p">:</span> <span class="mi">42</span><span class="p">}</span>
  2651. <span class="gp">&gt;&gt;&gt; </span><span class="n">in_json</span> <span class="o">=</span> <span class="n">json</span><span class="o">.</span><span class="n">dumps</span><span class="p">(</span><span class="n">data</span><span class="p">)</span> <span class="c1"># Encode the data</span>
  2652. <span class="gp">&gt;&gt;&gt; </span><span class="n">in_json</span>
  2653. <span class="go">&#39;{&quot;parrot&quot;: 42, &quot;spam&quot;: &quot;foo&quot;}&#39;</span>
  2654. <span class="gp">&gt;&gt;&gt; </span><span class="n">json</span><span class="o">.</span><span class="n">loads</span><span class="p">(</span><span class="n">in_json</span><span class="p">)</span> <span class="c1"># Decode into a Python object</span>
  2655. <span class="go">{&quot;spam&quot;: &quot;foo&quot;, &quot;parrot&quot;: 42}</span>
  2656. </pre></div>
  2657. </div>
  2658. <p>It’s also possible to write your own decoders and encoders to support
  2659. more types. Pretty-printing of the JSON strings is also supported.</p>
  2660. <p><a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> (originally called simplejson) was written by Bob
  2661. Ippolito.</p>
  2662. </section>
  2663. <section id="the-plistlib-module-a-property-list-parser">
  2664. <h3>The <a class="reference internal" href="../library/plistlib.html#module-plistlib" title="plistlib: Generate and parse Apple plist files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">plistlib</span></code></a> module: A Property-List Parser<a class="headerlink" href="#the-plistlib-module-a-property-list-parser" title="Link to this heading">¶</a></h3>
  2665. <p>The <code class="docutils literal notranslate"><span class="pre">.plist</span></code> format is commonly used on Mac OS X to
  2666. store basic data types (numbers, strings, lists,
  2667. and dictionaries) by serializing them into an XML-based format.
  2668. It resembles the XML-RPC serialization of data types.</p>
  2669. <p>Despite being primarily used on Mac OS X, the format
  2670. has nothing Mac-specific about it and the Python implementation works
  2671. on any platform that Python supports, so the <a class="reference internal" href="../library/plistlib.html#module-plistlib" title="plistlib: Generate and parse Apple plist files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">plistlib</span></code></a> module
  2672. has been promoted to the standard library.</p>
  2673. <p>Using the module is simple:</p>
  2674. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sys</span>
  2675. <span class="kn">import</span> <span class="nn">plistlib</span>
  2676. <span class="kn">import</span> <span class="nn">datetime</span>
  2677. <span class="c1"># Create data structure</span>
  2678. <span class="n">data_struct</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="n">lastAccessed</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>
  2679. <span class="n">version</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span>
  2680. <span class="n">categories</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;Personal&#39;</span><span class="p">,</span><span class="s1">&#39;Shared&#39;</span><span class="p">,</span><span class="s1">&#39;Private&#39;</span><span class="p">))</span>
  2681. <span class="c1"># Create string containing XML.</span>
  2682. <span class="n">plist_str</span> <span class="o">=</span> <span class="n">plistlib</span><span class="o">.</span><span class="n">writePlistToString</span><span class="p">(</span><span class="n">data_struct</span><span class="p">)</span>
  2683. <span class="n">new_struct</span> <span class="o">=</span> <span class="n">plistlib</span><span class="o">.</span><span class="n">readPlistFromString</span><span class="p">(</span><span class="n">plist_str</span><span class="p">)</span>
  2684. <span class="nb">print</span> <span class="n">data_struct</span>
  2685. <span class="nb">print</span> <span class="n">new_struct</span>
  2686. <span class="c1"># Write data structure to a file and read it back.</span>
  2687. <span class="n">plistlib</span><span class="o">.</span><span class="n">writePlist</span><span class="p">(</span><span class="n">data_struct</span><span class="p">,</span> <span class="s1">&#39;/tmp/customizations.plist&#39;</span><span class="p">)</span>
  2688. <span class="n">new_struct</span> <span class="o">=</span> <span class="n">plistlib</span><span class="o">.</span><span class="n">readPlist</span><span class="p">(</span><span class="s1">&#39;/tmp/customizations.plist&#39;</span><span class="p">)</span>
  2689. <span class="c1"># read/writePlist accepts file-like objects as well as paths.</span>
  2690. <span class="n">plistlib</span><span class="o">.</span><span class="n">writePlist</span><span class="p">(</span><span class="n">data_struct</span><span class="p">,</span> <span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="p">)</span>
  2691. </pre></div>
  2692. </div>
  2693. </section>
  2694. <section id="ctypes-enhancements">
  2695. <h3>ctypes Enhancements<a class="headerlink" href="#ctypes-enhancements" title="Link to this heading">¶</a></h3>
  2696. <p>Thomas Heller continued to maintain and enhance the
  2697. <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> module.</p>
  2698. <p><a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> now supports a <code class="xref py py-class docutils literal notranslate"><span class="pre">c_bool</span></code> datatype
  2699. that represents the C99 <code class="docutils literal notranslate"><span class="pre">bool</span></code> type. (Contributed by David Remahl;
  2700. <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1649190">bpo-1649190</a>.)</p>
  2701. <p>The <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> string, buffer and array types have improved
  2702. support for extended slicing syntax,
  2703. where various combinations of <code class="docutils literal notranslate"><span class="pre">(start,</span> <span class="pre">stop,</span> <span class="pre">step)</span></code> are supplied.
  2704. (Implemented by Thomas Wouters.)</p>
  2705. <p>All <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> data types now support
  2706. <code class="xref py py-meth docutils literal notranslate"><span class="pre">from_buffer()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">from_buffer_copy()</span></code>
  2707. methods that create a ctypes instance based on a
  2708. provided buffer object. <code class="xref py py-meth docutils literal notranslate"><span class="pre">from_buffer_copy()</span></code> copies
  2709. the contents of the object,
  2710. while <code class="xref py py-meth docutils literal notranslate"><span class="pre">from_buffer()</span></code> will share the same memory area.</p>
  2711. <p>A new calling convention tells <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> to clear the <code class="docutils literal notranslate"><span class="pre">errno</span></code> or
  2712. Win32 LastError variables at the outset of each wrapped call.
  2713. (Implemented by Thomas Heller; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1798">bpo-1798</a>.)</p>
  2714. <p>You can now retrieve the Unix <code class="docutils literal notranslate"><span class="pre">errno</span></code> variable after a function
  2715. call. When creating a wrapped function, you can supply
  2716. <code class="docutils literal notranslate"><span class="pre">use_errno=True</span></code> as a keyword parameter to the <code class="xref py py-func docutils literal notranslate"><span class="pre">DLL()</span></code> function
  2717. and then call the module-level methods <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_errno()</span></code> and
  2718. <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_errno()</span></code> to set and retrieve the error value.</p>
  2719. <p>The Win32 LastError variable is similarly supported by
  2720. the <code class="xref py py-func docutils literal notranslate"><span class="pre">DLL()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">OleDLL()</span></code>, and <code class="xref py py-func docutils literal notranslate"><span class="pre">WinDLL()</span></code> functions.
  2721. You supply <code class="docutils literal notranslate"><span class="pre">use_last_error=True</span></code> as a keyword parameter
  2722. and then call the module-level methods <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_last_error()</span></code>
  2723. and <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_last_error()</span></code>.</p>
  2724. <p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">byref()</span></code> function, used to retrieve a pointer to a ctypes
  2725. instance, now has an optional <em>offset</em> parameter that is a byte
  2726. count that will be added to the returned pointer.</p>
  2727. </section>
  2728. <section id="improved-ssl-support">
  2729. <h3>Improved SSL Support<a class="headerlink" href="#improved-ssl-support" title="Link to this heading">¶</a></h3>
  2730. <p>Bill Janssen made extensive improvements to Python 2.6’s support for
  2731. the Secure Sockets Layer by adding a new module, <a class="reference internal" href="../library/ssl.html#module-ssl" title="ssl: TLS/SSL wrapper for socket objects"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ssl</span></code></a>, that’s
  2732. built atop the <a class="reference external" href="https://www.openssl.org/">OpenSSL</a> library.
  2733. This new module provides more control over the protocol negotiated,
  2734. the X.509 certificates used, and has better support for writing SSL
  2735. servers (as opposed to clients) in Python. The existing SSL support
  2736. in 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 hasn’t been removed and continues to work,
  2737. though it will be removed in Python 3.0.</p>
  2738. <p>To use the new module, you must first create a TCP connection in the
  2739. usual way and then pass it to the <code class="xref py py-func docutils literal notranslate"><span class="pre">ssl.wrap_socket()</span></code> function.
  2740. It’s possible to specify whether a certificate is required, and to
  2741. obtain certificate info by calling the <code class="xref py py-meth docutils literal notranslate"><span class="pre">getpeercert()</span></code> method.</p>
  2742. <div class="admonition seealso">
  2743. <p class="admonition-title">See also</p>
  2744. <p>The documentation for the <a class="reference internal" href="../library/ssl.html#module-ssl" title="ssl: TLS/SSL wrapper for socket objects"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ssl</span></code></a> module.</p>
  2745. </div>
  2746. </section>
  2747. </section>
  2748. <section id="deprecations-and-removals">
  2749. <h2>Deprecations and Removals<a class="headerlink" href="#deprecations-and-removals" title="Link to this heading">¶</a></h2>
  2750. <ul>
  2751. <li><p>String exceptions have been removed. Attempting to use them raises a
  2752. <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.</p></li>
  2753. <li><p>Changes to the <a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><code class="xref py py-class docutils literal notranslate"><span class="pre">Exception</span></code></a> interface
  2754. as dictated by <span class="target" id="index-25"></span><a class="pep reference external" href="https://peps.python.org/pep-0352/"><strong>PEP 352</strong></a> continue to be made. For 2.6,
  2755. the <code class="xref py py-attr docutils literal notranslate"><span class="pre">message</span></code> attribute is being deprecated in favor of the
  2756. <a class="reference internal" href="../library/exceptions.html#BaseException.args" title="BaseException.args"><code class="xref py py-attr docutils literal notranslate"><span class="pre">args</span></code></a> attribute.</p></li>
  2757. <li><p>(3.0-warning mode) Python 3.0 will feature a reorganized standard
  2758. library that will drop many outdated modules and rename others.
  2759. Python 2.6 running in 3.0-warning mode will warn about these modules
  2760. when they are imported.</p>
  2761. <p>The list of deprecated modules is:
  2762. <code class="xref py py-mod docutils literal notranslate"><span class="pre">audiodev</span></code>,
  2763. <code class="xref py py-mod docutils literal notranslate"><span class="pre">bgenlocations</span></code>,
  2764. <code class="xref py py-mod docutils literal notranslate"><span class="pre">buildtools</span></code>,
  2765. <code class="xref py py-mod docutils literal notranslate"><span class="pre">bundlebuilder</span></code>,
  2766. <code class="xref py py-mod docutils literal notranslate"><span class="pre">Canvas</span></code>,
  2767. <code class="xref py py-mod docutils literal notranslate"><span class="pre">compiler</span></code>,
  2768. <code class="xref py py-mod docutils literal notranslate"><span class="pre">dircache</span></code>,
  2769. <code class="xref py py-mod docutils literal notranslate"><span class="pre">dl</span></code>,
  2770. <code class="xref py py-mod docutils literal notranslate"><span class="pre">fpformat</span></code>,
  2771. <code class="xref py py-mod docutils literal notranslate"><span class="pre">gensuitemodule</span></code>,
  2772. <code class="xref py py-mod docutils literal notranslate"><span class="pre">ihooks</span></code>,
  2773. <code class="xref py py-mod docutils literal notranslate"><span class="pre">imageop</span></code>,
  2774. <code class="xref py py-mod docutils literal notranslate"><span class="pre">imgfile</span></code>,
  2775. <code class="xref py py-mod docutils literal notranslate"><span class="pre">linuxaudiodev</span></code>,
  2776. <code class="xref py py-mod docutils literal notranslate"><span class="pre">mhlib</span></code>,
  2777. <code class="xref py py-mod docutils literal notranslate"><span class="pre">mimetools</span></code>,
  2778. <code class="xref py py-mod docutils literal notranslate"><span class="pre">multifile</span></code>,
  2779. <code class="xref py py-mod docutils literal notranslate"><span class="pre">new</span></code>,
  2780. <code class="xref py py-mod docutils literal notranslate"><span class="pre">pure</span></code>,
  2781. <code class="xref py py-mod docutils literal notranslate"><span class="pre">statvfs</span></code>,
  2782. <code class="xref py py-mod docutils literal notranslate"><span class="pre">sunaudiodev</span></code>,
  2783. <code class="xref py py-mod docutils literal notranslate"><span class="pre">test.testall</span></code>, and
  2784. <code class="xref py py-mod docutils literal notranslate"><span class="pre">toaiff</span></code>.</p>
  2785. </li>
  2786. <li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">gopherlib</span></code> module has been removed.</p></li>
  2787. <li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">MimeWriter</span></code> module and <code class="xref py py-mod docutils literal notranslate"><span class="pre">mimify</span></code> module
  2788. have been deprecated; use the <a class="reference internal" href="../library/email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a>
  2789. package instead.</p></li>
  2790. <li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">md5</span></code> module has been deprecated; use the <a class="reference internal" href="../library/hashlib.html#module-hashlib" title="hashlib: Secure hash and message digest algorithms."><code class="xref py py-mod docutils literal notranslate"><span class="pre">hashlib</span></code></a> module
  2791. instead.</p></li>
  2792. <li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">posixfile</span></code> module has been deprecated; <a class="reference internal" href="../library/fcntl.html#fcntl.lockf" title="fcntl.lockf"><code class="xref py py-func docutils literal notranslate"><span class="pre">fcntl.lockf()</span></code></a>
  2793. provides better locking.</p></li>
  2794. <li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">popen2</span></code> module has been deprecated; use the <a class="reference internal" href="../library/subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a>
  2795. module.</p></li>
  2796. <li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">rgbimg</span></code> module has been removed.</p></li>
  2797. <li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">sets</span></code> module has been deprecated; it’s better to
  2798. use the built-in <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> and <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> types.</p></li>
  2799. <li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">sha</span></code> module has been deprecated; use the <a class="reference internal" href="../library/hashlib.html#module-hashlib" title="hashlib: Secure hash and message digest algorithms."><code class="xref py py-mod docutils literal notranslate"><span class="pre">hashlib</span></code></a> module
  2800. instead.</p></li>
  2801. </ul>
  2802. </section>
  2803. <section id="build-and-c-api-changes">
  2804. <h2>Build and C API Changes<a class="headerlink" href="#build-and-c-api-changes" title="Link to this heading">¶</a></h2>
  2805. <p>Changes to Python’s build process and to the C API include:</p>
  2806. <ul>
  2807. <li><p>Python now must be compiled with C89 compilers (after 19
  2808. years!). This means that the Python source tree has dropped its
  2809. own implementations of <code class="xref c c-func docutils literal notranslate"><span class="pre">memmove()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">strerror()</span></code>, which
  2810. are in the C89 standard library.</p></li>
  2811. <li><p>Python 2.6 can be built with Microsoft Visual Studio 2008 (version
  2812. 9.0), and this is the new default compiler. See the
  2813. <code class="file docutils literal notranslate"><span class="pre">PCbuild</span></code> directory for the build files. (Implemented by
  2814. Christian Heimes.)</p></li>
  2815. <li><p>On Mac OS X, Python 2.6 can be compiled as a 4-way universal build.
  2816. The <strong class="program">configure</strong> script
  2817. can take a <code class="xref std std-option docutils literal notranslate"><span class="pre">--with-universal-archs=[32-bit|64-bit|all]</span></code>
  2818. switch, controlling whether the binaries are built for 32-bit
  2819. architectures (x86, PowerPC), 64-bit (x86-64 and PPC-64), or both.
  2820. (Contributed by Ronald Oussoren.)</p></li>
  2821. <li><p>A new function added in Python 2.6.6, <code class="xref c c-func docutils literal notranslate"><span class="pre">PySys_SetArgvEx()</span></code>, sets
  2822. the value of <code class="docutils literal notranslate"><span class="pre">sys.argv</span></code> and can optionally update <code class="docutils literal notranslate"><span class="pre">sys.path</span></code> to
  2823. include the directory containing the script named by <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code>
  2824. depending on the value of an <em>updatepath</em> parameter.</p>
  2825. <p>This function was added to close a security hole for applications
  2826. that embed Python. The old function, <code class="xref c c-func docutils literal notranslate"><span class="pre">PySys_SetArgv()</span></code>, would
  2827. always update <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>, and sometimes it would add the current
  2828. directory. This meant that, if you ran an application embedding
  2829. Python in a directory controlled by someone else, attackers could
  2830. put a Trojan-horse module in the directory (say, a file named
  2831. <code class="file docutils literal notranslate"><span class="pre">os.py</span></code>) that your application would then import and run.</p>
  2832. <p>If you maintain a C/C++ application that embeds Python, check
  2833. whether you’re calling <code class="xref c c-func docutils literal notranslate"><span class="pre">PySys_SetArgv()</span></code> and carefully consider
  2834. whether the application should be using <code class="xref c c-func docutils literal notranslate"><span class="pre">PySys_SetArgvEx()</span></code>
  2835. with <em>updatepath</em> set to false. Note that using this function will
  2836. break compatibility with Python versions 2.6.5 and earlier; if you
  2837. have to continue working with earlier versions, you can leave
  2838. the call to <code class="xref c c-func docutils literal notranslate"><span class="pre">PySys_SetArgv()</span></code> alone and call
  2839. <code class="docutils literal notranslate"><span class="pre">PyRun_SimpleString(&quot;sys.path.pop(0)\n&quot;)</span></code> afterwards to discard
  2840. the first <code class="docutils literal notranslate"><span class="pre">sys.path</span></code> component.</p>
  2841. <p>Security issue reported as <a class="reference external" href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983">CVE-2008-5983</a>;
  2842. discussed in <a class="reference external" href="https://github.com/python/cpython/issues/50003">gh-50003</a>, and fixed by Antoine Pitrou.</p>
  2843. </li>
  2844. <li><p>The BerkeleyDB module now has a C API object, available as
  2845. <code class="docutils literal notranslate"><span class="pre">bsddb.db.api</span></code>. This object can be used by other C extensions
  2846. that wish to use the <code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code> module for their own purposes.
  2847. (Contributed by Duncan Grisby.)</p></li>
  2848. <li><p>The new buffer interface, previously described in
  2849. <a class="reference external" href="#pep-3118-revised-buffer-protocol">the PEP 3118 section</a>,
  2850. adds <a class="reference internal" href="../c-api/buffer.html#c.PyObject_GetBuffer" title="PyObject_GetBuffer"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GetBuffer()</span></code></a> and <a class="reference internal" href="../c-api/buffer.html#c.PyBuffer_Release" title="PyBuffer_Release"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyBuffer_Release()</span></code></a>,
  2851. as well as a few other functions.</p></li>
  2852. <li><p>Python’s use of the C stdio library is now thread-safe, or at least
  2853. as thread-safe as the underlying library is. A long-standing potential
  2854. bug occurred if one thread closed a file object while another thread
  2855. was reading from or writing to the object. In 2.6 file objects
  2856. have a reference count, manipulated by the
  2857. <code class="xref c c-func docutils literal notranslate"><span class="pre">PyFile_IncUseCount()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">PyFile_DecUseCount()</span></code>
  2858. functions. File objects can’t be closed unless the reference count
  2859. is zero. <code class="xref c c-func docutils literal notranslate"><span class="pre">PyFile_IncUseCount()</span></code> should be called while the GIL
  2860. is still held, before carrying out an I/O operation using the
  2861. <code class="docutils literal notranslate"><span class="pre">FILE</span> <span class="pre">*</span></code> pointer, and <code class="xref c c-func docutils literal notranslate"><span class="pre">PyFile_DecUseCount()</span></code> should be called
  2862. immediately after the GIL is re-acquired.
  2863. (Contributed by Antoine Pitrou and Gregory P. Smith.)</p></li>
  2864. <li><p>Importing modules simultaneously in two different threads no longer
  2865. deadlocks; it will now raise an <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>. A new API
  2866. function, <a class="reference internal" href="../c-api/import.html#c.PyImport_ImportModuleNoBlock" title="PyImport_ImportModuleNoBlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_ImportModuleNoBlock()</span></code></a>, will look for a
  2867. module in <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code> first, then try to import it after
  2868. acquiring an import lock. If the import lock is held by another
  2869. thread, an <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> is raised.
  2870. (Contributed by Christian Heimes.)</p></li>
  2871. <li><p>Several functions return information about the platform’s
  2872. floating-point support. <a class="reference internal" href="../c-api/float.html#c.PyFloat_GetMax" title="PyFloat_GetMax"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyFloat_GetMax()</span></code></a> returns
  2873. the maximum representable floating point value,
  2874. and <a class="reference internal" href="../c-api/float.html#c.PyFloat_GetMin" title="PyFloat_GetMin"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyFloat_GetMin()</span></code></a> returns the minimum
  2875. positive value. <a class="reference internal" href="../c-api/float.html#c.PyFloat_GetInfo" title="PyFloat_GetInfo"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyFloat_GetInfo()</span></code></a> returns an object
  2876. containing more information from the <code class="file docutils literal notranslate"><span class="pre">float.h</span></code> file, such as
  2877. <code class="docutils literal notranslate"><span class="pre">&quot;mant_dig&quot;</span></code> (number of digits in the mantissa), <code class="docutils literal notranslate"><span class="pre">&quot;epsilon&quot;</span></code>
  2878. (smallest difference between 1.0 and the next largest value
  2879. representable), and several others.
  2880. (Contributed by Christian Heimes; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1534">bpo-1534</a>.)</p></li>
  2881. <li><p>C functions and methods that use
  2882. <a class="reference internal" href="../c-api/complex.html#c.PyComplex_AsCComplex" title="PyComplex_AsCComplex"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyComplex_AsCComplex()</span></code></a> will now accept arguments that
  2883. have a <code class="xref py py-meth docutils literal notranslate"><span class="pre">__complex__()</span></code> method. In particular, the functions in the
  2884. <a class="reference internal" href="../library/cmath.html#module-cmath" title="cmath: Mathematical functions for complex numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cmath</span></code></a> module will now accept objects with this method.
  2885. This is a backport of a Python 3.0 change.
  2886. (Contributed by Mark Dickinson; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1675423">bpo-1675423</a>.)</p></li>
  2887. <li><p>Python’s C API now includes two functions for case-insensitive string
  2888. comparisons, <code class="docutils literal notranslate"><span class="pre">PyOS_stricmp(char*,</span> <span class="pre">char*)</span></code>
  2889. and <code class="docutils literal notranslate"><span class="pre">PyOS_strnicmp(char*,</span> <span class="pre">char*,</span> <span class="pre">Py_ssize_t)</span></code>.
  2890. (Contributed by Christian Heimes; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1635">bpo-1635</a>.)</p></li>
  2891. <li><p>Many C extensions define their own little macro for adding
  2892. integers and strings to the module’s dictionary in the
  2893. <code class="docutils literal notranslate"><span class="pre">init*</span></code> function. Python 2.6 finally defines standard macros
  2894. for adding values to a module, <a class="reference internal" href="../c-api/module.html#c.PyModule_AddStringMacro" title="PyModule_AddStringMacro"><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyModule_AddStringMacro</span></code></a>
  2895. and <a class="reference internal" href="../c-api/module.html#c.PyModule_AddIntMacro" title="PyModule_AddIntMacro"><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyModule_AddIntMacro()</span></code></a>. (Contributed by
  2896. Christian Heimes.)</p></li>
  2897. <li><p>Some macros were renamed in both 3.0 and 2.6 to make it clearer that
  2898. they are macros,
  2899. not functions. <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_Size()</span></code> became <a class="reference internal" href="../c-api/structures.html#c.Py_SIZE" title="Py_SIZE"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_SIZE()</span></code></a>,
  2900. <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_Type()</span></code> became <a class="reference internal" href="../c-api/structures.html#c.Py_TYPE" title="Py_TYPE"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_TYPE()</span></code></a>, and
  2901. <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_Refcnt()</span></code> became <a class="reference internal" href="../c-api/refcounting.html#c.Py_REFCNT" title="Py_REFCNT"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_REFCNT()</span></code></a>.
  2902. The mixed-case macros are still available
  2903. in Python 2.6 for backward compatibility.
  2904. (<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1629">bpo-1629</a>)</p></li>
  2905. <li><p>Distutils now places C extensions it builds in a
  2906. different directory when running on a debug version of Python.
  2907. (Contributed by Collin Winter; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1530959">bpo-1530959</a>.)</p></li>
  2908. <li><p>Several basic data types, such as integers and strings, maintain
  2909. internal free lists of objects that can be re-used. The data
  2910. structures for these free lists now follow a naming convention: the
  2911. variable is always named <code class="docutils literal notranslate"><span class="pre">free_list</span></code>, the counter is always named
  2912. <code class="docutils literal notranslate"><span class="pre">numfree</span></code>, and a macro <code class="docutils literal notranslate"><span class="pre">Py&lt;typename&gt;_MAXFREELIST</span></code> is
  2913. always defined.</p></li>
  2914. <li><p>A new Makefile target, “make patchcheck”, prepares the Python source tree
  2915. for making a patch: it fixes trailing whitespace in all modified
  2916. <code class="docutils literal notranslate"><span class="pre">.py</span></code> files, checks whether the documentation has been changed,
  2917. and reports whether the <code class="file docutils literal notranslate"><span class="pre">Misc/ACKS</span></code> and <code class="file docutils literal notranslate"><span class="pre">Misc/NEWS</span></code> files
  2918. have been updated.
  2919. (Contributed by Brett Cannon.)</p>
  2920. <p>Another new target, “make profile-opt”, compiles a Python binary
  2921. using GCC’s profile-guided optimization. It compiles Python with
  2922. profiling enabled, runs the test suite to obtain a set of profiling
  2923. results, and then compiles using these results for optimization.
  2924. (Contributed by Gregory P. Smith.)</p>
  2925. </li>
  2926. </ul>
  2927. <section id="port-specific-changes-windows">
  2928. <h3>Port-Specific Changes: Windows<a class="headerlink" href="#port-specific-changes-windows" title="Link to this heading">¶</a></h3>
  2929. <ul>
  2930. <li><p>The support for Windows 95, 98, ME and NT4 has been dropped.
  2931. Python 2.6 requires at least Windows 2000 SP4.</p></li>
  2932. <li><p>The new default compiler on Windows is Visual Studio 2008 (version
  2933. 9.0). The build directories for Visual Studio 2003 (version 7.1) and
  2934. 2005 (version 8.0) were moved into the PC/ directory. The new
  2935. <code class="file docutils literal notranslate"><span class="pre">PCbuild</span></code> directory supports cross compilation for X64, debug
  2936. builds and Profile Guided Optimization (PGO). PGO builds are roughly
  2937. 10% faster than normal builds. (Contributed by Christian Heimes
  2938. with help from Amaury Forgeot d’Arc and Martin von Löwis.)</p></li>
  2939. <li><p>The <a class="reference internal" href="../library/msvcrt.html#module-msvcrt" title="msvcrt: Miscellaneous useful routines from the MS VC++ runtime. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">msvcrt</span></code></a> module now supports
  2940. both the normal and wide char variants of the console I/O
  2941. API. The <a class="reference internal" href="../library/msvcrt.html#msvcrt.getwch" title="msvcrt.getwch"><code class="xref py py-func docutils literal notranslate"><span class="pre">getwch()</span></code></a> function reads a keypress and returns a Unicode
  2942. value, as does the <a class="reference internal" href="../library/msvcrt.html#msvcrt.getwche" title="msvcrt.getwche"><code class="xref py py-func docutils literal notranslate"><span class="pre">getwche()</span></code></a> function. The <a class="reference internal" href="../library/msvcrt.html#msvcrt.putwch" title="msvcrt.putwch"><code class="xref py py-func docutils literal notranslate"><span class="pre">putwch()</span></code></a> function
  2943. takes a Unicode character and writes it to the console.
  2944. (Contributed by Christian Heimes.)</p></li>
  2945. <li><p><a class="reference internal" href="../library/os.path.html#os.path.expandvars" title="os.path.expandvars"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.path.expandvars()</span></code></a> will now expand environment variables in
  2946. the form “%var%”, and “~user” will be expanded into the user’s home
  2947. directory path. (Contributed by Josiah Carlson; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=957650">bpo-957650</a>.)</p></li>
  2948. <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’s socket objects now have an
  2949. <a class="reference internal" href="../library/socket.html#socket.socket.ioctl" title="socket.socket.ioctl"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ioctl()</span></code></a> method that provides a limited interface to the
  2950. <code class="xref c c-func docutils literal notranslate"><span class="pre">WSAIoctl()</span></code> system interface.</p></li>
  2951. <li><p>The <a class="reference internal" href="../library/winreg.html#module-winreg" title="winreg: Routines and objects for manipulating the Windows registry. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">_winreg</span></code></a> module now has a function,
  2952. <a class="reference internal" href="../library/winreg.html#winreg.ExpandEnvironmentStrings" title="winreg.ExpandEnvironmentStrings"><code class="xref py py-func docutils literal notranslate"><span class="pre">ExpandEnvironmentStrings()</span></code></a>,
  2953. that expands environment variable references such as <code class="docutils literal notranslate"><span class="pre">%NAME%</span></code>
  2954. in an input string. The handle objects provided by this
  2955. module now support the context protocol, so they can be used
  2956. in <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statements. (Contributed by Christian Heimes.)</p>
  2957. <p><a class="reference internal" href="../library/winreg.html#module-winreg" title="winreg: Routines and objects for manipulating the Windows registry. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">_winreg</span></code></a> also has better support for x64 systems,
  2958. exposing the <a class="reference internal" href="../library/winreg.html#winreg.DisableReflectionKey" title="winreg.DisableReflectionKey"><code class="xref py py-func docutils literal notranslate"><span class="pre">DisableReflectionKey()</span></code></a>, <a class="reference internal" href="../library/winreg.html#winreg.EnableReflectionKey" title="winreg.EnableReflectionKey"><code class="xref py py-func docutils literal notranslate"><span class="pre">EnableReflectionKey()</span></code></a>,
  2959. and <a class="reference internal" href="../library/winreg.html#winreg.QueryReflectionKey" title="winreg.QueryReflectionKey"><code class="xref py py-func docutils literal notranslate"><span class="pre">QueryReflectionKey()</span></code></a> functions, which enable and disable
  2960. registry reflection for 32-bit processes running on 64-bit systems.
  2961. (<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1753245">bpo-1753245</a>)</p>
  2962. </li>
  2963. <li><p>The <a class="reference internal" href="../library/msilib.html#module-msilib" title="msilib: Creation of Microsoft Installer files, and CAB files. (deprecated) (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">msilib</span></code></a> module’s <code class="xref py py-class docutils literal notranslate"><span class="pre">Record</span></code> object
  2964. gained <a class="reference internal" href="../library/msilib.html#msilib.Record.GetInteger" title="msilib.Record.GetInteger"><code class="xref py py-meth docutils literal notranslate"><span class="pre">GetInteger()</span></code></a> and <a class="reference internal" href="../library/msilib.html#msilib.Record.GetString" title="msilib.Record.GetString"><code class="xref py py-meth docutils literal notranslate"><span class="pre">GetString()</span></code></a> methods that
  2965. return field values as an integer or a string.
  2966. (Contributed by Floris Bruynooghe; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2125">bpo-2125</a>.)</p></li>
  2967. </ul>
  2968. </section>
  2969. <section id="port-specific-changes-mac-os-x">
  2970. <h3>Port-Specific Changes: Mac OS X<a class="headerlink" href="#port-specific-changes-mac-os-x" title="Link to this heading">¶</a></h3>
  2971. <ul class="simple">
  2972. <li><p>When compiling a framework build of Python, you can now specify the
  2973. framework name to be used by providing the
  2974. <code class="xref std std-option docutils literal notranslate"><span class="pre">--with-framework-name=</span></code> option to the
  2975. <strong class="program">configure</strong> script.</p></li>
  2976. <li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">macfs</span></code> module has been removed. This in turn required the
  2977. <code class="xref py py-func docutils literal notranslate"><span class="pre">macostools.touched()</span></code> function to be removed because it depended on the
  2978. <code class="xref py py-mod docutils literal notranslate"><span class="pre">macfs</span></code> module. (<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1490190">bpo-1490190</a>)</p></li>
  2979. <li><p>Many other Mac OS modules have been deprecated and will be removed in
  2980. Python 3.0:
  2981. <code class="xref py py-mod docutils literal notranslate"><span class="pre">_builtinSuites</span></code>,
  2982. <code class="xref py py-mod docutils literal notranslate"><span class="pre">aepack</span></code>,
  2983. <code class="xref py py-mod docutils literal notranslate"><span class="pre">aetools</span></code>,
  2984. <code class="xref py py-mod docutils literal notranslate"><span class="pre">aetypes</span></code>,
  2985. <code class="xref py py-mod docutils literal notranslate"><span class="pre">applesingle</span></code>,
  2986. <code class="xref py py-mod docutils literal notranslate"><span class="pre">appletrawmain</span></code>,
  2987. <code class="xref py py-mod docutils literal notranslate"><span class="pre">appletrunner</span></code>,
  2988. <code class="xref py py-mod docutils literal notranslate"><span class="pre">argvemulator</span></code>,
  2989. <code class="xref py py-mod docutils literal notranslate"><span class="pre">Audio_mac</span></code>,
  2990. <code class="xref py py-mod docutils literal notranslate"><span class="pre">autoGIL</span></code>,
  2991. <code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon</span></code>,
  2992. <code class="xref py py-mod docutils literal notranslate"><span class="pre">cfmfile</span></code>,
  2993. <code class="xref py py-mod docutils literal notranslate"><span class="pre">CodeWarrior</span></code>,
  2994. <code class="xref py py-mod docutils literal notranslate"><span class="pre">ColorPicker</span></code>,
  2995. <code class="xref py py-mod docutils literal notranslate"><span class="pre">EasyDialogs</span></code>,
  2996. <code class="xref py py-mod docutils literal notranslate"><span class="pre">Explorer</span></code>,
  2997. <code class="xref py py-mod docutils literal notranslate"><span class="pre">Finder</span></code>,
  2998. <code class="xref py py-mod docutils literal notranslate"><span class="pre">FrameWork</span></code>,
  2999. <code class="xref py py-mod docutils literal notranslate"><span class="pre">findertools</span></code>,
  3000. <code class="xref py py-mod docutils literal notranslate"><span class="pre">ic</span></code>,
  3001. <code class="xref py py-mod docutils literal notranslate"><span class="pre">icglue</span></code>,
  3002. <code class="xref py py-mod docutils literal notranslate"><span class="pre">icopen</span></code>,
  3003. <code class="xref py py-mod docutils literal notranslate"><span class="pre">macerrors</span></code>,
  3004. <code class="xref py py-mod docutils literal notranslate"><span class="pre">MacOS</span></code>,
  3005. <code class="xref py py-mod docutils literal notranslate"><span class="pre">macfs</span></code>,
  3006. <code class="xref py py-mod docutils literal notranslate"><span class="pre">macostools</span></code>,
  3007. <code class="xref py py-mod docutils literal notranslate"><span class="pre">macresource</span></code>,
  3008. <code class="xref py py-mod docutils literal notranslate"><span class="pre">MiniAEFrame</span></code>,
  3009. <code class="xref py py-mod docutils literal notranslate"><span class="pre">Nav</span></code>,
  3010. <code class="xref py py-mod docutils literal notranslate"><span class="pre">Netscape</span></code>,
  3011. <code class="xref py py-mod docutils literal notranslate"><span class="pre">OSATerminology</span></code>,
  3012. <code class="xref py py-mod docutils literal notranslate"><span class="pre">pimp</span></code>,
  3013. <code class="xref py py-mod docutils literal notranslate"><span class="pre">PixMapWrapper</span></code>,
  3014. <code class="xref py py-mod docutils literal notranslate"><span class="pre">StdSuites</span></code>,
  3015. <code class="xref py py-mod docutils literal notranslate"><span class="pre">SystemEvents</span></code>,
  3016. <code class="xref py py-mod docutils literal notranslate"><span class="pre">Terminal</span></code>, and
  3017. <code class="xref py py-mod docutils literal notranslate"><span class="pre">terminalcommand</span></code>.</p></li>
  3018. </ul>
  3019. </section>
  3020. <section id="port-specific-changes-irix">
  3021. <h3>Port-Specific Changes: IRIX<a class="headerlink" href="#port-specific-changes-irix" title="Link to this heading">¶</a></h3>
  3022. <p>A number of old IRIX-specific modules were deprecated and will
  3023. be removed in Python 3.0:
  3024. <code class="xref py py-mod docutils literal notranslate"><span class="pre">al</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">AL</span></code>,
  3025. <code class="xref py py-mod docutils literal notranslate"><span class="pre">cd</span></code>,
  3026. <code class="xref py py-mod docutils literal notranslate"><span class="pre">cddb</span></code>,
  3027. <code class="xref py py-mod docutils literal notranslate"><span class="pre">cdplayer</span></code>,
  3028. <code class="xref py py-mod docutils literal notranslate"><span class="pre">CL</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">cl</span></code>,
  3029. <code class="xref py py-mod docutils literal notranslate"><span class="pre">DEVICE</span></code>,
  3030. <code class="xref py py-mod docutils literal notranslate"><span class="pre">ERRNO</span></code>,
  3031. <code class="xref py py-mod docutils literal notranslate"><span class="pre">FILE</span></code>,
  3032. <code class="xref py py-mod docutils literal notranslate"><span class="pre">FL</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">fl</span></code>,
  3033. <code class="xref py py-mod docutils literal notranslate"><span class="pre">flp</span></code>,
  3034. <code class="xref py py-mod docutils literal notranslate"><span class="pre">fm</span></code>,
  3035. <code class="xref py py-mod docutils literal notranslate"><span class="pre">GET</span></code>,
  3036. <code class="xref py py-mod docutils literal notranslate"><span class="pre">GLWS</span></code>,
  3037. <code class="xref py py-mod docutils literal notranslate"><span class="pre">GL</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">gl</span></code>,
  3038. <code class="xref py py-mod docutils literal notranslate"><span class="pre">IN</span></code>,
  3039. <code class="xref py py-mod docutils literal notranslate"><span class="pre">IOCTL</span></code>,
  3040. <code class="xref py py-mod docutils literal notranslate"><span class="pre">jpeg</span></code>,
  3041. <code class="xref py py-mod docutils literal notranslate"><span class="pre">panelparser</span></code>,
  3042. <code class="xref py py-mod docutils literal notranslate"><span class="pre">readcd</span></code>,
  3043. <code class="xref py py-mod docutils literal notranslate"><span class="pre">SV</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">sv</span></code>,
  3044. <code class="xref py py-mod docutils literal notranslate"><span class="pre">torgb</span></code>,
  3045. <code class="xref py py-mod docutils literal notranslate"><span class="pre">videoreader</span></code>, and
  3046. <code class="xref py py-mod docutils literal notranslate"><span class="pre">WAIT</span></code>.</p>
  3047. </section>
  3048. </section>
  3049. <section id="porting-to-python-2-6">
  3050. <h2>Porting to Python 2.6<a class="headerlink" href="#porting-to-python-2-6" title="Link to this heading">¶</a></h2>
  3051. <p>This section lists previously described changes and other bugfixes
  3052. that may require changes to your code:</p>
  3053. <ul>
  3054. <li><p>Classes that aren’t supposed to be hashable should
  3055. set <code class="docutils literal notranslate"><span class="pre">__hash__</span> <span class="pre">=</span> <span class="pre">None</span></code> in their definitions to indicate
  3056. the fact.</p></li>
  3057. <li><p>String exceptions have been removed. Attempting to use them raises a
  3058. <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.</p></li>
  3059. <li><p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code> method of <a class="reference internal" href="../library/collections.html#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.deque</span></code></a>
  3060. now clears any existing contents of the deque
  3061. before adding elements from the iterable. This change makes the
  3062. behavior match <code class="docutils literal notranslate"><span class="pre">list.__init__()</span></code>.</p></li>
  3063. <li><p><a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__init__()</span></code></a> previously accepted arbitrary arguments and
  3064. keyword arguments, ignoring them. In Python 2.6, this is no longer
  3065. allowed and will result in 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>. This will affect
  3066. <code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code> methods that end up calling the corresponding
  3067. method on <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> (perhaps through using <a class="reference internal" href="../library/functions.html#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a>).
  3068. See <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1683368">bpo-1683368</a> for discussion.</p></li>
  3069. <li><p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code> constructor now accepts leading and trailing
  3070. whitespace when passed a string. Previously it would raise an
  3071. <code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidOperation</span></code> exception. On the other hand, the
  3072. <code class="xref py py-meth docutils literal notranslate"><span class="pre">create_decimal()</span></code> method of <code class="xref py py-class docutils literal notranslate"><span class="pre">Context</span></code> objects now
  3073. explicitly disallows extra whitespace, raising a
  3074. <code class="xref py py-exc docutils literal notranslate"><span class="pre">ConversionSyntax</span></code> exception.</p></li>
  3075. <li><p>Due to an implementation accident, if you passed a file path to
  3076. the built-in <a class="reference internal" href="../library/functions.html#import__" title="__import__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__import__()</span></code></a> function, it would actually import
  3077. the specified file. This was never intended to work, however, and
  3078. the implementation now explicitly checks for this case and raises
  3079. an <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>.</p></li>
  3080. <li><p>C API: the <a class="reference internal" href="../c-api/import.html#c.PyImport_Import" title="PyImport_Import"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_Import()</span></code></a> and <a class="reference internal" href="../c-api/import.html#c.PyImport_ImportModule" title="PyImport_ImportModule"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_ImportModule()</span></code></a>
  3081. functions now default to absolute imports, not relative imports.
  3082. This will affect C extensions that import other modules.</p></li>
  3083. <li><p>C API: extension data types that shouldn’t be hashable
  3084. should define their <code class="docutils literal notranslate"><span class="pre">tp_hash</span></code> slot to
  3085. <a class="reference internal" href="../c-api/object.html#c.PyObject_HashNotImplemented" title="PyObject_HashNotImplemented"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_HashNotImplemented()</span></code></a>.</p></li>
  3086. <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 exception <a class="reference internal" href="../library/socket.html#socket.error" title="socket.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">socket.error</span></code></a> now inherits
  3087. from <a class="reference internal" href="../library/exceptions.html#IOError" title="IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>. Previously it wasn’t a subclass of
  3088. <code class="xref py py-exc docutils literal notranslate"><span class="pre">StandardError</span></code> but now it is, through <a class="reference internal" href="../library/exceptions.html#IOError" title="IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>.
  3089. (Implemented by Gregory P. Smith; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1706815">bpo-1706815</a>.)</p></li>
  3090. <li><p>The <a class="reference internal" href="../library/xmlrpc.client.html#module-xmlrpc.client" title="xmlrpc.client: XML-RPC client access."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code></a> module no longer automatically converts
  3091. <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">datetime.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">datetime.time</span></code></a> to the
  3092. <a class="reference internal" href="../library/xmlrpc.client.html#xmlrpc.client.DateTime" title="xmlrpc.client.DateTime"><code class="xref py py-class docutils literal notranslate"><span class="pre">xmlrpclib.DateTime</span></code></a> type; the conversion semantics were
  3093. not necessarily correct for all applications. Code using
  3094. <code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code> should convert <code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code> 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>
  3095. instances. (<a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=1330538">bpo-1330538</a>)</p></li>
  3096. <li><p>(3.0-warning mode) The <a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><code class="xref py py-class docutils literal notranslate"><span class="pre">Exception</span></code></a> class now warns
  3097. when accessed using slicing or index access; having
  3098. <a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><code class="xref py py-class docutils literal notranslate"><span class="pre">Exception</span></code></a> behave like a tuple is being phased out.</p></li>
  3099. <li><p>(3.0-warning mode) inequality comparisons between two dictionaries
  3100. or two objects that don’t implement comparison methods are reported
  3101. as warnings. <code class="docutils literal notranslate"><span class="pre">dict1</span> <span class="pre">==</span> <span class="pre">dict2</span></code> still works, but <code class="docutils literal notranslate"><span class="pre">dict1</span> <span class="pre">&lt;</span> <span class="pre">dict2</span></code>
  3102. is being phased out.</p>
  3103. <p>Comparisons between cells, which are an implementation detail of Python’s
  3104. scoping rules, also cause warnings because such comparisons are forbidden
  3105. entirely in 3.0.</p>
  3106. </li>
  3107. </ul>
  3108. <p>For applications that embed Python:</p>
  3109. <ul class="simple">
  3110. <li><p>The <code class="xref c c-func docutils literal notranslate"><span class="pre">PySys_SetArgvEx()</span></code> function was added in Python 2.6.6,
  3111. letting applications close a security hole when the existing
  3112. <code class="xref c c-func docutils literal notranslate"><span class="pre">PySys_SetArgv()</span></code> function was used. Check whether you’re
  3113. calling <code class="xref c c-func docutils literal notranslate"><span class="pre">PySys_SetArgv()</span></code> and carefully consider whether the
  3114. application should be using <code class="xref c c-func docutils literal notranslate"><span class="pre">PySys_SetArgvEx()</span></code> with
  3115. <em>updatepath</em> set to false.</p></li>
  3116. </ul>
  3117. </section>
  3118. <section id="acknowledgements">
  3119. <span id="acks"></span><h2>Acknowledgements<a class="headerlink" href="#acknowledgements" title="Link to this heading">¶</a></h2>
  3120. <p>The author would like to thank the following people for offering
  3121. suggestions, corrections and assistance with various drafts of this
  3122. article: Georg Brandl, Steve Brown, Nick Coghlan, Ralph Corderoy,
  3123. Jim Jewett, Kent Johnson, Chris Lambacher, Martin Michlmayr,
  3124. Antoine Pitrou, Brian Warner.</p>
  3125. </section>
  3126. </section>
  3127. <div class="clearer"></div>
  3128. </div>
  3129. </div>
  3130. </div>
  3131. <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
  3132. <div class="sphinxsidebarwrapper">
  3133. <div>
  3134. <h3><a href="../contents.html">Table of Contents</a></h3>
  3135. <ul>
  3136. <li><a class="reference internal" href="#">What’s New in Python 2.6</a><ul>
  3137. <li><a class="reference internal" href="#python-3-0">Python 3.0</a></li>
  3138. <li><a class="reference internal" href="#changes-to-the-development-process">Changes to the Development Process</a><ul>
  3139. <li><a class="reference internal" href="#new-issue-tracker-roundup">New Issue Tracker: Roundup</a></li>
  3140. <li><a class="reference internal" href="#new-documentation-format-restructuredtext-using-sphinx">New Documentation Format: reStructuredText Using Sphinx</a></li>
  3141. </ul>
  3142. </li>
  3143. <li><a class="reference internal" href="#pep-343-the-with-statement">PEP 343: The ‘with’ statement</a><ul>
  3144. <li><a class="reference internal" href="#writing-context-managers">Writing Context Managers</a></li>
  3145. <li><a class="reference internal" href="#the-contextlib-module">The contextlib module</a></li>
  3146. </ul>
  3147. </li>
  3148. <li><a class="reference internal" href="#pep-366-explicit-relative-imports-from-a-main-module">PEP 366: Explicit Relative Imports From a Main Module</a></li>
  3149. <li><a class="reference internal" href="#pep-370-per-user-site-packages-directory">PEP 370: Per-user <code class="docutils literal notranslate"><span class="pre">site-packages</span></code> Directory</a></li>
  3150. <li><a class="reference internal" href="#pep-371-the-multiprocessing-package">PEP 371: The <code class="docutils literal notranslate"><span class="pre">multiprocessing</span></code> Package</a></li>
  3151. <li><a class="reference internal" href="#pep-3101-advanced-string-formatting">PEP 3101: Advanced String Formatting</a></li>
  3152. <li><a class="reference internal" href="#pep-3105-print-as-a-function">PEP 3105: <code class="docutils literal notranslate"><span class="pre">print</span></code> As a Function</a></li>
  3153. <li><a class="reference internal" href="#pep-3110-exception-handling-changes">PEP 3110: Exception-Handling Changes</a></li>
  3154. <li><a class="reference internal" href="#pep-3112-byte-literals">PEP 3112: Byte Literals</a></li>
  3155. <li><a class="reference internal" href="#pep-3116-new-i-o-library">PEP 3116: New I/O Library</a></li>
  3156. <li><a class="reference internal" href="#pep-3118-revised-buffer-protocol">PEP 3118: Revised Buffer Protocol</a></li>
  3157. <li><a class="reference internal" href="#pep-3119-abstract-base-classes">PEP 3119: Abstract Base Classes</a></li>
  3158. <li><a class="reference internal" href="#pep-3127-integer-literal-support-and-syntax">PEP 3127: Integer Literal Support and Syntax</a></li>
  3159. <li><a class="reference internal" href="#pep-3129-class-decorators">PEP 3129: Class Decorators</a></li>
  3160. <li><a class="reference internal" href="#pep-3141-a-type-hierarchy-for-numbers">PEP 3141: A Type Hierarchy for Numbers</a><ul>
  3161. <li><a class="reference internal" href="#the-fractions-module">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">fractions</span></code> Module</a></li>
  3162. </ul>
  3163. </li>
  3164. <li><a class="reference internal" href="#other-language-changes">Other Language Changes</a><ul>
  3165. <li><a class="reference internal" href="#optimizations">Optimizations</a></li>
  3166. <li><a class="reference internal" href="#interpreter-changes">Interpreter Changes</a></li>
  3167. </ul>
  3168. </li>
  3169. <li><a class="reference internal" href="#new-and-improved-modules">New and Improved Modules</a><ul>
  3170. <li><a class="reference internal" href="#the-ast-module">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">ast</span></code> module</a></li>
  3171. <li><a class="reference internal" href="#the-future-builtins-module">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">future_builtins</span></code> module</a></li>
  3172. <li><a class="reference internal" href="#the-json-module-javascript-object-notation">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code> module: JavaScript Object Notation</a></li>
  3173. <li><a class="reference internal" href="#the-plistlib-module-a-property-list-parser">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">plistlib</span></code> module: A Property-List Parser</a></li>
  3174. <li><a class="reference internal" href="#ctypes-enhancements">ctypes Enhancements</a></li>
  3175. <li><a class="reference internal" href="#improved-ssl-support">Improved SSL Support</a></li>
  3176. </ul>
  3177. </li>
  3178. <li><a class="reference internal" href="#deprecations-and-removals">Deprecations and Removals</a></li>
  3179. <li><a class="reference internal" href="#build-and-c-api-changes">Build and C API Changes</a><ul>
  3180. <li><a class="reference internal" href="#port-specific-changes-windows">Port-Specific Changes: Windows</a></li>
  3181. <li><a class="reference internal" href="#port-specific-changes-mac-os-x">Port-Specific Changes: Mac OS X</a></li>
  3182. <li><a class="reference internal" href="#port-specific-changes-irix">Port-Specific Changes: IRIX</a></li>
  3183. </ul>
  3184. </li>
  3185. <li><a class="reference internal" href="#porting-to-python-2-6">Porting to Python 2.6</a></li>
  3186. <li><a class="reference internal" href="#acknowledgements">Acknowledgements</a></li>
  3187. </ul>
  3188. </li>
  3189. </ul>
  3190. </div>
  3191. <div>
  3192. <h4>Previous topic</h4>
  3193. <p class="topless"><a href="2.7.html"
  3194. title="previous chapter">What’s New in Python 2.7</a></p>
  3195. </div>
  3196. <div>
  3197. <h4>Next topic</h4>
  3198. <p class="topless"><a href="2.5.html"
  3199. title="next chapter">What’s New in Python 2.5</a></p>
  3200. </div>
  3201. <div role="note" aria-label="source link">
  3202. <h3>This Page</h3>
  3203. <ul class="this-page-menu">
  3204. <li><a href="../bugs.html">Report a Bug</a></li>
  3205. <li>
  3206. <a href="https://github.com/python/cpython/blob/main/Doc/whatsnew/2.6.rst"
  3207. rel="nofollow">Show Source
  3208. </a>
  3209. </li>
  3210. </ul>
  3211. </div>
  3212. </div>
  3213. <div id="sidebarbutton" title="Collapse sidebar">
  3214. <span>«</span>
  3215. </div>
  3216. </div>
  3217. <div class="clearer"></div>
  3218. </div>
  3219. <div class="related" role="navigation" aria-label="related navigation">
  3220. <h3>Navigation</h3>
  3221. <ul>
  3222. <li class="right" style="margin-right: 10px">
  3223. <a href="../genindex.html" title="General Index"
  3224. >index</a></li>
  3225. <li class="right" >
  3226. <a href="../py-modindex.html" title="Python Module Index"
  3227. >modules</a> |</li>
  3228. <li class="right" >
  3229. <a href="2.5.html" title="What’s New in Python 2.5"
  3230. >next</a> |</li>
  3231. <li class="right" >
  3232. <a href="2.7.html" title="What’s New in Python 2.7"
  3233. >previous</a> |</li>
  3234. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  3235. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  3236. <li class="switchers">
  3237. <div class="language_switcher_placeholder"></div>
  3238. <div class="version_switcher_placeholder"></div>
  3239. </li>
  3240. <li>
  3241. </li>
  3242. <li id="cpython-language-and-version">
  3243. <a href="../index.html">3.12.3 Documentation</a> &#187;
  3244. </li>
  3245. <li class="nav-item nav-item-1"><a href="index.html" >What’s New in Python</a> &#187;</li>
  3246. <li class="nav-item nav-item-this"><a href="">What’s New in Python 2.6</a></li>
  3247. <li class="right">
  3248. <div class="inline-search" role="search">
  3249. <form class="inline-search" action="../search.html" method="get">
  3250. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  3251. <input type="submit" value="Go" />
  3252. </form>
  3253. </div>
  3254. |
  3255. </li>
  3256. <li class="right">
  3257. <label class="theme-selector-label">
  3258. Theme
  3259. <select class="theme-selector" oninput="activateTheme(this.value)">
  3260. <option value="auto" selected>Auto</option>
  3261. <option value="light">Light</option>
  3262. <option value="dark">Dark</option>
  3263. </select>
  3264. </label> |</li>
  3265. </ul>
  3266. </div>
  3267. <div class="footer">
  3268. &copy;
  3269. <a href="../copyright.html">
  3270. Copyright
  3271. </a>
  3272. 2001-2024, Python Software Foundation.
  3273. <br />
  3274. This page is licensed under the Python Software Foundation License Version 2.
  3275. <br />
  3276. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  3277. <br />
  3278. See <a href="/license.html">History and License</a> for more information.<br />
  3279. <br />
  3280. The Python Software Foundation is a non-profit corporation.
  3281. <a href="https://www.python.org/psf/donations/">Please donate.</a>
  3282. <br />
  3283. <br />
  3284. Last updated on Apr 09, 2024 (13:47 UTC).
  3285. <a href="/bugs.html">Found a bug</a>?
  3286. <br />
  3287. Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 7.2.6.
  3288. </div>
  3289. </body>
  3290. </html>
上海开阖软件有限公司 沪ICP备12045867号-1