Sophie

Sophie

distrib > Mandriva > 2010.1 > x86_64 > media > contrib-backports > by-pkgid > 3ba3bd1608c672ba2129b098a48e9e4d > files > 912

python3-docs-3.2.2-3mdv2010.2.noarch.rpm



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>What’s New in Python 2.5 &mdash; Python v3.2.2 documentation</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '3.2.2',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python v3.2.2 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python v3.2.2 documentation" href="../index.html" />
    <link rel="up" title="What’s New in Python" href="index.html" />
    <link rel="next" title="What’s New in Python 2.4" href="2.4.html" />
    <link rel="prev" title="What’s New in Python 2.6" href="2.6.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
 

  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="2.4.html" title="What’s New in Python 2.4"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="2.6.html" title="What’s New in Python 2.6"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="../index.html">Python v3.2.2 documentation</a> &raquo;</li>

          <li><a href="index.html" accesskey="U">What&#8217;s New in Python</a> &raquo;</li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="what-s-new-in-python-2-5">
<h1>What&#8217;s New in Python 2.5<a class="headerlink" href="#what-s-new-in-python-2-5" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field"><th class="field-name">Author:</th><td class="field-body">A.M. Kuchling</td>
</tr>
</tbody>
</table>
<p>This article explains the new features in Python 2.5.  The final release of
Python 2.5 is scheduled for August 2006; <span class="target" id="index-0"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0356"><strong>PEP 356</strong></a> describes the planned
release schedule.</p>
<p>The changes in Python 2.5 are an interesting mix of language and library
improvements. The library enhancements will be more important to Python&#8217;s user
community, I think, because several widely-useful packages were added.  New
modules include ElementTree for XML processing (<tt class="xref py py-mod docutils literal"><span class="pre">xml.etree</span></tt>),
the SQLite database module (<tt class="xref py py-mod docutils literal"><span class="pre">sqlite</span></tt>), and the <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a>
module for calling C functions.</p>
<p>The language changes are of middling significance.  Some pleasant new features
were added, but most of them aren&#8217;t features that you&#8217;ll use every day.
Conditional expressions were finally added to the language using a novel syntax;
see section <a class="reference internal" href="#pep-308"><em>PEP 308: Conditional Expressions</em></a>.  The new &#8216;<a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a>&#8216; statement will make
writing cleanup code easier (section <a class="reference internal" href="#pep-343"><em>PEP 343: The &#8216;with&#8217; statement</em></a>).  Values can now be passed
into generators (section <a class="reference internal" href="#pep-342"><em>PEP 342: New Generator Features</em></a>).  Imports are now visible as either
absolute or relative (section <a class="reference internal" href="#pep-328"><em>PEP 328: Absolute and Relative Imports</em></a>).  Some corner cases of exception
handling are handled better (section <a class="reference internal" href="#pep-341"><em>PEP 341: Unified try/except/finally</em></a>).  All these improvements
are worthwhile, but they&#8217;re improvements to one specific language feature or
another; none of them are broad modifications to Python&#8217;s semantics.</p>
<p>As well as the language and library additions, other improvements and bugfixes
were made throughout the source tree.  A search through the SVN change logs
finds there were 353 patches applied and 458 bugs fixed between Python 2.4 and
2.5.  (Both figures are likely to be underestimates.)</p>
<p>This article doesn&#8217;t try to be a complete specification of the new features;
instead changes are briefly introduced using helpful examples.  For full
details, you should always refer to the documentation for Python 2.5 at
<a class="reference external" href="http://docs.python.org">http://docs.python.org</a>. If you want to understand the complete implementation
and design rationale, refer to the PEP for a particular new feature.</p>
<p>Comments, suggestions, and error reports for this document are welcome; please
e-mail them to the author or open a bug in the Python bug tracker.</p>
<div class="section" id="pep-308-conditional-expressions">
<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>
<p>For a long time, people have been requesting a way to write conditional
expressions, which are expressions that return value A or value B depending on
whether a Boolean value is true or false.  A conditional expression lets you
write a single assignment statement that has the same effect as the following:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">if</span> <span class="n">condition</span><span class="p">:</span>
    <span class="n">x</span> <span class="o">=</span> <span class="n">true_value</span>
<span class="k">else</span><span class="p">:</span>
    <span class="n">x</span> <span class="o">=</span> <span class="n">false_value</span>
</pre></div>
</div>
<p>There have been endless tedious discussions of syntax on both python-dev and
comp.lang.python.  A vote was even held that found the majority of voters wanted
conditional expressions in some form, but there was no syntax that was preferred
by a clear majority. Candidates included C&#8217;s <tt class="docutils literal"><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></tt>, <tt class="docutils literal"><span class="pre">if</span>
<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></tt>, and 16 other variations.</p>
<p>Guido van Rossum eventually chose a surprising syntax:</p>
<div class="highlight-python3"><div class="highlight"><pre><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>
</pre></div>
</div>
<p>Evaluation is still lazy as in existing Boolean expressions, so the order of
evaluation jumps around a bit.  The <em>condition</em> expression in the middle is
evaluated first, and the <em>true_value</em> expression is evaluated only if the
condition was true.  Similarly, the <em>false_value</em> expression is only evaluated
when the condition is false.</p>
<p>This syntax may seem strange and backwards; why does the condition go in the
<em>middle</em> of the expression, and not in the front as in C&#8217;s <tt class="docutils literal"><span class="pre">c</span> <span class="pre">?</span> <span class="pre">x</span> <span class="pre">:</span> <span class="pre">y</span></tt>?  The
decision was checked by applying the new syntax to the modules in the standard
library and seeing how the resulting code read.  In many cases where a
conditional expression is used, one value seems to be the &#8216;common case&#8217; and one
value is an &#8216;exceptional case&#8217;, used only on rarer occasions when the condition
isn&#8217;t met.  The conditional syntax makes this pattern a bit more obvious:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">contents</span> <span class="o">=</span> <span class="p">((</span><span class="n">doc</span> <span class="o">+</span> <span class="s">&#39;</span><span class="se">\n</span><span class="s">&#39;</span><span class="p">)</span> <span class="k">if</span> <span class="n">doc</span> <span class="k">else</span> <span class="s">&#39;&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>I read the above statement as meaning &#8220;here <em>contents</em> is  usually assigned a
value of <tt class="docutils literal"><span class="pre">doc+'\n'</span></tt>; sometimes  <em>doc</em> is empty, in which special case an empty
string is returned.&#8221;   I doubt I will use conditional expressions very often
where there  isn&#8217;t a clear common and uncommon case.</p>
<p>There was some discussion of whether the language should require surrounding
conditional expressions with parentheses.  The decision was made to <em>not</em>
require parentheses in the Python language&#8217;s grammar, but as a matter of style I
think you should always use them. Consider these two statements:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="c"># First version -- no parens</span>
<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>

<span class="c"># Second version -- with parens</span>
<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>
</pre></div>
</div>
<p>In the first version, I think a reader&#8217;s eye might group the statement into
&#8216;level = 1&#8217;, &#8216;if logging&#8217;, &#8216;else 0&#8217;, and think that the condition decides
whether the assignment to <em>level</em> is performed.  The second version reads
better, in my opinion, because it makes it clear that the assignment is always
performed and the choice is being made between two values.</p>
<p>Another reason for including the brackets: a few odd combinations of list
comprehensions and lambdas could look like incorrect conditional expressions.
See <span class="target" id="index-1"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0308"><strong>PEP 308</strong></a> for some examples.  If you put parentheses around your
conditional expressions, you won&#8217;t run into this case.</p>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-2"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0308"><strong>PEP 308</strong></a> - Conditional Expressions</dt>
<dd>PEP written by Guido van Rossum and Raymond D. Hettinger; implemented by Thomas
Wouters.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-309-partial-function-application">
<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>
<p>The <a class="reference internal" href="../library/functools.html#module-functools" title="functools: Higher order functions and operations on callable objects."><tt class="xref py py-mod docutils literal"><span class="pre">functools</span></tt></a> module is intended to contain tools for functional-style
programming.</p>
<p>One useful tool in this module is the <tt class="xref py py-func docutils literal"><span class="pre">partial()</span></tt> function. For programs
written in a functional style, you&#8217;ll sometimes want to construct variants of
existing functions that have some of the parameters filled in.  Consider a
Python function <tt class="docutils literal"><span class="pre">f(a,</span> <span class="pre">b,</span> <span class="pre">c)</span></tt>; you could create a new function <tt class="docutils literal"><span class="pre">g(b,</span> <span class="pre">c)</span></tt> that
was equivalent to <tt class="docutils literal"><span class="pre">f(1,</span> <span class="pre">b,</span> <span class="pre">c)</span></tt>.  This is called &#8220;partial function
application&#8221;.</p>
<p><tt class="xref py py-func docutils literal"><span class="pre">partial()</span></tt> takes the arguments <tt class="docutils literal"><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>
<span class="pre">kwarg2=value2)</span></tt>.  The resulting object is callable, so you can just call it to
invoke <em>function</em> with the filled-in arguments.</p>
<p>Here&#8217;s a small but realistic example:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">functools</span>

<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>
    <span class="s">&quot;Write the contents of &#39;message&#39; to the specified subsystem.&quot;</span>
    <span class="nb">print</span> <span class="s">&#39;%s: %s&#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>
    <span class="o">...</span>

