2.5.html 254 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />
  6. <meta property="og:title" content="What’s New in Python 2.5" />
  7. <meta property="og:type" content="website" />
  8. <meta property="og:url" content="https://docs.python.org/3/whatsnew/2.5.html" />
  9. <meta property="og:site_name" content="Python documentation" />
  10. <meta property="og:description" content="Author, A.M. Kuchling,. This article explains the new features in Python 2.5. The final release of Python 2.5 is scheduled for August 2006; PEP 356 describes the planned release schedule. 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,. This article explains the new features in Python 2.5. The final release of Python 2.5 is scheduled for August 2006; PEP 356 describes the planned release schedule. 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.5 &#8212; Python 3.12.0 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
  18. <link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
  19. <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?digest=b37c26da2f7529d09fe70b41c4b2133fe4931a90" />
  20. <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css" />
  21. <script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script>
  22. <script src="../_static/jquery.js"></script>
  23. <script src="../_static/underscore.js"></script>
  24. <script src="../_static/doctools.js"></script>
  25. <script src="../_static/sidebar.js"></script>
  26. <link rel="search" type="application/opensearchdescription+xml"
  27. title="Search within Python 3.12.0 documentation"
  28. href="../_static/opensearch.xml"/>
  29. <link rel="author" title="About these documents" href="../about.html" />
  30. <link rel="index" title="Index" href="../genindex.html" />
  31. <link rel="search" title="Search" href="../search.html" />
  32. <link rel="copyright" title="Copyright" href="../copyright.html" />
  33. <link rel="next" title="What’s New in Python 2.4" href="2.4.html" />
  34. <link rel="prev" title="What’s New in Python 2.6" href="2.6.html" />
  35. <link rel="canonical" href="https://docs.python.org/3/whatsnew/2.5.html" />
  36. <style>
  37. @media only screen {
  38. table.full-width-table {
  39. width: 100%;
  40. }
  41. }
  42. </style>
  43. <link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
  44. <link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
  45. <script type="text/javascript" src="../_static/copybutton.js"></script>
  46. <script type="text/javascript" src="../_static/menu.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="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.5</a><ul>
  86. <li><a class="reference internal" href="#pep-308-conditional-expressions">PEP 308: Conditional Expressions</a></li>
  87. <li><a class="reference internal" href="#pep-309-partial-function-application">PEP 309: Partial Function Application</a></li>
  88. <li><a class="reference internal" href="#pep-314-metadata-for-python-software-packages-v1-1">PEP 314: Metadata for Python Software Packages v1.1</a></li>
  89. <li><a class="reference internal" href="#pep-328-absolute-and-relative-imports">PEP 328: Absolute and Relative Imports</a></li>
  90. <li><a class="reference internal" href="#pep-338-executing-modules-as-scripts">PEP 338: Executing Modules as Scripts</a></li>
  91. <li><a class="reference internal" href="#pep-341-unified-try-except-finally">PEP 341: Unified try/except/finally</a></li>
  92. <li><a class="reference internal" href="#pep-342-new-generator-features">PEP 342: New Generator Features</a></li>
  93. <li><a class="reference internal" href="#pep-343-the-with-statement">PEP 343: The ‘with’ statement</a><ul>
  94. <li><a class="reference internal" href="#writing-context-managers">Writing Context Managers</a></li>
  95. <li><a class="reference internal" href="#the-contextlib-module">The contextlib module</a></li>
  96. </ul>
  97. </li>
  98. <li><a class="reference internal" href="#pep-352-exceptions-as-new-style-classes">PEP 352: Exceptions as New-Style Classes</a></li>
  99. <li><a class="reference internal" href="#pep-353-using-ssize-t-as-the-index-type">PEP 353: Using ssize_t as the index type</a></li>
  100. <li><a class="reference internal" href="#pep-357-the-index-method">PEP 357: The ‘__index__’ method</a></li>
  101. <li><a class="reference internal" href="#other-language-changes">Other Language Changes</a><ul>
  102. <li><a class="reference internal" href="#interactive-interpreter-changes">Interactive Interpreter Changes</a></li>
  103. <li><a class="reference internal" href="#optimizations">Optimizations</a></li>
  104. </ul>
  105. </li>
  106. <li><a class="reference internal" href="#new-improved-and-removed-modules">New, Improved, and Removed Modules</a><ul>
  107. <li><a class="reference internal" href="#the-ctypes-package">The ctypes package</a></li>
  108. <li><a class="reference internal" href="#the-elementtree-package">The ElementTree package</a></li>
  109. <li><a class="reference internal" href="#the-hashlib-package">The hashlib package</a></li>
  110. <li><a class="reference internal" href="#the-sqlite3-package">The sqlite3 package</a></li>
  111. <li><a class="reference internal" href="#the-wsgiref-package">The wsgiref package</a></li>
  112. </ul>
  113. </li>
  114. <li><a class="reference internal" href="#build-and-c-api-changes">Build and C API Changes</a><ul>
  115. <li><a class="reference internal" href="#port-specific-changes">Port-Specific Changes</a></li>
  116. </ul>
  117. </li>
  118. <li><a class="reference internal" href="#porting-to-python-2-5">Porting to Python 2.5</a></li>
  119. <li><a class="reference internal" href="#acknowledgements">Acknowledgements</a></li>
  120. </ul>
  121. </li>
  122. </ul>
  123. </div>
  124. <div>
  125. <h4>Previous topic</h4>
  126. <p class="topless"><a href="2.6.html"
  127. title="previous chapter">What’s New in Python 2.6</a></p>
  128. </div>
  129. <div>
  130. <h4>Next topic</h4>
  131. <p class="topless"><a href="2.4.html"
  132. title="next chapter">What’s New in Python 2.4</a></p>
  133. </div>
  134. <div role="note" aria-label="source link">
  135. <h3>This Page</h3>
  136. <ul class="this-page-menu">
  137. <li><a href="../bugs.html">Report a Bug</a></li>
  138. <li>
  139. <a href="https://github.com/python/cpython/blob/main/Doc/whatsnew/2.5.rst"
  140. rel="nofollow">Show Source
  141. </a>
  142. </li>
  143. </ul>
  144. </div>
  145. </nav>
  146. </div>
  147. </div>
  148. <div class="related" role="navigation" aria-label="related navigation">
  149. <h3>Navigation</h3>
  150. <ul>
  151. <li class="right" style="margin-right: 10px">
  152. <a href="../genindex.html" title="General Index"
  153. accesskey="I">index</a></li>
  154. <li class="right" >
  155. <a href="../py-modindex.html" title="Python Module Index"
  156. >modules</a> |</li>
  157. <li class="right" >
  158. <a href="2.4.html" title="What’s New in Python 2.4"
  159. accesskey="N">next</a> |</li>
  160. <li class="right" >
  161. <a href="2.6.html" title="What’s New in Python 2.6"
  162. accesskey="P">previous</a> |</li>
  163. <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  164. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  165. <li class="switchers">
  166. <div class="language_switcher_placeholder"></div>
  167. <div class="version_switcher_placeholder"></div>
  168. </li>
  169. <li>
  170. </li>
  171. <li id="cpython-language-and-version">
  172. <a href="../index.html">3.12.0 Documentation</a> &#187;
  173. </li>
  174. <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">What’s New in Python</a> &#187;</li>
  175. <li class="nav-item nav-item-this"><a href="">What’s New in Python 2.5</a></li>
  176. <li class="right">
  177. <div class="inline-search" role="search">
  178. <form class="inline-search" action="../search.html" method="get">
  179. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  180. <input type="submit" value="Go" />
  181. </form>
  182. </div>
  183. |
  184. </li>
  185. <li class="right">
  186. <label class="theme-selector-label">
  187. Theme
  188. <select class="theme-selector" oninput="activateTheme(this.value)">
  189. <option value="auto" selected>Auto</option>
  190. <option value="light">Light</option>
  191. <option value="dark">Dark</option>
  192. </select>
  193. </label> |</li>
  194. </ul>
  195. </div>
  196. <div class="document">
  197. <div class="documentwrapper">
  198. <div class="bodywrapper">
  199. <div class="body" role="main">
  200. <section id="what-s-new-in-python-2-5">
  201. <h1>What’s New in Python 2.5<a class="headerlink" href="#what-s-new-in-python-2-5" title="Permalink to this headline">¶</a></h1>
  202. <dl class="field-list simple">
  203. <dt class="field-odd">Author</dt>
  204. <dd class="field-odd"><p>A.M. Kuchling</p>
  205. </dd>
  206. </dl>
  207. <p>This article explains the new features in Python 2.5. The final release of
  208. Python 2.5 is scheduled for August 2006; <span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0356/"><strong>PEP 356</strong></a> describes the planned
  209. release schedule. Python 2.5 was released on September 19, 2006.</p>
  210. <p>The changes in Python 2.5 are an interesting mix of language and library
  211. improvements. The library enhancements will be more important to Python’s user
  212. community, I think, because several widely useful packages were added. New
  213. modules include ElementTree for XML processing (<code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.etree</span></code>),
  214. the SQLite database module (<code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite</span></code>), and 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>
  215. module for calling C functions.</p>
  216. <p>The language changes are of middling significance. Some pleasant new features
  217. were added, but most of them aren’t features that you’ll use every day.
  218. Conditional expressions were finally added to the language using a novel syntax;
  219. see section <a class="reference internal" href="#pep-308"><span class="std std-ref">PEP 308: Conditional Expressions</span></a>. The new ‘<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 make
  220. writing cleanup code easier (section <a class="reference internal" href="#pep-343"><span class="std std-ref">PEP 343: The ‘with’ statement</span></a>). Values can now be passed
  221. into generators (section <a class="reference internal" href="#pep-342"><span class="std std-ref">PEP 342: New Generator Features</span></a>). Imports are now visible as either
  222. absolute or relative (section <a class="reference internal" href="#pep-328"><span class="std std-ref">PEP 328: Absolute and Relative Imports</span></a>). Some corner cases of exception
  223. handling are handled better (section <a class="reference internal" href="#pep-341"><span class="std std-ref">PEP 341: Unified try/except/finally</span></a>). All these improvements
  224. are worthwhile, but they’re improvements to one specific language feature or
  225. another; none of them are broad modifications to Python’s semantics.</p>
  226. <p>As well as the language and library additions, other improvements and bugfixes
  227. were made throughout the source tree. A search through the SVN change logs
  228. finds there were 353 patches applied and 458 bugs fixed between Python 2.4 and
  229. 2.5. (Both figures are likely to be underestimates.)</p>
  230. <p>This article doesn’t try to be a complete specification of the new features;
  231. instead changes are briefly introduced using helpful examples. For full
  232. details, you should always refer to the documentation for Python 2.5 at
  233. <a class="reference external" href="https://docs.python.org">https://docs.python.org</a>. If you want to understand the complete implementation
  234. and design rationale, refer to the PEP for a particular new feature.</p>
  235. <p>Comments, suggestions, and error reports for this document are welcome; please
  236. e-mail them to the author or open a bug in the Python bug tracker.</p>
  237. <section id="pep-308-conditional-expressions">
  238. <span id="pep-308"></span><h2>PEP 308: Conditional Expressions<a class="headerlink" href="#pep-308-conditional-expressions" title="Permalink to this headline">¶</a></h2>
  239. <p>For a long time, people have been requesting a way to write conditional
  240. expressions, which are expressions that return value A or value B depending on
  241. whether a Boolean value is true or false. A conditional expression lets you
  242. write a single assignment statement that has the same effect as the following:</p>
  243. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">condition</span><span class="p">:</span>
  244. <span class="n">x</span> <span class="o">=</span> <span class="n">true_value</span>
  245. <span class="k">else</span><span class="p">:</span>
  246. <span class="n">x</span> <span class="o">=</span> <span class="n">false_value</span>
  247. </pre></div>
  248. </div>
  249. <p>There have been endless tedious discussions of syntax on both python-dev and
  250. comp.lang.python. A vote was even held that found the majority of voters wanted
  251. conditional expressions in some form, but there was no syntax that was preferred
  252. by a clear majority. Candidates included C’s <code class="docutils literal notranslate"><span class="pre">cond</span> <span class="pre">?</span> <span class="pre">true_v</span> <span class="pre">:</span> <span class="pre">false_v</span></code>, <code class="docutils literal notranslate"><span class="pre">if</span>
  253. <span class="pre">cond</span> <span class="pre">then</span> <span class="pre">true_v</span> <span class="pre">else</span> <span class="pre">false_v</span></code>, and 16 other variations.</p>
  254. <p>Guido van Rossum eventually chose a surprising syntax:</p>
  255. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="n">true_value</span> <span class="k">if</span> <span class="n">condition</span> <span class="k">else</span> <span class="n">false_value</span>
  256. </pre></div>
  257. </div>
  258. <p>Evaluation is still lazy as in existing Boolean expressions, so the order of
  259. evaluation jumps around a bit. The <em>condition</em> expression in the middle is
  260. evaluated first, and the <em>true_value</em> expression is evaluated only if the
  261. condition was true. Similarly, the <em>false_value</em> expression is only evaluated
  262. when the condition is false.</p>
  263. <p>This syntax may seem strange and backwards; why does the condition go in the
  264. <em>middle</em> of the expression, and not in the front as in C’s <code class="docutils literal notranslate"><span class="pre">c</span> <span class="pre">?</span> <span class="pre">x</span> <span class="pre">:</span> <span class="pre">y</span></code>? The
  265. decision was checked by applying the new syntax to the modules in the standard
  266. library and seeing how the resulting code read. In many cases where a
  267. conditional expression is used, one value seems to be the ‘common case’ and one
  268. value is an ‘exceptional case’, used only on rarer occasions when the condition
  269. isn’t met. The conditional syntax makes this pattern a bit more obvious:</p>
  270. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">contents</span> <span class="o">=</span> <span class="p">((</span><span class="n">doc</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="k">if</span> <span class="n">doc</span> <span class="k">else</span> <span class="s1">&#39;&#39;</span><span class="p">)</span>
  271. </pre></div>
  272. </div>
  273. <p>I read the above statement as meaning “here <em>contents</em> is usually assigned a
  274. value of <code class="docutils literal notranslate"><span class="pre">doc+'\n'</span></code>; sometimes <em>doc</em> is empty, in which special case an empty
  275. string is returned.” I doubt I will use conditional expressions very often
  276. where there isn’t a clear common and uncommon case.</p>
  277. <p>There was some discussion of whether the language should require surrounding
  278. conditional expressions with parentheses. The decision was made to <em>not</em>
  279. require parentheses in the Python language’s grammar, but as a matter of style I
  280. think you should always use them. Consider these two statements:</p>
  281. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># First version -- no parens</span>
  282. <span class="n">level</span> <span class="o">=</span> <span class="mi">1</span> <span class="k">if</span> <span class="n">logging</span> <span class="k">else</span> <span class="mi">0</span>
  283. <span class="c1"># Second version -- with parens</span>
  284. <span class="n">level</span> <span class="o">=</span> <span class="p">(</span><span class="mi">1</span> <span class="k">if</span> <span class="n">logging</span> <span class="k">else</span> <span class="mi">0</span><span class="p">)</span>
  285. </pre></div>
  286. </div>
  287. <p>In the first version, I think a reader’s eye might group the statement into
  288. ‘level = 1’, ‘if logging’, ‘else 0’, and think that the condition decides
  289. whether the assignment to <em>level</em> is performed. The second version reads
  290. better, in my opinion, because it makes it clear that the assignment is always
  291. performed and the choice is being made between two values.</p>
  292. <p>Another reason for including the brackets: a few odd combinations of list
  293. comprehensions and lambdas could look like incorrect conditional expressions.
  294. See <span class="target" id="index-1"></span><a class="pep reference external" href="https://peps.python.org/pep-0308/"><strong>PEP 308</strong></a> for some examples. If you put parentheses around your
  295. conditional expressions, you won’t run into this case.</p>
  296. <div class="admonition seealso">
  297. <p class="admonition-title">See also</p>
  298. <dl class="simple">
  299. <dt><span class="target" id="index-2"></span><a class="pep reference external" href="https://peps.python.org/pep-0308/"><strong>PEP 308</strong></a> - Conditional Expressions</dt><dd><p>PEP written by Guido van Rossum and Raymond D. Hettinger; implemented by Thomas
  300. Wouters.</p>
  301. </dd>
  302. </dl>
  303. </div>
  304. </section>
  305. <section id="pep-309-partial-function-application">
  306. <span id="pep-309"></span><h2>PEP 309: Partial Function Application<a class="headerlink" href="#pep-309-partial-function-application" title="Permalink to this headline">¶</a></h2>
  307. <p>The <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 is intended to contain tools for functional-style
  308. programming.</p>
  309. <p>One useful tool in this module is the <code class="xref py py-func docutils literal notranslate"><span class="pre">partial()</span></code> function. For programs
  310. written in a functional style, you’ll sometimes want to construct variants of
  311. existing functions that have some of the parameters filled in. Consider a
  312. Python function <code class="docutils literal notranslate"><span class="pre">f(a,</span> <span class="pre">b,</span> <span class="pre">c)</span></code>; you could create a new function <code class="docutils literal notranslate"><span class="pre">g(b,</span> <span class="pre">c)</span></code> that
  313. was equivalent to <code class="docutils literal notranslate"><span class="pre">f(1,</span> <span class="pre">b,</span> <span class="pre">c)</span></code>. This is called “partial function
  314. application”.</p>
  315. <p><code class="xref py py-func docutils literal notranslate"><span class="pre">partial()</span></code> takes the arguments <code class="docutils literal notranslate"><span class="pre">(function,</span> <span class="pre">arg1,</span> <span class="pre">arg2,</span> <span class="pre">...</span> <span class="pre">kwarg1=value1,</span>
  316. <span class="pre">kwarg2=value2)</span></code>. The resulting object is callable, so you can just call it to
  317. invoke <em>function</em> with the filled-in arguments.</p>
  318. <p>Here’s a small but realistic example:</p>
  319. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">functools</span>
  320. <span class="k">def</span> <span class="nf">log</span> <span class="p">(</span><span class="n">message</span><span class="p">,</span> <span class="n">subsystem</span><span class="p">):</span>
  321. <span class="s2">&quot;Write the contents of &#39;message&#39; to the specified subsystem.&quot;</span>
  322. <span class="nb">print</span> <span class="s1">&#39;</span><span class="si">%s</span><span class="s1">: </span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">subsystem</span><span class="p">,</span> <span class="n">message</span><span class="p">)</span>
  323. <span class="o">...</span>
  324. <span class="n">server_log</span> <span class="o">=</span> <span class="n">functools</span><span class="o">.</span><span class="n">partial</span><span class="p">(</span><span class="n">log</span><span class="p">,</span> <span class="n">subsystem</span><span class="o">=</span><span class="s1">&#39;server&#39;</span><span class="p">)</span>
  325. <span class="n">server_log</span><span class="p">(</span><span class="s1">&#39;Unable to open socket&#39;</span><span class="p">)</span>
  326. </pre></div>
  327. </div>
  328. <p>Here’s another example, from a program that uses PyGTK. Here a context-sensitive
  329. pop-up menu is being constructed dynamically. The callback provided
  330. for the menu option is a partially applied version of the <code class="xref py py-meth docutils literal notranslate"><span class="pre">open_item()</span></code>
  331. method, where the first argument has been provided.</p>
  332. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="o">...</span>
  333. <span class="k">class</span> <span class="nc">Application</span><span class="p">:</span>
  334. <span class="k">def</span> <span class="nf">open_item</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">path</span><span class="p">):</span>
  335. <span class="o">...</span>
  336. <span class="k">def</span> <span class="nf">init</span> <span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  337. <span class="n">open_func</span> <span class="o">=</span> <span class="n">functools</span><span class="o">.</span><span class="n">partial</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">open_item</span><span class="p">,</span> <span class="n">item_path</span><span class="p">)</span>
  338. <span class="n">popup_menu</span><span class="o">.</span><span class="n">append</span><span class="p">(</span> <span class="p">(</span><span class="s2">&quot;Open&quot;</span><span class="p">,</span> <span class="n">open_func</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span> <span class="p">)</span>
  339. </pre></div>
  340. </div>
  341. <p>Another function in the <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 is the
  342. <code class="docutils literal notranslate"><span class="pre">update_wrapper(wrapper,</span> <span class="pre">wrapped)</span></code> function that helps you write
  343. well-behaved decorators. <code class="xref py py-func docutils literal notranslate"><span class="pre">update_wrapper()</span></code> copies the name, module, and
  344. docstring attribute to a wrapper function so that tracebacks inside the wrapped
  345. function are easier to understand. For example, you might write:</p>
  346. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">my_decorator</span><span class="p">(</span><span class="n">f</span><span class="p">):</span>
  347. <span class="k">def</span> <span class="nf">wrapper</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">kwds</span><span class="p">):</span>
  348. <span class="nb">print</span> <span class="s1">&#39;Calling decorated function&#39;</span>
  349. <span class="k">return</span> <span class="n">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">kwds</span><span class="p">)</span>
  350. <span class="n">functools</span><span class="o">.</span><span class="n">update_wrapper</span><span class="p">(</span><span class="n">wrapper</span><span class="p">,</span> <span class="n">f</span><span class="p">)</span>
  351. <span class="k">return</span> <span class="n">wrapper</span>
  352. </pre></div>
  353. </div>
  354. <p><code class="xref py py-func docutils literal notranslate"><span class="pre">wraps()</span></code> is a decorator that can be used inside your own decorators to copy
  355. the wrapped function’s information. An alternate version of the previous
  356. example would be:</p>
  357. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">my_decorator</span><span class="p">(</span><span class="n">f</span><span class="p">):</span>
  358. <span class="nd">@functools</span><span class="o">.</span><span class="n">wraps</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
  359. <span class="k">def</span> <span class="nf">wrapper</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">kwds</span><span class="p">):</span>
  360. <span class="nb">print</span> <span class="s1">&#39;Calling decorated function&#39;</span>
  361. <span class="k">return</span> <span class="n">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">kwds</span><span class="p">)</span>
  362. <span class="k">return</span> <span class="n">wrapper</span>
  363. </pre></div>
  364. </div>
  365. <div class="admonition seealso">
  366. <p class="admonition-title">See also</p>
  367. <dl class="simple">
  368. <dt><span class="target" id="index-3"></span><a class="pep reference external" href="https://peps.python.org/pep-0309/"><strong>PEP 309</strong></a> - Partial Function Application</dt><dd><p>PEP proposed and written by Peter Harris; implemented by Hye-Shik Chang and Nick
  369. Coghlan, with adaptations by Raymond Hettinger.</p>
  370. </dd>
  371. </dl>
  372. </div>
  373. </section>
  374. <section id="pep-314-metadata-for-python-software-packages-v1-1">
  375. <span id="pep-314"></span><h2>PEP 314: Metadata for Python Software Packages v1.1<a class="headerlink" href="#pep-314-metadata-for-python-software-packages-v1-1" title="Permalink to this headline">¶</a></h2>
  376. <p>Some simple dependency support was added to Distutils. The <code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code>
  377. function now has <code class="docutils literal notranslate"><span class="pre">requires</span></code>, <code class="docutils literal notranslate"><span class="pre">provides</span></code>, and <code class="docutils literal notranslate"><span class="pre">obsoletes</span></code> keyword
  378. parameters. When you build a source distribution using the <code class="docutils literal notranslate"><span class="pre">sdist</span></code> command,
  379. the dependency information will be recorded in the <code class="file docutils literal notranslate"><span class="pre">PKG-INFO</span></code> file.</p>
  380. <p>Another new keyword parameter is <code class="docutils literal notranslate"><span class="pre">download_url</span></code>, which should be set to a URL
  381. for the package’s source code. This means it’s now possible to look up an entry
  382. in the package index, determine the dependencies for a package, and download the
  383. required packages.</p>
  384. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">VERSION</span> <span class="o">=</span> <span class="s1">&#39;1.0&#39;</span>
  385. <span class="n">setup</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;PyPackage&#39;</span><span class="p">,</span>
  386. <span class="n">version</span><span class="o">=</span><span class="n">VERSION</span><span class="p">,</span>
  387. <span class="n">requires</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;numarray&#39;</span><span class="p">,</span> <span class="s1">&#39;zlib (&gt;=1.1.4)&#39;</span><span class="p">],</span>
  388. <span class="n">obsoletes</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;OldPackage&#39;</span><span class="p">]</span>
  389. <span class="n">download_url</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;http://www.example.com/pypackage/dist/pkg-</span><span class="si">%s</span><span class="s1">.tar.gz&#39;</span>
  390. <span class="o">%</span> <span class="n">VERSION</span><span class="p">),</span>
  391. <span class="p">)</span>
  392. </pre></div>
  393. </div>
  394. <p>Another new enhancement to the Python package index at
  395. <a class="reference external" href="https://pypi.org">https://pypi.org</a> is storing source and binary archives for a
  396. package. The new <strong class="command">upload</strong> Distutils command will upload a package to
  397. the repository.</p>
  398. <p>Before a package can be uploaded, you must be able to build a distribution using
  399. the <strong class="command">sdist</strong> Distutils command. Once that works, you can run <code class="docutils literal notranslate"><span class="pre">python</span>
  400. <span class="pre">setup.py</span> <span class="pre">upload</span></code> to add your package to the PyPI archive. Optionally you can
  401. GPG-sign the package by supplying the <code class="xref std std-option docutils literal notranslate"><span class="pre">--sign</span></code> and <code class="xref std std-option docutils literal notranslate"><span class="pre">--identity</span></code>
  402. options.</p>
  403. <p>Package uploading was implemented by Martin von Löwis and Richard Jones.</p>
  404. <div class="admonition seealso">
  405. <p class="admonition-title">See also</p>
  406. <dl class="simple">
  407. <dt><span class="target" id="index-4"></span><a class="pep reference external" href="https://peps.python.org/pep-0314/"><strong>PEP 314</strong></a> - Metadata for Python Software Packages v1.1</dt><dd><p>PEP proposed and written by A.M. Kuchling, Richard Jones, and Fred Drake;
  408. implemented by Richard Jones and Fred Drake.</p>
  409. </dd>
  410. </dl>
  411. </div>
  412. </section>
  413. <section id="pep-328-absolute-and-relative-imports">
  414. <span id="pep-328"></span><h2>PEP 328: Absolute and Relative Imports<a class="headerlink" href="#pep-328-absolute-and-relative-imports" title="Permalink to this headline">¶</a></h2>
  415. <p>The simpler part of <span class="target" id="index-5"></span><a class="pep reference external" href="https://peps.python.org/pep-0328/"><strong>PEP 328</strong></a> was implemented in Python 2.4: parentheses could now
  416. be used to enclose the names imported from a module using the <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">...</span> <span class="pre">import</span>
  417. <span class="pre">...</span></code> statement, making it easier to import many different names.</p>
  418. <p>The more complicated part has been implemented in Python 2.5: importing a module
  419. can be specified to use absolute or package-relative imports. The plan is to
  420. move toward making absolute imports the default in future versions of Python.</p>
  421. <p>Let’s say you have a package directory like this:</p>
  422. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">pkg</span><span class="o">/</span>
  423. <span class="n">pkg</span><span class="o">/</span><span class="fm">__init__</span><span class="o">.</span><span class="n">py</span>
  424. <span class="n">pkg</span><span class="o">/</span><span class="n">main</span><span class="o">.</span><span class="n">py</span>
  425. <span class="n">pkg</span><span class="o">/</span><span class="n">string</span><span class="o">.</span><span class="n">py</span>
  426. </pre></div>
  427. </div>
  428. <p>This defines a package named <code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg</span></code> containing the <code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.main</span></code> and
  429. <code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.string</span></code> submodules.</p>
  430. <p>Consider the code in the <code class="file docutils literal notranslate"><span class="pre">main.py</span></code> module. What happens if it executes
  431. the statement <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">string</span></code>? In Python 2.4 and earlier, it will first look
  432. in the package’s directory to perform a relative import, finds
  433. <code class="file docutils literal notranslate"><span class="pre">pkg/string.py</span></code>, imports the contents of that file as the
  434. <code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.string</span></code> module, and that module is bound to the name <code class="docutils literal notranslate"><span class="pre">string</span></code> in the
  435. <code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.main</span></code> module’s namespace.</p>
  436. <p>That’s fine if <code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.string</span></code> was what you wanted. But what if you wanted
  437. Python’s standard <a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> module? There’s no clean way to ignore
  438. <code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.string</span></code> and look for the standard module; generally you had to look at
  439. the contents of <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code>, which is slightly unclean. Holger Krekel’s
  440. <code class="xref py py-mod docutils literal notranslate"><span class="pre">py.std</span></code> package provides a tidier way to perform imports from the standard
  441. library, <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">py;</span> <span class="pre">py.std.string.join()</span></code>, but that package isn’t available
  442. on all Python installations.</p>
  443. <p>Reading code which relies on relative imports is also less clear, because a
  444. reader may be confused about which module, <a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> or <code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.string</span></code>,
  445. is intended to be used. Python users soon learned not to duplicate the names of
  446. standard library modules in the names of their packages’ submodules, but you
  447. can’t protect against having your submodule’s name being used for a new module
  448. added in a future version of Python.</p>
  449. <p>In Python 2.5, you can switch <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a>’s behaviour to absolute imports
  450. using a <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">absolute_import</span></code> directive. This absolute-import
  451. behaviour will become the default in a future version (probably Python
  452. 2.7). Once absolute imports are the default, <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">string</span></code> will always
  453. find the standard library’s version. It’s suggested that users should begin
  454. using absolute imports as much as possible, so it’s preferable to begin writing
  455. <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">pkg</span> <span class="pre">import</span> <span class="pre">string</span></code> in your code.</p>
  456. <p>Relative imports are still possible by adding a leading period to the module
  457. name when using the <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">...</span> <span class="pre">import</span></code> form:</p>
  458. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Import names from pkg.string</span>
  459. <span class="kn">from</span> <span class="nn">.string</span> <span class="kn">import</span> <span class="n">name1</span><span class="p">,</span> <span class="n">name2</span>
  460. <span class="c1"># Import pkg.string</span>
  461. <span class="kn">from</span> <span class="nn">.</span> <span class="kn">import</span> <span class="n">string</span>
  462. </pre></div>
  463. </div>
  464. <p>This imports the <a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> module relative to the current package, so in
  465. <code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.main</span></code> this will import <em>name1</em> and <em>name2</em> from <code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.string</span></code>.
  466. Additional leading periods perform the relative import starting from the parent
  467. of the current package. For example, code in the <code class="xref py py-mod docutils literal notranslate"><span class="pre">A.B.C</span></code> module can do:</p>
  468. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">.</span> <span class="kn">import</span> <span class="n">D</span> <span class="c1"># Imports A.B.D</span>
  469. <span class="kn">from</span> <span class="nn">..</span> <span class="kn">import</span> <span class="n">E</span> <span class="c1"># Imports A.E</span>
  470. <span class="kn">from</span> <span class="nn">..F</span> <span class="kn">import</span> <span class="n">G</span> <span class="c1"># Imports A.F.G</span>
  471. </pre></div>
  472. </div>
  473. <p>Leading periods cannot be used with the <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">modname</span></code> form of the import
  474. statement, only the <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">...</span> <span class="pre">import</span></code> form.</p>
  475. <div class="admonition seealso">
  476. <p class="admonition-title">See also</p>
  477. <dl class="simple">
  478. <dt><span class="target" id="index-6"></span><a class="pep reference external" href="https://peps.python.org/pep-0328/"><strong>PEP 328</strong></a> - Imports: Multi-Line and Absolute/Relative</dt><dd><p>PEP written by Aahz; implemented by Thomas Wouters.</p>
  479. </dd>
  480. <dt><a class="reference external" href="https://pylib.readthedocs.io/">https://pylib.readthedocs.io/</a></dt><dd><p>The py library by Holger Krekel, which contains the <code class="xref py py-mod docutils literal notranslate"><span class="pre">py.std</span></code> package.</p>
  481. </dd>
  482. </dl>
  483. </div>
  484. </section>
  485. <section id="pep-338-executing-modules-as-scripts">
  486. <span id="pep-338"></span><h2>PEP 338: Executing Modules as Scripts<a class="headerlink" href="#pep-338-executing-modules-as-scripts" title="Permalink to this headline">¶</a></h2>
  487. <p>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 added in Python 2.4 to execute a module as a script
  488. gained a few more abilities. Instead of being implemented in C code inside the
  489. Python interpreter, the switch now uses an implementation in a new module,
  490. <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>.</p>
  491. <p>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 implements a more sophisticated import mechanism so that
  492. it’s now possible to run modules in a package such as <code class="xref py py-mod docutils literal notranslate"><span class="pre">pychecker.checker</span></code>.
  493. The module also supports alternative import mechanisms such as the
  494. <a class="reference internal" href="../library/zipimport.html#module-zipimport" title="zipimport: Support for importing Python modules from ZIP archives."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipimport</span></code></a> module. This means you can add a .zip archive’s path to
  495. <code class="docutils literal notranslate"><span class="pre">sys.path</span></code> and then use 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 to execute code from the
  496. archive.</p>
  497. <div class="admonition seealso">
  498. <p class="admonition-title">See also</p>
  499. <dl class="simple">
  500. <dt><span class="target" id="index-7"></span><a class="pep reference external" href="https://peps.python.org/pep-0338/"><strong>PEP 338</strong></a> - Executing modules as scripts</dt><dd><p>PEP written and implemented by Nick Coghlan.</p>
  501. </dd>
  502. </dl>
  503. </div>
  504. </section>
  505. <section id="pep-341-unified-try-except-finally">
  506. <span id="pep-341"></span><h2>PEP 341: Unified try/except/finally<a class="headerlink" href="#pep-341-unified-try-except-finally" title="Permalink to this headline">¶</a></h2>
  507. <p>Until Python 2.5, the <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement came in two flavours. You could
  508. use a <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> block to ensure that code is always executed, or one or
  509. more <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> blocks to catch specific exceptions. You couldn’t
  510. combine both <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> blocks and a <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> block, because
  511. generating the right bytecode for the combined version was complicated and it
  512. wasn’t clear what the semantics of the combined statement should be.</p>
  513. <p>Guido van Rossum spent some time working with Java, which does support the
  514. equivalent of combining <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> blocks and a <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> block,
  515. and this clarified what the statement should mean. In Python 2.5, you can now
  516. write:</p>
  517. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
  518. <span class="n">block</span><span class="o">-</span><span class="mi">1</span> <span class="o">...</span>
  519. <span class="k">except</span> <span class="n">Exception1</span><span class="p">:</span>
  520. <span class="n">handler</span><span class="o">-</span><span class="mi">1</span> <span class="o">...</span>
  521. <span class="k">except</span> <span class="n">Exception2</span><span class="p">:</span>
  522. <span class="n">handler</span><span class="o">-</span><span class="mi">2</span> <span class="o">...</span>
  523. <span class="k">else</span><span class="p">:</span>
  524. <span class="k">else</span><span class="o">-</span><span class="n">block</span>
  525. <span class="k">finally</span><span class="p">:</span>
  526. <span class="n">final</span><span class="o">-</span><span class="n">block</span>
  527. </pre></div>
  528. </div>
  529. <p>The code in <em>block-1</em> is executed. If the code raises an exception, the various
  530. <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> blocks are tested: if the exception is of class
  531. <code class="xref py py-class docutils literal notranslate"><span class="pre">Exception1</span></code>, <em>handler-1</em> is executed; otherwise if it’s of class
  532. <code class="xref py py-class docutils literal notranslate"><span class="pre">Exception2</span></code>, <em>handler-2</em> is executed, and so forth. If no exception is
  533. raised, the <em>else-block</em> is executed.</p>
  534. <p>No matter what happened previously, the <em>final-block</em> is executed once the code
  535. block is complete and any raised exceptions handled. Even if there’s an error in
  536. an exception handler or the <em>else-block</em> and a new exception is raised, the code
  537. in the <em>final-block</em> is still run.</p>
  538. <div class="admonition seealso">
  539. <p class="admonition-title">See also</p>
  540. <dl class="simple">
  541. <dt><span class="target" id="index-8"></span><a class="pep reference external" href="https://peps.python.org/pep-0341/"><strong>PEP 341</strong></a> - Unifying try-except and try-finally</dt><dd><p>PEP written by Georg Brandl; implementation by Thomas Lee.</p>
  542. </dd>
  543. </dl>
  544. </div>
  545. </section>
  546. <section id="pep-342-new-generator-features">
  547. <span id="pep-342"></span><h2>PEP 342: New Generator Features<a class="headerlink" href="#pep-342-new-generator-features" title="Permalink to this headline">¶</a></h2>
  548. <p>Python 2.5 adds a simple way to pass values <em>into</em> a generator. As introduced in
  549. Python 2.3, generators only produce output; once a generator’s code was invoked
  550. to create an iterator, there was no way to pass any new information into the
  551. function when its execution is resumed. Sometimes the ability to pass in some
  552. information would be useful. Hackish solutions to this include making the
  553. generator’s code look at a global variable and then changing the global
  554. variable’s value, or passing in some mutable object that callers then modify.</p>
  555. <p>To refresh your memory of basic generators, here’s a simple example:</p>
  556. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">counter</span> <span class="p">(</span><span class="n">maximum</span><span class="p">):</span>
  557. <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span>
  558. <span class="k">while</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">maximum</span><span class="p">:</span>
  559. <span class="k">yield</span> <span class="n">i</span>
  560. <span class="n">i</span> <span class="o">+=</span> <span class="mi">1</span>
  561. </pre></div>
  562. </div>
  563. <p>When you call <code class="docutils literal notranslate"><span class="pre">counter(10)</span></code>, the result is an iterator that returns the values
  564. from 0 up to 9. On encountering the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement, the iterator
  565. returns the provided value and suspends the function’s execution, preserving the
  566. local variables. Execution resumes on the following call to the iterator’s
  567. <a class="reference internal" href="../library/functions.html#next" title="next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> method, picking up after the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code> statement.</p>
  568. <p>In Python 2.3, <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> was a statement; it didn’t return any value. In
  569. 2.5, <code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code> is now an expression, returning a value that can be
  570. assigned to a variable or otherwise operated on:</p>
  571. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">val</span> <span class="o">=</span> <span class="p">(</span><span class="k">yield</span> <span class="n">i</span><span class="p">)</span>
  572. </pre></div>
  573. </div>
  574. <p>I recommend that you always put parentheses around a <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> expression
  575. when you’re doing something with the returned value, as in the above example.
  576. The parentheses aren’t always necessary, but it’s easier to always add them
  577. instead of having to remember when they’re needed.</p>
  578. <p>(<span class="target" id="index-9"></span><a class="pep reference external" href="https://peps.python.org/pep-0342/"><strong>PEP 342</strong></a> explains the exact rules, which are that a
  579. <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>-expression must always be parenthesized except when it
  580. occurs at the top-level
  581. expression on the right-hand side of an assignment. This means you can write
  582. <code class="docutils literal notranslate"><span class="pre">val</span> <span class="pre">=</span> <span class="pre">yield</span> <span class="pre">i</span></code> but have to use parentheses when there’s an operation, as in
  583. <code class="docutils literal notranslate"><span class="pre">val</span> <span class="pre">=</span> <span class="pre">(yield</span> <span class="pre">i)</span> <span class="pre">+</span> <span class="pre">12</span></code>.)</p>
  584. <p>Values are sent into a generator by calling its <code class="docutils literal notranslate"><span class="pre">send(value)</span></code> method. The
  585. generator’s code is then resumed and 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> expression returns the
  586. specified <em>value</em>. If the regular <a class="reference internal" href="../library/functions.html#next" title="next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> method is called, the
  587. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code> returns <a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.</p>
  588. <p>Here’s the previous example, modified to allow changing the value of the
  589. internal counter.</p>
  590. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">counter</span> <span class="p">(</span><span class="n">maximum</span><span class="p">):</span>
  591. <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span>
  592. <span class="k">while</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">maximum</span><span class="p">:</span>
  593. <span class="n">val</span> <span class="o">=</span> <span class="p">(</span><span class="k">yield</span> <span class="n">i</span><span class="p">)</span>
  594. <span class="c1"># If value provided, change counter</span>
  595. <span class="k">if</span> <span class="n">val</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
  596. <span class="n">i</span> <span class="o">=</span> <span class="n">val</span>
  597. <span class="k">else</span><span class="p">:</span>
  598. <span class="n">i</span> <span class="o">+=</span> <span class="mi">1</span>
  599. </pre></div>
  600. </div>
  601. <p>And here’s an example of changing the counter:</p>
  602. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">it</span> <span class="o">=</span> <span class="n">counter</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
  603. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
  604. <span class="go">0</span>
  605. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
  606. <span class="go">1</span>
  607. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">it</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="mi">8</span><span class="p">)</span>
  608. <span class="go">8</span>
  609. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
  610. <span class="go">9</span>
  611. <span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
  612. <span class="gt">Traceback (most recent call last):</span>
  613. File <span class="nb">&quot;t.py&quot;</span>, line <span class="m">15</span>, in <span class="n">?</span>
  614. <span class="w"> </span><span class="nb">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
  615. <span class="gr">StopIteration</span>
  616. </pre></div>
  617. </div>
  618. <p><a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> will usually return <a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>, so you should always check
  619. for this case. Don’t just use its value in expressions unless you’re sure that
  620. the <code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code> method will be the only method used to resume your generator
  621. function.</p>
  622. <p>In addition to <code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code>, there are two other new methods on generators:</p>
  623. <ul>
  624. <li><p><code class="docutils literal notranslate"><span class="pre">throw(type,</span> <span class="pre">value=None,</span> <span class="pre">traceback=None)</span></code> is used to raise an exception
  625. inside the generator; the exception is raised by 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> expression
  626. where the generator’s execution is paused.</p></li>
  627. <li><p><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> raises a new <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 inside the generator
  628. to terminate the iteration. On receiving this exception, the generator’s code
  629. must either raise <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> or <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>. Catching the
  630. <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 and returning a value is illegal and will trigger
  631. a <a class="reference internal" href="../library/exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>; if the function raises some other exception, that
  632. exception is propagated to the caller. <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> will also be called by
  633. Python’s garbage collector when the generator is garbage-collected.</p>
  634. <p>If you need to run cleanup code when a <a class="reference internal" href="../library/exceptions.html#GeneratorExit" title="GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> occurs, I suggest
  635. using a <code class="docutils literal notranslate"><span class="pre">try:</span> <span class="pre">...</span> <span class="pre">finally:</span></code> suite instead of catching <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>.</p>
  636. </li>
  637. </ul>
  638. <p>The cumulative effect of these changes is to turn generators from one-way
  639. producers of information into both producers and consumers.</p>
  640. <p>Generators also become <em>coroutines</em>, a more generalized form of subroutines.
  641. Subroutines are entered at one point and exited at another point (the top of the
  642. function, and 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), but coroutines can be entered,
  643. exited, and resumed at many different points (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> statements).
  644. We’ll have to figure out patterns for using coroutines effectively in Python.</p>
  645. <p>The addition of the <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> method has one side effect that isn’t obvious.
  646. <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> is called when a generator is garbage-collected, so this means the
  647. generator’s code gets one last chance to run before the generator is destroyed.
  648. This last chance means that <code class="docutils literal notranslate"><span class="pre">try...finally</span></code> statements in generators can now
  649. be guaranteed to work; the <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause will now always get a
  650. chance to run. The syntactic restriction that you couldn’t mix <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>
  651. statements with a <code class="docutils literal notranslate"><span class="pre">try...finally</span></code> suite has therefore been removed. This
  652. seems like a minor bit of language trivia, but using generators and
  653. <code class="docutils literal notranslate"><span class="pre">try...finally</span></code> is actually necessary in order to implement the
  654. <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 described by <span class="target" id="index-10"></span><a class="pep reference external" href="https://peps.python.org/pep-0343/"><strong>PEP 343</strong></a>. I’ll look at this new statement
  655. in the following section.</p>
  656. <p>Another even more esoteric effect of this change: previously, the
  657. <code class="xref py py-attr docutils literal notranslate"><span class="pre">gi_frame</span></code> attribute of a generator was always a frame object. It’s now
  658. possible for <code class="xref py py-attr docutils literal notranslate"><span class="pre">gi_frame</span></code> to be <code class="docutils literal notranslate"><span class="pre">None</span></code> once the generator has been
  659. exhausted.</p>
  660. <div class="admonition seealso">
  661. <p class="admonition-title">See also</p>
  662. <dl>
  663. <dt><span class="target" id="index-11"></span><a class="pep reference external" href="https://peps.python.org/pep-0342/"><strong>PEP 342</strong></a> - Coroutines via Enhanced Generators</dt><dd><p>PEP written by Guido van Rossum and Phillip J. Eby; implemented by Phillip J.
  664. Eby. Includes examples of some fancier uses of generators as coroutines.</p>
  665. <p>Earlier versions of these features were proposed in <span class="target" id="index-12"></span><a class="pep reference external" href="https://peps.python.org/pep-0288/"><strong>PEP 288</strong></a> by Raymond
  666. Hettinger and <span class="target" id="index-13"></span><a class="pep reference external" href="https://peps.python.org/pep-0325/"><strong>PEP 325</strong></a> by Samuele Pedroni.</p>
  667. </dd>
  668. <dt><a class="reference external" href="https://en.wikipedia.org/wiki/Coroutine">https://en.wikipedia.org/wiki/Coroutine</a></dt><dd><p>The Wikipedia entry for coroutines.</p>
  669. </dd>
  670. <dt><a class="reference external" href="https://web.archive.org/web/20160321211320/http://www.sidhe.org/~dan/blog/archives/000178.html">https://web.archive.org/web/20160321211320/http://www.sidhe.org/~dan/blog/archives/000178.html</a></dt><dd><p>An explanation of coroutines from a Perl point of view, written by Dan Sugalski.</p>
  671. </dd>
  672. </dl>
  673. </div>
  674. </section>
  675. <section id="pep-343-the-with-statement">
  676. <span id="pep-343"></span><h2>PEP 343: The ‘with’ statement<a class="headerlink" href="#pep-343-the-with-statement" title="Permalink to this headline">¶</a></h2>
  677. <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
  678. <code class="docutils literal notranslate"><span class="pre">try...finally</span></code> blocks to ensure that clean-up code is executed. In this
  679. section, I’ll discuss the statement as it will commonly be used. In the next
  680. section, I’ll examine the implementation details and show how to write objects
  681. for use with this statement.</p>
  682. <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 new control-flow structure whose basic
  683. structure is:</p>
  684. <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>
  685. <span class="k">with</span><span class="o">-</span><span class="n">block</span>
  686. </pre></div>
  687. </div>
  688. <p>The expression is evaluated, and it should result in an object that supports the
  689. context management protocol (that is, has <code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code>
  690. methods.</p>
  691. <p>The object’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code> is called before <em>with-block</em> is executed and
  692. therefore can run set-up code. It also may return a value that is bound to the
  693. name <em>variable</em>, if given. (Note carefully that <em>variable</em> is <em>not</em> assigned
  694. the result of <em>expression</em>.)</p>
  695. <p>After execution of the <em>with-block</em> is finished, the object’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code>
  696. method is called, even if the block raised an exception, and can therefore run
  697. clean-up code.</p>
  698. <p>To enable the statement in Python 2.5, you need to add the following directive
  699. to your module:</p>
  700. <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">with_statement</span>
  701. </pre></div>
  702. </div>
  703. <p>The statement will always be enabled in Python 2.6.</p>
  704. <p>Some standard Python objects now support the context management protocol and can
  705. 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>
  706. <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>
  707. <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
  708. <span class="nb">print</span> <span class="n">line</span>
  709. <span class="o">...</span> <span class="n">more</span> <span class="n">processing</span> <span class="n">code</span> <span class="o">...</span>
  710. </pre></div>
  711. </div>
  712. <p>After this statement has executed, the file object in <em>f</em> will have been
  713. 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
  714. part-way through the block.</p>
  715. <div class="admonition note">
  716. <p class="admonition-title">Note</p>
  717. <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
  718. <code class="xref py py-meth docutils literal notranslate"><span class="pre">file.__enter__()</span></code> returns <em>self</em>.</p>
  719. </div>
  720. <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
  721. ‘<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>
  722. <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>
  723. <span class="k">with</span> <span class="n">lock</span><span class="p">:</span>
  724. <span class="c1"># Critical section of code</span>
  725. <span class="o">...</span>
  726. </pre></div>
  727. </div>
  728. <p>The lock is acquired before the block is executed and always released once the
  729. block is complete.</p>
  730. <p>The new <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
  731. to save and restore the current decimal context, which encapsulates the desired
  732. precision and rounding characteristics for computations:</p>
  733. <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>
  734. <span class="c1"># Displays with default precision of 28 digits</span>
  735. <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>
  736. <span class="nb">print</span> <span class="n">v</span><span class="o">.</span><span class="n">sqrt</span><span class="p">()</span>
  737. <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>
  738. <span class="c1"># All code in this block uses a precision of 16 digits.</span>
  739. <span class="c1"># The original context is restored on exiting the block.</span>
  740. <span class="nb">print</span> <span class="n">v</span><span class="o">.</span><span class="n">sqrt</span><span class="p">()</span>
  741. </pre></div>
  742. </div>
  743. <section id="writing-context-managers">
  744. <span id="new-25-context-managers"></span><h3>Writing Context Managers<a class="headerlink" href="#writing-context-managers" title="Permalink to this headline">¶</a></h3>
  745. <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
  746. 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
  747. don’t need to know these details, so you can skip the rest of this section if
  748. you like. Authors of new objects will need to understand the details of the
  749. underlying implementation and should keep reading.</p>
  750. <p>A high-level explanation of the context management protocol is:</p>
  751. <ul class="simple">
  752. <li><p>The expression is evaluated and should result in an object called a “context
  753. manager”. The context manager must have <code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code>
  754. methods.</p></li>
  755. <li><p>The context manager’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code> method is called. The value returned
  756. 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
  757. discarded.</p></li>
  758. <li><p>The code in <em>BLOCK</em> is executed.</p></li>
  759. <li><p>If <em>BLOCK</em> raises an exception, the <code class="docutils literal notranslate"><span class="pre">__exit__(type,</span> <span class="pre">value,</span> <span class="pre">traceback)</span></code>
  760. is called with the exception details, the same values returned by
  761. <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>. The method’s return value controls whether the exception
  762. is re-raised: any false value re-raises the exception, and <code class="docutils literal notranslate"><span class="pre">True</span></code> will result
  763. in suppressing it. You’ll only rarely want to suppress the exception, because
  764. 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
  765. never realize anything went wrong.</p></li>
  766. <li><p>If <em>BLOCK</em> didn’t raise an exception, the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code> method is still
  767. 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>
  768. </ul>
  769. <p>Let’s think through an example. I won’t present detailed code but will only
  770. sketch the methods necessary for a database that supports transactions.</p>
  771. <p>(For people unfamiliar with database terminology: a set of changes to the
  772. database are grouped into a transaction. Transactions can be either committed,
  773. meaning that all the changes are written into the database, or rolled back,
  774. meaning that the changes are all discarded and the database is unchanged. See
  775. any database textbook for more information.)</p>
  776. <p>Let’s assume there’s an object representing a database connection. Our goal will
  777. be to let the user write code like this:</p>
  778. <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>
  779. <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>
  780. <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>
  781. <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>
  782. <span class="c1"># ... more operations ...</span>
  783. </pre></div>
  784. </div>
  785. <p>The transaction should be committed if the code in the block runs flawlessly or
  786. rolled back if there’s an exception. Here’s the basic interface for
  787. <code class="xref py py-class docutils literal notranslate"><span class="pre">DatabaseConnection</span></code> that I’ll assume:</p>
  788. <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>
  789. <span class="c1"># Database interface</span>
  790. <span class="k">def</span> <span class="nf">cursor</span> <span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  791. <span class="s2">&quot;Returns a cursor object and starts a new transaction&quot;</span>
  792. <span class="k">def</span> <span class="nf">commit</span> <span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  793. <span class="s2">&quot;Commits current transaction&quot;</span>
  794. <span class="k">def</span> <span class="nf">rollback</span> <span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  795. <span class="s2">&quot;Rolls back current transaction&quot;</span>
  796. </pre></div>
  797. </div>
  798. <p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code> method is pretty easy, having only to start a new
  799. transaction. For this application the resulting cursor object would be a useful
  800. 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
  801. 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>
  802. <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>
  803. <span class="o">...</span>
  804. <span class="k">def</span> <span class="fm">__enter__</span> <span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  805. <span class="c1"># Code to start a new transaction</span>
  806. <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>
  807. <span class="k">return</span> <span class="n">cursor</span>
  808. </pre></div>
  809. </div>
  810. <p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code> method is the most complicated because it’s where most of
  811. the work has to be done. The method has to check if an exception occurred. If
  812. there was no exception, the transaction is committed. The transaction is rolled
  813. back if there was an exception.</p>
  814. <p>In the code below, execution will just fall off the end of the function,
  815. 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
  816. will be re-raised automatically. If you wished, you could be more explicit and
  817. 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>
  818. <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>
  819. <span class="o">...</span>
  820. <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>
  821. <span class="k">if</span> <span class="n">tb</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
  822. <span class="c1"># No exception, so commit</span>
  823. <span class="bp">self</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
  824. <span class="k">else</span><span class="p">:</span>
  825. <span class="c1"># Exception occurred, so rollback.</span>
  826. <span class="bp">self</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
  827. <span class="c1"># return False</span>
  828. </pre></div>
  829. </div>
  830. </section>
  831. <section id="the-contextlib-module">
  832. <span id="contextlibmod"></span><h3>The contextlib module<a class="headerlink" href="#the-contextlib-module" title="Permalink to this headline">¶</a></h3>
  833. <p>The new <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
  834. are useful for 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>
  835. <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
  836. generator function instead of defining a new class. The generator should yield
  837. 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
  838. <code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code> method, and the value yielded will be the method’s return
  839. 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
  840. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code> clause, if any. The code after 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
  841. executed in the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code> method. Any exception raised in the block will
  842. be raised by the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code> statement.</p>
  843. <p>Our database example from the previous section could be written using this
  844. decorator as:</p>
  845. <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>
  846. <span class="nd">@contextmanager</span>
  847. <span class="k">def</span> <span class="nf">db_transaction</span> <span class="p">(</span><span class="n">connection</span><span class="p">):</span>
  848. <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>
  849. <span class="k">try</span><span class="p">:</span>
  850. <span class="k">yield</span> <span class="n">cursor</span>
  851. <span class="k">except</span><span class="p">:</span>
  852. <span class="n">connection</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
  853. <span class="k">raise</span>
  854. <span class="k">else</span><span class="p">:</span>
  855. <span class="n">connection</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
  856. <span class="n">db</span> <span class="o">=</span> <span class="n">DatabaseConnection</span><span class="p">()</span>
  857. <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>
  858. <span class="o">...</span>
  859. </pre></div>
  860. </div>
  861. <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
  862. that combines a number of context managers so you don’t need to write nested
  863. ‘<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>’
  864. statement both starts a database transaction and acquires a thread lock:</p>
  865. <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>
  866. <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>
  867. <span class="o">...</span>
  868. </pre></div>
  869. </div>
  870. <p>Finally, the <code class="docutils literal notranslate"><span class="pre">closing(object)</span></code> function returns <em>object</em> so that it can be
  871. bound to a variable, and calls <code class="docutils literal notranslate"><span class="pre">object.close</span></code> at the end of the block.</p>
  872. <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>
  873. <span class="kn">from</span> <span class="nn">contextlib</span> <span class="kn">import</span> <span class="n">closing</span>
  874. <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>
  875. <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
  876. <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>
  877. </pre></div>
  878. </div>
  879. <div class="admonition seealso">
  880. <p class="admonition-title">See also</p>
  881. <dl class="simple">
  882. <dt><span class="target" id="index-14"></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,
  883. Guido van Rossum, and Neal Norwitz. The PEP shows the code generated for a
  884. ‘<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
  885. works.</p>
  886. </dd>
  887. </dl>
  888. <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>
  889. </div>
  890. </section>
  891. </section>
  892. <section id="pep-352-exceptions-as-new-style-classes">
  893. <span id="pep-352"></span><h2>PEP 352: Exceptions as New-Style Classes<a class="headerlink" href="#pep-352-exceptions-as-new-style-classes" title="Permalink to this headline">¶</a></h2>
  894. <p>Exception classes can now be new-style classes, not just classic classes, and
  895. the built-in <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> class and all the standard built-in exceptions
  896. (<a class="reference internal" href="../library/exceptions.html#NameError" title="NameError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NameError</span></code></a>, <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>, etc.) are now new-style classes.</p>
  897. <p>The inheritance hierarchy for exceptions has been rearranged a bit. In 2.5, the
  898. inheritance relationships are:</p>
  899. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="ne">BaseException</span> <span class="c1"># New in Python 2.5</span>
  900. <span class="o">|-</span> <span class="ne">KeyboardInterrupt</span>
  901. <span class="o">|-</span> <span class="ne">SystemExit</span>
  902. <span class="o">|-</span> <span class="ne">Exception</span>
  903. <span class="o">|-</span> <span class="p">(</span><span class="nb">all</span> <span class="n">other</span> <span class="n">current</span> <span class="n">built</span><span class="o">-</span><span class="ow">in</span> <span class="n">exceptions</span><span class="p">)</span>
  904. </pre></div>
  905. </div>
  906. <p>This rearrangement was done because people often want to catch all exceptions
  907. that indicate program errors. <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>
  908. aren’t errors, though, and usually represent an explicit action such as the user
  909. hitting <kbd class="kbd compound docutils literal notranslate"><kbd class="kbd docutils literal notranslate">Control</kbd>-<kbd class="kbd docutils literal notranslate">C</kbd></kbd> or code calling <a class="reference internal" href="../library/sys.html#sys.exit" title="sys.exit"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exit()</span></code></a>. A bare <code class="docutils literal notranslate"><span class="pre">except:</span></code> will
  910. catch all exceptions, so you commonly need to list <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
  911. <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> in order to re-raise them. The usual pattern is:</p>
  912. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
  913. <span class="o">...</span>
  914. <span class="k">except</span> <span class="p">(</span><span class="ne">KeyboardInterrupt</span><span class="p">,</span> <span class="ne">SystemExit</span><span class="p">):</span>
  915. <span class="k">raise</span>
  916. <span class="k">except</span><span class="p">:</span>
  917. <span class="c1"># Log error...</span>
  918. <span class="c1"># Continue running program...</span>
  919. </pre></div>
  920. </div>
  921. <p>In Python 2.5, you can now write <code class="docutils literal notranslate"><span class="pre">except</span> <span class="pre">Exception</span></code> to achieve the same
  922. result, catching all the exceptions that usually indicate errors but leaving
  923. <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> alone. As in previous versions,
  924. a bare <code class="docutils literal notranslate"><span class="pre">except:</span></code> still catches all exceptions.</p>
  925. <p>The goal for Python 3.0 is to require any class raised as an exception to derive
  926. from <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> or some descendant of <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>, and future
  927. releases in the Python 2.x series may begin to enforce this constraint.
  928. Therefore, I suggest you begin making all your exception classes derive from
  929. <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> now. It’s been suggested that the bare <code class="docutils literal notranslate"><span class="pre">except:</span></code> form should
  930. be removed in Python 3.0, but Guido van Rossum hasn’t decided whether to do this
  931. or not.</p>
  932. <p>Raising of strings as exceptions, as in the statement <code class="docutils literal notranslate"><span class="pre">raise</span> <span class="pre">&quot;Error</span>
  933. <span class="pre">occurred&quot;</span></code>, is deprecated in Python 2.5 and will trigger a warning. The aim is
  934. to be able to remove the string-exception feature in a few releases.</p>
  935. <div class="admonition seealso">
  936. <p class="admonition-title">See also</p>
  937. <dl class="simple">
  938. <dt><span class="target" id="index-15"></span><a class="pep reference external" href="https://peps.python.org/pep-0352/"><strong>PEP 352</strong></a> - Required Superclass for Exceptions</dt><dd><p>PEP written by Brett Cannon and Guido van Rossum; implemented by Brett Cannon.</p>
  939. </dd>
  940. </dl>
  941. </div>
  942. </section>
  943. <section id="pep-353-using-ssize-t-as-the-index-type">
  944. <span id="pep-353"></span><h2>PEP 353: Using ssize_t as the index type<a class="headerlink" href="#pep-353-using-ssize-t-as-the-index-type" title="Permalink to this headline">¶</a></h2>
  945. <p>A wide-ranging change to Python’s C API, using a new <a class="reference internal" href="../c-api/intro.html#c.Py_ssize_t" title="Py_ssize_t"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code></a> type
  946. definition instead of <span class="c-expr sig sig-inline c"><span class="kt">int</span></span>, will permit the interpreter to handle more
  947. data on 64-bit platforms. This change doesn’t affect Python’s capacity on 32-bit
  948. platforms.</p>
  949. <p>Various pieces of the Python interpreter used C’s <span class="c-expr sig sig-inline c"><span class="kt">int</span></span> type to store
  950. sizes or counts; for example, the number of items in a list or tuple were stored
  951. in an <span class="c-expr sig sig-inline c"><span class="kt">int</span></span>. The C compilers for most 64-bit platforms still define
  952. <span class="c-expr sig sig-inline c"><span class="kt">int</span></span> as a 32-bit type, so that meant that lists could only hold up to
  953. <code class="docutils literal notranslate"><span class="pre">2**31</span> <span class="pre">-</span> <span class="pre">1</span></code> = 2147483647 items. (There are actually a few different
  954. programming models that 64-bit C compilers can use – see
  955. <a class="reference external" href="https://unix.org/version2/whatsnew/lp64_wp.html">https://unix.org/version2/whatsnew/lp64_wp.html</a> for a discussion – but the
  956. most commonly available model leaves <span class="c-expr sig sig-inline c"><span class="kt">int</span></span> as 32 bits.)</p>
  957. <p>A limit of 2147483647 items doesn’t really matter on a 32-bit platform because
  958. you’ll run out of memory before hitting the length limit. Each list item
  959. requires space for a pointer, which is 4 bytes, plus space for a
  960. <a class="reference internal" href="../c-api/structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a> representing the item. 2147483647*4 is already more bytes
  961. than a 32-bit address space can contain.</p>
  962. <p>It’s possible to address that much memory on a 64-bit platform, however. The
  963. pointers for a list that size would only require 16 GiB of space, so it’s not
  964. unreasonable that Python programmers might construct lists that large.
  965. Therefore, the Python interpreter had to be changed to use some type other than
  966. <span class="c-expr sig sig-inline c"><span class="kt">int</span></span>, and this will be a 64-bit type on 64-bit platforms. The change
  967. will cause incompatibilities on 64-bit machines, so it was deemed worth making
  968. the transition now, while the number of 64-bit users is still relatively small.
  969. (In 5 or 10 years, we may <em>all</em> be on 64-bit machines, and the transition would
  970. be more painful then.)</p>
  971. <p>This change most strongly affects authors of C extension modules. Python
  972. strings and container types such as lists and tuples now use
  973. <a class="reference internal" href="../c-api/intro.html#c.Py_ssize_t" title="Py_ssize_t"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code></a> to store their size. Functions such as
  974. <a class="reference internal" href="../c-api/list.html#c.PyList_Size" title="PyList_Size"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_Size()</span></code></a> now return <a class="reference internal" href="../c-api/intro.html#c.Py_ssize_t" title="Py_ssize_t"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code></a>. Code in extension modules
  975. may therefore need to have some variables changed to <a class="reference internal" href="../c-api/intro.html#c.Py_ssize_t" title="Py_ssize_t"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code></a>.</p>
  976. <p>The <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> and <a class="reference internal" href="../c-api/arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a> functions have a new
  977. conversion code, <code class="docutils literal notranslate"><span class="pre">n</span></code>, for <a class="reference internal" href="../c-api/intro.html#c.Py_ssize_t" title="Py_ssize_t"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code></a>. <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>’s
  978. <code class="docutils literal notranslate"><span class="pre">s#</span></code> and <code class="docutils literal notranslate"><span class="pre">t#</span></code> still output <span class="c-expr sig sig-inline c"><span class="kt">int</span></span> by default, but you can define the
  979. macro <code class="xref c c-macro docutils literal notranslate"><span class="pre">PY_SSIZE_T_CLEAN</span></code> before including <code class="file docutils literal notranslate"><span class="pre">Python.h</span></code> to make
  980. them return <a class="reference internal" href="../c-api/intro.html#c.Py_ssize_t" title="Py_ssize_t"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code></a>.</p>
  981. <p><span class="target" id="index-16"></span><a class="pep reference external" href="https://peps.python.org/pep-0353/"><strong>PEP 353</strong></a> has a section on conversion guidelines that extension authors should
  982. read to learn about supporting 64-bit platforms.</p>
  983. <div class="admonition seealso">
  984. <p class="admonition-title">See also</p>
  985. <dl class="simple">
  986. <dt><span class="target" id="index-17"></span><a class="pep reference external" href="https://peps.python.org/pep-0353/"><strong>PEP 353</strong></a> - Using ssize_t as the index type</dt><dd><p>PEP written and implemented by Martin von Löwis.</p>
  987. </dd>
  988. </dl>
  989. </div>
  990. </section>
  991. <section id="pep-357-the-index-method">
  992. <span id="pep-357"></span><h2>PEP 357: The ‘__index__’ method<a class="headerlink" href="#pep-357-the-index-method" title="Permalink to this headline">¶</a></h2>
  993. <p>The NumPy developers had a problem that could only be solved by adding a new
  994. special method, <code class="xref py py-meth docutils literal notranslate"><span class="pre">__index__()</span></code>. When using slice notation, as in
  995. <code class="docutils literal notranslate"><span class="pre">[start:stop:step]</span></code>, the values of the <em>start</em>, <em>stop</em>, and <em>step</em> indexes
  996. must all be either integers or long integers. NumPy defines a variety of
  997. specialized integer types corresponding to unsigned and signed integers of 8,
  998. 16, 32, and 64 bits, but there was no way to signal that these types could be
  999. used as slice indexes.</p>
  1000. <p>Slicing can’t just use the existing <code class="xref py py-meth docutils literal notranslate"><span class="pre">__int__()</span></code> method because that method
  1001. is also used to implement coercion to integers. If slicing used
  1002. <code class="xref py py-meth docutils literal notranslate"><span class="pre">__int__()</span></code>, floating-point numbers would also become legal slice indexes
  1003. and that’s clearly an undesirable behaviour.</p>
  1004. <p>Instead, a new special method called <code class="xref py py-meth docutils literal notranslate"><span class="pre">__index__()</span></code> was added. It takes no
  1005. arguments and returns an integer giving the slice index to use. For example:</p>
  1006. <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>
  1007. <span class="k">def</span> <span class="fm">__index__</span> <span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  1008. <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">value</span>
  1009. </pre></div>
  1010. </div>
  1011. <p>The return value must be either a Python integer or long integer. The
  1012. interpreter will check that the type returned is correct, and raises a
  1013. <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> if this requirement isn’t met.</p>
  1014. <p>A corresponding <a class="reference internal" href="../c-api/typeobj.html#c.PyNumberMethods.nb_index" title="PyNumberMethods.nb_index"><code class="xref c c-member docutils literal notranslate"><span class="pre">nb_index</span></code></a> slot was added to the C-level
  1015. <a class="reference internal" href="../c-api/typeobj.html#c.PyNumberMethods" title="PyNumberMethods"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyNumberMethods</span></code></a> structure to let C extensions implement this protocol.
  1016. <code class="docutils literal notranslate"><span class="pre">PyNumber_Index(obj)</span></code> can be used in extension code to call the
  1017. <code class="xref py py-meth docutils literal notranslate"><span class="pre">__index__()</span></code> function and retrieve its result.</p>
  1018. <div class="admonition seealso">
  1019. <p class="admonition-title">See also</p>
  1020. <dl class="simple">
  1021. <dt><span class="target" id="index-18"></span><a class="pep reference external" href="https://peps.python.org/pep-0357/"><strong>PEP 357</strong></a> - Allowing Any Object to be Used for Slicing</dt><dd><p>PEP written and implemented by Travis Oliphant.</p>
  1022. </dd>
  1023. </dl>
  1024. </div>
  1025. </section>
  1026. <section id="other-language-changes">
  1027. <span id="other-lang"></span><h2>Other Language Changes<a class="headerlink" href="#other-language-changes" title="Permalink to this headline">¶</a></h2>
  1028. <p>Here are all of the changes that Python 2.5 makes to the core Python language.</p>
  1029. <ul>
  1030. <li><p>The <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> type has a new hook for letting subclasses provide a default
  1031. value when a key isn’t contained in the dictionary. When a key isn’t found, the
  1032. dictionary’s <code class="docutils literal notranslate"><span class="pre">__missing__(key)</span></code> method will be called. This hook is used
  1033. to implement the new <code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code> class 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>
  1034. module. The following example defines a dictionary that returns zero for any
  1035. missing key:</p>
  1036. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">zerodict</span> <span class="p">(</span><span class="nb">dict</span><span class="p">):</span>
  1037. <span class="k">def</span> <span class="fm">__missing__</span> <span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">):</span>
  1038. <span class="k">return</span> <span class="mi">0</span>
  1039. <span class="n">d</span> <span class="o">=</span> <span class="n">zerodict</span><span class="p">({</span><span class="mi">1</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">2</span><span class="p">})</span>
  1040. <span class="nb">print</span> <span class="n">d</span><span class="p">[</span><span class="mi">1</span><span class="p">],</span> <span class="n">d</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span> <span class="c1"># Prints 1, 2</span>
  1041. <span class="nb">print</span> <span class="n">d</span><span class="p">[</span><span class="mi">3</span><span class="p">],</span> <span class="n">d</span><span class="p">[</span><span class="mi">4</span><span class="p">]</span> <span class="c1"># Prints 0, 0</span>
  1042. </pre></div>
  1043. </div>
  1044. </li>
  1045. <li><p>Both 8-bit and Unicode strings have new <code class="docutils literal notranslate"><span class="pre">partition(sep)</span></code> and
  1046. <code class="docutils literal notranslate"><span class="pre">rpartition(sep)</span></code> methods that simplify a common use case.</p>
  1047. <p>The <code class="docutils literal notranslate"><span class="pre">find(S)</span></code> method is often used to get an index which is then used to
  1048. slice the string and obtain the pieces that are before and after the separator.
  1049. <code class="docutils literal notranslate"><span class="pre">partition(sep)</span></code> condenses this pattern into a single method call that
  1050. returns a 3-tuple containing the substring before the separator, the separator
  1051. itself, and the substring after the separator. If the separator isn’t found,
  1052. the first element of the tuple is the entire string and the other two elements
  1053. are empty. <code class="docutils literal notranslate"><span class="pre">rpartition(sep)</span></code> also returns a 3-tuple but starts searching
  1054. from the end of the string; the <code class="docutils literal notranslate"><span class="pre">r</span></code> stands for ‘reverse’.</p>
  1055. <p>Some examples:</p>
  1056. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="s1">&#39;http://www.python.org&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">partition</span><span class="p">(</span><span class="s1">&#39;://&#39;</span><span class="p">)</span>
  1057. <span class="go">(&#39;http&#39;, &#39;://&#39;, &#39;www.python.org&#39;)</span>
  1058. <span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="s1">&#39;file:/usr/share/doc/index.html&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">partition</span><span class="p">(</span><span class="s1">&#39;://&#39;</span><span class="p">)</span>
  1059. <span class="go">(&#39;file:/usr/share/doc/index.html&#39;, &#39;&#39;, &#39;&#39;)</span>
  1060. <span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="sa">u</span><span class="s1">&#39;Subject: a quick question&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">partition</span><span class="p">(</span><span class="s1">&#39;:&#39;</span><span class="p">)</span>
  1061. <span class="go">(u&#39;Subject&#39;, u&#39;:&#39;, u&#39; a quick question&#39;)</span>
  1062. <span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;www.python.org&#39;</span><span class="o">.</span><span class="n">rpartition</span><span class="p">(</span><span class="s1">&#39;.&#39;</span><span class="p">)</span>
  1063. <span class="go">(&#39;www.python&#39;, &#39;.&#39;, &#39;org&#39;)</span>
  1064. <span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;www.python.org&#39;</span><span class="o">.</span><span class="n">rpartition</span><span class="p">(</span><span class="s1">&#39;:&#39;</span><span class="p">)</span>
  1065. <span class="go">(&#39;&#39;, &#39;&#39;, &#39;www.python.org&#39;)</span>
  1066. </pre></div>
  1067. </div>
  1068. <p>(Implemented by Fredrik Lundh following a suggestion by Raymond Hettinger.)</p>
  1069. </li>
  1070. <li><p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">startswith()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">endswith()</span></code> methods of string types now accept
  1071. tuples of strings to check for.</p>
  1072. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">is_image_file</span> <span class="p">(</span><span class="n">filename</span><span class="p">):</span>
  1073. <span class="k">return</span> <span class="n">filename</span><span class="o">.</span><span class="n">endswith</span><span class="p">((</span><span class="s1">&#39;.gif&#39;</span><span class="p">,</span> <span class="s1">&#39;.jpg&#39;</span><span class="p">,</span> <span class="s1">&#39;.tiff&#39;</span><span class="p">))</span>
  1074. </pre></div>
  1075. </div>
  1076. <p>(Implemented by Georg Brandl following a suggestion by Tom Lynn.)</p>
  1077. </li>
  1078. <li><p>The <a class="reference internal" href="../library/functions.html#min" title="min"><code class="xref py py-func docutils literal notranslate"><span class="pre">min()</span></code></a> and <a class="reference internal" href="../library/functions.html#max" title="max"><code class="xref py py-func docutils literal notranslate"><span class="pre">max()</span></code></a> built-in functions gained a <code class="docutils literal notranslate"><span class="pre">key</span></code> keyword
  1079. parameter analogous to the <code class="docutils literal notranslate"><span class="pre">key</span></code> argument for <code class="xref py py-meth docutils literal notranslate"><span class="pre">sort()</span></code>. This parameter
  1080. supplies a function that takes a single argument and is called for every value
  1081. in the list; <a class="reference internal" href="../library/functions.html#min" title="min"><code class="xref py py-func docutils literal notranslate"><span class="pre">min()</span></code></a>/<a class="reference internal" href="../library/functions.html#max" title="max"><code class="xref py py-func docutils literal notranslate"><span class="pre">max()</span></code></a> will return the element with the
  1082. smallest/largest return value from this function. For example, to find the
  1083. longest string in a list, you can do:</p>
  1084. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;medium&#39;</span><span class="p">,</span> <span class="s1">&#39;longest&#39;</span><span class="p">,</span> <span class="s1">&#39;short&#39;</span><span class="p">]</span>
  1085. <span class="c1"># Prints &#39;longest&#39;</span>
  1086. <span class="nb">print</span> <span class="nb">max</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="nb">len</span><span class="p">)</span>
  1087. <span class="c1"># Prints &#39;short&#39;, because lexicographically &#39;short&#39; has the largest value</span>
  1088. <span class="nb">print</span> <span class="nb">max</span><span class="p">(</span><span class="n">L</span><span class="p">)</span>
  1089. </pre></div>
  1090. </div>
  1091. <p>(Contributed by Steven Bethard and Raymond Hettinger.)</p>
  1092. </li>
  1093. <li><p>Two new built-in functions, <a class="reference internal" href="../library/functions.html#any" title="any"><code class="xref py py-func docutils literal notranslate"><span class="pre">any()</span></code></a> and <a class="reference internal" href="../library/functions.html#all" title="all"><code class="xref py py-func docutils literal notranslate"><span class="pre">all()</span></code></a>, evaluate whether an
  1094. iterator contains any true or false values. <a class="reference internal" href="../library/functions.html#any" title="any"><code class="xref py py-func docutils literal notranslate"><span class="pre">any()</span></code></a> returns <a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>
  1095. if any value returned by the iterator is true; otherwise it will return
  1096. <a class="reference internal" href="../library/constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>. <a class="reference internal" href="../library/functions.html#all" title="all"><code class="xref py py-func docutils literal notranslate"><span class="pre">all()</span></code></a> returns <a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> only if all of the values
  1097. returned by the iterator evaluate as true. (Suggested by Guido van Rossum, and
  1098. implemented by Raymond Hettinger.)</p></li>
  1099. <li><p>The result of a class’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code> method can now be either a long
  1100. integer or a regular integer. If a long integer is returned, the hash of that
  1101. value is taken. In earlier versions the hash value was required to be a
  1102. regular integer, but in 2.5 the <a class="reference internal" href="../library/functions.html#id" title="id"><code class="xref py py-func docutils literal notranslate"><span class="pre">id()</span></code></a> built-in was changed to always
  1103. return non-negative numbers, and users often seem to use <code class="docutils literal notranslate"><span class="pre">id(self)</span></code> in
  1104. <code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code> methods (though this is discouraged).</p>
  1105. </li>
  1106. <li><p>ASCII is now the default encoding for modules. It’s now a syntax error if a
  1107. module contains string literals with 8-bit characters but doesn’t have an
  1108. encoding declaration. In Python 2.4 this triggered a warning, not a syntax
  1109. error. See <span class="target" id="index-19"></span><a class="pep reference external" href="https://peps.python.org/pep-0263/"><strong>PEP 263</strong></a> for how to declare a module’s encoding; for example, you
  1110. might add a line like this near the top of the source file:</p>
  1111. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># -*- coding: latin1 -*-</span>
  1112. </pre></div>
  1113. </div>
  1114. </li>
  1115. <li><p>A new warning, <a class="reference internal" href="../library/exceptions.html#UnicodeWarning" title="UnicodeWarning"><code class="xref py py-class docutils literal notranslate"><span class="pre">UnicodeWarning</span></code></a>, is triggered when you attempt to
  1116. compare a Unicode string and an 8-bit string that can’t be converted to Unicode
  1117. using the default ASCII encoding. The result of the comparison is false:</p>
  1118. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">chr</span><span class="p">(</span><span class="mi">128</span><span class="p">)</span> <span class="o">==</span> <span class="n">unichr</span><span class="p">(</span><span class="mi">128</span><span class="p">)</span> <span class="c1"># Can&#39;t convert chr(128) to Unicode</span>
  1119. <span class="go">__main__:1: UnicodeWarning: Unicode equal comparison failed</span>
  1120. <span class="go"> to convert both arguments to Unicode - interpreting them</span>
  1121. <span class="go"> as being unequal</span>
  1122. <span class="go">False</span>
  1123. <span class="gp">&gt;&gt;&gt; </span><span class="nb">chr</span><span class="p">(</span><span class="mi">127</span><span class="p">)</span> <span class="o">==</span> <span class="n">unichr</span><span class="p">(</span><span class="mi">127</span><span class="p">)</span> <span class="c1"># chr(127) can be converted</span>
  1124. <span class="go">True</span>
  1125. </pre></div>
  1126. </div>
  1127. <p>Previously this would raise a <a class="reference internal" href="../library/exceptions.html#UnicodeDecodeError" title="UnicodeDecodeError"><code class="xref py py-class docutils literal notranslate"><span class="pre">UnicodeDecodeError</span></code></a> exception, but in 2.5
  1128. this could result in puzzling problems when accessing a dictionary. If you
  1129. looked up <code class="docutils literal notranslate"><span class="pre">unichr(128)</span></code> and <code class="docutils literal notranslate"><span class="pre">chr(128)</span></code> was being used as a key, you’d get a
  1130. <a class="reference internal" href="../library/exceptions.html#UnicodeDecodeError" title="UnicodeDecodeError"><code class="xref py py-class docutils literal notranslate"><span class="pre">UnicodeDecodeError</span></code></a> exception. Other changes in 2.5 resulted in this
  1131. exception being raised instead of suppressed by the code in <code class="file docutils literal notranslate"><span class="pre">dictobject.c</span></code>
  1132. that implements dictionaries.</p>
  1133. <p>Raising an exception for such a comparison is strictly correct, but the change
  1134. might have broken code, so instead <a class="reference internal" href="../library/exceptions.html#UnicodeWarning" title="UnicodeWarning"><code class="xref py py-class docutils literal notranslate"><span class="pre">UnicodeWarning</span></code></a> was introduced.</p>
  1135. <p>(Implemented by Marc-André Lemburg.)</p>
  1136. </li>
  1137. <li><p>One error that Python programmers sometimes make is forgetting to include an
  1138. <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code> module in a package directory. Debugging this mistake can be
  1139. confusing, and usually requires running Python with the <a class="reference internal" href="../using/cmdline.html#cmdoption-1"><code class="xref std std-option docutils literal notranslate"><span class="pre">-v</span></code></a> switch to
  1140. log all the paths searched. In Python 2.5, a new <a class="reference internal" href="../library/exceptions.html#ImportWarning" title="ImportWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportWarning</span></code></a> warning is
  1141. triggered when an import would have picked up a directory as a package but no
  1142. <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code> was found. This warning is silently ignored by default;
  1143. provide the <a class="reference internal" href="../using/cmdline.html#cmdoption-W"><code class="xref std std-option docutils literal notranslate"><span class="pre">-Wd</span></code></a> option when running the Python executable to display
  1144. the warning message. (Implemented by Thomas Wouters.)</p></li>
  1145. <li><p>The list of base classes in a class definition can now be empty. As an
  1146. example, this is now legal:</p>
  1147. <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>
  1148. <span class="k">pass</span>
  1149. </pre></div>
  1150. </div>
  1151. <p>(Implemented by Brett Cannon.)</p>
  1152. </li>
  1153. </ul>
  1154. <section id="interactive-interpreter-changes">
  1155. <span id="interactive"></span><h3>Interactive Interpreter Changes<a class="headerlink" href="#interactive-interpreter-changes" title="Permalink to this headline">¶</a></h3>
  1156. <p>In the interactive interpreter, <code class="docutils literal notranslate"><span class="pre">quit</span></code> and <code class="docutils literal notranslate"><span class="pre">exit</span></code> have long been strings so
  1157. that new users get a somewhat helpful message when they try to quit:</p>
  1158. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">quit</span>
  1159. <span class="go">&#39;Use Ctrl-D (i.e. EOF) to exit.&#39;</span>
  1160. </pre></div>
  1161. </div>
  1162. <p>In Python 2.5, <code class="docutils literal notranslate"><span class="pre">quit</span></code> and <code class="docutils literal notranslate"><span class="pre">exit</span></code> are now objects that still produce string
  1163. representations of themselves, but are also callable. Newbies who try <code class="docutils literal notranslate"><span class="pre">quit()</span></code>
  1164. or <code class="docutils literal notranslate"><span class="pre">exit()</span></code> will now exit the interpreter as they expect. (Implemented by
  1165. Georg Brandl.)</p>
  1166. <p>The Python executable now accepts the standard long options <a class="reference internal" href="../using/cmdline.html#cmdoption-help"><code class="xref std std-option docutils literal notranslate"><span class="pre">--help</span></code></a>
  1167. and <a class="reference internal" href="../using/cmdline.html#cmdoption-version"><code class="xref std std-option docutils literal notranslate"><span class="pre">--version</span></code></a>; on Windows, it also accepts the <a class="reference internal" href="../using/cmdline.html#cmdoption-0"><code class="xref std std-option docutils literal notranslate"><span class="pre">/?</span></code></a> option
  1168. for displaying a help message. (Implemented by Georg Brandl.)</p>
  1169. </section>
  1170. <section id="optimizations">
  1171. <span id="opts"></span><h3>Optimizations<a class="headerlink" href="#optimizations" title="Permalink to this headline">¶</a></h3>
  1172. <p>Several of the optimizations were developed at the NeedForSpeed sprint, an event
  1173. held in Reykjavik, Iceland, from May 21–28 2006. The sprint focused on speed
  1174. enhancements to the CPython implementation and was funded by EWT LLC with local
  1175. support from CCP Games. Those optimizations added at this sprint are specially
  1176. marked in the following list.</p>
  1177. <ul class="simple">
  1178. <li><p>When they were introduced in Python 2.4, 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
  1179. <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 were built on top of Python’s dictionary type. In 2.5
  1180. the internal data structure has been customized for implementing sets, and as a
  1181. result sets will use a third less memory and are somewhat faster. (Implemented
  1182. by Raymond Hettinger.)</p></li>
  1183. <li><p>The speed of some Unicode operations, such as finding substrings, string
  1184. splitting, and character map encoding and decoding, has been improved.
  1185. (Substring search and splitting improvements were added by Fredrik Lundh and
  1186. Andrew Dalke at the NeedForSpeed sprint. Character maps were improved by Walter
  1187. Dörwald and Martin von Löwis.)</p>
  1188. </li>
  1189. <li><p>The <code class="docutils literal notranslate"><span class="pre">long(str,</span> <span class="pre">base)</span></code> function is now faster on long digit strings
  1190. because fewer intermediate results are calculated. The peak is for strings of
  1191. around 800–1000 digits where the function is 6 times faster. (Contributed by
  1192. Alan McIntyre and committed at the NeedForSpeed sprint.)</p>
  1193. </li>
  1194. <li><p>It’s now illegal to mix iterating over a file with <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">line</span> <span class="pre">in</span> <span class="pre">file</span></code> and
  1195. calling the file object’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code>/<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>/<code class="xref py py-meth docutils literal notranslate"><span class="pre">readlines()</span></code>
  1196. methods. Iteration uses an internal buffer and the <code class="xref py py-meth docutils literal notranslate"><span class="pre">read*()</span></code> methods
  1197. don’t use that buffer. Instead they would return the data following the
  1198. buffer, causing the data to appear out of order. Mixing iteration and these
  1199. methods will now trigger 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> from the <code class="xref py py-meth docutils literal notranslate"><span class="pre">read*()</span></code> method.
  1200. (Implemented by Thomas Wouters.)</p>
  1201. </li>
  1202. <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 compiles structure format strings into an
  1203. internal representation and caches this representation, yielding a 20% speedup.
  1204. (Contributed by Bob Ippolito at the NeedForSpeed sprint.)</p></li>
  1205. <li><p>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> module got a 1 or 2% speedup by switching to Python’s allocator
  1206. functions instead of the system’s <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code>.
  1207. (Contributed by Jack Diederich at the NeedForSpeed sprint.)</p></li>
  1208. <li><p>The code generator’s peephole optimizer now performs simple constant folding
  1209. in expressions. If you write something like <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">2+3</span></code>, the code generator
  1210. will do the arithmetic and produce code corresponding to <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">5</span></code>. (Proposed
  1211. and implemented by Raymond Hettinger.)</p></li>
  1212. <li><p>Function calls are now faster because code objects now keep the most recently
  1213. finished frame (a “zombie frame”) in an internal field of the code object,
  1214. reusing it the next time the code object is invoked. (Original patch by Michael
  1215. Hudson, modified by Armin Rigo and Richard Jones; committed at the NeedForSpeed
  1216. sprint.) Frame objects are also slightly smaller, which may improve cache
  1217. locality and reduce memory usage a bit. (Contributed by Neal Norwitz.)</p>
  1218. </li>
  1219. <li><p>Python’s built-in exceptions are now new-style classes, a change that speeds
  1220. up instantiation considerably. Exception handling in Python 2.5 is therefore
  1221. about 30% faster than in 2.4. (Contributed by Richard Jones, Georg Brandl and
  1222. Sean Reifschneider at the NeedForSpeed sprint.)</p></li>
  1223. <li><p>Importing now caches the paths tried, recording whether they exist or not so
  1224. that the interpreter makes fewer <code class="xref c c-func docutils literal notranslate"><span class="pre">open()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">stat()</span></code> calls on
  1225. startup. (Contributed by Martin von Löwis and Georg Brandl.)</p>
  1226. </li>
  1227. </ul>
  1228. </section>
  1229. </section>
  1230. <section id="new-improved-and-removed-modules">
  1231. <span id="modules"></span><h2>New, Improved, and Removed Modules<a class="headerlink" href="#new-improved-and-removed-modules" title="Permalink to this headline">¶</a></h2>
  1232. <p>The standard library received many enhancements and bug fixes in Python 2.5.
  1233. Here’s a partial list of the most notable changes, sorted alphabetically by
  1234. module name. Consult the <code class="file docutils literal notranslate"><span class="pre">Misc/NEWS</span></code> file in the source tree for a more
  1235. complete list of changes, or look through the SVN logs for all the details.</p>
  1236. <ul>
  1237. <li><p>The <a class="reference internal" href="../library/audioop.html#module-audioop" title="audioop: Manipulate raw audio data. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">audioop</span></code></a> module now supports the a-LAW encoding, and the code for
  1238. u-LAW encoding has been improved. (Contributed by Lars Immisch.)</p></li>
  1239. <li><p>The <a class="reference internal" href="../library/codecs.html#module-codecs" title="codecs: Encode and decode data and streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code></a> module gained support for incremental codecs. The
  1240. <code class="xref py py-func docutils literal notranslate"><span class="pre">codec.lookup()</span></code> function now returns a <code class="xref py py-class docutils literal notranslate"><span class="pre">CodecInfo</span></code> instance instead
  1241. of a tuple. <code class="xref py py-class docutils literal notranslate"><span class="pre">CodecInfo</span></code> instances behave like a 4-tuple to preserve
  1242. backward compatibility but also have the attributes <code class="xref py py-attr docutils literal notranslate"><span class="pre">encode</span></code>,
  1243. <code class="xref py py-attr docutils literal notranslate"><span class="pre">decode</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">incrementalencoder</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">incrementaldecoder</span></code>,
  1244. <code class="xref py py-attr docutils literal notranslate"><span class="pre">streamwriter</span></code>, and <code class="xref py py-attr docutils literal notranslate"><span class="pre">streamreader</span></code>. Incremental codecs can receive
  1245. input and produce output in multiple chunks; the output is the same as if the
  1246. entire input was fed to the non-incremental codec. See the <a class="reference internal" href="../library/codecs.html#module-codecs" title="codecs: Encode and decode data and streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code></a> module
  1247. documentation for details. (Designed and implemented by Walter Dörwald.)</p>
  1248. </li>
  1249. <li><p>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 gained a new type, <code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code>, that
  1250. subclasses the standard <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> type. The new type mostly behaves like a
  1251. dictionary but constructs a default value when a key isn’t present,
  1252. automatically adding it to the dictionary for the requested key value.</p>
  1253. <p>The first argument to <code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code>’s constructor is a factory function
  1254. that gets called whenever a key is requested but not found. This factory
  1255. function receives no arguments, so you can use built-in type constructors such
  1256. as <a class="reference internal" href="../library/stdtypes.html#list" title="list"><code class="xref py py-func docutils literal notranslate"><span class="pre">list()</span></code></a> or <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>. For example, you can make an index of words
  1257. based on their initial letter like this:</p>
  1258. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">words</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;Nel mezzo del cammin di nostra vita</span>
  1259. <span class="s2">mi ritrovai per una selva oscura</span>
  1260. <span class="s2">che la diritta via era smarrita&quot;&quot;&quot;</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span><span class="o">.</span><span class="n">split</span><span class="p">()</span>
  1261. <span class="n">index</span> <span class="o">=</span> <span class="n">defaultdict</span><span class="p">(</span><span class="nb">list</span><span class="p">)</span>
  1262. <span class="k">for</span> <span class="n">w</span> <span class="ow">in</span> <span class="n">words</span><span class="p">:</span>
  1263. <span class="n">init_letter</span> <span class="o">=</span> <span class="n">w</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
  1264. <span class="n">index</span><span class="p">[</span><span class="n">init_letter</span><span class="p">]</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">w</span><span class="p">)</span>
  1265. </pre></div>
  1266. </div>
  1267. <p>Printing <code class="docutils literal notranslate"><span class="pre">index</span></code> results in the following output:</p>
  1268. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">defaultdict</span><span class="p">(</span><span class="o">&lt;</span><span class="nb">type</span> <span class="s1">&#39;list&#39;</span><span class="o">&gt;</span><span class="p">,</span> <span class="p">{</span><span class="s1">&#39;c&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;cammin&#39;</span><span class="p">,</span> <span class="s1">&#39;che&#39;</span><span class="p">],</span> <span class="s1">&#39;e&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;era&#39;</span><span class="p">],</span>
  1269. <span class="s1">&#39;d&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;del&#39;</span><span class="p">,</span> <span class="s1">&#39;di&#39;</span><span class="p">,</span> <span class="s1">&#39;diritta&#39;</span><span class="p">],</span> <span class="s1">&#39;m&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;mezzo&#39;</span><span class="p">,</span> <span class="s1">&#39;mi&#39;</span><span class="p">],</span>
  1270. <span class="s1">&#39;l&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;la&#39;</span><span class="p">],</span> <span class="s1">&#39;o&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;oscura&#39;</span><span class="p">],</span> <span class="s1">&#39;n&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;nel&#39;</span><span class="p">,</span> <span class="s1">&#39;nostra&#39;</span><span class="p">],</span>
  1271. <span class="s1">&#39;p&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;per&#39;</span><span class="p">],</span> <span class="s1">&#39;s&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;selva&#39;</span><span class="p">,</span> <span class="s1">&#39;smarrita&#39;</span><span class="p">],</span>
  1272. <span class="s1">&#39;r&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;ritrovai&#39;</span><span class="p">],</span> <span class="s1">&#39;u&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;una&#39;</span><span class="p">],</span> <span class="s1">&#39;v&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;vita&#39;</span><span class="p">,</span> <span class="s1">&#39;via&#39;</span><span class="p">]}</span>
  1273. </pre></div>
  1274. </div>
  1275. <p>(Contributed by Guido van Rossum.)</p>
  1276. </li>
  1277. <li><p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code> double-ended queue type supplied by 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>
  1278. module now has a <code class="docutils literal notranslate"><span class="pre">remove(value)</span></code> method that removes the first occurrence
  1279. of <em>value</em> in the queue, raising <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> if the value isn’t found.
  1280. (Contributed by Raymond Hettinger.)</p></li>
  1281. <li><p>New module: 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 contains helper functions for use
  1282. with the new ‘<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. See section <a class="reference internal" href="#contextlibmod"><span class="std std-ref">The contextlib module</span></a>
  1283. for more about this module.</p></li>
  1284. <li><p>New module: The <a class="reference internal" href="../library/profile.html#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a> module is a C implementation of the existing
  1285. <a class="reference internal" href="../library/profile.html#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> module that has much lower overhead. The module’s interface is
  1286. the same as <a class="reference internal" href="../library/profile.html#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a>: you run <code class="docutils literal notranslate"><span class="pre">cProfile.run('main()')</span></code> to profile a
  1287. function, can save profile data to a file, etc. It’s not yet known if the
  1288. Hotshot profiler, which is also written in C but doesn’t match the
  1289. <a class="reference internal" href="../library/profile.html#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> module’s interface, will continue to be maintained in future
  1290. versions of Python. (Contributed by Armin Rigo.)</p>
  1291. <p>Also, the <a class="reference internal" href="../library/profile.html#module-pstats" title="pstats: Statistics object for use with the profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pstats</span></code></a> module for analyzing the data measured by the profiler
  1292. now supports directing the output to any file object by supplying a <em>stream</em>
  1293. argument to the <code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code> constructor. (Contributed by Skip Montanaro.)</p>
  1294. </li>
  1295. <li><p>The <a class="reference internal" href="../library/csv.html#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a> module, which parses files in comma-separated value format,
  1296. received several enhancements and a number of bugfixes. You can now set the
  1297. maximum size in bytes of a field by calling the
  1298. <code class="docutils literal notranslate"><span class="pre">csv.field_size_limit(new_limit)</span></code> function; omitting the <em>new_limit</em>
  1299. argument will return the currently set limit. The <code class="xref py py-class docutils literal notranslate"><span class="pre">reader</span></code> class now has
  1300. a <code class="xref py py-attr docutils literal notranslate"><span class="pre">line_num</span></code> attribute that counts the number of physical lines read from
  1301. the source; records can span multiple physical lines, so <code class="xref py py-attr docutils literal notranslate"><span class="pre">line_num</span></code> is not
  1302. the same as the number of records read.</p>
  1303. <p>The CSV parser is now stricter about multi-line quoted fields. Previously, if a
  1304. line ended within a quoted field without a terminating newline character, a
  1305. newline would be inserted into the returned field. This behavior caused problems
  1306. when reading files that contained carriage return characters within fields, so
  1307. the code was changed to return the field without inserting newlines. As a
  1308. consequence, if newlines embedded within fields are important, the input should
  1309. be split into lines in a manner that preserves the newline characters.</p>
  1310. <p>(Contributed by Skip Montanaro and Andrew McNamara.)</p>
  1311. </li>
  1312. <li><p>The <a class="reference internal" href="../library/datetime.html#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> class in 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 now has a
  1313. <code class="docutils literal notranslate"><span class="pre">strptime(string,</span> <span class="pre">format)</span></code> method for parsing date strings, contributed
  1314. by Josh Spoerri. It uses the same format characters as <a class="reference internal" href="../library/time.html#time.strptime" title="time.strptime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.strptime()</span></code></a> and
  1315. <a class="reference internal" href="../library/time.html#time.strftime" title="time.strftime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.strftime()</span></code></a>:</p>
  1316. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">datetime</span> <span class="kn">import</span> <span class="n">datetime</span>
  1317. <span class="n">ts</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">strptime</span><span class="p">(</span><span class="s1">&#39;10:13:15 2006-03-07&#39;</span><span class="p">,</span>
  1318. <span class="s1">&#39;%H:%M:%S %Y-%m-</span><span class="si">%d</span><span class="s1">&#39;</span><span class="p">)</span>
  1319. </pre></div>
  1320. </div>
  1321. </li>
  1322. <li><p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">SequenceMatcher.get_matching_blocks()</span></code> method in 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>
  1323. module now guarantees to return a minimal list of blocks describing matching
  1324. subsequences. Previously, the algorithm would occasionally break a block of
  1325. matching elements into two list entries. (Enhancement by Tim Peters.)</p></li>
  1326. <li><p>The <a class="reference internal" href="../library/doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> module gained a <code class="docutils literal notranslate"><span class="pre">SKIP</span></code> option that keeps an example from
  1327. being executed at all. This is intended for code snippets that are usage
  1328. examples intended for the reader and aren’t actually test cases.</p>
  1329. <p>An <em>encoding</em> parameter was added to the <code class="xref py py-func docutils literal notranslate"><span class="pre">testfile()</span></code> function and the
  1330. <code class="xref py py-class docutils literal notranslate"><span class="pre">DocFileSuite</span></code> class to specify the file’s encoding. This makes it
  1331. easier to use non-ASCII characters in tests contained within a docstring.
  1332. (Contributed by Bjorn Tillenius.)</p>
  1333. </li>
  1334. <li><p>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> package has been updated to version 4.0. (Contributed by
  1335. Barry Warsaw.)</p>
  1336. </li>
  1337. <li id="index-20"><p>The <a class="reference internal" href="../library/fileinput.html#module-fileinput" title="fileinput: Loop over standard input or a list of files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fileinput</span></code></a> module was made more flexible. Unicode filenames are now
  1338. supported, and a <em>mode</em> parameter that defaults to <code class="docutils literal notranslate"><span class="pre">&quot;r&quot;</span></code> was added to the
  1339. <a class="reference internal" href="../library/functions.html#input" title="input"><code class="xref py py-func docutils literal notranslate"><span class="pre">input()</span></code></a> function to allow opening files in binary or <a class="reference internal" href="../glossary.html#term-universal-newlines"><span class="xref std std-term">universal
  1340. newlines</span></a> mode. Another new parameter, <em>openhook</em>, lets you use a function
  1341. other than <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> to open the input files. Once you’re iterating over
  1342. the set of files, the <code class="xref py py-class docutils literal notranslate"><span class="pre">FileInput</span></code> object’s new <code class="xref py py-meth docutils literal notranslate"><span class="pre">fileno()</span></code> returns
  1343. the file descriptor for the currently opened file. (Contributed by Georg
  1344. Brandl.)</p></li>
  1345. <li><p>In the <a class="reference internal" href="../library/gc.html#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gc</span></code></a> module, the new <code class="xref py py-func docutils literal notranslate"><span class="pre">get_count()</span></code> function returns a 3-tuple
  1346. containing the current collection counts for the three GC generations. This is
  1347. accounting information for the garbage collector; when these counts reach a
  1348. specified threshold, a garbage collection sweep will be made. The existing
  1349. <a class="reference internal" href="../library/gc.html#gc.collect" title="gc.collect"><code class="xref py py-func docutils literal notranslate"><span class="pre">gc.collect()</span></code></a> function now takes an optional <em>generation</em> argument of 0, 1,
  1350. or 2 to specify which generation to collect. (Contributed by Barry Warsaw.)</p></li>
  1351. <li><p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">nsmallest()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">nlargest()</span></code> functions 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>
  1352. module now support a <code class="docutils literal notranslate"><span class="pre">key</span></code> keyword parameter similar to the one provided by
  1353. the <a class="reference internal" href="../library/functions.html#min" title="min"><code class="xref py py-func docutils literal notranslate"><span class="pre">min()</span></code></a>/<a class="reference internal" href="../library/functions.html#max" title="max"><code class="xref py py-func docutils literal notranslate"><span class="pre">max()</span></code></a> functions and the <code class="xref py py-meth docutils literal notranslate"><span class="pre">sort()</span></code> methods. For
  1354. example:</p>
  1355. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">heapq</span>
  1356. <span class="gp">&gt;&gt;&gt; </span><span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="s2">&quot;short&quot;</span><span class="p">,</span> <span class="s1">&#39;medium&#39;</span><span class="p">,</span> <span class="s1">&#39;longest&#39;</span><span class="p">,</span> <span class="s1">&#39;longer still&#39;</span><span class="p">]</span>
  1357. <span class="gp">&gt;&gt;&gt; </span><span class="n">heapq</span><span class="o">.</span><span class="n">nsmallest</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="n">L</span><span class="p">)</span> <span class="c1"># Return two lowest elements, lexicographically</span>
  1358. <span class="go">[&#39;longer still&#39;, &#39;longest&#39;]</span>
  1359. <span class="gp">&gt;&gt;&gt; </span><span class="n">heapq</span><span class="o">.</span><span class="n">nsmallest</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="n">L</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="nb">len</span><span class="p">)</span> <span class="c1"># Return two shortest elements</span>
  1360. <span class="go">[&#39;short&#39;, &#39;medium&#39;]</span>
  1361. </pre></div>
  1362. </div>
  1363. <p>(Contributed by Raymond Hettinger.)</p>
  1364. </li>
  1365. <li><p>The <a class="reference internal" href="../library/itertools.html#itertools.islice" title="itertools.islice"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.islice()</span></code></a> function now accepts <code class="docutils literal notranslate"><span class="pre">None</span></code> for the start and
  1366. step arguments. This makes it more compatible with the attributes of slice
  1367. objects, so that you can now write the following:</p>
  1368. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="nb">slice</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span> <span class="c1"># Create slice object</span>
  1369. <span class="n">itertools</span><span class="o">.</span><span class="n">islice</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">s</span><span class="o">.</span><span class="n">start</span><span class="p">,</span> <span class="n">s</span><span class="o">.</span><span class="n">stop</span><span class="p">,</span> <span class="n">s</span><span class="o">.</span><span class="n">step</span><span class="p">)</span>
  1370. </pre></div>
  1371. </div>
  1372. <p>(Contributed by Raymond Hettinger.)</p>
  1373. </li>
  1374. <li><p>The <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> function in the <a class="reference internal" href="../library/locale.html#module-locale" title="locale: Internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">locale</span></code></a> module has been modified and
  1375. two new functions were added, <code class="xref py py-func docutils literal notranslate"><span class="pre">format_string()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">currency()</span></code>.</p>
  1376. <p>The <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> function’s <em>val</em> parameter could previously be a string as
  1377. long as no more than one %char specifier appeared; now the parameter must be
  1378. exactly one %char specifier with no surrounding text. An optional <em>monetary</em>
  1379. parameter was also added which, if <code class="docutils literal notranslate"><span class="pre">True</span></code>, will use the locale’s rules for
  1380. formatting currency in placing a separator between groups of three digits.</p>
  1381. <p>To format strings with multiple %char specifiers, use the new
  1382. <code class="xref py py-func docutils literal notranslate"><span class="pre">format_string()</span></code> function that works like <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> but also supports
  1383. mixing %char specifiers with arbitrary text.</p>
  1384. <p>A new <code class="xref py py-func docutils literal notranslate"><span class="pre">currency()</span></code> function was also added that formats a number according
  1385. to the current locale’s settings.</p>
  1386. <p>(Contributed by Georg Brandl.)</p>
  1387. </li>
  1388. <li><p>The <a class="reference internal" href="../library/mailbox.html#module-mailbox" title="mailbox: Manipulate mailboxes in various formats"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mailbox</span></code></a> module underwent a massive rewrite to add the capability to
  1389. modify mailboxes in addition to reading them. A new set of classes that include
  1390. <code class="xref py py-class docutils literal notranslate"><span class="pre">mbox</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">MH</span></code>, and <code class="xref py py-class docutils literal notranslate"><span class="pre">Maildir</span></code> are used to read mailboxes, and
  1391. have an <code class="docutils literal notranslate"><span class="pre">add(message)</span></code> method to add messages, <code class="docutils literal notranslate"><span class="pre">remove(key)</span></code> to
  1392. remove messages, and <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">unlock()</span></code> to lock/unlock the mailbox.
  1393. The following example converts a maildir-format mailbox into an mbox-format
  1394. one:</p>
  1395. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">mailbox</span>
  1396. <span class="c1"># &#39;factory=None&#39; uses email.Message.Message as the class representing</span>
  1397. <span class="c1"># individual messages.</span>
  1398. <span class="n">src</span> <span class="o">=</span> <span class="n">mailbox</span><span class="o">.</span><span class="n">Maildir</span><span class="p">(</span><span class="s1">&#39;maildir&#39;</span><span class="p">,</span> <span class="n">factory</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span>
  1399. <span class="n">dest</span> <span class="o">=</span> <span class="n">mailbox</span><span class="o">.</span><span class="n">mbox</span><span class="p">(</span><span class="s1">&#39;/tmp/mbox&#39;</span><span class="p">)</span>
  1400. <span class="k">for</span> <span class="n">msg</span> <span class="ow">in</span> <span class="n">src</span><span class="p">:</span>
  1401. <span class="n">dest</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">msg</span><span class="p">)</span>
  1402. </pre></div>
  1403. </div>
  1404. <p>(Contributed by Gregory K. Johnson. Funding was provided by Google’s 2005
  1405. Summer of Code.)</p>
  1406. </li>
  1407. <li><p>New module: 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 allows creating Microsoft Installer
  1408. <code class="file docutils literal notranslate"><span class="pre">.msi</span></code> files and CAB files. Some support for reading the <code class="file docutils literal notranslate"><span class="pre">.msi</span></code>
  1409. database is also included. (Contributed by Martin von Löwis.)</p></li>
  1410. <li><p>The <a class="reference internal" href="../library/nis.html#module-nis" title="nis: Interface to Sun's NIS (Yellow Pages) library. (deprecated) (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">nis</span></code></a> module now supports accessing domains other than the system
  1411. default domain by supplying a <em>domain</em> argument to the <a class="reference internal" href="../library/nis.html#nis.match" title="nis.match"><code class="xref py py-func docutils literal notranslate"><span class="pre">nis.match()</span></code></a> and
  1412. <a class="reference internal" href="../library/nis.html#nis.maps" title="nis.maps"><code class="xref py py-func docutils literal notranslate"><span class="pre">nis.maps()</span></code></a> functions. (Contributed by Ben Bell.)</p></li>
  1413. <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’s <code class="xref py py-func docutils literal notranslate"><span class="pre">itemgetter()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">attrgetter()</span></code>
  1414. functions now support multiple fields. A call such as
  1415. <code class="docutils literal notranslate"><span class="pre">operator.attrgetter('a',</span> <span class="pre">'b')</span></code> will return a function that retrieves the
  1416. <code class="xref py py-attr docutils literal notranslate"><span class="pre">a</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">b</span></code> attributes. Combining this new feature with the
  1417. <code class="xref py py-meth docutils literal notranslate"><span class="pre">sort()</span></code> method’s <code class="docutils literal notranslate"><span class="pre">key</span></code> parameter lets you easily sort lists using
  1418. multiple fields. (Contributed by Raymond Hettinger.)</p></li>
  1419. <li><p>The <a class="reference internal" href="../library/optparse.html#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> module was updated to version 1.5.1 of the Optik library.
  1420. The <code class="xref py py-class docutils literal notranslate"><span class="pre">OptionParser</span></code> class gained an <code class="xref py py-attr docutils literal notranslate"><span class="pre">epilog</span></code> attribute, a string
  1421. that will be printed after the help message, and a <code class="xref py py-meth docutils literal notranslate"><span class="pre">destroy()</span></code> method to
  1422. break reference cycles created by the object. (Contributed by Greg Ward.)</p></li>
  1423. <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 underwent several changes. The <code class="xref py py-attr docutils literal notranslate"><span class="pre">stat_float_times</span></code>
  1424. variable now defaults to true, meaning that <a class="reference internal" href="../library/os.html#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.stat()</span></code></a> will now return time
  1425. values as floats. (This doesn’t necessarily mean that <a class="reference internal" href="../library/os.html#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.stat()</span></code></a> will
  1426. return times that are precise to fractions of a second; not all systems support
  1427. such precision.)</p>
  1428. <p>Constants named <a class="reference internal" href="../library/os.html#os.SEEK_SET" title="os.SEEK_SET"><code class="xref py py-const docutils literal notranslate"><span class="pre">os.SEEK_SET</span></code></a>, <a class="reference internal" href="../library/os.html#os.SEEK_CUR" title="os.SEEK_CUR"><code class="xref py py-const docutils literal notranslate"><span class="pre">os.SEEK_CUR</span></code></a>, and
  1429. <a class="reference internal" href="../library/os.html#os.SEEK_END" title="os.SEEK_END"><code class="xref py py-const docutils literal notranslate"><span class="pre">os.SEEK_END</span></code></a> have been added; these are the parameters to the
  1430. <a class="reference internal" href="../library/os.html#os.lseek" title="os.lseek"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.lseek()</span></code></a> function. Two new constants for locking are
  1431. <a class="reference internal" href="../library/os.html#os.O_SHLOCK" title="os.O_SHLOCK"><code class="xref py py-const docutils literal notranslate"><span class="pre">os.O_SHLOCK</span></code></a> and <a class="reference internal" href="../library/os.html#os.O_EXLOCK" title="os.O_EXLOCK"><code class="xref py py-const docutils literal notranslate"><span class="pre">os.O_EXLOCK</span></code></a>.</p>
  1432. <p>Two new functions, <code class="xref py py-func docutils literal notranslate"><span class="pre">wait3()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">wait4()</span></code>, were added. They’re similar
  1433. the <code class="xref py py-func docutils literal notranslate"><span class="pre">waitpid()</span></code> function which waits for a child process to exit and returns
  1434. a tuple of the process ID and its exit status, but <code class="xref py py-func docutils literal notranslate"><span class="pre">wait3()</span></code> and
  1435. <code class="xref py py-func docutils literal notranslate"><span class="pre">wait4()</span></code> return additional information. <code class="xref py py-func docutils literal notranslate"><span class="pre">wait3()</span></code> doesn’t take a
  1436. process ID as input, so it waits for any child process to exit and returns a
  1437. 3-tuple of <em>process-id</em>, <em>exit-status</em>, <em>resource-usage</em> as returned from the
  1438. <a class="reference internal" href="../library/resource.html#resource.getrusage" title="resource.getrusage"><code class="xref py py-func docutils literal notranslate"><span class="pre">resource.getrusage()</span></code></a> function. <code class="docutils literal notranslate"><span class="pre">wait4(pid)</span></code> does take a process ID.
  1439. (Contributed by Chad J. Schroeder.)</p>
  1440. <p>On FreeBSD, the <a class="reference internal" href="../library/os.html#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.stat()</span></code></a> function now returns times with nanosecond
  1441. resolution, and the returned object now has <code class="xref py py-attr docutils literal notranslate"><span class="pre">st_gen</span></code> and
  1442. <code class="xref py py-attr docutils literal notranslate"><span class="pre">st_birthtime</span></code>. The <code class="xref py py-attr docutils literal notranslate"><span class="pre">st_flags</span></code> attribute is also available, if the
  1443. platform supports it. (Contributed by Antti Louko and Diego Pettenò.)</p>
  1444. </li>
  1445. <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 can now store lists of
  1446. commands to execute when a breakpoint is reached and execution stops. Once
  1447. breakpoint #1 has been created, enter <code class="docutils literal notranslate"><span class="pre">commands</span> <span class="pre">1</span></code> and enter a series of
  1448. commands to be executed, finishing the list with <code class="docutils literal notranslate"><span class="pre">end</span></code>. The command list can
  1449. include commands that resume execution, such as <code class="docutils literal notranslate"><span class="pre">continue</span></code> or <code class="docutils literal notranslate"><span class="pre">next</span></code>.
  1450. (Contributed by Grégoire Dooms.)</p>
  1451. </li>
  1452. <li><p>The <a class="reference internal" href="../library/pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code> modules no longer accept a return value
  1453. of <code class="docutils literal notranslate"><span class="pre">None</span></code> from the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce__()</span></code> method; the method must return a tuple
  1454. of arguments instead. The ability to return <code class="docutils literal notranslate"><span class="pre">None</span></code> was deprecated in Python
  1455. 2.4, so this completes the removal of the feature.</p></li>
  1456. <li><p>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> module, containing various utility functions for finding
  1457. packages, was enhanced to support <span class="target" id="index-21"></span><a class="pep reference external" href="https://peps.python.org/pep-0302/"><strong>PEP 302</strong></a>’s import hooks and now also works for
  1458. packages stored in ZIP-format archives. (Contributed by Phillip J. Eby.)</p></li>
  1459. <li><p>The pybench benchmark suite by Marc-André Lemburg is now included in the
  1460. <code class="file docutils literal notranslate"><span class="pre">Tools/pybench</span></code> directory. The pybench suite is an improvement on the
  1461. commonly used <code class="file docutils literal notranslate"><span class="pre">pystone.py</span></code> program because pybench provides a more
  1462. detailed measurement of the interpreter’s speed. It times particular operations
  1463. such as function calls, tuple slicing, method lookups, and numeric operations,
  1464. instead of performing many different operations and reducing the result to a
  1465. single number as <code class="file docutils literal notranslate"><span class="pre">pystone.py</span></code> does.</p></li>
  1466. <li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">pyexpat</span></code> module now uses version 2.0 of the Expat parser.
  1467. (Contributed by Trent Mick.)</p></li>
  1468. <li><p>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> class provided by the <code class="xref py py-mod docutils literal notranslate"><span class="pre">Queue</span></code> module gained two new
  1469. methods. <code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code> blocks until all items in the queue have been retrieved
  1470. and all processing work on the items have been completed. Worker threads call
  1471. the other new method, <code class="xref py py-meth docutils literal notranslate"><span class="pre">task_done()</span></code>, to signal that processing for an item
  1472. has been completed. (Contributed by Raymond Hettinger.)</p></li>
  1473. <li><p>The old <code class="xref py py-mod docutils literal notranslate"><span class="pre">regex</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">regsub</span></code> modules, which have been deprecated
  1474. ever since Python 2.0, have finally been deleted. Other deleted modules:
  1475. <code class="xref py py-mod docutils literal notranslate"><span class="pre">statcache</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">tzparse</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">whrandom</span></code>.</p></li>
  1476. <li><p>Also deleted: the <code class="file docutils literal notranslate"><span class="pre">lib-old</span></code> directory, which includes ancient modules
  1477. such as <code class="xref py py-mod docutils literal notranslate"><span class="pre">dircmp</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">ni</span></code>, was removed. <code class="file docutils literal notranslate"><span class="pre">lib-old</span></code> wasn’t on the
  1478. default <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>, so unless your programs explicitly added the directory to
  1479. <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>, this removal shouldn’t affect your code.</p></li>
  1480. <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 is no longer dependent on importing the
  1481. <a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">readline</span></code></a> module and therefore now works on non-Unix platforms. (Patch
  1482. from Robert Kiendl.)</p>
  1483. </li>
  1484. <li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">SimpleXMLRPCServer</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">DocXMLRPCServer</span></code> classes now have a
  1485. <code class="xref py py-attr docutils literal notranslate"><span class="pre">rpc_paths</span></code> attribute that constrains XML-RPC operations to a limited set
  1486. of URL paths; the default is to allow only <code class="docutils literal notranslate"><span class="pre">'/'</span></code> and <code class="docutils literal notranslate"><span class="pre">'/RPC2'</span></code>. Setting
  1487. <code class="xref py py-attr docutils literal notranslate"><span class="pre">rpc_paths</span></code> to <code class="docutils literal notranslate"><span class="pre">None</span></code> or an empty tuple disables this path checking.</p>
  1488. </li>
  1489. <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 <code class="xref py py-const docutils literal notranslate"><span class="pre">AF_NETLINK</span></code> sockets on Linux,
  1490. thanks to a patch from Philippe Biondi. Netlink sockets are a Linux-specific
  1491. mechanism for communications between a user-space process and kernel code; an
  1492. introductory article about them is at <a class="reference external" href="https://www.linuxjournal.com/article/7356">https://www.linuxjournal.com/article/7356</a>.
  1493. In Python code, netlink addresses are represented as a tuple of 2 integers,
  1494. <code class="docutils literal notranslate"><span class="pre">(pid,</span> <span class="pre">group_mask)</span></code>.</p>
  1495. <p>Two new methods on socket objects, <code class="docutils literal notranslate"><span class="pre">recv_into(buffer)</span></code> and
  1496. <code class="docutils literal notranslate"><span class="pre">recvfrom_into(buffer)</span></code>, store the received data in an object that
  1497. supports the buffer protocol instead of returning the data as a string. This
  1498. means you can put the data directly into an array or a memory-mapped file.</p>
  1499. <p>Socket objects also gained <code class="xref py py-meth docutils literal notranslate"><span class="pre">getfamily()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">gettype()</span></code>, and
  1500. <code class="xref py py-meth docutils literal notranslate"><span class="pre">getproto()</span></code> accessor methods to retrieve the family, type, and protocol
  1501. values for the socket.</p>
  1502. </li>
  1503. <li><p>New module: the <a class="reference internal" href="../library/spwd.html#module-spwd" title="spwd: The shadow password database (getspnam() and friends). (deprecated) (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">spwd</span></code></a> module provides functions for accessing the shadow
  1504. password database on systems that support shadow passwords.</p></li>
  1505. <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> is now faster because it compiles format strings into
  1506. <code class="xref py py-class docutils literal notranslate"><span class="pre">Struct</span></code> objects with <code class="xref py py-meth docutils literal notranslate"><span class="pre">pack()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">unpack()</span></code> methods. This is
  1507. similar to how 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> module lets you create compiled regular expression
  1508. objects. You can still use the module-level <code class="xref py py-func docutils literal notranslate"><span class="pre">pack()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">unpack()</span></code>
  1509. functions; they’ll create <code class="xref py py-class docutils literal notranslate"><span class="pre">Struct</span></code> objects and cache them. Or you can
  1510. use <code class="xref py py-class docutils literal notranslate"><span class="pre">Struct</span></code> instances directly:</p>
  1511. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="n">struct</span><span class="o">.</span><span class="n">Struct</span><span class="p">(</span><span class="s1">&#39;ih3s&#39;</span><span class="p">)</span>
  1512. <span class="n">data</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">pack</span><span class="p">(</span><span class="mi">1972</span><span class="p">,</span> <span class="mi">187</span><span class="p">,</span> <span class="s1">&#39;abc&#39;</span><span class="p">)</span>
  1513. <span class="n">year</span><span class="p">,</span> <span class="n">number</span><span class="p">,</span> <span class="n">name</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">unpack</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
  1514. </pre></div>
  1515. </div>
  1516. <p>You can also pack and unpack data to and from buffer objects directly using the
  1517. <code class="docutils literal notranslate"><span class="pre">pack_into(buffer,</span> <span class="pre">offset,</span> <span class="pre">v1,</span> <span class="pre">v2,</span> <span class="pre">...)</span></code> and <code class="docutils literal notranslate"><span class="pre">unpack_from(buffer,</span>
  1518. <span class="pre">offset)</span></code> methods. This lets you store data directly into an array or a
  1519. memory-mapped file.</p>
  1520. <p>(<code class="xref py py-class docutils literal notranslate"><span class="pre">Struct</span></code> objects were implemented by Bob Ippolito at the NeedForSpeed
  1521. sprint. Support for buffer objects was added by Martin Blais, also at the
  1522. NeedForSpeed sprint.)</p>
  1523. </li>
  1524. <li><p>The Python developers switched from CVS to Subversion during the 2.5
  1525. development process. Information about the exact build version is available as
  1526. the <code class="docutils literal notranslate"><span class="pre">sys.subversion</span></code> variable, a 3-tuple of <code class="docutils literal notranslate"><span class="pre">(interpreter-name,</span> <span class="pre">branch-name,</span>
  1527. <span class="pre">revision-range)</span></code>. For example, at the time of writing my copy of 2.5 was
  1528. reporting <code class="docutils literal notranslate"><span class="pre">('CPython',</span> <span class="pre">'trunk',</span> <span class="pre">'45313:45315')</span></code>.</p>
  1529. <p>This information is also available to C extensions via the
  1530. <a class="reference internal" href="../c-api/init.html#c.Py_GetBuildInfo" title="Py_GetBuildInfo"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_GetBuildInfo()</span></code></a> function that returns a string of build information
  1531. like this: <code class="docutils literal notranslate"><span class="pre">&quot;trunk:45355:45356M,</span> <span class="pre">Apr</span> <span class="pre">13</span> <span class="pre">2006,</span> <span class="pre">07:42:19&quot;</span></code>. (Contributed by
  1532. Barry Warsaw.)</p>
  1533. </li>
  1534. <li><p>Another new function, <a class="reference internal" href="../library/sys.html#sys._current_frames" title="sys._current_frames"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys._current_frames()</span></code></a>, returns the current stack
  1535. frames for all running threads as a dictionary mapping thread identifiers to the
  1536. topmost stack frame currently active in that thread at the time the function is
  1537. called. (Contributed by Tim Peters.)</p></li>
  1538. <li><p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">TarFile</span></code> class in 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 has an
  1539. <code class="xref py py-meth docutils literal notranslate"><span class="pre">extractall()</span></code> method that extracts all members from the archive into the
  1540. current working directory. It’s also possible to set a different directory as
  1541. the extraction target, and to unpack only a subset of the archive’s members.</p>
  1542. <p>The compression used for a tarfile opened in stream mode can now be autodetected
  1543. using the mode <code class="docutils literal notranslate"><span class="pre">'r|*'</span></code>. (Contributed by Lars Gustäbel.)</p>
  1544. </li>
  1545. <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 now lets you set the stack size used when new
  1546. threads are created. The <code class="docutils literal notranslate"><span class="pre">stack_size([*size*])</span></code> function returns the
  1547. currently configured stack size, and supplying the optional <em>size</em> parameter
  1548. sets a new value. Not all platforms support changing the stack size, but
  1549. Windows, POSIX threading, and OS/2 all do. (Contributed by Andrew MacIntyre.)</p>
  1550. </li>
  1551. <li><p>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 has been updated to use version 4.1.0 of the
  1552. Unicode character database. Version 3.2.0 is required by some specifications,
  1553. so it’s still available as <a class="reference internal" href="../library/unicodedata.html#unicodedata.ucd_3_2_0" title="unicodedata.ucd_3_2_0"><code class="xref py py-data docutils literal notranslate"><span class="pre">unicodedata.ucd_3_2_0</span></code></a>.</p></li>
  1554. <li><p>New module: the <a class="reference internal" href="../library/uuid.html#module-uuid" title="uuid: UUID objects (universally unique identifiers) according to RFC 4122"><code class="xref py py-mod docutils literal notranslate"><span class="pre">uuid</span></code></a> module generates universally unique identifiers
  1555. (UUIDs) according to <span class="target" id="index-22"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc4122.html"><strong>RFC 4122</strong></a>. The RFC defines several different UUID
  1556. versions that are generated from a starting string, from system properties, or
  1557. purely randomly. This module contains a <code class="xref py py-class docutils literal notranslate"><span class="pre">UUID</span></code> class and functions
  1558. named <code class="xref py py-func docutils literal notranslate"><span class="pre">uuid1()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">uuid3()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">uuid4()</span></code>, and <code class="xref py py-func docutils literal notranslate"><span class="pre">uuid5()</span></code> to
  1559. generate different versions of UUID. (Version 2 UUIDs are not specified in
  1560. <span class="target" id="index-23"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc4122.html"><strong>RFC 4122</strong></a> and are not supported by this module.)</p>
  1561. <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">uuid</span>
  1562. <span class="gp">&gt;&gt;&gt; </span><span class="c1"># make a UUID based on the host ID and current time</span>
  1563. <span class="gp">&gt;&gt;&gt; </span><span class="n">uuid</span><span class="o">.</span><span class="n">uuid1</span><span class="p">()</span>
  1564. <span class="go">UUID(&#39;a8098c1a-f86e-11da-bd1a-00112444be1e&#39;)</span>
  1565. <span class="gp">&gt;&gt;&gt; </span><span class="c1"># make a UUID using an MD5 hash of a namespace UUID and a name</span>
  1566. <span class="gp">&gt;&gt;&gt; </span><span class="n">uuid</span><span class="o">.</span><span class="n">uuid3</span><span class="p">(</span><span class="n">uuid</span><span class="o">.</span><span class="n">NAMESPACE_DNS</span><span class="p">,</span> <span class="s1">&#39;python.org&#39;</span><span class="p">)</span>
  1567. <span class="go">UUID(&#39;6fa459ea-ee8a-3ca4-894e-db77e160355e&#39;)</span>
  1568. <span class="gp">&gt;&gt;&gt; </span><span class="c1"># make a random UUID</span>
  1569. <span class="gp">&gt;&gt;&gt; </span><span class="n">uuid</span><span class="o">.</span><span class="n">uuid4</span><span class="p">()</span>
  1570. <span class="go">UUID(&#39;16fd2706-8baf-433b-82eb-8c7fada847da&#39;)</span>
  1571. <span class="gp">&gt;&gt;&gt; </span><span class="c1"># make a UUID using a SHA-1 hash of a namespace UUID and a name</span>
  1572. <span class="gp">&gt;&gt;&gt; </span><span class="n">uuid</span><span class="o">.</span><span class="n">uuid5</span><span class="p">(</span><span class="n">uuid</span><span class="o">.</span><span class="n">NAMESPACE_DNS</span><span class="p">,</span> <span class="s1">&#39;python.org&#39;</span><span class="p">)</span>
  1573. <span class="go">UUID(&#39;886313e1-3b8a-5372-9b90-0c9aee199e5d&#39;)</span>
  1574. </pre></div>
  1575. </div>
  1576. <p>(Contributed by Ka-Ping Yee.)</p>
  1577. </li>
  1578. <li><p>The <a class="reference internal" href="../library/weakref.html#module-weakref" title="weakref: Support for weak references and weak dictionaries."><code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code></a> module’s <code class="xref py py-class docutils literal notranslate"><span class="pre">WeakKeyDictionary</span></code> and
  1579. <code class="xref py py-class docutils literal notranslate"><span class="pre">WeakValueDictionary</span></code> types gained new methods for iterating over the
  1580. weak references contained in the dictionary. <code class="xref py py-meth docutils literal notranslate"><span class="pre">iterkeyrefs()</span></code> and
  1581. <code class="xref py py-meth docutils literal notranslate"><span class="pre">keyrefs()</span></code> methods were added to <code class="xref py py-class docutils literal notranslate"><span class="pre">WeakKeyDictionary</span></code>, and
  1582. <code class="xref py py-meth docutils literal notranslate"><span class="pre">itervaluerefs()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">valuerefs()</span></code> were added to
  1583. <code class="xref py py-class docutils literal notranslate"><span class="pre">WeakValueDictionary</span></code>. (Contributed by Fred L. Drake, Jr.)</p></li>
  1584. <li><p>The <a class="reference internal" href="../library/webbrowser.html#module-webbrowser" title="webbrowser: Easy-to-use controller for web browsers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">webbrowser</span></code></a> module received a number of enhancements. It’s now
  1585. usable as a script with <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">-m</span> <span class="pre">webbrowser</span></code>, taking a URL as the argument;
  1586. there are a number of switches to control the behaviour (<code class="xref std std-option docutils literal notranslate"><span class="pre">-n</span></code> for a new
  1587. browser window, <code class="xref std std-option docutils literal notranslate"><span class="pre">-t</span></code> for a new tab). New module-level functions,
  1588. <code class="xref py py-func docutils literal notranslate"><span class="pre">open_new()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">open_new_tab()</span></code>, were added to support this. The
  1589. module’s <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> function supports an additional feature, an <em>autoraise</em>
  1590. parameter that signals whether to raise the open window when possible. A number
  1591. of additional browsers were added to the supported list such as Firefox, Opera,
  1592. Konqueror, and elinks. (Contributed by Oleg Broytmann and Georg Brandl.)</p>
  1593. </li>
  1594. <li><p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code> module now supports returning <a class="reference internal" href="../library/datetime.html#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> objects
  1595. for the XML-RPC date type. Supply <code class="docutils literal notranslate"><span class="pre">use_datetime=True</span></code> to the <code class="xref py py-func docutils literal notranslate"><span class="pre">loads()</span></code>
  1596. function or the <code class="xref py py-class docutils literal notranslate"><span class="pre">Unmarshaller</span></code> class to enable this feature. (Contributed
  1597. by Skip Montanaro.)</p>
  1598. </li>
  1599. <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 now supports the ZIP64 version of the format,
  1600. meaning that a .zip archive can now be larger than 4 GiB and can contain
  1601. individual files larger than 4 GiB. (Contributed by Ronald Oussoren.)</p>
  1602. </li>
  1603. <li><p>The <a class="reference internal" href="../library/zlib.html#module-zlib" title="zlib: Low-level interface to compression and decompression routines compatible with gzip."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zlib</span></code></a> module’s <code class="xref py py-class docutils literal notranslate"><span class="pre">Compress</span></code> and <code class="xref py py-class docutils literal notranslate"><span class="pre">Decompress</span></code> objects now
  1604. support a <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> method that makes a copy of the object’s internal state
  1605. and returns a new <code class="xref py py-class docutils literal notranslate"><span class="pre">Compress</span></code> or <code class="xref py py-class docutils literal notranslate"><span class="pre">Decompress</span></code> object.
  1606. (Contributed by Chris AtLee.)</p>
  1607. </li>
  1608. </ul>
  1609. <section id="the-ctypes-package">
  1610. <span id="module-ctypes"></span><h3>The ctypes package<a class="headerlink" href="#the-ctypes-package" title="Permalink to this headline">¶</a></h3>
  1611. <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> package, written by Thomas Heller, has been added to the
  1612. standard library. <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> lets you call arbitrary functions in shared
  1613. libraries or DLLs. Long-time users may remember the <code class="xref py py-mod docutils literal notranslate"><span class="pre">dl</span></code> module, which
  1614. provides functions for loading shared libraries and calling functions in them.
  1615. 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> package is much fancier.</p>
  1616. <p>To load a shared library or DLL, you must create an instance of the
  1617. <code class="xref py py-class docutils literal notranslate"><span class="pre">CDLL</span></code> class and provide the name or path of the shared library or DLL.
  1618. Once that’s done, you can call arbitrary functions by accessing them as
  1619. attributes of the <code class="xref py py-class docutils literal notranslate"><span class="pre">CDLL</span></code> object.</p>
  1620. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">ctypes</span>
  1621. <span class="n">libc</span> <span class="o">=</span> <span class="n">ctypes</span><span class="o">.</span><span class="n">CDLL</span><span class="p">(</span><span class="s1">&#39;libc.so.6&#39;</span><span class="p">)</span>
  1622. <span class="n">result</span> <span class="o">=</span> <span class="n">libc</span><span class="o">.</span><span class="n">printf</span><span class="p">(</span><span class="s2">&quot;Line of output</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span>
  1623. </pre></div>
  1624. </div>
  1625. <p>Type constructors for the various C types are provided: <code class="xref py py-func docutils literal notranslate"><span class="pre">c_int()</span></code>,
  1626. <code class="xref py py-func docutils literal notranslate"><span class="pre">c_float()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">c_double()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">c_char_p()</span></code> (equivalent to <span class="c-expr sig sig-inline c"><span class="kt">char</span><span class="p">*</span></span>), and so forth. Unlike Python’s types, the C versions are all mutable; you
  1627. can assign to their <code class="xref py py-attr docutils literal notranslate"><span class="pre">value</span></code> attribute to change the wrapped value. Python
  1628. integers and strings will be automatically converted to the corresponding C
  1629. types, but for other types you must call the correct type constructor. (And I
  1630. mean <em>must</em>; getting it wrong will often result in the interpreter crashing
  1631. with a segmentation fault.)</p>
  1632. <p>You shouldn’t use <code class="xref py py-func docutils literal notranslate"><span class="pre">c_char_p()</span></code> with a Python string when the C function will
  1633. be modifying the memory area, because Python strings are supposed to be
  1634. immutable; breaking this rule will cause puzzling bugs. When you need a
  1635. modifiable memory area, use <code class="xref py py-func docutils literal notranslate"><span class="pre">create_string_buffer()</span></code>:</p>
  1636. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;this is a string&quot;</span>
  1637. <span class="n">buf</span> <span class="o">=</span> <span class="n">ctypes</span><span class="o">.</span><span class="n">create_string_buffer</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
  1638. <span class="n">libc</span><span class="o">.</span><span class="n">strfry</span><span class="p">(</span><span class="n">buf</span><span class="p">)</span>
  1639. </pre></div>
  1640. </div>
  1641. <p>C functions are assumed to return integers, but you can set the <code class="xref py py-attr docutils literal notranslate"><span class="pre">restype</span></code>
  1642. attribute of the function object to change this:</p>
  1643. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">libc</span><span class="o">.</span><span class="n">atof</span><span class="p">(</span><span class="s1">&#39;2.71828&#39;</span><span class="p">)</span>
  1644. <span class="go">-1783957616</span>
  1645. <span class="gp">&gt;&gt;&gt; </span><span class="n">libc</span><span class="o">.</span><span class="n">atof</span><span class="o">.</span><span class="n">restype</span> <span class="o">=</span> <span class="n">ctypes</span><span class="o">.</span><span class="n">c_double</span>
  1646. <span class="gp">&gt;&gt;&gt; </span><span class="n">libc</span><span class="o">.</span><span class="n">atof</span><span class="p">(</span><span class="s1">&#39;2.71828&#39;</span><span class="p">)</span>
  1647. <span class="go">2.71828</span>
  1648. </pre></div>
  1649. </div>
  1650. <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> also provides a wrapper for Python’s C API as the
  1651. <code class="docutils literal notranslate"><span class="pre">ctypes.pythonapi</span></code> object. This object does <em>not</em> release the global
  1652. interpreter lock before calling a function, because the lock must be held when
  1653. calling into the interpreter’s code. There’s a <code class="xref py py-class docutils literal notranslate"><span class="pre">py_object()</span></code> type
  1654. constructor that will create a <span class="c-expr sig sig-inline c"><a class="reference internal" href="../c-api/structures.html#c.PyObject" title="PyObject"><span class="n">PyObject</span></a><span class="p">*</span></span> pointer. A simple usage:</p>
  1655. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">ctypes</span>
  1656. <span class="n">d</span> <span class="o">=</span> <span class="p">{}</span>
  1657. <span class="n">ctypes</span><span class="o">.</span><span class="n">pythonapi</span><span class="o">.</span><span class="n">PyObject_SetItem</span><span class="p">(</span><span class="n">ctypes</span><span class="o">.</span><span class="n">py_object</span><span class="p">(</span><span class="n">d</span><span class="p">),</span>
  1658. <span class="n">ctypes</span><span class="o">.</span><span class="n">py_object</span><span class="p">(</span><span class="s2">&quot;abc&quot;</span><span class="p">),</span> <span class="n">ctypes</span><span class="o">.</span><span class="n">py_object</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span>
  1659. <span class="c1"># d is now {&#39;abc&#39;, 1}.</span>
  1660. </pre></div>
  1661. </div>
  1662. <p>Don’t forget to use <code class="xref py py-class docutils literal notranslate"><span class="pre">py_object()</span></code>; if it’s omitted you end up with a
  1663. segmentation fault.</p>
  1664. <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> has been around for a while, but people still write and
  1665. distribution hand-coded extension modules because you can’t rely on
  1666. <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> being present. Perhaps developers will begin to write Python
  1667. wrappers atop a library accessed through <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> instead of extension
  1668. modules, now that <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> is included with core Python.</p>
  1669. <div class="admonition seealso">
  1670. <p class="admonition-title">See also</p>
  1671. <dl class="simple">
  1672. <dt><a class="reference external" href="https://web.archive.org/web/20180410025338/http://starship.python.net/crew/theller/ctypes/">https://web.archive.org/web/20180410025338/http://starship.python.net/crew/theller/ctypes/</a></dt><dd><p>The pre-stdlib ctypes web page, with a tutorial, reference, and FAQ.</p>
  1673. </dd>
  1674. </dl>
  1675. <p>The documentation for 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> module.</p>
  1676. </div>
  1677. </section>
  1678. <section id="the-elementtree-package">
  1679. <span id="module-etree"></span><h3>The ElementTree package<a class="headerlink" href="#the-elementtree-package" title="Permalink to this headline">¶</a></h3>
  1680. <p>A subset of Fredrik Lundh’s ElementTree library for processing XML has been
  1681. added to the standard library as <code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.etree</span></code>. The available modules are
  1682. <code class="xref py py-mod docutils literal notranslate"><span class="pre">ElementTree</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">ElementPath</span></code>, and <code class="xref py py-mod docutils literal notranslate"><span class="pre">ElementInclude</span></code> from
  1683. ElementTree 1.2.6. The <code class="xref py py-mod docutils literal notranslate"><span class="pre">cElementTree</span></code> accelerator module is also
  1684. included.</p>
  1685. <p>The rest of this section will provide a brief overview of using ElementTree.
  1686. Full documentation for ElementTree is available at
  1687. <a class="reference external" href="https://web.archive.org/web/20201124024954/http://effbot.org/zone/element-index.htm">https://web.archive.org/web/20201124024954/http://effbot.org/zone/element-index.htm</a>.</p>
  1688. <p>ElementTree represents an XML document as a tree of element nodes. The text
  1689. content of the document is stored as the <code class="xref py py-attr docutils literal notranslate"><span class="pre">text</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">tail</span></code>
  1690. attributes of (This is one of the major differences between ElementTree and
  1691. the Document Object Model; in the DOM there are many different types of node,
  1692. including <code class="xref py py-class docutils literal notranslate"><span class="pre">TextNode</span></code>.)</p>
  1693. <p>The most commonly used parsing function is <code class="xref py py-func docutils literal notranslate"><span class="pre">parse()</span></code>, that takes either a
  1694. string (assumed to contain a filename) or a file-like object and returns an
  1695. <code class="xref py py-class docutils literal notranslate"><span class="pre">ElementTree</span></code> instance:</p>
  1696. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">xml.etree</span> <span class="kn">import</span> <span class="n">ElementTree</span> <span class="k">as</span> <span class="n">ET</span>
  1697. <span class="n">tree</span> <span class="o">=</span> <span class="n">ET</span><span class="o">.</span><span class="n">parse</span><span class="p">(</span><span class="s1">&#39;ex-1.xml&#39;</span><span class="p">)</span>
  1698. <span class="n">feed</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span>
  1699. <span class="s1">&#39;http://planet.python.org/rss10.xml&#39;</span><span class="p">)</span>
  1700. <span class="n">tree</span> <span class="o">=</span> <span class="n">ET</span><span class="o">.</span><span class="n">parse</span><span class="p">(</span><span class="n">feed</span><span class="p">)</span>
  1701. </pre></div>
  1702. </div>
  1703. <p>Once you have an <code class="xref py py-class docutils literal notranslate"><span class="pre">ElementTree</span></code> instance, you can call its <code class="xref py py-meth docutils literal notranslate"><span class="pre">getroot()</span></code>
  1704. method to get the root <code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code> node.</p>
  1705. <p>There’s also an <code class="xref py py-func docutils literal notranslate"><span class="pre">XML()</span></code> function that takes a string literal and returns an
  1706. <code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code> node (not an <code class="xref py py-class docutils literal notranslate"><span class="pre">ElementTree</span></code>). This function provides a
  1707. tidy way to incorporate XML fragments, approaching the convenience of an XML
  1708. literal:</p>
  1709. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">svg</span> <span class="o">=</span> <span class="n">ET</span><span class="o">.</span><span class="n">XML</span><span class="p">(</span><span class="s2">&quot;&quot;&quot;&lt;svg width=&quot;10px&quot; version=&quot;1.0&quot;&gt;</span>
  1710. <span class="s2"> &lt;/svg&gt;&quot;&quot;&quot;</span><span class="p">)</span>
  1711. <span class="n">svg</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;height&#39;</span><span class="p">,</span> <span class="s1">&#39;320px&#39;</span><span class="p">)</span>
  1712. <span class="n">svg</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">elem1</span><span class="p">)</span>
  1713. </pre></div>
  1714. </div>
  1715. <p>Each XML element supports some dictionary-like and some list-like access
  1716. methods. Dictionary-like operations are used to access attribute values, and
  1717. list-like operations are used to access child nodes.</p>
  1718. <table class="docutils align-default">
  1719. <colgroup>
  1720. <col style="width: 41%" />
  1721. <col style="width: 59%" />
  1722. </colgroup>
  1723. <thead>
  1724. <tr class="row-odd"><th class="head"><p>Operation</p></th>
  1725. <th class="head"><p>Result</p></th>
  1726. </tr>
  1727. </thead>
  1728. <tbody>
  1729. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">elem[n]</span></code></p></td>
  1730. <td><p>Returns n’th child element.</p></td>
  1731. </tr>
  1732. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">elem[m:n]</span></code></p></td>
  1733. <td><p>Returns list of m’th through n’th child
  1734. elements.</p></td>
  1735. </tr>
  1736. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">len(elem)</span></code></p></td>
  1737. <td><p>Returns number of child elements.</p></td>
  1738. </tr>
  1739. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">list(elem)</span></code></p></td>
  1740. <td><p>Returns list of child elements.</p></td>
  1741. </tr>
  1742. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">elem.append(elem2)</span></code></p></td>
  1743. <td><p>Adds <em>elem2</em> as a child.</p></td>
  1744. </tr>
  1745. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">elem.insert(index,</span> <span class="pre">elem2)</span></code></p></td>
  1746. <td><p>Inserts <em>elem2</em> at the specified location.</p></td>
  1747. </tr>
  1748. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">elem[n]</span></code></p></td>
  1749. <td><p>Deletes n’th child element.</p></td>
  1750. </tr>
  1751. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">elem.keys()</span></code></p></td>
  1752. <td><p>Returns list of attribute names.</p></td>
  1753. </tr>
  1754. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">elem.get(name)</span></code></p></td>
  1755. <td><p>Returns value of attribute <em>name</em>.</p></td>
  1756. </tr>
  1757. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">elem.set(name,</span> <span class="pre">value)</span></code></p></td>
  1758. <td><p>Sets new value for attribute <em>name</em>.</p></td>
  1759. </tr>
  1760. <tr class="row-even"><td><p><code class="docutils literal notranslate"><span class="pre">elem.attrib</span></code></p></td>
  1761. <td><p>Retrieves the dictionary containing
  1762. attributes.</p></td>
  1763. </tr>
  1764. <tr class="row-odd"><td><p><code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">elem.attrib[name]</span></code></p></td>
  1765. <td><p>Deletes attribute <em>name</em>.</p></td>
  1766. </tr>
  1767. </tbody>
  1768. </table>
  1769. <p>Comments and processing instructions are also represented as <code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code>
  1770. nodes. To check if a node is a comment or processing instructions:</p>
  1771. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">elem</span><span class="o">.</span><span class="n">tag</span> <span class="ow">is</span> <span class="n">ET</span><span class="o">.</span><span class="n">Comment</span><span class="p">:</span>
  1772. <span class="o">...</span>
  1773. <span class="k">elif</span> <span class="n">elem</span><span class="o">.</span><span class="n">tag</span> <span class="ow">is</span> <span class="n">ET</span><span class="o">.</span><span class="n">ProcessingInstruction</span><span class="p">:</span>
  1774. <span class="o">...</span>
  1775. </pre></div>
  1776. </div>
  1777. <p>To generate XML output, you should call the <code class="xref py py-meth docutils literal notranslate"><span class="pre">ElementTree.write()</span></code> method.
  1778. Like <code class="xref py py-func docutils literal notranslate"><span class="pre">parse()</span></code>, it can take either a string or a file-like object:</p>
  1779. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Encoding is US-ASCII</span>
  1780. <span class="n">tree</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;output.xml&#39;</span><span class="p">)</span>
  1781. <span class="c1"># Encoding is UTF-8</span>
  1782. <span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;output.xml&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span>
  1783. <span class="n">tree</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="n">encoding</span><span class="o">=</span><span class="s1">&#39;utf-8&#39;</span><span class="p">)</span>
  1784. </pre></div>
  1785. </div>
  1786. <p>(Caution: the default encoding used for output is ASCII. For general XML work,
  1787. where an element’s name may contain arbitrary Unicode characters, ASCII isn’t a
  1788. very useful encoding because it will raise an exception if an element’s name
  1789. contains any characters with values greater than 127. Therefore, it’s best to
  1790. specify a different encoding such as UTF-8 that can handle any Unicode
  1791. character.)</p>
  1792. <p>This section is only a partial description of the ElementTree interfaces. Please
  1793. read the package’s official documentation for more details.</p>
  1794. <div class="admonition seealso">
  1795. <p class="admonition-title">See also</p>
  1796. <dl class="simple">
  1797. <dt><a class="reference external" href="https://web.archive.org/web/20201124024954/http://effbot.org/zone/element-index.htm">https://web.archive.org/web/20201124024954/http://effbot.org/zone/element-index.htm</a></dt><dd><p>Official documentation for ElementTree.</p>
  1798. </dd>
  1799. </dl>
  1800. </div>
  1801. </section>
  1802. <section id="the-hashlib-package">
  1803. <span id="module-hashlib"></span><h3>The hashlib package<a class="headerlink" href="#the-hashlib-package" title="Permalink to this headline">¶</a></h3>
  1804. <p>A new <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, written by Gregory P. Smith, has been added to
  1805. replace the <code class="xref py py-mod docutils literal notranslate"><span class="pre">md5</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">sha</span></code> modules. <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> adds support for
  1806. additional secure hashes (SHA-224, SHA-256, SHA-384, and SHA-512). When
  1807. available, the module uses OpenSSL for fast platform optimized implementations
  1808. of algorithms.</p>
  1809. <p>The old <code class="xref py py-mod docutils literal notranslate"><span class="pre">md5</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">sha</span></code> modules still exist as wrappers around hashlib
  1810. to preserve backwards compatibility. The new module’s interface is very close
  1811. to that of the old modules, but not identical. The most significant difference
  1812. is that the constructor functions for creating new hashing objects are named
  1813. differently.</p>
  1814. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Old versions</span>
  1815. <span class="n">h</span> <span class="o">=</span> <span class="n">md5</span><span class="o">.</span><span class="n">md5</span><span class="p">()</span>
  1816. <span class="n">h</span> <span class="o">=</span> <span class="n">md5</span><span class="o">.</span><span class="n">new</span><span class="p">()</span>
  1817. <span class="c1"># New version</span>
  1818. <span class="n">h</span> <span class="o">=</span> <span class="n">hashlib</span><span class="o">.</span><span class="n">md5</span><span class="p">()</span>
  1819. <span class="c1"># Old versions</span>
  1820. <span class="n">h</span> <span class="o">=</span> <span class="n">sha</span><span class="o">.</span><span class="n">sha</span><span class="p">()</span>
  1821. <span class="n">h</span> <span class="o">=</span> <span class="n">sha</span><span class="o">.</span><span class="n">new</span><span class="p">()</span>
  1822. <span class="c1"># New version</span>
  1823. <span class="n">h</span> <span class="o">=</span> <span class="n">hashlib</span><span class="o">.</span><span class="n">sha1</span><span class="p">()</span>
  1824. <span class="c1"># Hash that weren&#39;t previously available</span>
  1825. <span class="n">h</span> <span class="o">=</span> <span class="n">hashlib</span><span class="o">.</span><span class="n">sha224</span><span class="p">()</span>
  1826. <span class="n">h</span> <span class="o">=</span> <span class="n">hashlib</span><span class="o">.</span><span class="n">sha256</span><span class="p">()</span>
  1827. <span class="n">h</span> <span class="o">=</span> <span class="n">hashlib</span><span class="o">.</span><span class="n">sha384</span><span class="p">()</span>
  1828. <span class="n">h</span> <span class="o">=</span> <span class="n">hashlib</span><span class="o">.</span><span class="n">sha512</span><span class="p">()</span>
  1829. <span class="c1"># Alternative form</span>
  1830. <span class="n">h</span> <span class="o">=</span> <span class="n">hashlib</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="s1">&#39;md5&#39;</span><span class="p">)</span> <span class="c1"># Provide algorithm as a string</span>
  1831. </pre></div>
  1832. </div>
  1833. <p>Once a hash object has been created, its methods are the same as before:
  1834. <code class="docutils literal notranslate"><span class="pre">update(string)</span></code> hashes the specified string into the current digest
  1835. state, <code class="xref py py-meth docutils literal notranslate"><span class="pre">digest()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">hexdigest()</span></code> return the digest value as a binary
  1836. string or a string of hex digits, and <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> returns a new hashing object
  1837. with the same digest state.</p>
  1838. <div class="admonition seealso">
  1839. <p class="admonition-title">See also</p>
  1840. <p>The documentation for 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.</p>
  1841. </div>
  1842. </section>
  1843. <section id="the-sqlite3-package">
  1844. <span id="module-sqlite"></span><h3>The sqlite3 package<a class="headerlink" href="#the-sqlite3-package" title="Permalink to this headline">¶</a></h3>
  1845. <p>The pysqlite module (<a class="reference external" href="https://www.pysqlite.org">https://www.pysqlite.org</a>), a wrapper for the SQLite embedded
  1846. database, has been added to the standard library under the package name
  1847. <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>.</p>
  1848. <p>SQLite is a C library that provides a lightweight disk-based database that
  1849. doesn’t require a separate server process and allows accessing the database
  1850. using a nonstandard variant of the SQL query language. Some applications can use
  1851. SQLite for internal data storage. It’s also possible to prototype an
  1852. application using SQLite and then port the code to a larger database such as
  1853. PostgreSQL or Oracle.</p>
  1854. <p>pysqlite was written by Gerhard Häring and provides a SQL interface compliant
  1855. with the DB-API 2.0 specification described by <span class="target" id="index-24"></span><a class="pep reference external" href="https://peps.python.org/pep-0249/"><strong>PEP 249</strong></a>.</p>
  1856. <p>If you’re compiling the Python source yourself, note that the source tree
  1857. doesn’t include the SQLite code, only the wrapper module. You’ll need to have
  1858. the SQLite libraries and headers installed before compiling Python, and the
  1859. build process will compile the module when the necessary headers are available.</p>
  1860. <p>To use the module, you must first create a <code class="xref py py-class docutils literal notranslate"><span class="pre">Connection</span></code> object that
  1861. represents the database. Here the data will be stored in the
  1862. <code class="file docutils literal notranslate"><span class="pre">/tmp/example</span></code> file:</p>
  1863. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">conn</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s1">&#39;/tmp/example&#39;</span><span class="p">)</span>
  1864. </pre></div>
  1865. </div>
  1866. <p>You can also supply the special name <code class="docutils literal notranslate"><span class="pre">:memory:</span></code> to create a database in RAM.</p>
  1867. <p>Once you have a <code class="xref py py-class docutils literal notranslate"><span class="pre">Connection</span></code>, you can create a <code class="xref py py-class docutils literal notranslate"><span class="pre">Cursor</span></code> object
  1868. and call its <code class="xref py py-meth docutils literal notranslate"><span class="pre">execute()</span></code> method to perform SQL commands:</p>
  1869. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">c</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
  1870. <span class="c1"># Create table</span>
  1871. <span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">&#39;&#39;&#39;create table stocks</span>
  1872. <span class="s1">(date text, trans text, symbol text,</span>
  1873. <span class="s1"> qty real, price real)&#39;&#39;&#39;</span><span class="p">)</span>
  1874. <span class="c1"># Insert a row of data</span>
  1875. <span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;&quot;&quot;insert into stocks</span>
  1876. <span class="s2"> values (&#39;2006-01-05&#39;,&#39;BUY&#39;,&#39;RHAT&#39;,100,35.14)&quot;&quot;&quot;</span><span class="p">)</span>
  1877. </pre></div>
  1878. </div>
  1879. <p>Usually your SQL operations will need to use values from Python variables. You
  1880. shouldn’t assemble your query using Python’s string operations because doing so
  1881. is insecure; it makes your program vulnerable to an SQL injection attack.</p>
  1882. <p>Instead, use the DB-API’s parameter substitution. Put <code class="docutils literal notranslate"><span class="pre">?</span></code> as a placeholder
  1883. wherever you want to use a value, and then provide a tuple of values as the
  1884. second argument to the cursor’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">execute()</span></code> method. (Other database modules
  1885. may use a different placeholder, such as <code class="docutils literal notranslate"><span class="pre">%s</span></code> or <code class="docutils literal notranslate"><span class="pre">:1</span></code>.) For example:</p>
  1886. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Never do this -- insecure!</span>
  1887. <span class="n">symbol</span> <span class="o">=</span> <span class="s1">&#39;IBM&#39;</span>
  1888. <span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;... where symbol = &#39;</span><span class="si">%s</span><span class="s2">&#39;&quot;</span> <span class="o">%</span> <span class="n">symbol</span><span class="p">)</span>
  1889. <span class="c1"># Do this instead</span>
  1890. <span class="n">t</span> <span class="o">=</span> <span class="p">(</span><span class="n">symbol</span><span class="p">,)</span>
  1891. <span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">&#39;select * from stocks where symbol=?&#39;</span><span class="p">,</span> <span class="n">t</span><span class="p">)</span>
  1892. <span class="c1"># Larger example</span>
  1893. <span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="p">((</span><span class="s1">&#39;2006-03-28&#39;</span><span class="p">,</span> <span class="s1">&#39;BUY&#39;</span><span class="p">,</span> <span class="s1">&#39;IBM&#39;</span><span class="p">,</span> <span class="mi">1000</span><span class="p">,</span> <span class="mf">45.00</span><span class="p">),</span>
  1894. <span class="p">(</span><span class="s1">&#39;2006-04-05&#39;</span><span class="p">,</span> <span class="s1">&#39;BUY&#39;</span><span class="p">,</span> <span class="s1">&#39;MSOFT&#39;</span><span class="p">,</span> <span class="mi">1000</span><span class="p">,</span> <span class="mf">72.00</span><span class="p">),</span>
  1895. <span class="p">(</span><span class="s1">&#39;2006-04-06&#39;</span><span class="p">,</span> <span class="s1">&#39;SELL&#39;</span><span class="p">,</span> <span class="s1">&#39;IBM&#39;</span><span class="p">,</span> <span class="mi">500</span><span class="p">,</span> <span class="mf">53.00</span><span class="p">),</span>
  1896. <span class="p">):</span>
  1897. <span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">&#39;insert into stocks values (?,?,?,?,?)&#39;</span><span class="p">,</span> <span class="n">t</span><span class="p">)</span>
  1898. </pre></div>
  1899. </div>
  1900. <p>To retrieve data after executing a SELECT statement, you can either treat the
  1901. cursor as an iterator, call the cursor’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">fetchone()</span></code> method to retrieve a
  1902. single matching row, or call <code class="xref py py-meth docutils literal notranslate"><span class="pre">fetchall()</span></code> to get a list of the matching
  1903. rows.</p>
  1904. <p>This example uses the iterator form:</p>
  1905. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
  1906. <span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">&#39;select * from stocks order by price&#39;</span><span class="p">)</span>
  1907. <span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">c</span><span class="p">:</span>
  1908. <span class="gp">... </span> <span class="nb">print</span> <span class="n">row</span>
  1909. <span class="gp">...</span>
  1910. <span class="go">(u&#39;2006-01-05&#39;, u&#39;BUY&#39;, u&#39;RHAT&#39;, 100, 35.140000000000001)</span>
  1911. <span class="go">(u&#39;2006-03-28&#39;, u&#39;BUY&#39;, u&#39;IBM&#39;, 1000, 45.0)</span>
  1912. <span class="go">(u&#39;2006-04-06&#39;, u&#39;SELL&#39;, u&#39;IBM&#39;, 500, 53.0)</span>
  1913. <span class="go">(u&#39;2006-04-05&#39;, u&#39;BUY&#39;, u&#39;MSOFT&#39;, 1000, 72.0)</span>
  1914. <span class="gp">&gt;&gt;&gt;</span>
  1915. </pre></div>
  1916. </div>
  1917. <p>For more information about the SQL dialect supported by SQLite, see
  1918. <a class="reference external" href="https://www.sqlite.org">https://www.sqlite.org</a>.</p>
  1919. <div class="admonition seealso">
  1920. <p class="admonition-title">See also</p>
  1921. <dl class="simple">
  1922. <dt><a class="reference external" href="https://www.pysqlite.org">https://www.pysqlite.org</a></dt><dd><p>The pysqlite web page.</p>
  1923. </dd>
  1924. <dt><a class="reference external" href="https://www.sqlite.org">https://www.sqlite.org</a></dt><dd><p>The SQLite web page; the documentation describes the syntax and the available
  1925. data types for the supported SQL dialect.</p>
  1926. </dd>
  1927. </dl>
  1928. <p>The documentation for 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.</p>
  1929. <dl class="simple">
  1930. <dt><span class="target" id="index-25"></span><a class="pep reference external" href="https://peps.python.org/pep-0249/"><strong>PEP 249</strong></a> - Database API Specification 2.0</dt><dd><p>PEP written by Marc-André Lemburg.</p>
  1931. </dd>
  1932. </dl>
  1933. </div>
  1934. </section>
  1935. <section id="the-wsgiref-package">
  1936. <span id="module-wsgiref"></span><h3>The wsgiref package<a class="headerlink" href="#the-wsgiref-package" title="Permalink to this headline">¶</a></h3>
  1937. <p>The Web Server Gateway Interface (WSGI) v1.0 defines a standard interface
  1938. between web servers and Python web applications and is described in <span class="target" id="index-26"></span><a class="pep reference external" href="https://peps.python.org/pep-0333/"><strong>PEP 333</strong></a>.
  1939. The <a class="reference internal" href="../library/wsgiref.html#module-wsgiref" title="wsgiref: WSGI Utilities and Reference Implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">wsgiref</span></code></a> package is a reference implementation of the WSGI
  1940. specification.</p>
  1941. <p>The package includes a basic HTTP server that will run a WSGI application; this
  1942. server is useful for debugging but isn’t intended for production use. Setting
  1943. up a server takes only a few lines of code:</p>
  1944. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">wsgiref</span> <span class="kn">import</span> <span class="n">simple_server</span>
  1945. <span class="n">wsgi_app</span> <span class="o">=</span> <span class="o">...</span>
  1946. <span class="n">host</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>
  1947. <span class="n">port</span> <span class="o">=</span> <span class="mi">8000</span>
  1948. <span class="n">httpd</span> <span class="o">=</span> <span class="n">simple_server</span><span class="o">.</span><span class="n">make_server</span><span class="p">(</span><span class="n">host</span><span class="p">,</span> <span class="n">port</span><span class="p">,</span> <span class="n">wsgi_app</span><span class="p">)</span>
  1949. <span class="n">httpd</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>
  1950. </pre></div>
  1951. </div>
  1952. <div class="admonition seealso">
  1953. <p class="admonition-title">See also</p>
  1954. <dl class="simple">
  1955. <dt><a class="reference external" href="https://web.archive.org/web/20160331090247/http://wsgi.readthedocs.org/en/latest/">https://web.archive.org/web/20160331090247/http://wsgi.readthedocs.org/en/latest/</a></dt><dd><p>A central web site for WSGI-related resources.</p>
  1956. </dd>
  1957. <dt><span class="target" id="index-27"></span><a class="pep reference external" href="https://peps.python.org/pep-0333/"><strong>PEP 333</strong></a> - Python Web Server Gateway Interface v1.0</dt><dd><p>PEP written by Phillip J. Eby.</p>
  1958. </dd>
  1959. </dl>
  1960. </div>
  1961. </section>
  1962. </section>
  1963. <section id="build-and-c-api-changes">
  1964. <span id="build-api"></span><h2>Build and C API Changes<a class="headerlink" href="#build-and-c-api-changes" title="Permalink to this headline">¶</a></h2>
  1965. <p>Changes to Python’s build process and to the C API include:</p>
  1966. <ul>
  1967. <li><p>The Python source tree was converted from CVS to Subversion, in a complex
  1968. migration procedure that was supervised and flawlessly carried out by Martin von
  1969. Löwis. The procedure was developed as <span class="target" id="index-28"></span><a class="pep reference external" href="https://peps.python.org/pep-0347/"><strong>PEP 347</strong></a>.</p></li>
  1970. <li><p>Coverity, a company that markets a source code analysis tool called Prevent,
  1971. provided the results of their examination of the Python source code. The
  1972. analysis found about 60 bugs that were quickly fixed. Many of the bugs were
  1973. refcounting problems, often occurring in error-handling code. See
  1974. <a class="reference external" href="https://scan.coverity.com">https://scan.coverity.com</a> for the statistics.</p></li>
  1975. <li><p>The largest change to the C API came from <span class="target" id="index-29"></span><a class="pep reference external" href="https://peps.python.org/pep-0353/"><strong>PEP 353</strong></a>, which modifies the
  1976. interpreter to use a <a class="reference internal" href="../c-api/intro.html#c.Py_ssize_t" title="Py_ssize_t"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code></a> type definition instead of
  1977. <span class="c-expr sig sig-inline c"><span class="kt">int</span></span>. See the earlier section <a class="reference internal" href="#pep-353"><span class="std std-ref">PEP 353: Using ssize_t as the index type</span></a> for a discussion of this
  1978. change.</p></li>
  1979. <li><p>The design of the bytecode compiler has changed a great deal, no longer
  1980. generating bytecode by traversing the parse tree. Instead the parse tree is
  1981. converted to an abstract syntax tree (or AST), and it is the abstract syntax
  1982. tree that’s traversed to produce the bytecode.</p>
  1983. <p>It’s possible for Python code to obtain AST objects by using the
  1984. <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 and specifying <code class="docutils literal notranslate"><span class="pre">_ast.PyCF_ONLY_AST</span></code> as the value of
  1985. the <em>flags</em> parameter:</p>
  1986. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">_ast</span> <span class="kn">import</span> <span class="n">PyCF_ONLY_AST</span>
  1987. <span class="n">ast</span> <span class="o">=</span> <span class="nb">compile</span><span class="p">(</span><span class="s2">&quot;&quot;&quot;a=0</span>
  1988. <span class="s2">for i in range(10):</span>
  1989. <span class="s2"> a += i</span>
  1990. <span class="s2">&quot;&quot;&quot;</span><span class="p">,</span> <span class="s2">&quot;&lt;string&gt;&quot;</span><span class="p">,</span> <span class="s1">&#39;exec&#39;</span><span class="p">,</span> <span class="n">PyCF_ONLY_AST</span><span class="p">)</span>
  1991. <span class="n">assignment</span> <span class="o">=</span> <span class="n">ast</span><span class="o">.</span><span class="n">body</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
  1992. <span class="n">for_loop</span> <span class="o">=</span> <span class="n">ast</span><span class="o">.</span><span class="n">body</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>
  1993. </pre></div>
  1994. </div>
  1995. <p>No official documentation has been written for the AST code yet, but <span class="target" id="index-30"></span><a class="pep reference external" href="https://peps.python.org/pep-0339/"><strong>PEP 339</strong></a>
  1996. discusses the design. To start learning about the code, read the definition of
  1997. the various AST nodes in <code class="file docutils literal notranslate"><span class="pre">Parser/Python.asdl</span></code>. A Python script reads this
  1998. file and generates a set of C structure definitions in
  1999. <code class="file docutils literal notranslate"><span class="pre">Include/Python-ast.h</span></code>. The <code class="xref c c-func docutils literal notranslate"><span class="pre">PyParser_ASTFromString()</span></code> and
  2000. <code class="xref c c-func docutils literal notranslate"><span class="pre">PyParser_ASTFromFile()</span></code>, defined in <code class="file docutils literal notranslate"><span class="pre">Include/pythonrun.h</span></code>, take
  2001. Python source as input and return the root of an AST representing the contents.
  2002. This AST can then be turned into a code object by <code class="xref c c-func docutils literal notranslate"><span class="pre">PyAST_Compile()</span></code>. For
  2003. more information, read the source code, and then ask questions on python-dev.</p>
  2004. <p>The AST code was developed under Jeremy Hylton’s management, and implemented by
  2005. (in alphabetical order) Brett Cannon, Nick Coghlan, Grant Edwards, John
  2006. Ehresman, Kurt Kaiser, Neal Norwitz, Tim Peters, Armin Rigo, and Neil
  2007. Schemenauer, plus the participants in a number of AST sprints at conferences
  2008. such as PyCon.</p>
  2009. </li>
  2010. <li><p>Evan Jones’s patch to obmalloc, first described in a talk at PyCon DC 2005,
  2011. was applied. Python 2.4 allocated small objects in 256K-sized arenas, but never
  2012. freed arenas. With this patch, Python will free arenas when they’re empty. The
  2013. net effect is that on some platforms, when you allocate many objects, Python’s
  2014. memory usage may actually drop when you delete them and the memory may be
  2015. returned to the operating system. (Implemented by Evan Jones, and reworked by
  2016. Tim Peters.)</p>
  2017. <p>Note that this change means extension modules must be more careful when
  2018. allocating memory. Python’s API has many different functions for allocating
  2019. memory that are grouped into families. For example, <a class="reference internal" href="../c-api/memory.html#c.PyMem_Malloc" title="PyMem_Malloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_Malloc()</span></code></a>,
  2020. <a class="reference internal" href="../c-api/memory.html#c.PyMem_Realloc" title="PyMem_Realloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_Realloc()</span></code></a>, and <a class="reference internal" href="../c-api/memory.html#c.PyMem_Free" title="PyMem_Free"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_Free()</span></code></a> are one family that allocates
  2021. raw memory, while <a class="reference internal" href="../c-api/memory.html#c.PyObject_Malloc" title="PyObject_Malloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Malloc()</span></code></a>, <a class="reference internal" href="../c-api/memory.html#c.PyObject_Realloc" title="PyObject_Realloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Realloc()</span></code></a>, and
  2022. <a class="reference internal" href="../c-api/memory.html#c.PyObject_Free" title="PyObject_Free"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Free()</span></code></a> are another family that’s supposed to be used for
  2023. creating Python objects.</p>
  2024. <p>Previously these different families all reduced to the platform’s
  2025. <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code> functions. This meant it didn’t matter if
  2026. you got things wrong and allocated memory with the <code class="docutils literal notranslate"><span class="pre">PyMem</span></code> function but
  2027. freed it with the <code class="docutils literal notranslate"><span class="pre">PyObject</span></code> function. With 2.5’s changes to obmalloc,
  2028. these families now do different things and mismatches will probably result in a
  2029. segfault. You should carefully test your C extension modules with Python 2.5.</p>
  2030. </li>
  2031. <li><p>The built-in set types now have an official C API. Call <a class="reference internal" href="../c-api/set.html#c.PySet_New" title="PySet_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySet_New()</span></code></a>
  2032. and <a class="reference internal" href="../c-api/set.html#c.PyFrozenSet_New" title="PyFrozenSet_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyFrozenSet_New()</span></code></a> to create a new set, <a class="reference internal" href="../c-api/set.html#c.PySet_Add" title="PySet_Add"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySet_Add()</span></code></a> and
  2033. <a class="reference internal" href="../c-api/set.html#c.PySet_Discard" title="PySet_Discard"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySet_Discard()</span></code></a> to add and remove elements, and <a class="reference internal" href="../c-api/set.html#c.PySet_Contains" title="PySet_Contains"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySet_Contains()</span></code></a>
  2034. and <a class="reference internal" href="../c-api/set.html#c.PySet_Size" title="PySet_Size"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySet_Size()</span></code></a> to examine the set’s state. (Contributed by Raymond
  2035. Hettinger.)</p></li>
  2036. <li><p>C code can now obtain information about the exact revision of the Python
  2037. interpreter by calling the <a class="reference internal" href="../c-api/init.html#c.Py_GetBuildInfo" title="Py_GetBuildInfo"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_GetBuildInfo()</span></code></a> function that returns a
  2038. string of build information like this: <code class="docutils literal notranslate"><span class="pre">&quot;trunk:45355:45356M,</span> <span class="pre">Apr</span> <span class="pre">13</span> <span class="pre">2006,</span>
  2039. <span class="pre">07:42:19&quot;</span></code>. (Contributed by Barry Warsaw.)</p></li>
  2040. <li><p>Two new macros can be used to indicate C functions that are local to the
  2041. current file so that a faster calling convention can be used.
  2042. <code class="docutils literal notranslate"><span class="pre">Py_LOCAL(type)</span></code> declares the function as returning a value of the
  2043. specified <em>type</em> and uses a fast-calling qualifier.
  2044. <code class="docutils literal notranslate"><span class="pre">Py_LOCAL_INLINE(type)</span></code> does the same thing and also requests the
  2045. function be inlined. If macro <code class="xref c c-macro docutils literal notranslate"><span class="pre">PY_LOCAL_AGGRESSIVE</span></code> is defined before
  2046. <code class="file docutils literal notranslate"><span class="pre">python.h</span></code> is included, a set of more aggressive optimizations are enabled
  2047. for the module; you should benchmark the results to find out if these
  2048. optimizations actually make the code faster. (Contributed by Fredrik Lundh at
  2049. the NeedForSpeed sprint.)</p></li>
  2050. <li><p><code class="docutils literal notranslate"><span class="pre">PyErr_NewException(name,</span> <span class="pre">base,</span> <span class="pre">dict)</span></code> can now accept a tuple of base
  2051. classes as its <em>base</em> argument. (Contributed by Georg Brandl.)</p></li>
  2052. <li><p>The <code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Warn()</span></code> function for issuing warnings is now deprecated in
  2053. favour of <code class="docutils literal notranslate"><span class="pre">PyErr_WarnEx(category,</span> <span class="pre">message,</span> <span class="pre">stacklevel)</span></code> which lets you
  2054. specify the number of stack frames separating this function and the caller. A
  2055. <em>stacklevel</em> of 1 is the function calling <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_WarnEx" title="PyErr_WarnEx"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_WarnEx()</span></code></a>, 2 is the
  2056. function above that, and so forth. (Added by Neal Norwitz.)</p></li>
  2057. <li><p>The CPython interpreter is still written in C, but the code can now be
  2058. compiled with a C++ compiler without errors. (Implemented by Anthony Baxter,
  2059. Martin von Löwis, Skip Montanaro.)</p></li>
  2060. <li><p>The <code class="xref c c-func docutils literal notranslate"><span class="pre">PyRange_New()</span></code> function was removed. It was never documented, never
  2061. used in the core code, and had dangerously lax error checking. In the unlikely
  2062. case that your extensions were using it, you can replace it by something like
  2063. the following:</p>
  2064. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nb">range</span> <span class="o">=</span> <span class="n">PyObject_CallFunction</span><span class="p">((</span><span class="n">PyObject</span><span class="o">*</span><span class="p">)</span> <span class="o">&amp;</span><span class="n">PyRange_Type</span><span class="p">,</span> <span class="s2">&quot;lll&quot;</span><span class="p">,</span>
  2065. <span class="n">start</span><span class="p">,</span> <span class="n">stop</span><span class="p">,</span> <span class="n">step</span><span class="p">);</span>
  2066. </pre></div>
  2067. </div>
  2068. </li>
  2069. </ul>
  2070. <section id="port-specific-changes">
  2071. <span id="ports"></span><h3>Port-Specific Changes<a class="headerlink" href="#port-specific-changes" title="Permalink to this headline">¶</a></h3>
  2072. <ul class="simple">
  2073. <li><p>MacOS X (10.3 and higher): dynamic loading of modules now uses the
  2074. <code class="xref c c-func docutils literal notranslate"><span class="pre">dlopen()</span></code> function instead of MacOS-specific functions.</p></li>
  2075. <li><p>MacOS X: an <code class="xref std std-option docutils literal notranslate"><span class="pre">--enable-universalsdk</span></code> switch was added to the
  2076. <strong class="program">configure</strong> script that compiles the interpreter as a universal binary
  2077. able to run on both PowerPC and Intel processors. (Contributed by Ronald
  2078. Oussoren; <a class="reference external" href="https://bugs.python.org/issue?&#64;action=redirect&amp;bpo=2573">bpo-2573</a>.)</p></li>
  2079. <li><p>Windows: <code class="file docutils literal notranslate"><span class="pre">.dll</span></code> is no longer supported as a filename extension for
  2080. extension modules. <code class="file docutils literal notranslate"><span class="pre">.pyd</span></code> is now the only filename extension that will be
  2081. searched for.</p></li>
  2082. </ul>
  2083. </section>
  2084. </section>
  2085. <section id="porting-to-python-2-5">
  2086. <span id="porting"></span><h2>Porting to Python 2.5<a class="headerlink" href="#porting-to-python-2-5" title="Permalink to this headline">¶</a></h2>
  2087. <p>This section lists previously described changes that may require changes to your
  2088. code:</p>
  2089. <ul class="simple">
  2090. <li><p>ASCII is now the default encoding for modules. It’s now a syntax error if a
  2091. module contains string literals with 8-bit characters but doesn’t have an
  2092. encoding declaration. In Python 2.4 this triggered a warning, not a syntax
  2093. error.</p></li>
  2094. <li><p>Previously, the <code class="xref py py-attr docutils literal notranslate"><span class="pre">gi_frame</span></code> attribute of a generator was always a frame
  2095. object. Because of the <span class="target" id="index-31"></span><a class="pep reference external" href="https://peps.python.org/pep-0342/"><strong>PEP 342</strong></a> changes described in section <a class="reference internal" href="#pep-342"><span class="std std-ref">PEP 342: New Generator Features</span></a>,
  2096. it’s now possible for <code class="xref py py-attr docutils literal notranslate"><span class="pre">gi_frame</span></code> to be <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p></li>
  2097. <li><p>A new warning, <a class="reference internal" href="../library/exceptions.html#UnicodeWarning" title="UnicodeWarning"><code class="xref py py-class docutils literal notranslate"><span class="pre">UnicodeWarning</span></code></a>, is triggered when you attempt to
  2098. compare a Unicode string and an 8-bit string that can’t be converted to Unicode
  2099. using the default ASCII encoding. Previously such comparisons would raise a
  2100. <a class="reference internal" href="../library/exceptions.html#UnicodeDecodeError" title="UnicodeDecodeError"><code class="xref py py-class docutils literal notranslate"><span class="pre">UnicodeDecodeError</span></code></a> exception.</p></li>
  2101. <li><p>Library: the <a class="reference internal" href="../library/csv.html#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a> module is now stricter about multi-line quoted fields.
  2102. If your files contain newlines embedded within fields, the input should be split
  2103. into lines in a manner which preserves the newline characters.</p></li>
  2104. <li><p>Library: the <a class="reference internal" href="../library/locale.html#module-locale" title="locale: Internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">locale</span></code></a> module’s <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> function’s would
  2105. previously accept any string as long as no more than one %char specifier
  2106. appeared. In Python 2.5, the argument must be exactly one %char specifier with
  2107. no surrounding text.</p></li>
  2108. <li><p>Library: The <a class="reference internal" href="../library/pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code> modules no longer accept a
  2109. return value of <code class="docutils literal notranslate"><span class="pre">None</span></code> from the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce__()</span></code> method; the method must
  2110. return a tuple of arguments instead. The modules also no longer accept the
  2111. deprecated <em>bin</em> keyword parameter.</p></li>
  2112. <li><p>Library: The <code class="xref py py-mod docutils literal notranslate"><span class="pre">SimpleXMLRPCServer</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">DocXMLRPCServer</span></code> classes now
  2113. have a <code class="xref py py-attr docutils literal notranslate"><span class="pre">rpc_paths</span></code> attribute that constrains XML-RPC operations to a
  2114. limited set of URL paths; the default is to allow only <code class="docutils literal notranslate"><span class="pre">'/'</span></code> and <code class="docutils literal notranslate"><span class="pre">'/RPC2'</span></code>.
  2115. Setting <code class="xref py py-attr docutils literal notranslate"><span class="pre">rpc_paths</span></code> to <code class="docutils literal notranslate"><span class="pre">None</span></code> or an empty tuple disables this path
  2116. checking.</p></li>
  2117. <li><p>C API: Many functions now use <a class="reference internal" href="../c-api/intro.html#c.Py_ssize_t" title="Py_ssize_t"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code></a> instead of <span class="c-expr sig sig-inline c"><span class="kt">int</span></span> to
  2118. allow processing more data on 64-bit machines. Extension code may need to make
  2119. the same change to avoid warnings and to support 64-bit machines. See the
  2120. earlier section <a class="reference internal" href="#pep-353"><span class="std std-ref">PEP 353: Using ssize_t as the index type</span></a> for a discussion of this change.</p></li>
  2121. <li><p>C API: The obmalloc changes mean that you must be careful to not mix usage
  2122. of the <code class="docutils literal notranslate"><span class="pre">PyMem_*</span></code> and <code class="docutils literal notranslate"><span class="pre">PyObject_*</span></code> families of functions. Memory
  2123. allocated with one family’s <code class="docutils literal notranslate"><span class="pre">*_Malloc</span></code> must be freed with the
  2124. corresponding family’s <code class="docutils literal notranslate"><span class="pre">*_Free</span></code> function.</p></li>
  2125. </ul>
  2126. </section>
  2127. <section id="acknowledgements">
  2128. <h2>Acknowledgements<a class="headerlink" href="#acknowledgements" title="Permalink to this headline">¶</a></h2>
  2129. <p>The author would like to thank the following people for offering suggestions,
  2130. corrections and assistance with various drafts of this article: Georg Brandl,
  2131. Nick Coghlan, Phillip J. Eby, Lars Gustäbel, Raymond Hettinger, Ralf W.
  2132. Grosse-Kunstleve, Kent Johnson, Iain Lowe, Martin von Löwis, Fredrik Lundh, Andrew
  2133. McNamara, Skip Montanaro, Gustavo Niemeyer, Paul Prescod, James Pryor, Mike
  2134. Rovner, Scott Weikart, Barry Warsaw, Thomas Wouters.</p>
  2135. </section>
  2136. </section>
  2137. <div class="clearer"></div>
  2138. </div>
  2139. </div>
  2140. </div>
  2141. <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
  2142. <div class="sphinxsidebarwrapper">
  2143. <div>
  2144. <h3><a href="../contents.html">Table of Contents</a></h3>
  2145. <ul>
  2146. <li><a class="reference internal" href="#">What’s New in Python 2.5</a><ul>
  2147. <li><a class="reference internal" href="#pep-308-conditional-expressions">PEP 308: Conditional Expressions</a></li>
  2148. <li><a class="reference internal" href="#pep-309-partial-function-application">PEP 309: Partial Function Application</a></li>
  2149. <li><a class="reference internal" href="#pep-314-metadata-for-python-software-packages-v1-1">PEP 314: Metadata for Python Software Packages v1.1</a></li>
  2150. <li><a class="reference internal" href="#pep-328-absolute-and-relative-imports">PEP 328: Absolute and Relative Imports</a></li>
  2151. <li><a class="reference internal" href="#pep-338-executing-modules-as-scripts">PEP 338: Executing Modules as Scripts</a></li>
  2152. <li><a class="reference internal" href="#pep-341-unified-try-except-finally">PEP 341: Unified try/except/finally</a></li>
  2153. <li><a class="reference internal" href="#pep-342-new-generator-features">PEP 342: New Generator Features</a></li>
  2154. <li><a class="reference internal" href="#pep-343-the-with-statement">PEP 343: The ‘with’ statement</a><ul>
  2155. <li><a class="reference internal" href="#writing-context-managers">Writing Context Managers</a></li>
  2156. <li><a class="reference internal" href="#the-contextlib-module">The contextlib module</a></li>
  2157. </ul>
  2158. </li>
  2159. <li><a class="reference internal" href="#pep-352-exceptions-as-new-style-classes">PEP 352: Exceptions as New-Style Classes</a></li>
  2160. <li><a class="reference internal" href="#pep-353-using-ssize-t-as-the-index-type">PEP 353: Using ssize_t as the index type</a></li>
  2161. <li><a class="reference internal" href="#pep-357-the-index-method">PEP 357: The ‘__index__’ method</a></li>
  2162. <li><a class="reference internal" href="#other-language-changes">Other Language Changes</a><ul>
  2163. <li><a class="reference internal" href="#interactive-interpreter-changes">Interactive Interpreter Changes</a></li>
  2164. <li><a class="reference internal" href="#optimizations">Optimizations</a></li>
  2165. </ul>
  2166. </li>
  2167. <li><a class="reference internal" href="#new-improved-and-removed-modules">New, Improved, and Removed Modules</a><ul>
  2168. <li><a class="reference internal" href="#the-ctypes-package">The ctypes package</a></li>
  2169. <li><a class="reference internal" href="#the-elementtree-package">The ElementTree package</a></li>
  2170. <li><a class="reference internal" href="#the-hashlib-package">The hashlib package</a></li>
  2171. <li><a class="reference internal" href="#the-sqlite3-package">The sqlite3 package</a></li>
  2172. <li><a class="reference internal" href="#the-wsgiref-package">The wsgiref package</a></li>
  2173. </ul>
  2174. </li>
  2175. <li><a class="reference internal" href="#build-and-c-api-changes">Build and C API Changes</a><ul>
  2176. <li><a class="reference internal" href="#port-specific-changes">Port-Specific Changes</a></li>
  2177. </ul>
  2178. </li>
  2179. <li><a class="reference internal" href="#porting-to-python-2-5">Porting to Python 2.5</a></li>
  2180. <li><a class="reference internal" href="#acknowledgements">Acknowledgements</a></li>
  2181. </ul>
  2182. </li>
  2183. </ul>
  2184. </div>
  2185. <div>
  2186. <h4>Previous topic</h4>
  2187. <p class="topless"><a href="2.6.html"
  2188. title="previous chapter">What’s New in Python 2.6</a></p>
  2189. </div>
  2190. <div>
  2191. <h4>Next topic</h4>
  2192. <p class="topless"><a href="2.4.html"
  2193. title="next chapter">What’s New in Python 2.4</a></p>
  2194. </div>
  2195. <div role="note" aria-label="source link">
  2196. <h3>This Page</h3>
  2197. <ul class="this-page-menu">
  2198. <li><a href="../bugs.html">Report a Bug</a></li>
  2199. <li>
  2200. <a href="https://github.com/python/cpython/blob/main/Doc/whatsnew/2.5.rst"
  2201. rel="nofollow">Show Source
  2202. </a>
  2203. </li>
  2204. </ul>
  2205. </div>
  2206. </div>
  2207. </div>
  2208. <div class="clearer"></div>
  2209. </div>
  2210. <div class="related" role="navigation" aria-label="related navigation">
  2211. <h3>Navigation</h3>
  2212. <ul>
  2213. <li class="right" style="margin-right: 10px">
  2214. <a href="../genindex.html" title="General Index"
  2215. >index</a></li>
  2216. <li class="right" >
  2217. <a href="../py-modindex.html" title="Python Module Index"
  2218. >modules</a> |</li>
  2219. <li class="right" >
  2220. <a href="2.4.html" title="What’s New in Python 2.4"
  2221. >next</a> |</li>
  2222. <li class="right" >
  2223. <a href="2.6.html" title="What’s New in Python 2.6"
  2224. >previous</a> |</li>
  2225. <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  2226. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  2227. <li class="switchers">
  2228. <div class="language_switcher_placeholder"></div>
  2229. <div class="version_switcher_placeholder"></div>
  2230. </li>
  2231. <li>
  2232. </li>
  2233. <li id="cpython-language-and-version">
  2234. <a href="../index.html">3.12.0 Documentation</a> &#187;
  2235. </li>
  2236. <li class="nav-item nav-item-1"><a href="index.html" >What’s New in Python</a> &#187;</li>
  2237. <li class="nav-item nav-item-this"><a href="">What’s New in Python 2.5</a></li>
  2238. <li class="right">
  2239. <div class="inline-search" role="search">
  2240. <form class="inline-search" action="../search.html" method="get">
  2241. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  2242. <input type="submit" value="Go" />
  2243. </form>
  2244. </div>
  2245. |
  2246. </li>
  2247. <li class="right">
  2248. <label class="theme-selector-label">
  2249. Theme
  2250. <select class="theme-selector" oninput="activateTheme(this.value)">
  2251. <option value="auto" selected>Auto</option>
  2252. <option value="light">Light</option>
  2253. <option value="dark">Dark</option>
  2254. </select>
  2255. </label> |</li>
  2256. </ul>
  2257. </div>
  2258. <div class="footer">
  2259. &copy; <a href="../copyright.html">Copyright</a> 2001-2023, Python Software Foundation.
  2260. <br />
  2261. This page is licensed under the Python Software Foundation License Version 2.
  2262. <br />
  2263. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  2264. <br />
  2265. See <a href="/license.html">History and License</a> for more information.<br />
  2266. <br />
  2267. The Python Software Foundation is a non-profit corporation.
  2268. <a href="https://www.python.org/psf/donations/">Please donate.</a>
  2269. <br />
  2270. <br />
  2271. Last updated on Oct 02, 2023.
  2272. <a href="/bugs.html">Found a bug</a>?
  2273. <br />
  2274. Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 4.5.0.
  2275. </div>
  2276. </body>
  2277. </html>