<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="s">&#39;server&#39;</span><span class="p">)</span>
<span class="n">server_log</span><span class="p">(</span><span class="s">&#39;Unable to open socket&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Here&#8217;s another example, from a program that uses PyGTK.  Here a context-
sensitive pop-up menu is being constructed dynamically.  The callback provided
for the menu option is a partially applied version of the <tt class="xref py py-meth docutils literal"><span class="pre">open_item()</span></tt>
method, where the first argument has been provided.</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="o">...</span>
<span class="k">class</span> <span class="nc">Application</span><span class="p">:</span>
    <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>
       <span class="o">...</span>
    <span class="k">def</span> <span class="nf">init</span> <span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <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>
        <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="s">&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>
</pre></div>
</div>
<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."><tt class="xref py py-mod docutils literal"><span class="pre">functools</span></tt></a> module is the
<tt class="xref py py-func docutils literal"><span class="pre">update_wrapper(wrapper,</span> <span class="pre">wrapped)()</span></tt> function that helps you write well-
behaved decorators.  <tt class="xref py py-func docutils literal"><span class="pre">update_wrapper()</span></tt> copies the name, module, and
docstring attribute to a wrapper function so that tracebacks inside the wrapped
function are easier to understand.  For example, you might write:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">def</span> <span class="nf">my_decorator</span><span class="p">(</span><span class="n">f</span><span class="p">):</span>
    <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>
        <span class="nb">print</span> <span class="s">&#39;Calling decorated function&#39;</span>
        <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>
    <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>
    <span class="k">return</span> <span class="n">wrapper</span>
</pre></div>
</div>
<p><tt class="xref py py-func docutils literal"><span class="pre">wraps()</span></tt> is a decorator that can be used inside your own decorators to copy
the wrapped function&#8217;s information.  An alternate  version of the previous
example would be:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">def</span> <span class="nf">my_decorator</span><span class="p">(</span><span class="n">f</span><span class="p">):</span>
    <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>
    <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>
        <span class="nb">print</span> <span class="s">&#39;Calling decorated function&#39;</span>
        <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>
    <span class="k">return</span> <span class="n">wrapper</span>
</pre></div>
</div>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-3"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0309"><strong>PEP 309</strong></a> - Partial Function Application</dt>
<dd>PEP proposed and written by Peter Harris; implemented by Hye-Shik Chang and Nick
Coghlan, with adaptations by Raymond Hettinger.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-314-metadata-for-python-software-packages-v1-1">
<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>
<p>Some simple dependency support was added to Distutils.  The <tt class="xref py py-func docutils literal"><span class="pre">setup()</span></tt>
function now has <tt class="docutils literal"><span class="pre">requires</span></tt>, <tt class="docutils literal"><span class="pre">provides</span></tt>, and <tt class="docutils literal"><span class="pre">obsoletes</span></tt> keyword
parameters.  When you build a source distribution using the <tt class="docutils literal"><span class="pre">sdist</span></tt> command,
the dependency information will be recorded in the <tt class="file docutils literal"><span class="pre">PKG-INFO</span></tt> file.</p>
<p>Another new keyword parameter is <tt class="docutils literal"><span class="pre">download_url</span></tt>, which should be set to a URL
for the package&#8217;s source code.  This means it&#8217;s now possible to look up an entry
in the package index, determine the dependencies for a package, and download the
required packages.</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">VERSION</span> <span class="o">=</span> <span class="s">&#39;1.0&#39;</span>
<span class="n">setup</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">&#39;PyPackage&#39;</span><span class="p">,</span>
      <span class="n">version</span><span class="o">=</span><span class="n">VERSION</span><span class="p">,</span>
      <span class="n">requires</span><span class="o">=</span><span class="p">[</span><span class="s">&#39;numarray&#39;</span><span class="p">,</span> <span class="s">&#39;zlib (&gt;=1.1.4)&#39;</span><span class="p">],</span>
      <span class="n">obsoletes</span><span class="o">=</span><span class="p">[</span><span class="s">&#39;OldPackage&#39;</span><span class="p">]</span>
      <span class="n">download_url</span><span class="o">=</span><span class="p">(</span><span class="s">&#39;http://www.example.com/pypackage/dist/pkg-%s.tar.gz&#39;</span>
                    <span class="o">%</span> <span class="n">VERSION</span><span class="p">),</span>
     <span class="p">)</span>
</pre></div>
</div>
<p>Another new enhancement to the Python package index at
<a class="reference external" href="http://cheeseshop.python.org">http://cheeseshop.python.org</a> is storing source and binary archives for a
package.  The new <strong class="command">upload</strong> Distutils command will upload a package to
the repository.</p>
<p>Before a package can be uploaded, you must be able to build a distribution using
the <strong class="command">sdist</strong> Distutils command.  Once that works, you can run <tt class="docutils literal"><span class="pre">python</span>
<span class="pre">setup.py</span> <span class="pre">upload</span></tt> to add your package to the PyPI archive.  Optionally you can
GPG-sign the package by supplying the <em class="xref std std-option">--sign</em> and <em class="xref std std-option">--identity</em>
options.</p>
<p>Package uploading was implemented by Martin von Löwis and Richard Jones.</p>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-4"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0314"><strong>PEP 314</strong></a> - Metadata for Python Software Packages v1.1</dt>
<dd>PEP proposed and written by A.M. Kuchling, Richard Jones, and Fred Drake;
implemented by Richard Jones and Fred Drake.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-328-absolute-and-relative-imports">
<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>
<p>The simpler part of PEP 328 was implemented in Python 2.4: parentheses could now
be used to enclose the names imported from a module using the <tt class="docutils literal"><span class="pre">from</span> <span class="pre">...</span> <span class="pre">import</span>
<span class="pre">...</span></tt> statement, making it easier to import many different names.</p>
<p>The more complicated part has been implemented in Python 2.5: importing a module
can be specified to use absolute or package-relative imports.  The plan is to
move toward making absolute imports the default in future versions of Python.</p>
<p>Let&#8217;s say you have a package directory like this:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">pkg</span><span class="o">/</span>
<span class="n">pkg</span><span class="o">/</span><span class="n">__init__</span><span class="o">.</span><span class="n">py</span>
<span class="n">pkg</span><span class="o">/</span><span class="n">main</span><span class="o">.</span><span class="n">py</span>
<span class="n">pkg</span><span class="o">/</span><span class="n">string</span><span class="o">.</span><span class="n">py</span>
</pre></div>
</div>
<p>This defines a package named <tt class="xref py py-mod docutils literal"><span class="pre">pkg</span></tt> containing the <tt class="xref py py-mod docutils literal"><span class="pre">pkg.main</span></tt> and
<tt class="xref py py-mod docutils literal"><span class="pre">pkg.string</span></tt> submodules.</p>
<p>Consider the code in the <tt class="file docutils literal"><span class="pre">main.py</span></tt> module.  What happens if it executes
the statement <tt class="docutils literal"><span class="pre">import</span> <span class="pre">string</span></tt>?  In Python 2.4 and earlier, it will first look
in the package&#8217;s directory to perform a relative import, finds
<tt class="file docutils literal"><span class="pre">pkg/string.py</span></tt>, imports the contents of that file as the
<tt class="xref py py-mod docutils literal"><span class="pre">pkg.string</span></tt> module, and that module is bound to the name <tt class="docutils literal"><span class="pre">string</span></tt> in the
<tt class="xref py py-mod docutils literal"><span class="pre">pkg.main</span></tt> module&#8217;s namespace.</p>
<p>That&#8217;s fine if <tt class="xref py py-mod docutils literal"><span class="pre">pkg.string</span></tt> was what you wanted.  But what if you wanted
Python&#8217;s standard <a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><tt class="xref py py-mod docutils literal"><span class="pre">string</span></tt></a> module?  There&#8217;s no clean way to ignore
<tt class="xref py py-mod docutils literal"><span class="pre">pkg.string</span></tt> and look for the standard module; generally you had to look at
the contents of <tt class="docutils literal"><span class="pre">sys.modules</span></tt>, which is slightly unclean.    Holger Krekel&#8217;s
<tt class="xref py py-mod docutils literal"><span class="pre">py.std</span></tt> package provides a tidier way to perform imports from the standard
library, <tt class="docutils literal"><span class="pre">import</span> <span class="pre">py</span> <span class="pre">;</span> <span class="pre">py.std.string.join()</span></tt>, but that package isn&#8217;t available
on all Python installations.</p>
<p>Reading code which relies on relative imports is also less clear, because a
reader may be confused about which module, <a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><tt class="xref py py-mod docutils literal"><span class="pre">string</span></tt></a> or <tt class="xref py py-mod docutils literal"><span class="pre">pkg.string</span></tt>,
is intended to be used.  Python users soon learned not to duplicate the names of
standard library modules in the names of their packages&#8217; submodules, but you
can&#8217;t protect against having your submodule&#8217;s name being used for a new module
added in a future version of Python.</p>
<p>In Python 2.5, you can switch <a class="reference internal" href="../reference/simple_stmts.html#import"><tt class="xref std std-keyword docutils literal"><span class="pre">import</span></tt></a>&#8216;s behaviour to  absolute imports
using a <tt class="docutils literal"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">absolute_import</span></tt> directive.  This absolute-
import behaviour will become the default in a future version (probably Python
2.7).  Once absolute imports  are the default, <tt class="docutils literal"><span class="pre">import</span> <span class="pre">string</span></tt> will always
find the standard library&#8217;s version. It&#8217;s suggested that users should begin
using absolute imports as much as possible, so it&#8217;s preferable to begin writing
<tt class="docutils literal"><span class="pre">from</span> <span class="pre">pkg</span> <span class="pre">import</span> <span class="pre">string</span></tt> in your code.</p>
<p>Relative imports are still possible by adding a leading period  to the module
name when using the <tt class="docutils literal"><span class="pre">from</span> <span class="pre">...</span> <span class="pre">import</span></tt> form:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="c"># Import names from pkg.string</span>
<span class="kn">from</span> <span class="nn">.string</span> <span class="k">import</span> <span class="n">name1</span><span class="p">,</span> <span class="n">name2</span>
<span class="c"># Import pkg.string</span>
<span class="kn">from</span> <span class="nn">.</span> <span class="k">import</span> <span class="n">string</span>
</pre></div>
</div>
<p>This imports the <a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><tt class="xref py py-mod docutils literal"><span class="pre">string</span></tt></a> module relative to the current package, so in
<tt class="xref py py-mod docutils literal"><span class="pre">pkg.main</span></tt> this will import <em>name1</em> and <em>name2</em> from <tt class="xref py py-mod docutils literal"><span class="pre">pkg.string</span></tt>.
Additional leading periods perform the relative import starting from the parent
of the current package.  For example, code in the <tt class="xref py py-mod docutils literal"><span class="pre">A.B.C</span></tt> module can do:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">.</span> <span class="k">import</span> <span class="n">D</span>                 <span class="c"># Imports A.B.D</span>
<span class="kn">from</span> <span class="nn">..</span> <span class="k">import</span> <span class="n">E</span>                <span class="c"># Imports A.E</span>
<span class="kn">from</span> <span class="nn">..F</span> <span class="k">import</span> <span class="n">G</span>               <span class="c"># Imports A.F.G</span>
</pre></div>
</div>
<p>Leading periods cannot be used with the <tt class="docutils literal"><span class="pre">import</span> <span class="pre">modname</span></tt>  form of the import
statement, only the <tt class="docutils literal"><span class="pre">from</span> <span class="pre">...</span> <span class="pre">import</span></tt> form.</p>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-5"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0328"><strong>PEP 328</strong></a> - Imports: Multi-Line and Absolute/Relative</dt>
<dd>PEP written by Aahz; implemented by Thomas Wouters.</dd>
<dt><a class="reference external" href="http://codespeak.net/py/current/doc/index.html">http://codespeak.net/py/current/doc/index.html</a></dt>
<dd>The py library by Holger Krekel, which contains the <tt class="xref py py-mod docutils literal"><span class="pre">py.std</span></tt> package.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-338-executing-modules-as-scripts">
<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>
<p>The <a class="reference internal" href="../using/cmdline.html#cmdoption-m"><em class="xref std std-option">-m</em></a> switch added in Python 2.4 to execute a module as a script
gained a few more abilities.  Instead of being implemented in C code inside the
Python interpreter, the switch now uses an implementation in a new module,
<a class="reference internal" href="../library/runpy.html#module-runpy" title="runpy: Locate and run Python modules without importing them first."><tt class="xref py py-mod docutils literal"><span class="pre">runpy</span></tt></a>.</p>
<p>The <a class="reference internal" href="../library/runpy.html#module-runpy" title="runpy: Locate and run Python modules without importing them first."><tt class="xref py py-mod docutils literal"><span class="pre">runpy</span></tt></a> module implements a more sophisticated import mechanism so that
it&#8217;s now possible to run modules in a package such as <tt class="xref py py-mod docutils literal"><span class="pre">pychecker.checker</span></tt>.
The module also supports alternative import mechanisms such as the
<a class="reference internal" href="../library/zipimport.html#module-zipimport" title="zipimport: support for importing Python modules from ZIP archives."><tt class="xref py py-mod docutils literal"><span class="pre">zipimport</span></tt></a> module.  This means you can add a .zip archive&#8217;s path to
<tt class="docutils literal"><span class="pre">sys.path</span></tt> and then use the <a class="reference internal" href="../using/cmdline.html#cmdoption-m"><em class="xref std std-option">-m</em></a> switch to execute code from the
archive.</p>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-6"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0338"><strong>PEP 338</strong></a> - Executing modules as scripts</dt>
<dd>PEP written and  implemented by Nick Coghlan.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-341-unified-try-except-finally">
<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>
<p>Until Python 2.5, the <a class="reference internal" href="../reference/compound_stmts.html#try"><tt class="xref std std-keyword docutils literal"><span class="pre">try</span></tt></a> statement came in two flavours. You could
use a <a class="reference internal" href="../reference/compound_stmts.html#finally"><tt class="xref std std-keyword docutils literal"><span class="pre">finally</span></tt></a> block to ensure that code is always executed, or one or
more <a class="reference internal" href="../reference/compound_stmts.html#except"><tt class="xref std std-keyword docutils literal"><span class="pre">except</span></tt></a> blocks to catch  specific exceptions.  You couldn&#8217;t
combine both <a class="reference internal" href="../reference/compound_stmts.html#except"><tt class="xref std std-keyword docutils literal"><span class="pre">except</span></tt></a> blocks and a <a class="reference internal" href="../reference/compound_stmts.html#finally"><tt class="xref std std-keyword docutils literal"><span class="pre">finally</span></tt></a> block, because
generating the right bytecode for the combined version was complicated and it
wasn&#8217;t clear what the semantics of the combined statement should be.</p>
<p>Guido van Rossum spent some time working with Java, which does support the
equivalent of combining <a class="reference internal" href="../reference/compound_stmts.html#except"><tt class="xref std std-keyword docutils literal"><span class="pre">except</span></tt></a> blocks and a <a class="reference internal" href="../reference/compound_stmts.html#finally"><tt class="xref std std-keyword docutils literal"><span class="pre">finally</span></tt></a> block,
and this clarified what the statement should mean.  In Python 2.5, you can now
write:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">try</span><span class="p">:</span>
    <span class="n">block</span><span class="o">-</span><span class="mi">1</span> <span class="o">...</span>
<span class="k">except</span> <span class="n">Exception1</span><span class="p">:</span>
    <span class="n">handler</span><span class="o">-</span><span class="mi">1</span> <span class="o">...</span>
<span class="k">except</span> <span class="n">Exception2</span><span class="p">:</span>
    <span class="n">handler</span><span class="o">-</span><span class="mi">2</span> <span class="o">...</span>
<span class="k">else</span><span class="p">:</span>
    <span class="k">else</span><span class="o">-</span><span class="n">block</span>
<span class="k">finally</span><span class="p">:</span>
    <span class="n">final</span><span class="o">-</span><span class="n">block</span>
</pre></div>
</div>
<p>The code in <em>block-1</em> is executed.  If the code raises an exception, the various
<a class="reference internal" href="../reference/compound_stmts.html#except"><tt class="xref std std-keyword docutils literal"><span class="pre">except</span></tt></a> blocks are tested: if the exception is of class
<tt class="xref py py-class docutils literal"><span class="pre">Exception1</span></tt>, <em>handler-1</em> is executed; otherwise if it&#8217;s of class
<tt class="xref py py-class docutils literal"><span class="pre">Exception2</span></tt>, <em>handler-2</em> is executed, and so forth.  If no exception is
raised, the <em>else-block</em> is executed.</p>
<p>No matter what happened previously, the <em>final-block</em> is executed once the code
block is complete and any raised exceptions handled. Even if there&#8217;s an error in
an exception handler or the <em>else-block</em> and a new exception is raised, the code
in the <em>final-block</em> is still run.</p>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-7"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0341"><strong>PEP 341</strong></a> - Unifying try-except and try-finally</dt>
<dd>PEP written by Georg Brandl;  implementation by Thomas Lee.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-342-new-generator-features">
<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>
<p>Python 2.5 adds a simple way to pass values <em>into</em> a generator. As introduced in
Python 2.3, generators only produce output; once a generator&#8217;s code was invoked
to create an iterator, there was no way to pass any new information into the
function when its execution is resumed.  Sometimes the ability to pass in some
information would be useful.  Hackish solutions to this include making the
generator&#8217;s code look at a global variable and then changing the global
variable&#8217;s value, or passing in some mutable object that callers then modify.</p>
<p>To refresh your memory of basic generators, here&#8217;s a simple example:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">def</span> <span class="nf">counter</span> <span class="p">(</span><span class="n">maximum</span><span class="p">):</span>
    <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="k">while</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">maximum</span><span class="p">:</span>
        <span class="k">yield</span> <span class="n">i</span>
        <span class="n">i</span> <span class="o">+=</span> <span class="mi">1</span>
</pre></div>
</div>
<p>When you call <tt class="docutils literal"><span class="pre">counter(10)</span></tt>, the result is an iterator that returns the values
from 0 up to 9.  On encountering the <a class="reference internal" href="../reference/simple_stmts.html#yield"><tt class="xref std std-keyword docutils literal"><span class="pre">yield</span></tt></a> statement, the iterator
returns the provided value and suspends the function&#8217;s execution, preserving the
local variables. Execution resumes on the following call to the iterator&#8217;s
<a class="reference internal" href="../library/functions.html#next" title="next"><tt class="xref py py-meth docutils literal"><span class="pre">next()</span></tt></a> method, picking up after the <a class="reference internal" href="../reference/simple_stmts.html#yield"><tt class="xref std std-keyword docutils literal"><span class="pre">yield</span></tt></a> statement.</p>
<p>In Python 2.3, <a class="reference internal" href="../reference/simple_stmts.html#yield"><tt class="xref std std-keyword docutils literal"><span class="pre">yield</span></tt></a> was a statement; it didn&#8217;t return any value.  In
2.5, <a class="reference internal" href="../reference/simple_stmts.html#yield"><tt class="xref std std-keyword docutils literal"><span class="pre">yield</span></tt></a> is now an expression, returning a value that can be
assigned to a variable or otherwise operated on:</p>
<div class="highlight-python3"><div class="highlight"><pre><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>
</pre></div>
</div>
<p>I recommend that you always put parentheses around a <a class="reference internal" href="../reference/simple_stmts.html#yield"><tt class="xref std std-keyword docutils literal"><span class="pre">yield</span></tt></a> expression
when you&#8217;re doing something with the returned value, as in the above example.
The parentheses aren&#8217;t always necessary, but it&#8217;s easier to always add them
instead of having to remember when they&#8217;re needed.</p>
<p>(<span class="target" id="index-8"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0342"><strong>PEP 342</strong></a> explains the exact rules, which are that a <a class="reference internal" href="../reference/simple_stmts.html#yield"><tt class="xref std std-keyword docutils literal"><span class="pre">yield</span></tt></a>-expression must always be parenthesized except when it occurs at the top-level
expression on the right-hand side of an assignment.  This means you can write
<tt class="docutils literal"><span class="pre">val</span> <span class="pre">=</span> <span class="pre">yield</span> <span class="pre">i</span></tt> but have to use parentheses when there&#8217;s an operation, as in
<tt class="docutils literal"><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></tt>.)</p>
<p>Values are sent into a generator by calling its <tt class="xref py py-meth docutils literal"><span class="pre">send(value)()</span></tt> method.  The
generator&#8217;s code is then resumed and the <a class="reference internal" href="../reference/simple_stmts.html#yield"><tt class="xref std std-keyword docutils literal"><span class="pre">yield</span></tt></a> expression returns the
specified <em>value</em>.  If the regular <a class="reference internal" href="../library/functions.html#next" title="next"><tt class="xref py py-meth docutils literal"><span class="pre">next()</span></tt></a> method is called, the
<a class="reference internal" href="../reference/simple_stmts.html#yield"><tt class="xref std std-keyword docutils literal"><span class="pre">yield</span></tt></a> returns <a class="reference internal" href="../library/constants.html#None" title="None"><tt class="xref py py-const xref docutils literal"><span class="pre">None</span></tt></a>.</p>
<p>Here&#8217;s the previous example, modified to allow changing the value of the
internal counter.</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">def</span> <span class="nf">counter</span> <span class="p">(</span><span class="n">maximum</span><span class="p">):</span>
    <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="k">while</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">maximum</span><span class="p">:</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>
        <span class="c"># If value provided, change counter</span>
        <span class="k">if</span> <span class="n">val</span> <span class="ow">is</span> <span class="ow">not</span> <span class="k">None</span><span class="p">:</span>
            <span class="n">i</span> <span class="o">=</span> <span class="n">val</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">i</span> <span class="o">+=</span> <span class="mi">1</span>
</pre></div>
</div>
<p>And here&#8217;s an example of changing the counter:</p>
<div class="highlight-python3"><div class="highlight"><pre><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>
<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>
<span class="go">0</span>
<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>
<span class="go">1</span>
<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>
<span class="go">8</span>
<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>
<span class="go">9</span>
<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>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;t.py&quot;</span>, line <span class="m">15</span>, in <span class="n-Identifier">?</span>
    <span class="nb">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="nc">StopIteration</span>
</pre></div>
</div>
<p><a class="reference internal" href="../reference/simple_stmts.html#yield"><tt class="xref std std-keyword docutils literal"><span class="pre">yield</span></tt></a> will usually return <a class="reference internal" href="../library/constants.html#None" title="None"><tt class="xref py py-const xref docutils literal"><span class="pre">None</span></tt></a>, so you should always check
for this case.  Don&#8217;t just use its value in expressions unless you&#8217;re sure that
the <tt class="xref py py-meth docutils literal"><span class="pre">send()</span></tt> method will be the only method used to resume your generator
function.</p>
<p>In addition to <tt class="xref py py-meth docutils literal"><span class="pre">send()</span></tt>, there are two other new methods on generators:</p>
<ul>
<li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">throw(type,</span> <span class="pre">value=None,</span> <span class="pre">traceback=None)()</span></tt> is used to raise an exception
inside the generator; the exception is raised by the <a class="reference internal" href="../reference/simple_stmts.html#yield"><tt class="xref std std-keyword docutils literal"><span class="pre">yield</span></tt></a> expression
where the generator&#8217;s execution is paused.</p>
</li>
<li><p class="first"><tt class="xref py py-meth docutils literal"><span class="pre">close()</span></tt> raises a new <a class="reference internal" href="../library/exceptions.html#GeneratorExit" title="GeneratorExit"><tt class="xref py py-exc docutils literal"><span class="pre">GeneratorExit</span></tt></a> exception inside the generator
to terminate the iteration.  On receiving this exception, the generator&#8217;s code
must either raise <a class="reference internal" href="../library/exceptions.html#GeneratorExit" title="GeneratorExit"><tt class="xref py py-exc docutils literal"><span class="pre">GeneratorExit</span></tt></a> or <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><tt class="xref py py-exc docutils literal"><span class="pre">StopIteration</span></tt></a>.  Catching the
<a class="reference internal" href="../library/exceptions.html#GeneratorExit" title="GeneratorExit"><tt class="xref py py-exc docutils literal"><span class="pre">GeneratorExit</span></tt></a> exception and returning a value is illegal and will trigger
a <a class="reference internal" href="../library/exceptions.html#RuntimeError" title="RuntimeError"><tt class="xref py py-exc docutils literal"><span class="pre">RuntimeError</span></tt></a>; if the function raises some other exception, that
exception is propagated to the caller.  <tt class="xref py py-meth docutils literal"><span class="pre">close()</span></tt> will also be called by
Python&#8217;s garbage collector when the generator is garbage-collected.</p>
<p>If you need to run cleanup code when a <a class="reference internal" href="../library/exceptions.html#GeneratorExit" title="GeneratorExit"><tt class="xref py py-exc docutils literal"><span class="pre">GeneratorExit</span></tt></a> occurs, I suggest
using a <tt class="docutils literal"><span class="pre">try:</span> <span class="pre">...</span> <span class="pre">finally:</span></tt> suite instead of  catching <a class="reference internal" href="../library/exceptions.html#GeneratorExit" title="GeneratorExit"><tt class="xref py py-exc docutils literal"><span class="pre">GeneratorExit</span></tt></a>.</p>
</li>
</ul>
<p>The cumulative effect of these changes is to turn generators from one-way
producers of information into both producers and consumers.</p>
<p>Generators also become <em>coroutines</em>, a more generalized form of subroutines.
Subroutines are entered at one point and exited at another point (the top of the
function, and a <a class="reference internal" href="../reference/simple_stmts.html#return"><tt class="xref std std-keyword docutils literal"><span class="pre">return</span></tt></a> statement), but coroutines can be entered,
exited, and resumed at many different points (the <a class="reference internal" href="../reference/simple_stmts.html#yield"><tt class="xref std std-keyword docutils literal"><span class="pre">yield</span></tt></a> statements).
We&#8217;ll have to figure out patterns for using coroutines effectively in Python.</p>
<p>The addition of the <tt class="xref py py-meth docutils literal"><span class="pre">close()</span></tt> method has one side effect that isn&#8217;t obvious.
<tt class="xref py py-meth docutils literal"><span class="pre">close()</span></tt> is called when a generator is garbage-collected, so this means the
generator&#8217;s code gets one last chance to run before the generator is destroyed.
This last chance means that <tt class="docutils literal"><span class="pre">try...finally</span></tt> statements in generators can now
be guaranteed to work; the <a class="reference internal" href="../reference/compound_stmts.html#finally"><tt class="xref std std-keyword docutils literal"><span class="pre">finally</span></tt></a> clause will now always get a
chance to run.  The syntactic restriction that you couldn&#8217;t mix <a class="reference internal" href="../reference/simple_stmts.html#yield"><tt class="xref std std-keyword docutils literal"><span class="pre">yield</span></tt></a>
statements with a <tt class="docutils literal"><span class="pre">try...finally</span></tt> suite has therefore been removed.  This
seems like a minor bit of language trivia, but using generators and
<tt class="docutils literal"><span class="pre">try...finally</span></tt> is actually necessary in order to implement the
<a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a> statement described by PEP 343.  I&#8217;ll look at this new statement
in the following  section.</p>
<p>Another even more esoteric effect of this change: previously, the
<tt class="xref py py-attr docutils literal"><span class="pre">gi_frame</span></tt> attribute of a generator was always a frame object. It&#8217;s now
possible for <tt class="xref py py-attr docutils literal"><span class="pre">gi_frame</span></tt> to be <tt class="xref docutils literal"><span class="pre">None</span></tt> once the generator has been
exhausted.</p>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-9"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0342"><strong>PEP 342</strong></a> - Coroutines via Enhanced Generators</dt>
<dd><p class="first">PEP written by  Guido van Rossum and Phillip J. Eby; implemented by Phillip J.
Eby.  Includes examples of  some fancier uses of generators as coroutines.</p>
<p class="last">Earlier versions of these features were proposed in  <span class="target" id="index-10"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0288"><strong>PEP 288</strong></a> by Raymond
Hettinger and <span class="target" id="index-11"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0325"><strong>PEP 325</strong></a> by Samuele Pedroni.</p>
</dd>
<dt><a class="reference external" href="http://en.wikipedia.org/wiki/Coroutine">http://en.wikipedia.org/wiki/Coroutine</a></dt>
<dd>The Wikipedia entry for  coroutines.</dd>
<dt><a class="reference external" href="http://www.sidhe.org/~dan/blog/archives/000178.html">http://www.sidhe.org/~dan/blog/archives/000178.html</a></dt>
<dd>An explanation of coroutines from a Perl point of view, written by Dan Sugalski.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-343-the-with-statement">
<span id="pep-343"></span><h2>PEP 343: The &#8216;with&#8217; statement<a class="headerlink" href="#pep-343-the-with-statement" title="Permalink to this headline">¶</a></h2>
<p>The &#8216;<a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a>&#8216; statement clarifies code that previously would use
<tt class="docutils literal"><span class="pre">try...finally</span></tt> blocks to ensure that clean-up code is executed.  In this
section, I&#8217;ll discuss the statement as it will commonly be used.  In the next
section, I&#8217;ll examine the implementation details and show how to write objects
for use with this statement.</p>
<p>The &#8216;<a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a>&#8216; statement is a new control-flow structure whose basic
structure is:</p>
<div class="highlight-python3"><div class="highlight"><pre><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>
    <span class="k">with</span><span class="o">-</span><span class="n">block</span>
</pre></div>
</div>
<p>The expression is evaluated, and it should result in an object that supports the
context management protocol (that is, has <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><tt class="xref py py-meth docutils literal"><span class="pre">__enter__()</span></tt></a> and <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><tt class="xref py py-meth docutils literal"><span class="pre">__exit__()</span></tt></a>
methods.</p>
<p>The object&#8217;s <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><tt class="xref py py-meth docutils literal"><span class="pre">__enter__()</span></tt></a> is called before <em>with-block</em> is executed and
therefore can run set-up code. It also may return a value that is bound to the
name <em>variable</em>, if given.  (Note carefully that <em>variable</em> is <em>not</em> assigned
the result of <em>expression</em>.)</p>
<p>After execution of the <em>with-block</em> is finished, the object&#8217;s <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><tt class="xref py py-meth docutils literal"><span class="pre">__exit__()</span></tt></a>
method is called, even if the block raised an exception, and can therefore run
clean-up code.</p>
<p>To enable the statement in Python 2.5, you need to add the following directive
to your module:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">__future__</span> <span class="k">import</span> <span class="n">with_statement</span>
</pre></div>
</div>
<p>The statement will always be enabled in Python 2.6.</p>
<p>Some standard Python objects now support the context management protocol and can
be used with the &#8216;<a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a>&#8216; statement. File objects are one example:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s">&#39;/etc/passwd&#39;</span><span class="p">,</span> <span class="s">&#39;r&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
        <span class="nb">print</span> <span class="n">line</span>
        <span class="o">...</span> <span class="n">more</span> <span class="n">processing</span> <span class="n">code</span> <span class="o">...</span>
</pre></div>
</div>
<p>After this statement has executed, the file object in <em>f</em> will have been
automatically closed, even if the <a class="reference internal" href="../reference/compound_stmts.html#for"><tt class="xref std std-keyword docutils literal"><span class="pre">for</span></tt></a> loop raised an exception part-
way through the block.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">In this case, <em>f</em> is the same object created by <a class="reference internal" href="../library/functions.html#open" title="open"><tt class="xref py py-func docutils literal"><span class="pre">open()</span></tt></a>, because
<tt class="xref py py-meth docutils literal"><span class="pre">file.__enter__()</span></tt> returns <em>self</em>.</p>
</div>
<p>The <a class="reference internal" href="../library/threading.html#module-threading" title="threading: Thread-based parallelism."><tt class="xref py py-mod docutils literal"><span class="pre">threading</span></tt></a> module&#8217;s locks and condition variables  also support the
&#8216;<a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a>&#8216; statement:</p>
<div class="highlight-python3"><div class="highlight"><pre><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>
<span class="k">with</span> <span class="n">lock</span><span class="p">:</span>
    <span class="c"># Critical section of code</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>The lock is acquired before the block is executed and always released once  the
block is complete.</p>
<p>The new <tt class="xref py py-func docutils literal"><span class="pre">localcontext()</span></tt> function in the <a class="reference internal" href="../library/decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic  Specification."><tt class="xref py py-mod docutils literal"><span class="pre">decimal</span></tt></a> module makes it easy
to save and restore the current decimal context, which encapsulates the desired
precision and rounding characteristics for computations:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">decimal</span> <span class="k">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>

<span class="c"># Displays with default precision of 28 digits</span>
<span class="n">v</span> <span class="o">=</span> <span class="n">Decimal</span><span class="p">(</span><span class="s">&#39;578&#39;</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">v</span><span class="o">.</span><span class="n">sqrt</span><span class="p">()</span>

<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>
    <span class="c"># All code in this block uses a precision of 16 digits.</span>
    <span class="c"># The original context is restored on exiting the block.</span>
    <span class="nb">print</span> <span class="n">v</span><span class="o">.</span><span class="n">sqrt</span><span class="p">()</span>
</pre></div>
</div>
<div class="section" id="writing-context-managers">
<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>
<p>Under the hood, the &#8216;<a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a>&#8216; statement is fairly complicated. Most
people will only use &#8216;<a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a>&#8216; in company with existing objects and
don&#8217;t need to know these details, so you can skip the rest of this section if
you like.  Authors of new objects will need to understand the details of the
underlying implementation and should keep reading.</p>
<p>A high-level explanation of the context management protocol is:</p>
<ul class="simple">
<li>The expression is evaluated and should result in an object called a &#8220;context
manager&#8221;.  The context manager must have <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><tt class="xref py py-meth docutils literal"><span class="pre">__enter__()</span></tt></a> and <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><tt class="xref py py-meth docutils literal"><span class="pre">__exit__()</span></tt></a>
methods.</li>
<li>The context manager&#8217;s <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><tt class="xref py py-meth docutils literal"><span class="pre">__enter__()</span></tt></a> method is called.  The value returned
is assigned to <em>VAR</em>.  If no <tt class="docutils literal"><span class="pre">'as</span> <span class="pre">VAR'</span></tt> clause is present, the value is simply
discarded.</li>
<li>The code in <em>BLOCK</em> is executed.</li>
<li>If <em>BLOCK</em> raises an exception, the <tt class="xref py py-meth docutils literal"><span class="pre">__exit__(type,</span> <span class="pre">value,</span> <span class="pre">traceback)()</span></tt>
is called with the exception details, the same values returned by
<a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><tt class="xref py py-func docutils literal"><span class="pre">sys.exc_info()</span></tt></a>.  The method&#8217;s return value controls whether the exception
is re-raised: any false value re-raises the exception, and <tt class="xref docutils literal"><span class="pre">True</span></tt> will result
in suppressing it.  You&#8217;ll only rarely want to suppress the exception, because
if you do the author of the code containing the &#8216;<a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a>&#8216; statement will
never realize anything went wrong.</li>
<li>If <em>BLOCK</em> didn&#8217;t raise an exception,  the <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><tt class="xref py py-meth docutils literal"><span class="pre">__exit__()</span></tt></a> method is still
called, but <em>type</em>, <em>value</em>, and <em>traceback</em> are all <tt class="xref docutils literal"><span class="pre">None</span></tt>.</li>
</ul>
<p>Let&#8217;s think through an example.  I won&#8217;t present detailed code but will only
sketch the methods necessary for a database that supports transactions.</p>
<p>(For people unfamiliar with database terminology: a set of changes to the
database are grouped into a transaction.  Transactions can be either committed,
meaning that all the changes are written into the database, or rolled back,
meaning that the changes are all discarded and the database is unchanged.  See
any database textbook for more information.)</p>
<p>Let&#8217;s assume there&#8217;s an object representing a database connection. Our goal will
be to let the user write code like this:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">db_connection</span> <span class="o">=</span> <span class="n">DatabaseConnection</span><span class="p">()</span>
<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>
    <span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&#39;insert into ...&#39;</span><span class="p">)</span>
    <span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&#39;delete from ...&#39;</span><span class="p">)</span>
    <span class="c"># ... more operations ...</span>
</pre></div>
</div>
<p>The transaction should be committed if the code in the block runs flawlessly or
rolled back if there&#8217;s an exception. Here&#8217;s the basic interface for
<tt class="xref py py-class docutils literal"><span class="pre">DatabaseConnection</span></tt> that I&#8217;ll assume:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">class</span> <span class="nc">DatabaseConnection</span><span class="p">:</span>
    <span class="c"># Database interface</span>
    <span class="k">def</span> <span class="nf">cursor</span> <span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="s">&quot;Returns a cursor object and starts a new transaction&quot;</span>
    <span class="k">def</span> <span class="nf">commit</span> <span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="s">&quot;Commits current transaction&quot;</span>
    <span class="k">def</span> <span class="nf">rollback</span> <span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="s">&quot;Rolls back current transaction&quot;</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><tt class="xref py py-meth docutils literal"><span class="pre">__enter__()</span></tt></a> method is pretty easy, having only to start a new
transaction.  For this application the resulting cursor object would be a useful
result, so the method will return it.  The user can then add <tt class="docutils literal"><span class="pre">as</span> <span class="pre">cursor</span></tt> to
their &#8216;<a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a>&#8216; statement to bind the cursor to a variable name.</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">class</span> <span class="nc">DatabaseConnection</span><span class="p">:</span>
    <span class="o">...</span>
    <span class="k">def</span> <span class="nf">__enter__</span> <span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c"># Code to start a new transaction</span>
        <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>
        <span class="k">return</span> <span class="n">cursor</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><tt class="xref py py-meth docutils literal"><span class="pre">__exit__()</span></tt></a> method is the most complicated because it&#8217;s where most of
the work has to be done.  The method has to check if an exception occurred.  If
there was no exception, the transaction is committed.  The transaction is rolled
back if there was an exception.</p>
<p>In the code below, execution will just fall off the end of the function,
returning the default value of <tt class="xref docutils literal"><span class="pre">None</span></tt>.  <tt class="xref docutils literal"><span class="pre">None</span></tt> is false, so the exception
will be re-raised automatically.  If you wished, you could be more explicit and
add a <a class="reference internal" href="../reference/simple_stmts.html#return"><tt class="xref std std-keyword docutils literal"><span class="pre">return</span></tt></a> statement at the marked location.</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">class</span> <span class="nc">DatabaseConnection</span><span class="p">:</span>
    <span class="o">...</span>
    <span class="k">def</span> <span class="nf">__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>
        <span class="k">if</span> <span class="n">tb</span> <span class="ow">is</span> <span class="k">None</span><span class="p">:</span>
            <span class="c"># No exception, so commit</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="c"># Exception occurred, so rollback.</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
            <span class="c"># return False</span>
</pre></div>
</div>
</div>
<div class="section" id="the-contextlib-module">
<span id="contextlibmod"></span><h3>The contextlib module<a class="headerlink" href="#the-contextlib-module" title="Permalink to this headline">¶</a></h3>
<p>The new <a class="reference internal" href="../library/contextlib.html#module-contextlib" title="contextlib: Utilities for with-statement contexts."><tt class="xref py py-mod docutils literal"><span class="pre">contextlib</span></tt></a> module provides some functions and a decorator that
are useful for writing objects for use with the &#8216;<a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a>&#8216; statement.</p>
<p>The decorator is called <tt class="xref py py-func docutils literal"><span class="pre">contextmanager()</span></tt>, and lets you write a single
generator function instead of defining a new class.  The generator should yield
exactly one value.  The code up to the <a class="reference internal" href="../reference/simple_stmts.html#yield"><tt class="xref std std-keyword docutils literal"><span class="pre">yield</span></tt></a> will be executed as the
<a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><tt class="xref py py-meth docutils literal"><span class="pre">__enter__()</span></tt></a> method, and the value yielded will be the method&#8217;s return
value that will get bound to the variable in the &#8216;<a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a>&#8216; statement&#8217;s
<a class="reference internal" href="../reference/compound_stmts.html#as"><tt class="xref std std-keyword docutils literal"><span class="pre">as</span></tt></a> clause, if any.  The code after the <a class="reference internal" href="../reference/simple_stmts.html#yield"><tt class="xref std std-keyword docutils literal"><span class="pre">yield</span></tt></a> will be
executed in the <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><tt class="xref py py-meth docutils literal"><span class="pre">__exit__()</span></tt></a> method.  Any exception raised in the block will
be raised by the <a class="reference internal" href="../reference/simple_stmts.html#yield"><tt class="xref std std-keyword docutils literal"><span class="pre">yield</span></tt></a> statement.</p>
<p>Our database example from the previous section could be written  using this
decorator as:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">contextlib</span> <span class="k">import</span> <span class="n">contextmanager</span>

<span class="nd">@contextmanager</span>
<span class="k">def</span> <span class="nf">db_transaction</span> <span class="p">(</span><span class="n">connection</span><span class="p">):</span>
    <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>
    <span class="k">try</span><span class="p">:</span>
        <span class="k">yield</span> <span class="n">cursor</span>
    <span class="k">except</span><span class="p">:</span>
        <span class="n">connection</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
        <span class="k">raise</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">connection</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>

<span class="n">db</span> <span class="o">=</span> <span class="n">DatabaseConnection</span><span class="p">()</span>
<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>
    <span class="o">...</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/contextlib.html#module-contextlib" title="contextlib: Utilities for with-statement contexts."><tt class="xref py py-mod docutils literal"><span class="pre">contextlib</span></tt></a> module also has a <tt class="xref py py-func docutils literal"><span class="pre">nested(mgr1,</span> <span class="pre">mgr2,</span> <span class="pre">...)()</span></tt> function
that combines a number of context managers so you don&#8217;t need to write nested
&#8216;<a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a>&#8216; statements.  In this example, the single &#8216;<a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a>&#8216;
statement both starts a database transaction and acquires a thread lock:</p>
<div class="highlight-python3"><div class="highlight"><pre><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>
<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>
    <span class="o">...</span>
</pre></div>
</div>
<p>Finally, the <tt class="xref py py-func docutils literal"><span class="pre">closing(object)()</span></tt> function returns <em>object</em> so that it can be
bound to a variable, and calls <tt class="docutils literal"><span class="pre">object.close</span></tt> at the end of the block.</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">urllib</span><span class="o">,</span> <span class="nn">sys</span>
<span class="kn">from</span> <span class="nn">contextlib</span> <span class="k">import</span> <span class="n">closing</span>

<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="s">&#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>
    <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
        <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>
</pre></div>
</div>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="docutils">
<dt><span class="target" id="index-12"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0343"><strong>PEP 343</strong></a> - The &#8220;with&#8221; statement</dt>
<dd>PEP written by Guido van Rossum and Nick Coghlan; implemented by Mike Bland,
Guido van Rossum, and Neal Norwitz.  The PEP shows the code generated for a
&#8216;<a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a>&#8216; statement, which can be helpful in learning how the statement
works.</dd>
</dl>
<p class="last">The documentation  for the <a class="reference internal" href="../library/contextlib.html#module-contextlib" title="contextlib: Utilities for with-statement contexts."><tt class="xref py py-mod docutils literal"><span class="pre">contextlib</span></tt></a> module.</p>
</div>
</div>
</div>
<div class="section" id="pep-352-exceptions-as-new-style-classes">
<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>
<p>Exception classes can now be new-style classes, not just classic classes, and
the built-in <a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><tt class="xref py py-exc docutils literal"><span class="pre">Exception</span></tt></a> class and all the standard built-in exceptions
(<a class="reference internal" href="../library/exceptions.html#NameError" title="NameError"><tt class="xref py py-exc docutils literal"><span class="pre">NameError</span></tt></a>, <a class="reference internal" href="../library/exceptions.html#ValueError" title="ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a>, etc.) are now new-style classes.</p>
<p>The inheritance hierarchy for exceptions has been rearranged a bit. In 2.5, the
inheritance relationships are:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="ne">BaseException</span>       <span class="c"># New in Python 2.5</span>
<span class="o">|-</span> <span class="ne">KeyboardInterrupt</span>
<span class="o">|-</span> <span class="ne">SystemExit</span>
<span class="o">|-</span> <span class="ne">Exception</span>
   <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>
</pre></div>
</div>
<p>This rearrangement was done because people often want to catch all exceptions
that indicate program errors.  <a class="reference internal" href="../library/exceptions.html#KeyboardInterrupt" title="KeyboardInterrupt"><tt class="xref py py-exc docutils literal"><span class="pre">KeyboardInterrupt</span></tt></a> and <a class="reference internal" href="../library/exceptions.html#SystemExit" title="SystemExit"><tt class="xref py py-exc docutils literal"><span class="pre">SystemExit</span></tt></a>
aren&#8217;t errors, though, and usually represent an explicit action such as the user
hitting Control-C or code calling <a class="reference internal" href="../library/sys.html#sys.exit" title="sys.exit"><tt class="xref py py-func docutils literal"><span class="pre">sys.exit()</span></tt></a>.  A bare <tt class="docutils literal"><span class="pre">except:</span></tt> will
catch all exceptions, so you commonly need to list <a class="reference internal" href="../library/exceptions.html#KeyboardInterrupt" title="KeyboardInterrupt"><tt class="xref py py-exc docutils literal"><span class="pre">KeyboardInterrupt</span></tt></a> and
<a class="reference internal" href="../library/exceptions.html#SystemExit" title="SystemExit"><tt class="xref py py-exc docutils literal"><span class="pre">SystemExit</span></tt></a> in order to re-raise them.  The usual pattern is:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">try</span><span class="p">:</span>
    <span class="o">...</span>
<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>
    <span class="k">raise</span>
<span class="k">except</span><span class="p">:</span>
    <span class="c"># Log error...</span>
    <span class="c"># Continue running program...</span>
</pre></div>
</div>
<p>In Python 2.5, you can now write <tt class="docutils literal"><span class="pre">except</span> <span class="pre">Exception</span></tt> to achieve the same
result, catching all the exceptions that usually indicate errors  but leaving
<a class="reference internal" href="../library/exceptions.html#KeyboardInterrupt" title="KeyboardInterrupt"><tt class="xref py py-exc docutils literal"><span class="pre">KeyboardInterrupt</span></tt></a> and <a class="reference internal" href="../library/exceptions.html#SystemExit" title="SystemExit"><tt class="xref py py-exc docutils literal"><span class="pre">SystemExit</span></tt></a> alone.  As in previous versions,
a bare <tt class="docutils literal"><span class="pre">except:</span></tt> still catches all exceptions.</p>
<p>The goal for Python 3.0 is to require any class raised as an exception to derive
from <a class="reference internal" href="../library/exceptions.html#BaseException" title="BaseException"><tt class="xref py py-exc docutils literal"><span class="pre">BaseException</span></tt></a> or some descendant of <a class="reference internal" href="../library/exceptions.html#BaseException" title="BaseException"><tt class="xref py py-exc docutils literal"><span class="pre">BaseException</span></tt></a>, and future
releases in the Python 2.x series may begin to enforce this constraint.
Therefore, I suggest you begin making all your exception classes derive from
<a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><tt class="xref py py-exc docutils literal"><span class="pre">Exception</span></tt></a> now.  It&#8217;s been suggested that the bare <tt class="docutils literal"><span class="pre">except:</span></tt> form should
be removed in Python 3.0, but Guido van Rossum hasn&#8217;t decided whether to do this
or not.</p>
<p>Raising of strings as exceptions, as in the statement <tt class="docutils literal"><span class="pre">raise</span> <span class="pre">&quot;Error</span>
<span class="pre">occurred&quot;</span></tt>, is deprecated in Python 2.5 and will trigger a warning.  The aim is
to be able to remove the string-exception feature in a few releases.</p>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-13"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0352"><strong>PEP 352</strong></a> - Required Superclass for Exceptions</dt>
<dd>PEP written by  Brett Cannon and Guido van Rossum; implemented by Brett Cannon.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-353-using-ssize-t-as-the-index-type">
<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>
<p>A wide-ranging change to Python&#8217;s C API, using a new  <tt class="xref c c-type docutils literal"><span class="pre">Py_ssize_t</span></tt> type
definition instead of <tt class="xref c c-type docutils literal"><span class="pre">int</span></tt>,  will permit the interpreter to handle more
data on 64-bit platforms. This change doesn&#8217;t affect Python&#8217;s capacity on 32-bit
platforms.</p>
<p>Various pieces of the Python interpreter used C&#8217;s <tt class="xref c c-type docutils literal"><span class="pre">int</span></tt> type to store
sizes or counts; for example, the number of items in a list or tuple were stored
in an <tt class="xref c c-type docutils literal"><span class="pre">int</span></tt>.  The C compilers for most 64-bit platforms still define
<tt class="xref c c-type docutils literal"><span class="pre">int</span></tt> as a 32-bit type, so that meant that lists could only hold up to
<tt class="docutils literal"><span class="pre">2**31</span> <span class="pre">-</span> <span class="pre">1</span></tt> = 2147483647 items. (There are actually a few different
programming models that 64-bit C compilers can use &#8211; see
<a class="reference external" href="http://www.unix.org/version2/whatsnew/lp64_wp.html">http://www.unix.org/version2/whatsnew/lp64_wp.html</a> for a discussion &#8211; but the
most commonly available model leaves <tt class="xref c c-type docutils literal"><span class="pre">int</span></tt> as 32 bits.)</p>
<p>A limit of 2147483647 items doesn&#8217;t really matter on a 32-bit platform because
you&#8217;ll run out of memory before hitting the length limit. Each list item
requires space for a pointer, which is 4 bytes, plus space for a
<a class="reference internal" href="../c-api/structures.html#PyObject" title="PyObject"><tt class="xref c c-type docutils literal"><span class="pre">PyObject</span></tt></a> representing the item.  2147483647*4 is already more bytes
than a 32-bit address space can contain.</p>
<p>It&#8217;s possible to address that much memory on a 64-bit platform, however.  The
pointers for a list that size would only require 16 GiB of space, so it&#8217;s not
unreasonable that Python programmers might construct lists that large.
Therefore, the Python interpreter had to be changed to use some type other than
<tt class="xref c c-type docutils literal"><span class="pre">int</span></tt>, and this will be a 64-bit type on 64-bit platforms.  The change
will cause incompatibilities on 64-bit machines, so it was deemed worth making
the transition now, while the number of 64-bit users is still relatively small.
(In 5 or 10 years, we may <em>all</em> be on 64-bit machines, and the transition would
be more painful then.)</p>
<p>This change most strongly affects authors of C extension modules.   Python
strings and container types such as lists and tuples  now use
<tt class="xref c c-type docutils literal"><span class="pre">Py_ssize_t</span></tt> to store their size.   Functions such as
<a class="reference internal" href="../c-api/list.html#PyList_Size" title="PyList_Size"><tt class="xref c c-func docutils literal"><span class="pre">PyList_Size()</span></tt></a>  now return <tt class="xref c c-type docutils literal"><span class="pre">Py_ssize_t</span></tt>.  Code in extension modules
may therefore need to have some variables changed to <tt class="xref c c-type docutils literal"><span class="pre">Py_ssize_t</span></tt>.</p>
<p>The <a class="reference internal" href="../c-api/arg.html#PyArg_ParseTuple" title="PyArg_ParseTuple"><tt class="xref c c-func docutils literal"><span class="pre">PyArg_ParseTuple()</span></tt></a> and <a class="reference internal" href="../c-api/arg.html#Py_BuildValue" title="Py_BuildValue"><tt class="xref c c-func docutils literal"><span class="pre">Py_BuildValue()</span></tt></a> functions have a new
conversion code, <tt class="docutils literal"><span class="pre">n</span></tt>, for <tt class="xref c c-type docutils literal"><span class="pre">Py_ssize_t</span></tt>.   <a class="reference internal" href="../c-api/arg.html#PyArg_ParseTuple" title="PyArg_ParseTuple"><tt class="xref c c-func docutils literal"><span class="pre">PyArg_ParseTuple()</span></tt></a>&#8216;s
<tt class="docutils literal"><span class="pre">s#</span></tt> and <tt class="docutils literal"><span class="pre">t#</span></tt> still output <tt class="xref c c-type docutils literal"><span class="pre">int</span></tt> by default, but you can define the
macro  <tt class="xref c c-macro docutils literal"><span class="pre">PY_SSIZE_T_CLEAN</span></tt> before including <tt class="file docutils literal"><span class="pre">Python.h</span></tt>  to make
them return <tt class="xref c c-type docutils literal"><span class="pre">Py_ssize_t</span></tt>.</p>
<p><span class="target" id="index-14"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0353"><strong>PEP 353</strong></a> has a section on conversion guidelines that  extension authors should
read to learn about supporting 64-bit platforms.</p>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-15"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0353"><strong>PEP 353</strong></a> - Using ssize_t as the index type</dt>
<dd>PEP written and implemented by Martin von Löwis.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-357-the-index-method">
<span id="pep-357"></span><h2>PEP 357: The &#8216;__index__&#8217; method<a class="headerlink" href="#pep-357-the-index-method" title="Permalink to this headline">¶</a></h2>
<p>The NumPy developers had a problem that could only be solved by adding a new
special method, <a class="reference internal" href="../reference/datamodel.html#object.__index__" title="object.__index__"><tt class="xref py py-meth docutils literal"><span class="pre">__index__()</span></tt></a>.  When using slice notation, as in
<tt class="docutils literal"><span class="pre">[start:stop:step]</span></tt>, the values of the <em>start</em>, <em>stop</em>, and <em>step</em> indexes
must all be either integers or long integers.  NumPy defines a variety of
specialized integer types corresponding to unsigned and signed integers of 8,
16, 32, and 64 bits, but there was no way to signal that these types could be
used as slice indexes.</p>
<p>Slicing can&#8217;t just use the existing <a class="reference internal" href="../reference/datamodel.html#object.__int__" title="object.__int__"><tt class="xref py py-meth docutils literal"><span class="pre">__int__()</span></tt></a> method because that method
is also used to implement coercion to integers.  If slicing used
<a class="reference internal" href="../reference/datamodel.html#object.__int__" title="object.__int__"><tt class="xref py py-meth docutils literal"><span class="pre">__int__()</span></tt></a>, floating-point numbers would also become legal slice indexes
and that&#8217;s clearly an undesirable behaviour.</p>
<p>Instead, a new special method called <a class="reference internal" href="../reference/datamodel.html#object.__index__" title="object.__index__"><tt class="xref py py-meth docutils literal"><span class="pre">__index__()</span></tt></a> was added.  It takes no
arguments and returns an integer giving the slice index to use.  For example:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__index__</span> <span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">value</span>
</pre></div>
</div>
<p>The return value must be either a Python integer or long integer. The
interpreter will check that the type returned is correct, and raises a
<a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></a> if this requirement isn&#8217;t met.</p>
<p>A corresponding <tt class="xref py py-attr docutils literal"><span class="pre">nb_index</span></tt> slot was added to the C-level
<a class="reference internal" href="../c-api/typeobj.html#PyNumberMethods" title="PyNumberMethods"><tt class="xref c c-type docutils literal"><span class="pre">PyNumberMethods</span></tt></a> structure to let C extensions implement this protocol.
<tt class="xref c c-func docutils literal"><span class="pre">PyNumber_Index(obj)()</span></tt> can be used in extension code to call the
<a class="reference internal" href="../reference/datamodel.html#object.__index__" title="object.__index__"><tt class="xref py py-meth docutils literal"><span class="pre">__index__()</span></tt></a> function and retrieve its result.</p>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-16"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0357"><strong>PEP 357</strong></a> - Allowing Any Object to be Used for Slicing</dt>
<dd>PEP written  and implemented by Travis Oliphant.</dd>
</dl>
</div>
</div>
<div class="section" id="other-language-changes">
<span id="other-lang"></span><h2>Other Language Changes<a class="headerlink" href="#other-language-changes" title="Permalink to this headline">¶</a></h2>
<p>Here are all of the changes that Python 2.5 makes to the core Python language.</p>
<ul>
<li><p class="first">The <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a> type has a new hook for letting subclasses provide a default
value when a key isn&#8217;t contained in the dictionary. When a key isn&#8217;t found, the
dictionary&#8217;s <tt class="xref py py-meth docutils literal"><span class="pre">__missing__(key)()</span></tt> method will be called.  This hook is used
to implement the new <tt class="xref py py-class docutils literal"><span class="pre">defaultdict</span></tt> class in the <a class="reference internal" href="../library/collections.html#module-collections" title="collections: Container datatypes"><tt class="xref py py-mod docutils literal"><span class="pre">collections</span></tt></a>
module.  The following example defines a dictionary  that returns zero for any
missing key:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">class</span> <span class="nc">zerodict</span> <span class="p">(</span><span class="nb">dict</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__missing__</span> <span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">):</span>
        <span class="k">return</span> <span class="mi">0</span>

<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>
<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="c"># Prints 1, 2</span>
<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="c"># Prints 0, 0</span>
</pre></div>
</div>
</li>
<li><p class="first">Both 8-bit and Unicode strings have new <tt class="xref py py-meth docutils literal"><span class="pre">partition(sep)()</span></tt>  and
<tt class="xref py py-meth docutils literal"><span class="pre">rpartition(sep)()</span></tt> methods that simplify a common use case.</p>
<p>The <tt class="xref py py-meth docutils literal"><span class="pre">find(S)()</span></tt> method is often used to get an index which is then used to
slice the string and obtain the pieces that are before and after the separator.
<tt class="xref py py-meth docutils literal"><span class="pre">partition(sep)()</span></tt> condenses this pattern into a single method call that
returns a 3-tuple containing the substring before the separator, the separator
itself, and the substring after the separator.  If the separator isn&#8217;t found,
the first element of the tuple is the entire string and the other two elements
are empty.  <tt class="xref py py-meth docutils literal"><span class="pre">rpartition(sep)()</span></tt> also returns a 3-tuple but starts searching
from the end of the string; the <tt class="docutils literal"><span class="pre">r</span></tt> stands for &#8216;reverse&#8217;.</p>
<p>Some examples:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="s">&#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="s">&#39;://&#39;</span><span class="p">)</span>
<span class="go">(&#39;http&#39;, &#39;://&#39;, &#39;www.python.org&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="s">&#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="s">&#39;://&#39;</span><span class="p">)</span>
<span class="go">(&#39;file:/usr/share/doc/index.html&#39;, &#39;&#39;, &#39;&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="s">u&#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="s">&#39;:&#39;</span><span class="p">)</span>
<span class="go">(u&#39;Subject&#39;, u&#39;:&#39;, u&#39; a quick question&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s">&#39;www.python.org&#39;</span><span class="o">.</span><span class="n">rpartition</span><span class="p">(</span><span class="s">&#39;.&#39;</span><span class="p">)</span>
<span class="go">(&#39;www.python&#39;, &#39;.&#39;, &#39;org&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s">&#39;www.python.org&#39;</span><span class="o">.</span><span class="n">rpartition</span><span class="p">(</span><span class="s">&#39;:&#39;</span><span class="p">)</span>
<span class="go">(&#39;&#39;, &#39;&#39;, &#39;www.python.org&#39;)</span>
</pre></div>
</div>
<p>(Implemented by Fredrik Lundh following a suggestion by Raymond Hettinger.)</p>
</li>
<li><p class="first">The <tt class="xref py py-meth docutils literal"><span class="pre">startswith()</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">endswith()</span></tt> methods of string types now accept
tuples of strings to check for.</p>
<div class="highlight-python3"><div class="highlight"><pre><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>
    <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="s">&#39;.gif&#39;</span><span class="p">,</span> <span class="s">&#39;.jpg&#39;</span><span class="p">,</span> <span class="s">&#39;.tiff&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>(Implemented by Georg Brandl following a suggestion by Tom Lynn.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/functions.html#min" title="min"><tt class="xref py py-func docutils literal"><span class="pre">min()</span></tt></a> and <a class="reference internal" href="../library/functions.html#max" title="max"><tt class="xref py py-func docutils literal"><span class="pre">max()</span></tt></a> built-in functions gained a <tt class="docutils literal"><span class="pre">key</span></tt> keyword
parameter analogous to the <tt class="docutils literal"><span class="pre">key</span></tt> argument for <tt class="xref py py-meth docutils literal"><span class="pre">sort()</span></tt>.  This parameter
supplies a function that takes a single argument and is called for every value
in the list; <a class="reference internal" href="../library/functions.html#min" title="min"><tt class="xref py py-func docutils literal"><span class="pre">min()</span></tt></a>/<a class="reference internal" href="../library/functions.html#max" title="max"><tt class="xref py py-func docutils literal"><span class="pre">max()</span></tt></a> will return the element with the
smallest/largest return value from this function. For example, to find the
longest string in a list, you can do:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="s">&#39;medium&#39;</span><span class="p">,</span> <span class="s">&#39;longest&#39;</span><span class="p">,</span> <span class="s">&#39;short&#39;</span><span class="p">]</span>
<span class="c"># Prints &#39;longest&#39;</span>
<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>
<span class="c"># Prints &#39;short&#39;, because lexicographically &#39;short&#39; has the largest value</span>
<span class="nb">print</span> <span class="nb">max</span><span class="p">(</span><span class="n">L</span><span class="p">)</span>
</pre></div>
</div>
<p>(Contributed by Steven Bethard and Raymond Hettinger.)</p>
</li>
<li><p class="first">Two new built-in functions, <a class="reference internal" href="../library/functions.html#any" title="any"><tt class="xref py py-func docutils literal"><span class="pre">any()</span></tt></a> and <a class="reference internal" href="../library/functions.html#all" title="all"><tt class="xref py py-func docutils literal"><span class="pre">all()</span></tt></a>, evaluate whether an
iterator contains any true or false values.  <a class="reference internal" href="../library/functions.html#any" title="any"><tt class="xref py py-func docutils literal"><span class="pre">any()</span></tt></a> returns <a class="reference internal" href="../library/constants.html#True" title="True"><tt class="xref py py-const xref docutils literal"><span class="pre">True</span></tt></a>
if any value returned by the iterator is true; otherwise it will return
<a class="reference internal" href="../library/constants.html#False" title="False"><tt class="xref py py-const xref docutils literal"><span class="pre">False</span></tt></a>.  <a class="reference internal" href="../library/functions.html#all" title="all"><tt class="xref py py-func docutils literal"><span class="pre">all()</span></tt></a> returns <a class="reference internal" href="../library/constants.html#True" title="True"><tt class="xref py py-const xref docutils literal"><span class="pre">True</span></tt></a> only if all of the values
returned by the iterator evaluate as true. (Suggested by Guido van Rossum, and
implemented by Raymond Hettinger.)</p>
</li>
<li><p class="first">The result of a class&#8217;s <a class="reference internal" href="../reference/datamodel.html#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a> method can now be either a long
integer or a regular integer.  If a long integer is returned, the hash of that
value is taken.  In earlier versions the hash value was required to be a
regular integer, but in 2.5 the <a class="reference internal" href="../library/functions.html#id" title="id"><tt class="xref py py-func docutils literal"><span class="pre">id()</span></tt></a> built-in was changed to always
return non-negative numbers, and users often seem to use <tt class="docutils literal"><span class="pre">id(self)</span></tt> in
<a class="reference internal" href="../reference/datamodel.html#object.__hash__" title="object.__hash__"><tt class="xref py py-meth docutils literal"><span class="pre">__hash__()</span></tt></a> methods (though this is discouraged).</p>
</li>
<li><p class="first">ASCII is now the default encoding for modules.  It&#8217;s now  a syntax error if a
module contains string literals with 8-bit characters but doesn&#8217;t have an
encoding declaration.  In Python 2.4 this triggered a warning, not a syntax
error.  See <span class="target" id="index-17"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0263"><strong>PEP 263</strong></a>  for how to declare a module&#8217;s encoding; for example, you
might add  a line like this near the top of the source file:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="c"># -*- coding: latin1 -*-</span>
</pre></div>
</div>
</li>
<li><p class="first">A new warning, <a class="reference internal" href="../library/exceptions.html#UnicodeWarning" title="UnicodeWarning"><tt class="xref py py-class docutils literal"><span class="pre">UnicodeWarning</span></tt></a>, is triggered when  you attempt to
compare a Unicode string and an 8-bit string  that can&#8217;t be converted to Unicode
using the default ASCII encoding.   The result of the comparison is false:</p>
<div class="highlight-python3"><div class="highlight"><pre><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="c"># Can&#39;t convert chr(128) to Unicode</span>
<span class="go">__main__:1: UnicodeWarning: Unicode equal comparison failed</span>
<span class="go">  to convert both arguments to Unicode - interpreting them</span>
<span class="go">  as being unequal</span>
<span class="go">False</span>
<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="c"># chr(127) can be converted</span>
<span class="go">True</span>
</pre></div>
</div>
<p>Previously this would raise a <a class="reference internal" href="../library/exceptions.html#UnicodeDecodeError" title="UnicodeDecodeError"><tt class="xref py py-class docutils literal"><span class="pre">UnicodeDecodeError</span></tt></a> exception, but in 2.5
this could result in puzzling problems when accessing a dictionary.  If you
looked up <tt class="docutils literal"><span class="pre">unichr(128)</span></tt> and <tt class="docutils literal"><span class="pre">chr(128)</span></tt> was being used as a key, you&#8217;d get a
<a class="reference internal" href="../library/exceptions.html#UnicodeDecodeError" title="UnicodeDecodeError"><tt class="xref py py-class docutils literal"><span class="pre">UnicodeDecodeError</span></tt></a> exception.  Other changes in 2.5 resulted in this
exception being raised instead of suppressed by the code in <tt class="file docutils literal"><span class="pre">dictobject.c</span></tt>
that implements dictionaries.</p>
<p>Raising an exception for such a comparison is strictly correct, but the change
might have broken code, so instead  <a class="reference internal" href="../library/exceptions.html#UnicodeWarning" title="UnicodeWarning"><tt class="xref py py-class docutils literal"><span class="pre">UnicodeWarning</span></tt></a> was introduced.</p>
<p>(Implemented by Marc-André Lemburg.)</p>
</li>
<li><p class="first">One error that Python programmers sometimes make is forgetting to include an
<tt class="file docutils literal"><span class="pre">__init__.py</span></tt> module in a package directory. Debugging this mistake can be
confusing, and usually requires running Python with the <a class="reference internal" href="../using/cmdline.html#cmdoption-v"><em class="xref std std-option">-v</em></a> switch to
log all the paths searched. In Python 2.5, a new <a class="reference internal" href="../library/exceptions.html#ImportWarning" title="ImportWarning"><tt class="xref py py-exc docutils literal"><span class="pre">ImportWarning</span></tt></a> warning is
triggered when an import would have picked up a directory as a package but no
<tt class="file docutils literal"><span class="pre">__init__.py</span></tt> was found.  This warning is silently ignored by default;
provide the <em class="xref std std-option">-Wd</em> option when running the Python executable to display
the warning message. (Implemented by Thomas Wouters.)</p>
</li>
<li><p class="first">The list of base classes in a class definition can now be empty.   As an
example, this is now legal:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">class</span> <span class="nc">C</span><span class="p">():</span>
    <span class="k">pass</span>
</pre></div>
</div>
<p>(Implemented by Brett Cannon.)</p>
</li>
</ul>
<div class="section" id="interactive-interpreter-changes">
<span id="interactive"></span><h3>Interactive Interpreter Changes<a class="headerlink" href="#interactive-interpreter-changes" title="Permalink to this headline">¶</a></h3>
<p>In the interactive interpreter, <tt class="docutils literal"><span class="pre">quit</span></tt> and <tt class="docutils literal"><span class="pre">exit</span></tt>  have long been strings so
that new users get a somewhat helpful message when they try to quit:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">quit</span>
<span class="go">&#39;Use Ctrl-D (i.e. EOF) to exit.&#39;</span>
</pre></div>
</div>
<p>In Python 2.5, <tt class="docutils literal"><span class="pre">quit</span></tt> and <tt class="docutils literal"><span class="pre">exit</span></tt> are now objects that still produce string
representations of themselves, but are also callable. Newbies who try <tt class="docutils literal"><span class="pre">quit()</span></tt>
or <tt class="docutils literal"><span class="pre">exit()</span></tt> will now exit the interpreter as they expect.  (Implemented by
Georg Brandl.)</p>
<p>The Python executable now accepts the standard long options  <a class="reference internal" href="../using/cmdline.html#cmdoption--help"><em class="xref std std-option">--help</em></a>
and <a class="reference internal" href="../using/cmdline.html#cmdoption--version"><em class="xref std std-option">--version</em></a>; on Windows,  it also accepts the <em class="xref std std-option">/?</em> option
for displaying a help message. (Implemented by Georg Brandl.)</p>
</div>
<div class="section" id="optimizations">
<span id="opts"></span><h3>Optimizations<a class="headerlink" href="#optimizations" title="Permalink to this headline">¶</a></h3>
<p>Several of the optimizations were developed at the NeedForSpeed sprint, an event
held in Reykjavik, Iceland, from May 21&#8211;28 2006. The sprint focused on speed
enhancements to the CPython implementation and was funded by EWT LLC with local
support from CCP Games.  Those optimizations added at this sprint are specially
marked in the following list.</p>
<ul class="simple">
<li>When they were introduced  in Python 2.4, the built-in <a class="reference internal" href="../library/stdtypes.html#set" title="set"><tt class="xref py py-class docutils literal"><span class="pre">set</span></tt></a> and
<a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><tt class="xref py py-class docutils literal"><span class="pre">frozenset</span></tt></a> types were built on top of Python&#8217;s dictionary type.   In 2.5
the internal data structure has been customized for implementing sets, and as a
result sets will use a third less memory and are somewhat faster. (Implemented
by Raymond Hettinger.)</li>
<li>The speed of some Unicode operations, such as finding substrings, string
splitting, and character map encoding and decoding, has been improved.
(Substring search and splitting improvements were added by Fredrik Lundh and
Andrew Dalke at the NeedForSpeed sprint. Character maps were improved by Walter
Dörwald and Martin von Löwis.)</li>
<li>The <tt class="xref py py-func docutils literal"><span class="pre">long(str,</span> <span class="pre">base)()</span></tt> function is now faster on long digit strings
because fewer intermediate results are calculated.  The peak is for strings of
around 800&#8211;1000 digits where  the function is 6 times faster. (Contributed by
Alan McIntyre and committed at the NeedForSpeed sprint.)</li>
<li>It&#8217;s now illegal to mix iterating over a file  with <tt class="docutils literal"><span class="pre">for</span> <span class="pre">line</span> <span class="pre">in</span> <span class="pre">file</span></tt> and
calling  the file object&#8217;s <tt class="xref py py-meth docutils literal"><span class="pre">read()</span></tt>/<a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><tt class="xref py py-meth docutils literal"><span class="pre">readline()</span></tt></a>/<tt class="xref py py-meth docutils literal"><span class="pre">readlines()</span></tt>
methods.  Iteration uses an internal buffer and the  <tt class="xref py py-meth docutils literal"><span class="pre">read*()</span></tt> methods
don&#8217;t use that buffer.   Instead they would return the data following the
buffer, causing the data to appear out of order.  Mixing iteration and these
methods will now trigger a <a class="reference internal" href="../library/exceptions.html#ValueError" title="ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a> from the <tt class="xref py py-meth docutils literal"><span class="pre">read*()</span></tt> method.
(Implemented by Thomas Wouters.)</li>
<li>The <a class="reference internal" href="../library/struct.html#module-struct" title="struct: Interpret bytes as packed binary data."><tt class="xref py py-mod docutils literal"><span class="pre">struct</span></tt></a> module now compiles structure format  strings into an
internal representation and caches this representation, yielding a 20% speedup.
(Contributed by Bob Ippolito at the NeedForSpeed sprint.)</li>
<li>The <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><tt class="xref py py-mod docutils literal"><span class="pre">re</span></tt></a> module got a 1 or 2% speedup by switching to  Python&#8217;s allocator
functions instead of the system&#8217;s  <tt class="xref c c-func docutils literal"><span class="pre">malloc()</span></tt> and <tt class="xref c c-func docutils literal"><span class="pre">free()</span></tt>.
(Contributed by Jack Diederich at the NeedForSpeed sprint.)</li>
<li>The code generator&#8217;s peephole optimizer now performs simple constant folding
in expressions.  If you write something like <tt class="docutils literal"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">2+3</span></tt>, the code generator
will do the arithmetic and produce code corresponding to <tt class="docutils literal"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">5</span></tt>.  (Proposed
and implemented  by Raymond Hettinger.)</li>
<li>Function calls are now faster because code objects now keep  the most recently
finished frame (a &#8220;zombie frame&#8221;) in an internal field of the code object,
reusing it the next time the code object is invoked.  (Original patch by Michael
Hudson, modified by Armin Rigo and Richard Jones; committed at the NeedForSpeed
sprint.)  Frame objects are also slightly smaller, which may improve cache
locality and reduce memory usage a bit.  (Contributed by Neal Norwitz.)</li>
<li>Python&#8217;s built-in exceptions are now new-style classes, a change that speeds
up instantiation considerably.  Exception handling in Python 2.5 is therefore
about 30% faster than in 2.4. (Contributed by Richard Jones, Georg Brandl and
Sean Reifschneider at the NeedForSpeed sprint.)</li>
<li>Importing now caches the paths tried, recording whether  they exist or not so
that the interpreter makes fewer  <tt class="xref c c-func docutils literal"><span class="pre">open()</span></tt> and <tt class="xref c c-func docutils literal"><span class="pre">stat()</span></tt> calls on
startup. (Contributed by Martin von Löwis and Georg Brandl.)</li>
</ul>
</div>
</div>
<div class="section" id="new-improved-and-removed-modules">
<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>
<p>The standard library received many enhancements and bug fixes in Python 2.5.
Here&#8217;s a partial list of the most notable changes, sorted alphabetically by
module name. Consult the <tt class="file docutils literal"><span class="pre">Misc/NEWS</span></tt> file in the source tree for a more
complete list of changes, or look through the SVN logs for all the details.</p>
<ul>
<li><p class="first">The <a class="reference internal" href="../library/audioop.html#module-audioop" title="audioop: Manipulate raw audio data."><tt class="xref py py-mod docutils literal"><span class="pre">audioop</span></tt></a> module now supports the a-LAW encoding, and the code for
u-LAW encoding has been improved.  (Contributed by Lars Immisch.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/codecs.html#module-codecs" title="codecs: Encode and decode data and streams."><tt class="xref py py-mod docutils literal"><span class="pre">codecs</span></tt></a> module gained support for incremental codecs.  The
<tt class="xref py py-func docutils literal"><span class="pre">codec.lookup()</span></tt> function now returns a <tt class="xref py py-class docutils literal"><span class="pre">CodecInfo</span></tt> instance instead
of a tuple. <tt class="xref py py-class docutils literal"><span class="pre">CodecInfo</span></tt> instances behave like a 4-tuple to preserve
backward compatibility but also have the attributes <tt class="xref py py-attr docutils literal"><span class="pre">encode</span></tt>,
<tt class="xref py py-attr docutils literal"><span class="pre">decode</span></tt>, <tt class="xref py py-attr docutils literal"><span class="pre">incrementalencoder</span></tt>, <tt class="xref py py-attr docutils literal"><span class="pre">incrementaldecoder</span></tt>,
<tt class="xref py py-attr docutils literal"><span class="pre">streamwriter</span></tt>, and <tt class="xref py py-attr docutils literal"><span class="pre">streamreader</span></tt>.  Incremental codecs  can receive
input and produce output in multiple chunks; the output is the same as if the
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."><tt class="xref py py-mod docutils literal"><span class="pre">codecs</span></tt></a> module
documentation for details. (Designed and implemented by Walter Dörwald.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/collections.html#module-collections" title="collections: Container datatypes"><tt class="xref py py-mod docutils literal"><span class="pre">collections</span></tt></a> module gained a new type, <tt class="xref py py-class docutils literal"><span class="pre">defaultdict</span></tt>, that
subclasses the standard <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a> type.  The new type mostly behaves like a
dictionary but constructs a default value when a key isn&#8217;t present,
automatically adding it to the dictionary for the requested key value.</p>
<p>The first argument to <tt class="xref py py-class docutils literal"><span class="pre">defaultdict</span></tt>&#8216;s constructor is a factory function
that gets called whenever a key is requested but not found. This factory
function receives no arguments, so you can use built-in type constructors such
as <a class="reference internal" href="../library/functions.html#list" title="list"><tt class="xref py py-func docutils literal"><span class="pre">list()</span></tt></a> or <a class="reference internal" href="../library/functions.html#int" title="int"><tt class="xref py py-func docutils literal"><span class="pre">int()</span></tt></a>.  For example,  you can make an index of words
based on their initial letter like this:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">words</span> <span class="o">=</span> <span class="s">&quot;&quot;&quot;Nel mezzo del cammin di nostra vita</span>
<span class="s">mi ritrovai per una selva oscura</span>
<span class="s">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>

<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>

<span class="k">for</span> <span class="n">w</span> <span class="ow">in</span> <span class="n">words</span><span class="p">:</span>
    <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>
    <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>
</pre></div>
</div>
<p>Printing <tt class="docutils literal"><span class="pre">index</span></tt> results in the following output:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">defaultdict</span><span class="p">(</span><span class="o">&lt;</span><span class="nb">type</span> <span class="s">&#39;list&#39;</span><span class="o">&gt;</span><span class="p">,</span> <span class="p">{</span><span class="s">&#39;c&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s">&#39;cammin&#39;</span><span class="p">,</span> <span class="s">&#39;che&#39;</span><span class="p">],</span> <span class="s">&#39;e&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s">&#39;era&#39;</span><span class="p">],</span>
        <span class="s">&#39;d&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s">&#39;del&#39;</span><span class="p">,</span> <span class="s">&#39;di&#39;</span><span class="p">,</span> <span class="s">&#39;diritta&#39;</span><span class="p">],</span> <span class="s">&#39;m&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s">&#39;mezzo&#39;</span><span class="p">,</span> <span class="s">&#39;mi&#39;</span><span class="p">],</span>
        <span class="s">&#39;l&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s">&#39;la&#39;</span><span class="p">],</span> <span class="s">&#39;o&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s">&#39;oscura&#39;</span><span class="p">],</span> <span class="s">&#39;n&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s">&#39;nel&#39;</span><span class="p">,</span> <span class="s">&#39;nostra&#39;</span><span class="p">],</span>
        <span class="s">&#39;p&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s">&#39;per&#39;</span><span class="p">],</span> <span class="s">&#39;s&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s">&#39;selva&#39;</span><span class="p">,</span> <span class="s">&#39;smarrita&#39;</span><span class="p">],</span>
        <span class="s">&#39;r&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s">&#39;ritrovai&#39;</span><span class="p">],</span> <span class="s">&#39;u&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s">&#39;una&#39;</span><span class="p">],</span> <span class="s">&#39;v&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s">&#39;vita&#39;</span><span class="p">,</span> <span class="s">&#39;via&#39;</span><span class="p">]}</span>
</pre></div>
</div>
<p>(Contributed by Guido van Rossum.)</p>
</li>
<li><p class="first">The <tt class="xref py py-class docutils literal"><span class="pre">deque</span></tt> double-ended queue type supplied by the <a class="reference internal" href="../library/collections.html#module-collections" title="collections: Container datatypes"><tt class="xref py py-mod docutils literal"><span class="pre">collections</span></tt></a>
module now has a <tt class="xref py py-meth docutils literal"><span class="pre">remove(value)()</span></tt> method that removes the first occurrence
of <em>value</em> in the queue, raising <a class="reference internal" href="../library/exceptions.html#ValueError" title="ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a> if the value isn&#8217;t found.
(Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">New module: The <a class="reference internal" href="../library/contextlib.html#module-contextlib" title="contextlib: Utilities for with-statement contexts."><tt class="xref py py-mod docutils literal"><span class="pre">contextlib</span></tt></a> module contains helper functions for use
with the new &#8216;<a class="reference internal" href="../reference/compound_stmts.html#with"><tt class="xref std std-keyword docutils literal"><span class="pre">with</span></tt></a>&#8216; statement.  See section <a class="reference internal" href="#contextlibmod"><em>The contextlib module</em></a>
for more about this module.</p>
</li>
<li><p class="first">New module: The <a class="reference internal" href="../library/profile.html#module-cProfile" title="cProfile: Python profiler"><tt class="xref py py-mod docutils literal"><span class="pre">cProfile</span></tt></a> module is a C implementation of  the existing
<a class="reference internal" href="../library/profile.html#module-profile" title="profile: Python source profiler."><tt class="xref py py-mod docutils literal"><span class="pre">profile</span></tt></a> module that has much lower overhead. The module&#8217;s interface is
the same as <a class="reference internal" href="../library/profile.html#module-profile" title="profile: Python source profiler."><tt class="xref py py-mod docutils literal"><span class="pre">profile</span></tt></a>: you run <tt class="docutils literal"><span class="pre">cProfile.run('main()')</span></tt> to profile a
function, can save profile data to a file, etc.  It&#8217;s not yet known if the
Hotshot profiler, which is also written in C but doesn&#8217;t match the
<a class="reference internal" href="../library/profile.html#module-profile" title="profile: Python source profiler."><tt class="xref py py-mod docutils literal"><span class="pre">profile</span></tt></a> module&#8217;s interface, will continue to be maintained in future
versions of Python.  (Contributed by Armin Rigo.)</p>
<p>Also, the <a class="reference internal" href="../library/profile.html#module-pstats" title="pstats: Statistics object for use with the profiler."><tt class="xref py py-mod docutils literal"><span class="pre">pstats</span></tt></a> module for analyzing the data measured by the profiler
now supports directing the output to any file object by supplying a <em>stream</em>
argument to the <tt class="xref py py-class docutils literal"><span class="pre">Stats</span></tt> constructor. (Contributed by Skip Montanaro.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/csv.html#module-csv" title="csv: Write and read tabular data to and from delimited files."><tt class="xref py py-mod docutils literal"><span class="pre">csv</span></tt></a> module, which parses files in comma-separated value format,
received several enhancements and a number of bugfixes.  You can now set the
maximum size in bytes of a field by calling the
<tt class="xref py py-meth docutils literal"><span class="pre">csv.field_size_limit(new_limit)()</span></tt> function; omitting the <em>new_limit</em>
argument will return the currently-set limit.  The <tt class="xref py py-class docutils literal"><span class="pre">reader</span></tt> class now has
a <tt class="xref py py-attr docutils literal"><span class="pre">line_num</span></tt> attribute that counts the number of physical lines read from
the source; records can span multiple physical lines, so <tt class="xref py py-attr docutils literal"><span class="pre">line_num</span></tt> is not
the same as the number of records read.</p>
<p>The CSV parser is now stricter about multi-line quoted fields. Previously, if a
line ended within a quoted field without a terminating newline character, a
newline would be inserted into the returned field. This behavior caused problems
when reading files that contained carriage return characters within fields, so
the code was changed to return the field without inserting newlines. As a
consequence, if newlines embedded within fields are important, the input should
be split into lines in a manner that preserves the newline characters.</p>
<p>(Contributed by Skip Montanaro and Andrew McNamara.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/datetime.html#module-datetime" title="datetime: Basic date and time types."><tt class="xref py py-class docutils literal"><span class="pre">datetime</span></tt></a> class in the <a class="reference internal" href="../library/datetime.html#module-datetime" title="datetime: Basic date and time types."><tt class="xref py py-mod docutils literal"><span class="pre">datetime</span></tt></a>  module now has a
<tt class="xref py py-meth docutils literal"><span class="pre">strptime(string,</span> <span class="pre">format)()</span></tt>  method for parsing date strings, contributed
by Josh Spoerri. It uses the same format characters as <a class="reference internal" href="../library/time.html#time.strptime" title="time.strptime"><tt class="xref py py-func docutils literal"><span class="pre">time.strptime()</span></tt></a> and
<a class="reference internal" href="../library/time.html#time.strftime" title="time.strftime"><tt class="xref py py-func docutils literal"><span class="pre">time.strftime()</span></tt></a>:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">datetime</span> <span class="k">import</span> <span class="n">datetime</span>

<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="s">&#39;10:13:15 2006-03-07&#39;</span><span class="p">,</span>
                       <span class="s">&#39;%H:%M:%S %Y-%m-%d&#39;</span><span class="p">)</span>
</pre></div>
</div>
</li>
<li><p class="first">The <tt class="xref py py-meth docutils literal"><span class="pre">SequenceMatcher.get_matching_blocks()</span></tt> method in the <a class="reference internal" href="../library/difflib.html#module-difflib" title="difflib: Helpers for computing differences between objects."><tt class="xref py py-mod docutils literal"><span class="pre">difflib</span></tt></a>
module now guarantees to return a minimal list of blocks describing matching
subsequences.  Previously, the algorithm would occasionally break a block of
matching elements into two list entries. (Enhancement by Tim Peters.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><tt class="xref py py-mod docutils literal"><span class="pre">doctest</span></tt></a> module gained a <tt class="docutils literal"><span class="pre">SKIP</span></tt> option that keeps an example from
being executed at all.  This is intended for code snippets that are usage
examples intended for the reader and aren&#8217;t actually test cases.</p>
<p>An <em>encoding</em> parameter was added to the <tt class="xref py py-func docutils literal"><span class="pre">testfile()</span></tt> function and the
<tt class="xref py py-class docutils literal"><span class="pre">DocFileSuite</span></tt> class to specify the file&#8217;s encoding.  This makes it
easier to use non-ASCII characters in  tests contained within a docstring.
(Contributed by Bjorn Tillenius.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><tt class="xref py py-mod docutils literal"><span class="pre">email</span></tt></a> package has been updated to version 4.0. (Contributed by
Barry Warsaw.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/fileinput.html#module-fileinput" title="fileinput: Loop over standard input or a list of files."><tt class="xref py py-mod docutils literal"><span class="pre">fileinput</span></tt></a> module was made more flexible. Unicode filenames are now
supported, and a <em>mode</em> parameter that defaults to <tt class="docutils literal"><span class="pre">&quot;r&quot;</span></tt> was added to the
<a class="reference internal" href="../library/functions.html#input" title="input"><tt class="xref py py-func docutils literal"><span class="pre">input()</span></tt></a> function to allow opening files in binary or universal-newline
mode.  Another new parameter, <em>openhook</em>, lets you use a function other than
<a class="reference internal" href="../library/functions.html#open" title="open"><tt class="xref py py-func docutils literal"><span class="pre">open()</span></tt></a>  to open the input files.  Once you&#8217;re iterating over  the set of
files, the <tt class="xref py py-class docutils literal"><span class="pre">FileInput</span></tt> object&#8217;s new <tt class="xref py py-meth docutils literal"><span class="pre">fileno()</span></tt> returns the file
descriptor for the currently opened file. (Contributed by Georg Brandl.)</p>
</li>
<li><p class="first">In the <a class="reference internal" href="../library/gc.html#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><tt class="xref py py-mod docutils literal"><span class="pre">gc</span></tt></a> module, the new <tt class="xref py py-func docutils literal"><span class="pre">get_count()</span></tt> function returns a 3-tuple
containing the current collection counts for the three GC generations.  This is
accounting information for the garbage collector; when these counts reach a
specified threshold, a garbage collection sweep will be made.  The existing
<a class="reference internal" href="../library/gc.html#gc.collect" title="gc.collect"><tt class="xref py py-func docutils literal"><span class="pre">gc.collect()</span></tt></a> function now takes an optional <em>generation</em> argument of 0, 1,
or 2 to specify which generation to collect. (Contributed by Barry Warsaw.)</p>
</li>
<li><p class="first">The <tt class="xref py py-func docutils literal"><span class="pre">nsmallest()</span></tt> and  <tt class="xref py py-func docutils literal"><span class="pre">nlargest()</span></tt> functions in the <a class="reference internal" href="../library/heapq.html#module-heapq" title="heapq: Heap queue algorithm (a.k.a. priority queue)."><tt class="xref py py-mod docutils literal"><span class="pre">heapq</span></tt></a>
module  now support a <tt class="docutils literal"><span class="pre">key</span></tt> keyword parameter similar to the one provided by
the <a class="reference internal" href="../library/functions.html#min" title="min"><tt class="xref py py-func docutils literal"><span class="pre">min()</span></tt></a>/<a class="reference internal" href="../library/functions.html#max" title="max"><tt class="xref py py-func docutils literal"><span class="pre">max()</span></tt></a> functions and the <tt class="xref py py-meth docutils literal"><span class="pre">sort()</span></tt> methods.  For
example:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">heapq</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="s">&quot;short&quot;</span><span class="p">,</span> <span class="s">&#39;medium&#39;</span><span class="p">,</span> <span class="s">&#39;longest&#39;</span><span class="p">,</span> <span class="s">&#39;longer still&#39;</span><span class="p">]</span>
<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="c"># Return two lowest elements, lexicographically</span>
<span class="go">[&#39;longer still&#39;, &#39;longest&#39;]</span>
<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="c"># Return two shortest elements</span>
<span class="go">[&#39;short&#39;, &#39;medium&#39;]</span>
</pre></div>
</div>
<p>(Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/itertools.html#itertools.islice" title="itertools.islice"><tt class="xref py py-func docutils literal"><span class="pre">itertools.islice()</span></tt></a> function now accepts <tt class="xref docutils literal"><span class="pre">None</span></tt> for the start and
step arguments.  This makes it more compatible with the attributes of slice
objects, so that you can now write the following:</p>
<div class="highlight-python3"><div class="highlight"><pre><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="c"># Create slice object</span>
<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>
</pre></div>
</div>
<p>(Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/functions.html#format" title="format"><tt class="xref py py-func docutils literal"><span class="pre">format()</span></tt></a> function in the <a class="reference internal" href="../library/locale.html#module-locale" title="locale: Internationalization services."><tt class="xref py py-mod docutils literal"><span class="pre">locale</span></tt></a> module has been modified and
two new functions were added, <tt class="xref py py-func docutils literal"><span class="pre">format_string()</span></tt> and <tt class="xref py py-func docutils literal"><span class="pre">currency()</span></tt>.</p>
<p>The <a class="reference internal" href="../library/functions.html#format" title="format"><tt class="xref py py-func docutils literal"><span class="pre">format()</span></tt></a> function&#8217;s <em>val</em> parameter could previously be a string as
long as no more than one %char specifier appeared; now the parameter must be
exactly one %char specifier with no surrounding text.  An optional <em>monetary</em>
parameter was also added which, if <tt class="xref docutils literal"><span class="pre">True</span></tt>, will use the locale&#8217;s rules for
formatting currency in placing a separator between groups of three digits.</p>
<p>To format strings with multiple %char specifiers, use the new
<tt class="xref py py-func docutils literal"><span class="pre">format_string()</span></tt> function that works like <a class="reference internal" href="../library/functions.html#format" title="format"><tt class="xref py py-func docutils literal"><span class="pre">format()</span></tt></a> but also supports
mixing %char specifiers with arbitrary text.</p>
<p>A new <tt class="xref py py-func docutils literal"><span class="pre">currency()</span></tt> function was also added that formats a number according
to the current locale&#8217;s settings.</p>
<p>(Contributed by Georg Brandl.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/mailbox.html#module-mailbox" title="mailbox: Manipulate mailboxes in various formats"><tt class="xref py py-mod docutils literal"><span class="pre">mailbox</span></tt></a> module underwent a massive rewrite to add the capability to
modify mailboxes in addition to reading them.  A new set of classes that include
<tt class="xref py py-class docutils literal"><span class="pre">mbox</span></tt>, <tt class="xref py py-class docutils literal"><span class="pre">MH</span></tt>, and <tt class="xref py py-class docutils literal"><span class="pre">Maildir</span></tt> are used to read mailboxes, and
have an <tt class="xref py py-meth docutils literal"><span class="pre">add(message)()</span></tt> method to add messages, <tt class="xref py py-meth docutils literal"><span class="pre">remove(key)()</span></tt> to
remove messages, and <tt class="xref py py-meth docutils literal"><span class="pre">lock()</span></tt>/<tt class="xref py py-meth docutils literal"><span class="pre">unlock()</span></tt> to lock/unlock the mailbox.
The following example converts a maildir-format mailbox into an mbox-format
one:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">mailbox</span>

<span class="c"># &#39;factory=None&#39; uses email.Message.Message as the class representing</span>
<span class="c"># individual messages.</span>
<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="s">&#39;maildir&#39;</span><span class="p">,</span> <span class="n">factory</span><span class="o">=</span><span class="k">None</span><span class="p">)</span>
<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="s">&#39;/tmp/mbox&#39;</span><span class="p">)</span>

<span class="k">for</span> <span class="n">msg</span> <span class="ow">in</span> <span class="n">src</span><span class="p">:</span>
    <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>
</pre></div>
</div>
<p>(Contributed by Gregory K. Johnson.  Funding was provided by Google&#8217;s 2005
Summer of Code.)</p>
</li>
<li><p class="first">New module: the <a class="reference internal" href="../library/msilib.html#module-msilib" title="msilib: Creation of Microsoft Installer files, and CAB files. (Windows)"><tt class="xref py py-mod docutils literal"><span class="pre">msilib</span></tt></a> module allows creating Microsoft Installer
<tt class="file docutils literal"><span class="pre">.msi</span></tt> files and CAB files.  Some support for reading the <tt class="file docutils literal"><span class="pre">.msi</span></tt>
database is also included. (Contributed by Martin von Löwis.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/nis.html#module-nis" title="nis: Interface to Sun's NIS (Yellow Pages) library. (Unix)"><tt class="xref py py-mod docutils literal"><span class="pre">nis</span></tt></a> module now supports accessing domains other than the system
default domain by supplying a <em>domain</em> argument to the <a class="reference internal" href="../library/nis.html#nis.match" title="nis.match"><tt class="xref py py-func docutils literal"><span class="pre">nis.match()</span></tt></a> and
<a class="reference internal" href="../library/nis.html#nis.maps" title="nis.maps"><tt class="xref py py-func docutils literal"><span class="pre">nis.maps()</span></tt></a> functions. (Contributed by Ben Bell.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/operator.html#module-operator" title="operator: Functions corresponding to the standard operators."><tt class="xref py py-mod docutils literal"><span class="pre">operator</span></tt></a> module&#8217;s <tt class="xref py py-func docutils literal"><span class="pre">itemgetter()</span></tt>  and <tt class="xref py py-func docutils literal"><span class="pre">attrgetter()</span></tt>
functions now support multiple fields.   A call such as
<tt class="docutils literal"><span class="pre">operator.attrgetter('a',</span> <span class="pre">'b')</span></tt> will return a function  that retrieves the
<tt class="xref py py-attr docutils literal"><span class="pre">a</span></tt> and <tt class="xref py py-attr docutils literal"><span class="pre">b</span></tt> attributes.  Combining  this new feature with the
<tt class="xref py py-meth docutils literal"><span class="pre">sort()</span></tt> method&#8217;s <tt class="docutils literal"><span class="pre">key</span></tt> parameter  lets you easily sort lists using
multiple fields. (Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/optparse.html#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><tt class="xref py py-mod docutils literal"><span class="pre">optparse</span></tt></a> module was updated to version 1.5.1 of the Optik library.
The <tt class="xref py py-class docutils literal"><span class="pre">OptionParser</span></tt> class gained an <tt class="xref py py-attr docutils literal"><span class="pre">epilog</span></tt> attribute, a string
that will be printed after the help message, and a <tt class="xref py py-meth docutils literal"><span class="pre">destroy()</span></tt> method to
break reference cycles created by the object. (Contributed by Greg Ward.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/os.html#module-os" title="os: Miscellaneous operating system interfaces."><tt class="xref py py-mod docutils literal"><span class="pre">os</span></tt></a> module underwent several changes.  The <tt class="xref py py-attr docutils literal"><span class="pre">stat_float_times</span></tt>
variable now defaults to true, meaning that <a class="reference internal" href="../library/os.html#os.stat" title="os.stat"><tt class="xref py py-func docutils literal"><span class="pre">os.stat()</span></tt></a> will now return time
values as floats.  (This doesn&#8217;t necessarily mean that <a class="reference internal" href="../library/os.html#os.stat" title="os.stat"><tt class="xref py py-func docutils literal"><span class="pre">os.stat()</span></tt></a> will
return times that are precise to fractions of a second; not all systems support
such precision.)</p>
<p>Constants named <a class="reference internal" href="../library/os.html#os.SEEK_SET" title="os.SEEK_SET"><tt class="xref py py-attr docutils literal"><span class="pre">os.SEEK_SET</span></tt></a>, <a class="reference internal" href="../library/os.html#os.SEEK_CUR" title="os.SEEK_CUR"><tt class="xref py py-attr docutils literal"><span class="pre">os.SEEK_CUR</span></tt></a>, and
<a class="reference internal" href="../library/os.html#os.SEEK_END" title="os.SEEK_END"><tt class="xref py py-attr docutils literal"><span class="pre">os.SEEK_END</span></tt></a> have been added; these are the parameters to the
<a class="reference internal" href="../library/os.html#os.lseek" title="os.lseek"><tt class="xref py py-func docutils literal"><span class="pre">os.lseek()</span></tt></a> function.  Two new constants for locking are
<a class="reference internal" href="../library/os.html#os.O_SHLOCK" title="os.O_SHLOCK"><tt class="xref py py-attr docutils literal"><span class="pre">os.O_SHLOCK</span></tt></a> and <a class="reference internal" href="../library/os.html#os.O_EXLOCK" title="os.O_EXLOCK"><tt class="xref py py-attr docutils literal"><span class="pre">os.O_EXLOCK</span></tt></a>.</p>
<p>Two new functions, <tt class="xref py py-func docutils literal"><span class="pre">wait3()</span></tt> and <tt class="xref py py-func docutils literal"><span class="pre">wait4()</span></tt>, were added.  They&#8217;re similar
the <tt class="xref py py-func docutils literal"><span class="pre">waitpid()</span></tt> function which waits for a child process to exit and returns
a tuple of the process ID and its exit status, but <tt class="xref py py-func docutils literal"><span class="pre">wait3()</span></tt> and
<tt class="xref py py-func docutils literal"><span class="pre">wait4()</span></tt> return additional information.  <tt class="xref py py-func docutils literal"><span class="pre">wait3()</span></tt> doesn&#8217;t take a
process ID as input, so it waits for any child process to exit and returns a
3-tuple of <em>process-id</em>, <em>exit-status</em>, <em>resource-usage</em> as returned from the
<a class="reference internal" href="../library/resource.html#resource.getrusage" title="resource.getrusage"><tt class="xref py py-func docutils literal"><span class="pre">resource.getrusage()</span></tt></a> function. <tt class="xref py py-func docutils literal"><span class="pre">wait4(pid)()</span></tt> does take a process ID.
(Contributed by Chad J. Schroeder.)</p>
<p>On FreeBSD, the <a class="reference internal" href="../library/os.html#os.stat" title="os.stat"><tt class="xref py py-func docutils literal"><span class="pre">os.stat()</span></tt></a> function now returns  times with nanosecond
resolution, and the returned object now has <tt class="xref py py-attr docutils literal"><span class="pre">st_gen</span></tt> and
<tt class="xref py py-attr docutils literal"><span class="pre">st_birthtime</span></tt>. The <tt class="xref py py-attr docutils literal"><span class="pre">st_flags</span></tt> attribute is also available, if the
platform supports it. (Contributed by Antti Louko and  Diego Pettenò.)</p>
</li>
<li><p class="first">The Python debugger provided by the <a class="reference internal" href="../library/pdb.html#module-pdb" title="pdb: The Python debugger for interactive interpreters."><tt class="xref py py-mod docutils literal"><span class="pre">pdb</span></tt></a> module can now store lists of
commands to execute when a breakpoint is reached and execution stops.  Once
breakpoint #1 has been created, enter <tt class="docutils literal"><span class="pre">commands</span> <span class="pre">1</span></tt> and enter a series of
commands to be executed, finishing the list with <tt class="docutils literal"><span class="pre">end</span></tt>.  The command list can
include commands that resume execution, such as <tt class="docutils literal"><span class="pre">continue</span></tt> or <tt class="docutils literal"><span class="pre">next</span></tt>.
(Contributed by Grégoire Dooms.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><tt class="xref py py-mod docutils literal"><span class="pre">pickle</span></tt></a> and <tt class="xref py py-mod docutils literal"><span class="pre">cPickle</span></tt> modules no longer accept a return value
of <tt class="xref docutils literal"><span class="pre">None</span></tt> from the <tt class="xref py py-meth docutils literal"><span class="pre">__reduce__()</span></tt> method; the method must return a tuple
of arguments instead.  The ability to return <tt class="xref docutils literal"><span class="pre">None</span></tt> was deprecated in Python
2.4, so this completes the removal of the feature.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/pkgutil.html#module-pkgutil" title="pkgutil: Utilities for the import system."><tt class="xref py py-mod docutils literal"><span class="pre">pkgutil</span></tt></a> module, containing various utility functions for finding
packages, was enhanced to support PEP 302&#8217;s import hooks and now also works for
packages stored in ZIP-format archives. (Contributed by Phillip J. Eby.)</p>
</li>
<li><p class="first">The pybench benchmark suite by Marc-André Lemburg is now included in the
<tt class="file docutils literal"><span class="pre">Tools/pybench</span></tt> directory.  The pybench suite is an improvement on the
commonly used <tt class="file docutils literal"><span class="pre">pystone.py</span></tt> program because pybench provides a more
detailed measurement of the interpreter&#8217;s speed.  It times particular operations
such as function calls, tuple slicing, method lookups, and numeric operations,
instead of performing many different operations and reducing the result to a
single number as <tt class="file docutils literal"><span class="pre">pystone.py</span></tt> does.</p>
</li>
<li><p class="first">The <tt class="xref py py-mod docutils literal"><span class="pre">pyexpat</span></tt> module now uses version 2.0 of the Expat parser.
(Contributed by Trent Mick.)</p>
</li>
<li><p class="first">The <tt class="xref py py-class docutils literal"><span class="pre">Queue</span></tt> class provided by the <tt class="xref py py-mod docutils literal"><span class="pre">Queue</span></tt> module gained two new
methods.  <tt class="xref py py-meth docutils literal"><span class="pre">join()</span></tt> blocks until all items in the queue have been retrieved
and all processing work on the items  have been completed.  Worker threads call
the other new method,  <tt class="xref py py-meth docutils literal"><span class="pre">task_done()</span></tt>, to signal that processing for an item
has been completed.  (Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">The old <tt class="xref py py-mod docutils literal"><span class="pre">regex</span></tt> and <tt class="xref py py-mod docutils literal"><span class="pre">regsub</span></tt> modules, which have been  deprecated
ever since Python 2.0, have finally been deleted.   Other deleted modules:
<tt class="xref py py-mod docutils literal"><span class="pre">statcache</span></tt>, <tt class="xref py py-mod docutils literal"><span class="pre">tzparse</span></tt>, <tt class="xref py py-mod docutils literal"><span class="pre">whrandom</span></tt>.</p>
</li>
<li><p class="first">Also deleted: the <tt class="file docutils literal"><span class="pre">lib-old</span></tt> directory, which includes ancient modules
such as <tt class="xref py py-mod docutils literal"><span class="pre">dircmp</span></tt> and <tt class="xref py py-mod docutils literal"><span class="pre">ni</span></tt>, was removed.  <tt class="file docutils literal"><span class="pre">lib-old</span></tt> wasn&#8217;t on the
default <tt class="docutils literal"><span class="pre">sys.path</span></tt>, so unless your programs explicitly added the directory to
<tt class="docutils literal"><span class="pre">sys.path</span></tt>, this removal shouldn&#8217;t affect your code.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/rlcompleter.html#module-rlcompleter" title="rlcompleter: Python identifier completion, suitable for the GNU readline library."><tt class="xref py py-mod docutils literal"><span class="pre">rlcompleter</span></tt></a> module is no longer  dependent on importing the
<a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><tt class="xref py py-mod docutils literal"><span class="pre">readline</span></tt></a> module and therefore now works on non-Unix platforms. (Patch
from Robert Kiendl.)</p>
</li>
<li><p class="first">The <tt class="xref py py-mod docutils literal"><span class="pre">SimpleXMLRPCServer</span></tt> and <tt class="xref py py-mod docutils literal"><span class="pre">DocXMLRPCServer</span></tt>  classes now have a
<tt class="xref py py-attr docutils literal"><span class="pre">rpc_paths</span></tt> attribute that constrains XML-RPC operations to a limited set
of URL paths; the default is to allow only <tt class="docutils literal"><span class="pre">'/'</span></tt> and <tt class="docutils literal"><span class="pre">'/RPC2'</span></tt>.  Setting
<tt class="xref py py-attr docutils literal"><span class="pre">rpc_paths</span></tt> to <tt class="xref docutils literal"><span class="pre">None</span></tt> or an empty tuple disables  this path checking.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><tt class="xref py py-mod docutils literal"><span class="pre">socket</span></tt></a> module now supports <tt class="xref py py-const docutils literal"><span class="pre">AF_NETLINK</span></tt> sockets on Linux,
thanks to a patch from Philippe Biondi.   Netlink sockets are a Linux-specific
mechanism for communications between a user-space process and kernel code; an
introductory  article about them is at <a class="reference external" href="http://www.linuxjournal.com/article/7356">http://www.linuxjournal.com/article/7356</a>.
In Python code, netlink addresses are represented as a tuple of 2 integers,
<tt class="docutils literal"><span class="pre">(pid,</span> <span class="pre">group_mask)</span></tt>.</p>
<p>Two new methods on socket objects, <tt class="xref py py-meth docutils literal"><span class="pre">recv_into(buffer)()</span></tt> and
<tt class="xref py py-meth docutils literal"><span class="pre">recvfrom_into(buffer)()</span></tt>, store the received data in an object  that
supports the buffer protocol instead of returning the data as a string.  This
means you can put the data directly into an array or a memory-mapped file.</p>
<p>Socket objects also gained <tt class="xref py py-meth docutils literal"><span class="pre">getfamily()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">gettype()</span></tt>, and
<tt class="xref py py-meth docutils literal"><span class="pre">getproto()</span></tt> accessor methods to retrieve the family, type, and protocol
values for the socket.</p>
</li>
<li><p class="first">New module: the <a class="reference internal" href="../library/spwd.html#module-spwd" title="spwd: The shadow password database (getspnam() and friends). (Unix)"><tt class="xref py py-mod docutils literal"><span class="pre">spwd</span></tt></a> module provides functions for accessing the shadow
password database on systems that support  shadow passwords.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/struct.html#module-struct" title="struct: Interpret bytes as packed binary data."><tt class="xref py py-mod docutils literal"><span class="pre">struct</span></tt></a> is now faster because it  compiles format strings into
<tt class="xref py py-class docutils literal"><span class="pre">Struct</span></tt> objects with <tt class="xref py py-meth docutils literal"><span class="pre">pack()</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">unpack()</span></tt> methods.  This is
similar to how the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><tt class="xref py py-mod docutils literal"><span class="pre">re</span></tt></a> module lets you create compiled regular expression
objects.  You can still use the module-level  <tt class="xref py py-func docutils literal"><span class="pre">pack()</span></tt> and <tt class="xref py py-func docutils literal"><span class="pre">unpack()</span></tt>
functions; they&#8217;ll create  <tt class="xref py py-class docutils literal"><span class="pre">Struct</span></tt> objects and cache them.  Or you can
use  <tt class="xref py py-class docutils literal"><span class="pre">Struct</span></tt> instances directly:</p>
<div class="highlight-python3"><div class="highlight"><pre><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="s">&#39;ih3s&#39;</span><span class="p">)</span>

<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="s">&#39;abc&#39;</span><span class="p">)</span>
<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>
</pre></div>
</div>
<p>You can also pack and unpack data to and from buffer objects directly using the
<tt class="xref py py-meth docutils literal"><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></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">unpack_from(buffer,</span>
<span class="pre">offset)()</span></tt> methods.  This lets you store data directly into an array or a memory-
mapped file.</p>
<p>(<tt class="xref py py-class docutils literal"><span class="pre">Struct</span></tt> objects were implemented by Bob Ippolito at the NeedForSpeed
sprint.  Support for buffer objects was added by Martin Blais, also at the
NeedForSpeed sprint.)</p>
</li>
<li><p class="first">The Python developers switched from CVS to Subversion during the 2.5
development process.  Information about the exact build version is available as
the <tt class="docutils literal"><span class="pre">sys.subversion</span></tt> variable, a 3-tuple of <tt class="docutils literal"><span class="pre">(interpreter-name,</span> <span class="pre">branch-name,</span>
<span class="pre">revision-range)</span></tt>.  For example, at the time of writing my copy of 2.5 was
reporting <tt class="docutils literal"><span class="pre">('CPython',</span> <span class="pre">'trunk',</span> <span class="pre">'45313:45315')</span></tt>.</p>
<p>This information is also available to C extensions via the
<a class="reference internal" href="../c-api/init.html#Py_GetBuildInfo" title="Py_GetBuildInfo"><tt class="xref c c-func docutils literal"><span class="pre">Py_GetBuildInfo()</span></tt></a> function that returns a  string of build information
like this: <tt class="docutils literal"><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></tt>.   (Contributed by
Barry Warsaw.)</p>
</li>
<li><p class="first">Another new function, <a class="reference internal" href="../library/sys.html#sys._current_frames" title="sys._current_frames"><tt class="xref py py-func docutils literal"><span class="pre">sys._current_frames()</span></tt></a>, returns the current stack
frames for all running threads as a dictionary mapping thread identifiers to the
topmost stack frame currently active in that thread at the time the function is
called.  (Contributed by Tim Peters.)</p>
</li>
<li><p class="first">The <tt class="xref py py-class docutils literal"><span class="pre">TarFile</span></tt> class in the <a class="reference internal" href="../library/tarfile.html#module-tarfile" title="tarfile: Read and write tar-format archive files."><tt class="xref py py-mod docutils literal"><span class="pre">tarfile</span></tt></a> module now has an
<tt class="xref py py-meth docutils literal"><span class="pre">extractall()</span></tt> method that extracts all members from the archive into the
current working directory.  It&#8217;s also possible to set a different directory as
the extraction target, and to unpack only a subset of the archive&#8217;s members.</p>
<p>The compression used for a tarfile opened in stream mode can now be autodetected
using the mode <tt class="docutils literal"><span class="pre">'r|*'</span></tt>. (Contributed by Lars Gustäbel.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/threading.html#module-threading" title="threading: Thread-based parallelism."><tt class="xref py py-mod docutils literal"><span class="pre">threading</span></tt></a> module now lets you set the stack size used when new
threads are created. The <tt class="xref py py-func docutils literal"><span class="pre">stack_size([*size*])()</span></tt> function returns the
currently configured stack size, and supplying the optional <em>size</em> parameter
sets a new value.  Not all platforms support changing the stack size, but
Windows, POSIX threading, and OS/2 all do. (Contributed by Andrew MacIntyre.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/unicodedata.html#module-unicodedata" title="unicodedata: Access the Unicode Database."><tt class="xref py py-mod docutils literal"><span class="pre">unicodedata</span></tt></a> module has been updated to use version 4.1.0 of the
Unicode character database.  Version 3.2.0 is required  by some specifications,
so it&#8217;s still available as  <a class="reference internal" href="../library/unicodedata.html#unicodedata.ucd_3_2_0" title="unicodedata.ucd_3_2_0"><tt class="xref py py-attr docutils literal"><span class="pre">unicodedata.ucd_3_2_0</span></tt></a>.</p>
</li>
<li><p class="first">New module: the  <a class="reference internal" href="../library/uuid.html#module-uuid" title="uuid: UUID objects (universally unique identifiers) according to RFC 4122"><tt class="xref py py-mod docutils literal"><span class="pre">uuid</span></tt></a> module generates  universally unique identifiers
(UUIDs) according to <span class="target" id="index-18"></span><a class="rfc reference external" href="http://tools.ietf.org/html/rfc4122.html"><strong>RFC 4122</strong></a>.  The RFC defines several different UUID
versions that are generated from a starting string, from system properties, or
purely randomly.  This module contains a <tt class="xref py py-class docutils literal"><span class="pre">UUID</span></tt> class and  functions
named <tt class="xref py py-func docutils literal"><span class="pre">uuid1()</span></tt>, <tt class="xref py py-func docutils literal"><span class="pre">uuid3()</span></tt>, <tt class="xref py py-func docutils literal"><span class="pre">uuid4()</span></tt>,  and  <tt class="xref py py-func docutils literal"><span class="pre">uuid5()</span></tt> to
generate different versions of UUID.  (Version 2 UUIDs  are not specified in
<span class="target" id="index-19"></span><a class="rfc reference external" href="http://tools.ietf.org/html/rfc4122.html"><strong>RFC 4122</strong></a> and are not supported by this module.)</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">uuid</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c"># make a UUID based on the host ID and current time</span>
<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>
<span class="go">UUID(&#39;a8098c1a-f86e-11da-bd1a-00112444be1e&#39;)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c"># make a UUID using an MD5 hash of a namespace UUID and a name</span>
<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="s">&#39;python.org&#39;</span><span class="p">)</span>
<span class="go">UUID(&#39;6fa459ea-ee8a-3ca4-894e-db77e160355e&#39;)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c"># make a random UUID</span>
<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>
<span class="go">UUID(&#39;16fd2706-8baf-433b-82eb-8c7fada847da&#39;)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c"># make a UUID using a SHA-1 hash of a namespace UUID and a name</span>
<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="s">&#39;python.org&#39;</span><span class="p">)</span>
<span class="go">UUID(&#39;886313e1-3b8a-5372-9b90-0c9aee199e5d&#39;)</span>
</pre></div>
</div>
<p>(Contributed by Ka-Ping Yee.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/weakref.html#module-weakref" title="weakref: Support for weak references and weak dictionaries."><tt class="xref py py-mod docutils literal"><span class="pre">weakref</span></tt></a> module&#8217;s <tt class="xref py py-class docutils literal"><span class="pre">WeakKeyDictionary</span></tt> and
<tt class="xref py py-class docutils literal"><span class="pre">WeakValueDictionary</span></tt> types gained new methods for iterating over the
weak references contained in the dictionary.  <tt class="xref py py-meth docutils literal"><span class="pre">iterkeyrefs()</span></tt> and
<tt class="xref py py-meth docutils literal"><span class="pre">keyrefs()</span></tt> methods were added to <tt class="xref py py-class docutils literal"><span class="pre">WeakKeyDictionary</span></tt>, and
<tt class="xref py py-meth docutils literal"><span class="pre">itervaluerefs()</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">valuerefs()</span></tt> were added to
<tt class="xref py py-class docutils literal"><span class="pre">WeakValueDictionary</span></tt>.  (Contributed by Fred L. Drake, Jr.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/webbrowser.html#module-webbrowser" title="webbrowser: Easy-to-use controller for Web browsers."><tt class="xref py py-mod docutils literal"><span class="pre">webbrowser</span></tt></a> module received a number of enhancements. It&#8217;s now
usable as a script with <tt class="docutils literal"><span class="pre">python</span> <span class="pre">-m</span> <span class="pre">webbrowser</span></tt>, taking a URL as the argument;
there are a number of switches  to control the behaviour (<em class="xref std std-option">-n</em> for a new
browser window,  <em class="xref std std-option">-t</em> for a new tab).  New module-level functions,
<tt class="xref py py-func docutils literal"><span class="pre">open_new()</span></tt> and <tt class="xref py py-func docutils literal"><span class="pre">open_new_tab()</span></tt>, were added  to support this.  The
module&#8217;s <a class="reference internal" href="../library/functions.html#open" title="open"><tt class="xref py py-func docutils literal"><span class="pre">open()</span></tt></a> function supports an additional feature, an <em>autoraise</em>
parameter that signals whether to raise the open window when possible. A number
of additional browsers were added to the supported list such as Firefox, Opera,
Konqueror, and elinks.  (Contributed by Oleg Broytmann and Georg Brandl.)</p>
</li>
<li><p class="first">The <tt class="xref py py-mod docutils literal"><span class="pre">xmlrpclib</span></tt> module now supports returning  <a class="reference internal" href="../library/datetime.html#module-datetime" title="datetime: Basic date and time types."><tt class="xref py py-class docutils literal"><span class="pre">datetime</span></tt></a> objects
for the XML-RPC date type.  Supply  <tt class="docutils literal"><span class="pre">use_datetime=True</span></tt> to the <tt class="xref py py-func docutils literal"><span class="pre">loads()</span></tt>
function or the <tt class="xref py py-class docutils literal"><span class="pre">Unmarshaller</span></tt> class to enable this feature. (Contributed
by Skip Montanaro.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/zipfile.html#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><tt class="xref py py-mod docutils literal"><span class="pre">zipfile</span></tt></a> module now supports the ZIP64 version of the  format,
meaning that a .zip archive can now be larger than 4 GiB and can contain
individual files larger than 4 GiB.  (Contributed by Ronald Oussoren.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/zlib.html#module-zlib" title="zlib: Low-level interface to compression and decompression routines compatible with gzip."><tt class="xref py py-mod docutils literal"><span class="pre">zlib</span></tt></a> module&#8217;s <tt class="xref py py-class docutils literal"><span class="pre">Compress</span></tt> and <tt class="xref py py-class docutils literal"><span class="pre">Decompress</span></tt> objects now
support a <a class="reference internal" href="../library/copy.html#module-copy" title="copy: Shallow and deep copy operations."><tt class="xref py py-meth docutils literal"><span class="pre">copy()</span></tt></a> method that makes a copy of the  object&#8217;s internal state
and returns a new  <tt class="xref py py-class docutils literal"><span class="pre">Compress</span></tt> or <tt class="xref py py-class docutils literal"><span class="pre">Decompress</span></tt> object.
(Contributed by Chris AtLee.)</p>
</li>
</ul>
<div class="section" id="the-ctypes-package">
<span id="module-ctypes"></span><h3>The ctypes package<a class="headerlink" href="#the-ctypes-package" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> package, written by Thomas Heller, has been added  to the
standard library.  <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> lets you call arbitrary functions  in shared
libraries or DLLs.  Long-time users may remember the <tt class="xref py py-mod docutils literal"><span class="pre">dl</span></tt> module, which
provides functions for loading shared libraries and calling functions in them.
The <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> package is much fancier.</p>
<p>To load a shared library or DLL, you must create an instance of the
<tt class="xref py py-class docutils literal"><span class="pre">CDLL</span></tt> class and provide the name or path of the shared library or DLL.
Once that&#8217;s done, you can call arbitrary functions by accessing them as
attributes of the <tt class="xref py py-class docutils literal"><span class="pre">CDLL</span></tt> object.</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">ctypes</span>

<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="s">&#39;libc.so.6&#39;</span><span class="p">)</span>
<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="s">&quot;Line of output</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Type constructors for the various C types are provided: <tt class="xref py py-func docutils literal"><span class="pre">c_int()</span></tt>,
<tt class="xref py py-func docutils literal"><span class="pre">c_float()</span></tt>, <tt class="xref py py-func docutils literal"><span class="pre">c_double()</span></tt>, <tt class="xref py py-func docutils literal"><span class="pre">c_char_p()</span></tt> (equivalent to <tt class="xref c c-type docutils literal"><span class="pre">char</span>
<span class="pre">*</span></tt>), and so forth.  Unlike Python&#8217;s types, the C versions are all mutable; you
can assign to their <tt class="xref py py-attr docutils literal"><span class="pre">value</span></tt> attribute to change the wrapped value.  Python
integers and strings will be automatically converted to the corresponding C
types, but for other types you  must call the correct type constructor.  (And I
mean <em>must</em>;  getting it wrong will often result in the interpreter crashing
with a segmentation fault.)</p>
<p>You shouldn&#8217;t use <tt class="xref py py-func docutils literal"><span class="pre">c_char_p()</span></tt> with a Python string when the C function will
be modifying the memory area, because Python strings are  supposed to be
immutable; breaking this rule will cause puzzling bugs.  When you need a
modifiable memory area, use <tt class="xref py py-func docutils literal"><span class="pre">create_string_buffer()</span></tt>:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">s</span> <span class="o">=</span> <span class="s">&quot;this is a string&quot;</span>
<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>
<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>
</pre></div>
</div>
<p>C functions are assumed to return integers, but you can set the <tt class="xref py py-attr docutils literal"><span class="pre">restype</span></tt>
attribute of the function object to  change this:</p>
<div class="highlight-python3"><div class="highlight"><pre><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="s">&#39;2.71828&#39;</span><span class="p">)</span>
<span class="go">-1783957616</span>
<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>
<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="s">&#39;2.71828&#39;</span><span class="p">)</span>
<span class="go">2.71828</span>
</pre></div>
</div>
<p><a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> also provides a wrapper for Python&#8217;s C API  as the
<tt class="docutils literal"><span class="pre">ctypes.pythonapi</span></tt> object.  This object does <em>not</em>  release the global
interpreter lock before calling a function, because the lock must be held when
calling into the interpreter&#8217;s code.   There&#8217;s a <tt class="xref py py-class docutils literal"><span class="pre">py_object()</span></tt> type
constructor that will create a  <a class="reference internal" href="../c-api/structures.html#PyObject" title="PyObject"><tt class="xref c c-type docutils literal"><span class="pre">PyObject</span> <span class="pre">*</span></tt></a> pointer.  A simple usage:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">ctypes</span>

<span class="n">d</span> <span class="o">=</span> <span class="p">{}</span>
<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>
          <span class="n">ctypes</span><span class="o">.</span><span class="n">py_object</span><span class="p">(</span><span class="s">&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>
<span class="c"># d is now {&#39;abc&#39;, 1}.</span>
</pre></div>
</div>
<p>Don&#8217;t forget to use <tt class="xref py py-class docutils literal"><span class="pre">py_object()</span></tt>; if it&#8217;s omitted you end  up with a
segmentation fault.</p>
<p><a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> has been around for a while, but people still write  and
distribution hand-coded extension modules because you can&#8217;t rely on
<a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> being present. Perhaps developers will begin to write  Python
wrappers atop a library accessed through <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> instead of extension
modules, now that <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> is included with core Python.</p>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="docutils">
<dt><a class="reference external" href="http://starship.python.net/crew/theller/ctypes/">http://starship.python.net/crew/theller/ctypes/</a></dt>
<dd>The ctypes web page, with a tutorial, reference, and FAQ.</dd>
</dl>
<p class="last">The documentation  for the <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> module.</p>
</div>
</div>
<div class="section" id="the-elementtree-package">
<span id="module-etree"></span><h3>The ElementTree package<a class="headerlink" href="#the-elementtree-package" title="Permalink to this headline">¶</a></h3>
<p>A subset of Fredrik Lundh&#8217;s ElementTree library for processing XML has been
added to the standard library as <tt class="xref py py-mod docutils literal"><span class="pre">xml.etree</span></tt>.  The available modules are
<tt class="xref py py-mod docutils literal"><span class="pre">ElementTree</span></tt>, <tt class="xref py py-mod docutils literal"><span class="pre">ElementPath</span></tt>, and <tt class="xref py py-mod docutils literal"><span class="pre">ElementInclude</span></tt> from
ElementTree 1.2.6.    The <tt class="xref py py-mod docutils literal"><span class="pre">cElementTree</span></tt> accelerator module is also
included.</p>
<p>The rest of this section will provide a brief overview of using ElementTree.
Full documentation for ElementTree is available at
<a class="reference external" href="http://effbot.org/zone/element-index.htm">http://effbot.org/zone/element-index.htm</a>.</p>
<p>ElementTree represents an XML document as a tree of element nodes. The text
content of the document is stored as the <tt class="xref py py-attr docutils literal"><span class="pre">text</span></tt> and <tt class="xref py py-attr docutils literal"><span class="pre">tail</span></tt>
attributes of  (This is one of the major differences between ElementTree and
the Document Object Model; in the DOM there are many different types of node,
including <tt class="xref py py-class docutils literal"><span class="pre">TextNode</span></tt>.)</p>
<p>The most commonly used parsing function is <tt class="xref py py-func docutils literal"><span class="pre">parse()</span></tt>, that takes either a
string (assumed to contain a filename) or a file-like object and returns an
<tt class="xref py py-class docutils literal"><span class="pre">ElementTree</span></tt> instance:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">xml.etree</span> <span class="k">import</span> <span class="n">ElementTree</span> <span class="k">as</span> <span class="n">ET</span>

<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="s">&#39;ex-1.xml&#39;</span><span class="p">)</span>

<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>
          <span class="s">&#39;http://planet.python.org/rss10.xml&#39;</span><span class="p">)</span>
<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>
</pre></div>
</div>
<p>Once you have an <tt class="xref py py-class docutils literal"><span class="pre">ElementTree</span></tt> instance, you can call its <tt class="xref py py-meth docutils literal"><span class="pre">getroot()</span></tt>
method to get the root <tt class="xref py py-class docutils literal"><span class="pre">Element</span></tt> node.</p>
<p>There&#8217;s also an <tt class="xref py py-func docutils literal"><span class="pre">XML()</span></tt> function that takes a string literal and returns an
<tt class="xref py py-class docutils literal"><span class="pre">Element</span></tt> node (not an <tt class="xref py py-class docutils literal"><span class="pre">ElementTree</span></tt>).   This function provides a
tidy way to incorporate XML fragments, approaching the convenience of an XML
literal:</p>
<div class="highlight-python3"><div class="highlight"><pre><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="s">&quot;&quot;&quot;&lt;svg width=&quot;10px&quot; version=&quot;1.0&quot;&gt;</span>
<span class="s">             &lt;/svg&gt;&quot;&quot;&quot;</span><span class="p">)</span>
<span class="n">svg</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s">&#39;height&#39;</span><span class="p">,</span> <span class="s">&#39;320px&#39;</span><span class="p">)</span>
<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>
</pre></div>
</div>
<p>Each XML element supports some dictionary-like and some list-like access
methods.  Dictionary-like operations are used to access attribute values, and
list-like operations are used to access child nodes.</p>
<table border="1" class="docutils">
<colgroup>
<col width="41%" />
<col width="59%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Operation</th>
<th class="head">Result</th>
</tr>
</thead>
<tbody valign="top">
<tr><td><tt class="docutils literal"><span class="pre">elem[n]</span></tt></td>
<td>Returns n&#8217;th child element.</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">elem[m:n]</span></tt></td>
<td>Returns list of m&#8217;th through n&#8217;th child
elements.</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">len(elem)</span></tt></td>
<td>Returns number of child elements.</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">list(elem)</span></tt></td>
<td>Returns list of child elements.</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">elem.append(elem2)</span></tt></td>
<td>Adds <em>elem2</em> as a child.</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">elem.insert(index,</span> <span class="pre">elem2)</span></tt></td>
<td>Inserts <em>elem2</em> at the specified location.</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">del</span> <span class="pre">elem[n]</span></tt></td>
<td>Deletes n&#8217;th child element.</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">elem.keys()</span></tt></td>
<td>Returns list of attribute names.</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">elem.get(name)</span></tt></td>
<td>Returns value of attribute <em>name</em>.</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">elem.set(name,</span> <span class="pre">value)</span></tt></td>
<td>Sets new value for attribute <em>name</em>.</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">elem.attrib</span></tt></td>
<td>Retrieves the dictionary containing
attributes.</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">del</span> <span class="pre">elem.attrib[name]</span></tt></td>
<td>Deletes attribute <em>name</em>.</td>
</tr>
</tbody>
</table>
<p>Comments and processing instructions are also represented as <tt class="xref py py-class docutils literal"><span class="pre">Element</span></tt>
nodes.  To check if a node is a comment or processing instructions:</p>
<div class="highlight-python3"><div class="highlight"><pre><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>
    <span class="o">...</span>
<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>
    <span class="o">...</span>
</pre></div>
</div>
<p>To generate XML output, you should call the <tt class="xref py py-meth docutils literal"><span class="pre">ElementTree.write()</span></tt> method.
Like <tt class="xref py py-func docutils literal"><span class="pre">parse()</span></tt>, it can take either a string or a file-like object:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="c"># Encoding is US-ASCII</span>
<span class="n">tree</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s">&#39;output.xml&#39;</span><span class="p">)</span>

<span class="c"># Encoding is UTF-8</span>
<span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s">&#39;output.xml&#39;</span><span class="p">,</span> <span class="s">&#39;w&#39;</span><span class="p">)</span>
<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="s">&#39;utf-8&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>(Caution: the default encoding used for output is ASCII.  For general XML work,
where an element&#8217;s name may contain arbitrary Unicode characters, ASCII isn&#8217;t a
very useful encoding because it will raise an exception if an element&#8217;s name
contains any characters with values greater than 127.  Therefore, it&#8217;s best to
specify a different encoding such as UTF-8 that can handle any Unicode
character.)</p>
<p>This section is only a partial description of the ElementTree interfaces. Please
read the package&#8217;s official documentation for more details.</p>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://effbot.org/zone/element-index.htm">http://effbot.org/zone/element-index.htm</a></dt>
<dd>Official documentation for ElementTree.</dd>
</dl>
</div>
</div>
<div class="section" id="the-hashlib-package">
<span id="module-hashlib"></span><h3>The hashlib package<a class="headerlink" href="#the-hashlib-package" title="Permalink to this headline">¶</a></h3>
<p>A new <a class="reference internal" href="../library/hashlib.html#module-hashlib" title="hashlib: Secure hash and message digest algorithms."><tt class="xref py py-mod docutils literal"><span class="pre">hashlib</span></tt></a> module, written by Gregory P. Smith,  has been added to
replace the <tt class="xref py py-mod docutils literal"><span class="pre">md5</span></tt> and <tt class="xref py py-mod docutils literal"><span class="pre">sha</span></tt> modules.  <a class="reference internal" href="../library/hashlib.html#module-hashlib" title="hashlib: Secure hash and message digest algorithms."><tt class="xref py py-mod docutils literal"><span class="pre">hashlib</span></tt></a> adds support for
additional secure hashes (SHA-224, SHA-256, SHA-384, and SHA-512). When
available, the module uses OpenSSL for fast platform optimized implementations
of algorithms.</p>
<p>The old <tt class="xref py py-mod docutils literal"><span class="pre">md5</span></tt> and <tt class="xref py py-mod docutils literal"><span class="pre">sha</span></tt> modules still exist as wrappers around hashlib
to preserve backwards compatibility.  The new module&#8217;s interface is very close
to that of the old modules, but not identical. The most significant difference
is that the constructor functions for creating new hashing objects are named
differently.</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="c"># Old versions</span>
<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>
<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>

<span class="c"># New version</span>
<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>

<span class="c"># Old versions</span>
<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>
<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>

<span class="c"># New version</span>
<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>

<span class="c"># Hash that weren&#39;t previously available</span>
<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>
<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>
<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>
<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>

<span class="c"># Alternative form</span>
<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="s">&#39;md5&#39;</span><span class="p">)</span>          <span class="c"># Provide algorithm as a string</span>
</pre></div>
</div>
<p>Once a hash object has been created, its methods are the same as before:
<tt class="xref py py-meth docutils literal"><span class="pre">update(string)()</span></tt> hashes the specified string into the  current digest
state, <tt class="xref py py-meth docutils literal"><span class="pre">digest()</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">hexdigest()</span></tt> return the digest value as a binary
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."><tt class="xref py py-meth docutils literal"><span class="pre">copy()</span></tt></a> returns a new hashing object
with the same digest state.</p>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">The documentation  for the <a class="reference internal" href="../library/hashlib.html#module-hashlib" title="hashlib: Secure hash and message digest algorithms."><tt class="xref py py-mod docutils literal"><span class="pre">hashlib</span></tt></a> module.</p>
</div>
</div>
<div class="section" id="the-sqlite3-package">
<span id="module-sqlite"></span><h3>The sqlite3 package<a class="headerlink" href="#the-sqlite3-package" title="Permalink to this headline">¶</a></h3>
<p>The pysqlite module (<a class="reference external" href="http://www.pysqlite.org">http://www.pysqlite.org</a>), a wrapper for the SQLite embedded
database, has been added to the standard library under the package name
<a class="reference internal" href="../library/sqlite3.html#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><tt class="xref py py-mod docutils literal"><span class="pre">sqlite3</span></tt></a>.</p>
<p>SQLite is a C library that provides a lightweight disk-based database that
doesn&#8217;t require a separate server process and allows accessing the database
using a nonstandard variant of the SQL query language. Some applications can use
SQLite for internal data storage.  It&#8217;s also possible to prototype an
application using SQLite and then port the code to a larger database such as
PostgreSQL or Oracle.</p>
<p>pysqlite was written by Gerhard Häring and provides a SQL interface compliant
with the DB-API 2.0 specification described by <span class="target" id="index-20"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0249"><strong>PEP 249</strong></a>.</p>
<p>If you&#8217;re compiling the Python source yourself, note that the source tree
doesn&#8217;t include the SQLite code, only the wrapper module. You&#8217;ll need to have
the SQLite libraries and headers installed before compiling Python, and the
build process will compile the module when the necessary headers are available.</p>
<p>To use the module, you must first create a <tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt> object that
represents the database.  Here the data will be stored in the
<tt class="file docutils literal"><span class="pre">/tmp/example</span></tt> file:</p>
<div class="highlight-python3"><div class="highlight"><pre><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="s">&#39;/tmp/example&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>You can also supply the special name <tt class="docutils literal"><span class="pre">:memory:</span></tt> to create a database in RAM.</p>
<p>Once you have a <tt class="xref py py-class docutils literal"><span class="pre">Connection</span></tt>, you can create a <tt class="xref py py-class docutils literal"><span class="pre">Cursor</span></tt>  object
and call its <tt class="xref py py-meth docutils literal"><span class="pre">execute()</span></tt> method to perform SQL commands:</p>
<div class="highlight-python3"><div class="highlight"><pre><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>

<span class="c"># Create table</span>
<span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&#39;&#39;&#39;create table stocks</span>
<span class="s">(date text, trans text, symbol text,</span>
<span class="s"> qty real, price real)&#39;&#39;&#39;</span><span class="p">)</span>

<span class="c"># Insert a row of data</span>
<span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;&quot;&quot;insert into stocks</span>
<span class="s">          values (&#39;2006-01-05&#39;,&#39;BUY&#39;,&#39;RHAT&#39;,100,35.14)&quot;&quot;&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Usually your SQL operations will need to use values from Python variables.  You
shouldn&#8217;t assemble your query using Python&#8217;s string operations because doing so
is insecure; it makes your program vulnerable to an SQL injection attack.</p>
<p>Instead, use the DB-API&#8217;s parameter substitution.  Put <tt class="docutils literal"><span class="pre">?</span></tt> as a placeholder
wherever you want to use a value, and then provide a tuple of values as the
second argument to the cursor&#8217;s <tt class="xref py py-meth docutils literal"><span class="pre">execute()</span></tt> method.  (Other database modules
may use a different placeholder, such as <tt class="docutils literal"><span class="pre">%s</span></tt> or <tt class="docutils literal"><span class="pre">:1</span></tt>.) For example:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="c"># Never do this -- insecure!</span>
<span class="n">symbol</span> <span class="o">=</span> <span class="s">&#39;IBM&#39;</span>
<span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;... where symbol = &#39;%s&#39;&quot;</span> <span class="o">%</span> <span class="n">symbol</span><span class="p">)</span>

<span class="c"># Do this instead</span>
<span class="n">t</span> <span class="o">=</span> <span class="p">(</span><span class="n">symbol</span><span class="p">,)</span>
<span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&#39;select * from stocks where symbol=?&#39;</span><span class="p">,</span> <span class="n">t</span><span class="p">)</span>

<span class="c"># Larger example</span>
<span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="p">((</span><span class="s">&#39;2006-03-28&#39;</span><span class="p">,</span> <span class="s">&#39;BUY&#39;</span><span class="p">,</span> <span class="s">&#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>
          <span class="p">(</span><span class="s">&#39;2006-04-05&#39;</span><span class="p">,</span> <span class="s">&#39;BUY&#39;</span><span class="p">,</span> <span class="s">&#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>
          <span class="p">(</span><span class="s">&#39;2006-04-06&#39;</span><span class="p">,</span> <span class="s">&#39;SELL&#39;</span><span class="p">,</span> <span class="s">&#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>
         <span class="p">):</span>
    <span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&#39;insert into stocks values (?,?,?,?,?)&#39;</span><span class="p">,</span> <span class="n">t</span><span class="p">)</span>
</pre></div>
</div>
<p>To retrieve data after executing a SELECT statement, you can either  treat the
cursor as an iterator, call the cursor&#8217;s <tt class="xref py py-meth docutils literal"><span class="pre">fetchone()</span></tt> method to retrieve a
single matching row,  or call <tt class="xref py py-meth docutils literal"><span class="pre">fetchall()</span></tt> to get a list of the matching
rows.</p>
<p>This example uses the iterator form:</p>
<div class="highlight-python3"><div class="highlight"><pre><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>
<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="s">&#39;select * from stocks order by price&#39;</span><span class="p">)</span>
<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>
<span class="gp">... </span>   <span class="nb">print</span> <span class="n">row</span>
<span class="gp">...</span>
<span class="go">(u&#39;2006-01-05&#39;, u&#39;BUY&#39;, u&#39;RHAT&#39;, 100, 35.140000000000001)</span>
<span class="go">(u&#39;2006-03-28&#39;, u&#39;BUY&#39;, u&#39;IBM&#39;, 1000, 45.0)</span>
<span class="go">(u&#39;2006-04-06&#39;, u&#39;SELL&#39;, u&#39;IBM&#39;, 500, 53.0)</span>
<span class="go">(u&#39;2006-04-05&#39;, u&#39;BUY&#39;, u&#39;MSOFT&#39;, 1000, 72.0)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>For more information about the SQL dialect supported by SQLite, see
<a class="reference external" href="http://www.sqlite.org">http://www.sqlite.org</a>.</p>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="docutils">
<dt><a class="reference external" href="http://www.pysqlite.org">http://www.pysqlite.org</a></dt>
<dd>The pysqlite web page.</dd>
<dt><a class="reference external" href="http://www.sqlite.org">http://www.sqlite.org</a></dt>
<dd>The SQLite web page; the documentation describes the syntax and the available
data types for the supported SQL dialect.</dd>
</dl>
<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."><tt class="xref py py-mod docutils literal"><span class="pre">sqlite3</span></tt></a> module.</p>
<dl class="last docutils">
<dt><span class="target" id="index-21"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0249"><strong>PEP 249</strong></a> - Database API Specification 2.0</dt>
<dd>PEP written by Marc-André Lemburg.</dd>
</dl>
</div>
</div>
<div class="section" id="the-wsgiref-package">
<span id="module-wsgiref"></span><h3>The wsgiref package<a class="headerlink" href="#the-wsgiref-package" title="Permalink to this headline">¶</a></h3>
<p>The Web Server Gateway Interface (WSGI) v1.0 defines a standard interface
between web servers and Python web applications and is described in <span class="target" id="index-22"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0333"><strong>PEP 333</strong></a>.
The <a class="reference internal" href="../library/wsgiref.html#module-wsgiref" title="wsgiref: WSGI Utilities and Reference Implementation."><tt class="xref py py-mod docutils literal"><span class="pre">wsgiref</span></tt></a> package is a reference implementation of the WSGI
specification.</p>
<p>The package includes a basic HTTP server that will run a WSGI application; this
server is useful for debugging but isn&#8217;t intended for  production use.  Setting
up a server takes only a few lines of code:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">wsgiref</span> <span class="k">import</span> <span class="n">simple_server</span>

<span class="n">wsgi_app</span> <span class="o">=</span> <span class="o">...</span>

<span class="n">host</span> <span class="o">=</span> <span class="s">&#39;&#39;</span>
<span class="n">port</span> <span class="o">=</span> <span class="mi">8000</span>
<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>
<span class="n">httpd</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>
</pre></div>
</div>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://www.wsgi.org">http://www.wsgi.org</a></dt>
<dd>A central web site for WSGI-related resources.</dd>
<dt><span class="target" id="index-23"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0333"><strong>PEP 333</strong></a> - Python Web Server Gateway Interface v1.0</dt>
<dd>PEP written by Phillip J. Eby.</dd>
</dl>
</div>
</div>
</div>
<div class="section" id="build-and-c-api-changes">
<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>
<p>Changes to Python&#8217;s build process and to the C API include:</p>
<ul>
<li><p class="first">The Python source tree was converted from CVS to Subversion,  in a complex
migration procedure that was supervised and flawlessly carried out by Martin von
Löwis.  The procedure was developed as <span class="target" id="index-24"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0347"><strong>PEP 347</strong></a>.</p>
</li>
<li><p class="first">Coverity, a company that markets a source code analysis tool called Prevent,
provided the results of their examination of the Python source code.  The
analysis found about 60 bugs that  were quickly fixed.  Many of the bugs were
refcounting problems, often occurring in error-handling code.  See
<a class="reference external" href="http://scan.coverity.com">http://scan.coverity.com</a> for the statistics.</p>
</li>
<li><p class="first">The largest change to the C API came from <span class="target" id="index-25"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0353"><strong>PEP 353</strong></a>, which modifies the
interpreter to use a <tt class="xref c c-type docutils literal"><span class="pre">Py_ssize_t</span></tt> type definition instead of
<tt class="xref c c-type docutils literal"><span class="pre">int</span></tt>.  See the earlier section <a class="reference internal" href="#pep-353"><em>PEP 353: Using ssize_t as the index type</em></a> for a discussion of this
change.</p>
</li>
<li><p class="first">The design of the bytecode compiler has changed a great deal,  no longer
generating bytecode by traversing the parse tree.  Instead the parse tree is
converted to an abstract syntax tree (or AST), and it is  the abstract syntax
tree that&#8217;s traversed to produce the bytecode.</p>
<p>It&#8217;s possible for Python code to obtain AST objects by using the
<a class="reference internal" href="../library/functions.html#compile" title="compile"><tt class="xref py py-func docutils literal"><span class="pre">compile()</span></tt></a> built-in and specifying <tt class="docutils literal"><span class="pre">_ast.PyCF_ONLY_AST</span></tt> as the value of
the  <em>flags</em> parameter:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">_ast</span> <span class="k">import</span> <span class="n">PyCF_ONLY_AST</span>
<span class="n">ast</span> <span class="o">=</span> <span class="nb">compile</span><span class="p">(</span><span class="s">&quot;&quot;&quot;a=0</span>
<span class="s">for i in range(10):</span>
<span class="s">    a += i</span>
<span class="s">&quot;&quot;&quot;</span><span class="p">,</span> <span class="s">&quot;&lt;string&gt;&quot;</span><span class="p">,</span> <span class="s">&#39;exec&#39;</span><span class="p">,</span> <span class="n">PyCF_ONLY_AST</span><span class="p">)</span>

<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>
<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>
</pre></div>
</div>
<p>No official documentation has been written for the AST code yet, but <span class="target" id="index-26"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0339"><strong>PEP 339</strong></a>
discusses the design.  To start learning about the code, read the definition of
the various AST nodes in <tt class="file docutils literal"><span class="pre">Parser/Python.asdl</span></tt>.  A Python script reads this
file and generates a set of C structure definitions in
<tt class="file docutils literal"><span class="pre">Include/Python-ast.h</span></tt>.  The <tt class="xref c c-func docutils literal"><span class="pre">PyParser_ASTFromString()</span></tt> and
<tt class="xref c c-func docutils literal"><span class="pre">PyParser_ASTFromFile()</span></tt>, defined in <tt class="file docutils literal"><span class="pre">Include/pythonrun.h</span></tt>, take
Python source as input and return the root of an AST representing the contents.
This AST can then be turned into a code object by <tt class="xref c c-func docutils literal"><span class="pre">PyAST_Compile()</span></tt>.  For
more information, read the source code, and then ask questions on python-dev.</p>
<p>The AST code was developed under Jeremy Hylton&#8217;s management, and implemented by
(in alphabetical order) Brett Cannon, Nick Coghlan, Grant Edwards, John
Ehresman, Kurt Kaiser, Neal Norwitz, Tim Peters, Armin Rigo, and Neil
Schemenauer, plus the participants in a number of AST sprints at conferences
such as PyCon.</p>
</li>
<li><p class="first">Evan Jones&#8217;s patch to obmalloc, first described in a talk at PyCon DC 2005,
was applied.  Python 2.4 allocated small objects in 256K-sized arenas, but never
freed arenas.  With this patch, Python will free arenas when they&#8217;re empty.  The
net effect is that on some platforms, when you allocate many objects, Python&#8217;s
memory usage may actually drop when you delete them and the memory may be
returned to the operating system.  (Implemented by Evan Jones, and reworked by
Tim Peters.)</p>
<p>Note that this change means extension modules must be more careful when
allocating memory.  Python&#8217;s API has many different functions for allocating
memory that are grouped into families.  For example, <a class="reference internal" href="../c-api/memory.html#PyMem_Malloc" title="PyMem_Malloc"><tt class="xref c c-func docutils literal"><span class="pre">PyMem_Malloc()</span></tt></a>,
<a class="reference internal" href="../c-api/memory.html#PyMem_Realloc" title="PyMem_Realloc"><tt class="xref c c-func docutils literal"><span class="pre">PyMem_Realloc()</span></tt></a>, and <a class="reference internal" href="../c-api/memory.html#PyMem_Free" title="PyMem_Free"><tt class="xref c c-func docutils literal"><span class="pre">PyMem_Free()</span></tt></a> are one family that allocates
raw memory, while <tt class="xref c c-func docutils literal"><span class="pre">PyObject_Malloc()</span></tt>, <tt class="xref c c-func docutils literal"><span class="pre">PyObject_Realloc()</span></tt>, and
<tt class="xref c c-func docutils literal"><span class="pre">PyObject_Free()</span></tt> are another family that&#8217;s supposed to be used for
creating Python objects.</p>
<p>Previously these different families all reduced to the platform&#8217;s
<tt class="xref c c-func docutils literal"><span class="pre">malloc()</span></tt> and <tt class="xref c c-func docutils literal"><span class="pre">free()</span></tt> functions.  This meant  it didn&#8217;t matter if
you got things wrong and allocated memory with the <tt class="xref c c-func docutils literal"><span class="pre">PyMem()</span></tt> function but
freed it with the <a class="reference internal" href="../c-api/structures.html#PyObject" title="PyObject"><tt class="xref c c-func docutils literal"><span class="pre">PyObject()</span></tt></a> function.  With 2.5&#8217;s changes to obmalloc,
these families now do different things and mismatches will probably result in a
segfault.  You should carefully test your C extension modules with Python 2.5.</p>
</li>
<li><p class="first">The built-in set types now have an official C API.  Call <a class="reference internal" href="../c-api/set.html#PySet_New" title="PySet_New"><tt class="xref c c-func docutils literal"><span class="pre">PySet_New()</span></tt></a>
and <a class="reference internal" href="../c-api/set.html#PyFrozenSet_New" title="PyFrozenSet_New"><tt class="xref c c-func docutils literal"><span class="pre">PyFrozenSet_New()</span></tt></a> to create a new set, <a class="reference internal" href="../c-api/set.html#PySet_Add" title="PySet_Add"><tt class="xref c c-func docutils literal"><span class="pre">PySet_Add()</span></tt></a> and
<a class="reference internal" href="../c-api/set.html#PySet_Discard" title="PySet_Discard"><tt class="xref c c-func docutils literal"><span class="pre">PySet_Discard()</span></tt></a> to add and remove elements, and <a class="reference internal" href="../c-api/set.html#PySet_Contains" title="PySet_Contains"><tt class="xref c c-func docutils literal"><span class="pre">PySet_Contains()</span></tt></a>
and <a class="reference internal" href="../c-api/set.html#PySet_Size" title="PySet_Size"><tt class="xref c c-func docutils literal"><span class="pre">PySet_Size()</span></tt></a> to examine the set&#8217;s state. (Contributed by Raymond
Hettinger.)</p>
</li>
<li><p class="first">C code can now obtain information about the exact revision of the Python
interpreter by calling the  <a class="reference internal" href="../c-api/init.html#Py_GetBuildInfo" title="Py_GetBuildInfo"><tt class="xref c c-func docutils literal"><span class="pre">Py_GetBuildInfo()</span></tt></a> function that returns a
string of build information like this: <tt class="docutils literal"><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></tt>.   (Contributed by Barry Warsaw.)</p>
</li>
<li><p class="first">Two new macros can be used to indicate C functions that are local to the
current file so that a faster calling convention can be used.
<tt class="xref c c-func docutils literal"><span class="pre">Py_LOCAL(type)()</span></tt> declares the function as returning a value of the
specified <em>type</em> and uses a fast-calling qualifier.
<tt class="xref c c-func docutils literal"><span class="pre">Py_LOCAL_INLINE(type)()</span></tt> does the same thing and also requests the
function be inlined.  If <tt class="xref c c-func docutils literal"><span class="pre">PY_LOCAL_AGGRESSIVE()</span></tt> is defined before
<tt class="file docutils literal"><span class="pre">python.h</span></tt> is included, a set of more aggressive optimizations are enabled
for the module; you should benchmark the results to find out if these
optimizations actually make the code faster.  (Contributed by Fredrik Lundh at
the NeedForSpeed sprint.)</p>
</li>
<li><p class="first"><tt class="xref c c-func docutils literal"><span class="pre">PyErr_NewException(name,</span> <span class="pre">base,</span> <span class="pre">dict)()</span></tt> can now accept a tuple of base
classes as its <em>base</em> argument.  (Contributed by Georg Brandl.)</p>
</li>
<li><p class="first">The <tt class="xref c c-func docutils literal"><span class="pre">PyErr_Warn()</span></tt> function for issuing warnings is now deprecated in
favour of <tt class="xref c c-func docutils literal"><span class="pre">PyErr_WarnEx(category,</span> <span class="pre">message,</span> <span class="pre">stacklevel)()</span></tt> which lets you
specify the number of stack frames separating this function and the caller.  A
<em>stacklevel</em> of 1 is the function calling <a class="reference internal" href="../c-api/exceptions.html#PyErr_WarnEx" title="PyErr_WarnEx"><tt class="xref c c-func docutils literal"><span class="pre">PyErr_WarnEx()</span></tt></a>, 2 is the
function above that, and so forth.  (Added by Neal Norwitz.)</p>
</li>
<li><p class="first">The CPython interpreter is still written in C, but  the code can now be
compiled with a C++ compiler without errors.   (Implemented by Anthony Baxter,
Martin von Löwis, Skip Montanaro.)</p>
</li>
<li><p class="first">The <tt class="xref c c-func docutils literal"><span class="pre">PyRange_New()</span></tt> function was removed.  It was never documented, never
used in the core code, and had dangerously lax error checking.  In the unlikely
case that your extensions were using it, you can replace it by something like
the following:</p>
<div class="highlight-python3"><div class="highlight"><pre><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="s">&quot;lll&quot;</span><span class="p">,</span>
                              <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>
</pre></div>
</div>
</li>
</ul>
<div class="section" id="port-specific-changes">
<span id="ports"></span><h3>Port-Specific Changes<a class="headerlink" href="#port-specific-changes" title="Permalink to this headline">¶</a></h3>
<ul class="simple">
<li>MacOS X (10.3 and higher): dynamic loading of modules now uses the
<tt class="xref c c-func docutils literal"><span class="pre">dlopen()</span></tt> function instead of MacOS-specific functions.</li>
<li>MacOS X: an <em class="xref std std-option">--enable-universalsdk</em> switch was added to the
<strong class="program">configure</strong> script that compiles the interpreter as a universal binary
able to run on both PowerPC and Intel processors. (Contributed by Ronald
Oussoren; <a class="reference external" href="http://bugs.python.org/issue2573">issue 2573</a>.)</li>
<li>Windows: <tt class="file docutils literal"><span class="pre">.dll</span></tt> is no longer supported as a filename extension for
extension modules.  <tt class="file docutils literal"><span class="pre">.pyd</span></tt> is now the only filename extension that will be
searched for.</li>
</ul>
</div>
</div>
<div class="section" id="porting-to-python-2-5">
<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>
<p>This section lists previously described changes that may require changes to your
code:</p>
<ul class="simple">
<li>ASCII is now the default encoding for modules.  It&#8217;s now  a syntax error if a
module contains string literals with 8-bit characters but doesn&#8217;t have an
encoding declaration.  In Python 2.4 this triggered a warning, not a syntax
error.</li>
<li>Previously, the <tt class="xref py py-attr docutils literal"><span class="pre">gi_frame</span></tt> attribute of a generator was always a frame
object.  Because of the <span class="target" id="index-27"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0342"><strong>PEP 342</strong></a> changes described in section <a class="reference internal" href="#pep-342"><em>PEP 342: New Generator Features</em></a>,
it&#8217;s now possible for <tt class="xref py py-attr docutils literal"><span class="pre">gi_frame</span></tt> to be <tt class="xref docutils literal"><span class="pre">None</span></tt>.</li>
<li>A new warning, <a class="reference internal" href="../library/exceptions.html#UnicodeWarning" title="UnicodeWarning"><tt class="xref py py-class docutils literal"><span class="pre">UnicodeWarning</span></tt></a>, is triggered when  you attempt to
compare a Unicode string and an 8-bit string that can&#8217;t be converted to Unicode
using the default ASCII encoding.  Previously such comparisons would raise a
<a class="reference internal" href="../library/exceptions.html#UnicodeDecodeError" title="UnicodeDecodeError"><tt class="xref py py-class docutils literal"><span class="pre">UnicodeDecodeError</span></tt></a> exception.</li>
<li>Library: the <a class="reference internal" href="../library/csv.html#module-csv" title="csv: Write and read tabular data to and from delimited files."><tt class="xref py py-mod docutils literal"><span class="pre">csv</span></tt></a> module is now stricter about multi-line quoted fields.
If your files contain newlines embedded within fields, the input should be split
into lines in a manner which preserves the newline characters.</li>
<li>Library: the <a class="reference internal" href="../library/locale.html#module-locale" title="locale: Internationalization services."><tt class="xref py py-mod docutils literal"><span class="pre">locale</span></tt></a> module&#8217;s  <a class="reference internal" href="../library/functions.html#format" title="format"><tt class="xref py py-func docutils literal"><span class="pre">format()</span></tt></a> function&#8217;s would
previously  accept any string as long as no more than one %char specifier
appeared.  In Python 2.5, the argument must be exactly one %char specifier with
no surrounding text.</li>
<li>Library: The <a class="reference internal" href="../library/pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><tt class="xref py py-mod docutils literal"><span class="pre">pickle</span></tt></a> and <tt class="xref py py-mod docutils literal"><span class="pre">cPickle</span></tt> modules no longer accept a
return value of <tt class="xref docutils literal"><span class="pre">None</span></tt> from the <tt class="xref py py-meth docutils literal"><span class="pre">__reduce__()</span></tt> method; the method must
return a tuple of arguments instead.  The modules also no longer accept the
deprecated <em>bin</em> keyword parameter.</li>
<li>Library: The <tt class="xref py py-mod docutils literal"><span class="pre">SimpleXMLRPCServer</span></tt> and <tt class="xref py py-mod docutils literal"><span class="pre">DocXMLRPCServer</span></tt>  classes now
have a <tt class="xref py py-attr docutils literal"><span class="pre">rpc_paths</span></tt> attribute that constrains XML-RPC operations to a
limited set of URL paths; the default is to allow only <tt class="docutils literal"><span class="pre">'/'</span></tt> and <tt class="docutils literal"><span class="pre">'/RPC2'</span></tt>.
Setting  <tt class="xref py py-attr docutils literal"><span class="pre">rpc_paths</span></tt> to <tt class="xref docutils literal"><span class="pre">None</span></tt> or an empty tuple disables  this path
checking.</li>
<li>C API: Many functions now use <tt class="xref c c-type docutils literal"><span class="pre">Py_ssize_t</span></tt>  instead of <tt class="xref c c-type docutils literal"><span class="pre">int</span></tt> to
allow processing more data on 64-bit machines.  Extension code may need to make
the same change to avoid warnings and to support 64-bit machines.  See the
earlier section <a class="reference internal" href="#pep-353"><em>PEP 353: Using ssize_t as the index type</em></a> for a discussion of this change.</li>
<li>C API:  The obmalloc changes mean that  you must be careful to not mix usage
of the <tt class="xref c c-func docutils literal"><span class="pre">PyMem_*()</span></tt> and <tt class="xref c c-func docutils literal"><span class="pre">PyObject_*()</span></tt> families of functions. Memory
allocated with  one family&#8217;s <tt class="xref c c-func docutils literal"><span class="pre">*_Malloc()</span></tt> must be  freed with the
corresponding family&#8217;s <tt class="xref c c-func docutils literal"><span class="pre">*_Free()</span></tt> function.</li>
</ul>
</div>
<div class="section" id="acknowledgements">
<h2>Acknowledgements<a class="headerlink" href="#acknowledgements" title="Permalink to this headline">¶</a></h2>
<p>The author would like to thank the following people for offering suggestions,
corrections and assistance with various drafts of this article: Georg Brandl,
Nick Coghlan, Phillip J. Eby, Lars Gustäbel, Raymond Hettinger, Ralf W. Grosse-
Kunstleve, Kent Johnson, Iain Lowe, Martin von Löwis, Fredrik Lundh, Andrew
McNamara, Skip Montanaro, Gustavo Niemeyer, Paul Prescod, James Pryor, Mike
Rovner, Scott Weikart, Barry Warsaw, Thomas Wouters.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">What&#8217;s New in Python 2.5</a><ul>
<li><a class="reference internal" href="#pep-308-conditional-expressions">PEP 308: Conditional Expressions</a></li>
<li><a class="reference internal" href="#pep-309-partial-function-application">PEP 309: Partial Function Application</a></li>
<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>
<li><a class="reference internal" href="#pep-328-absolute-and-relative-imports">PEP 328: Absolute and Relative Imports</a></li>
<li><a class="reference internal" href="#pep-338-executing-modules-as-scripts">PEP 338: Executing Modules as Scripts</a></li>
<li><a class="reference internal" href="#pep-341-unified-try-except-finally">PEP 341: Unified try/except/finally</a></li>
<li><a class="reference internal" href="#pep-342-new-generator-features">PEP 342: New Generator Features</a></li>
<li><a class="reference internal" href="#pep-343-the-with-statement">PEP 343: The &#8216;with&#8217; statement</a><ul>
<li><a class="reference internal" href="#writing-context-managers">Writing Context Managers</a></li>
<li><a class="reference internal" href="#the-contextlib-module">The contextlib module</a></li>
</ul>
</li>
<li><a class="reference internal" href="#pep-352-exceptions-as-new-style-classes">PEP 352: Exceptions as New-Style Classes</a></li>
<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>
<li><a class="reference internal" href="#pep-357-the-index-method">PEP 357: The &#8216;__index__&#8217; method</a></li>
<li><a class="reference internal" href="#other-language-changes">Other Language Changes</a><ul>
<li><a class="reference internal" href="#interactive-interpreter-changes">Interactive Interpreter Changes</a></li>
<li><a class="reference internal" href="#optimizations">Optimizations</a></li>
</ul>
</li>
<li><a class="reference internal" href="#new-improved-and-removed-modules">New, Improved, and Removed Modules</a><ul>
<li><a class="reference internal" href="#the-ctypes-package">The ctypes package</a></li>
<li><a class="reference internal" href="#the-elementtree-package">The ElementTree package</a></li>
<li><a class="reference internal" href="#the-hashlib-package">The hashlib package</a></li>
<li><a class="reference internal" href="#the-sqlite3-package">The sqlite3 package</a></li>
<li><a class="reference internal" href="#the-wsgiref-package">The wsgiref package</a></li>
</ul>
</li>
<li><a class="reference internal" href="#build-and-c-api-changes">Build and C API Changes</a><ul>
<li><a class="reference internal" href="#port-specific-changes">Port-Specific Changes</a></li>
</ul>
</li>
<li><a class="reference internal" href="#porting-to-python-2-5">Porting to Python 2.5</a></li>
<li><a class="reference internal" href="#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="2.6.html"
                        title="previous chapter">What&#8217;s New in Python 2.6</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="2.4.html"
                        title="next chapter">What&#8217;s New in Python 2.4</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
  <li><a href="../bugs.html">Report a Bug</a></li>
  <li><a href="../_sources/whatsnew/2.5.txt"
         rel="nofollow">Show Source</a></li>
</ul>

<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" size="18" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="2.4.html" title="What’s New in Python 2.4"
             >next</a> |</li>
        <li class="right" >
          <a href="2.6.html" title="What’s New in Python 2.6"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="../index.html">Python v3.2.2 documentation</a> &raquo;</li>

          <li><a href="index.html" >What&#8217;s New in Python</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2011, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.  
    <a href="http://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Sep 04, 2011.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.0.7.
    </div>

  </body>
</html>