[ SEA-GHOST MINI SHELL]
<!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.3 — Python 2.7.5 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: '2.7.5',
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 2.7.5 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 2.7.5 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.2" href="2.2.html" />
<link rel="prev" title="What’s New in Python 2.4" href="2.4.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
</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.2.html" title="What’s New in Python 2.2"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="2.4.html" title="What’s New in Python 2.4"
accesskey="P">previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="http://www.python.org/">Python</a> »</li>
<li>
<a href="../index.html">Python 2.7.5 documentation</a> »
</li>
<li><a href="index.html" accesskey="U">What’s New in Python</a> »</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-3">
<h1>What’s New in Python 2.3<a class="headerlink" href="#what-s-new-in-python-2-3" 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-odd 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.3. Python 2.3 was released
on July 29, 2003.</p>
<p>The main themes for Python 2.3 are polishing some of the features added in 2.2,
adding various small but useful enhancements to the core language, and expanding
the standard library. The new object model introduced in the previous version
has benefited from 18 months of bugfixes and from optimization efforts that have
improved the performance of new-style classes. A few new built-in functions
have been added such as <a class="reference internal" href="../library/functions.html#sum" title="sum"><tt class="xref py py-func docutils literal"><span class="pre">sum()</span></tt></a> and <a class="reference internal" href="../library/functions.html#enumerate" title="enumerate"><tt class="xref py py-func docutils literal"><span class="pre">enumerate()</span></tt></a>. The <a class="reference internal" href="../reference/expressions.html#in"><tt class="xref std std-keyword docutils literal"><span class="pre">in</span></tt></a>
operator can now be used for substring searches (e.g. <tt class="docutils literal"><span class="pre">"ab"</span> <span class="pre">in</span> <span class="pre">"abc"</span></tt> returns
<a class="reference internal" href="../library/constants.html#True" title="True"><tt class="xref py py-const docutils literal"><span class="pre">True</span></tt></a>).</p>
<p>Some of the many new library features include Boolean, set, heap, and date/time
data types, the ability to import modules from ZIP-format archives, metadata
support for the long-awaited Python catalog, an updated version of IDLE, and
modules for logging messages, wrapping text, parsing CSV files, processing
command-line options, using BerkeleyDB databases... the list of new and
enhanced modules is lengthy.</p>
<p>This article doesn’t attempt to provide a complete specification of the new
features, but instead provides a convenient overview. For full details, you
should refer to the documentation for Python 2.3, such as the Python Library
Reference and the Python Reference Manual. If you want to understand the
complete implementation and design rationale, refer to the PEP for a particular
new feature.</p>
<div class="section" id="pep-218-a-standard-set-datatype">
<h2>PEP 218: A Standard Set Datatype<a class="headerlink" href="#pep-218-a-standard-set-datatype" title="Permalink to this headline">¶</a></h2>
<p>The new <a class="reference internal" href="../library/sets.html#module-sets" title="sets: Implementation of sets of unique elements. (deprecated)"><tt class="xref py py-mod docutils literal"><span class="pre">sets</span></tt></a> module contains an implementation of a set datatype. The
<tt class="xref py py-class docutils literal"><span class="pre">Set</span></tt> class is for mutable sets, sets that can have members added and
removed. The <tt class="xref py py-class docutils literal"><span class="pre">ImmutableSet</span></tt> class is for sets that can’t be modified,
and instances of <tt class="xref py py-class docutils literal"><span class="pre">ImmutableSet</span></tt> can therefore be used as dictionary keys.
Sets are built on top of dictionaries, so the elements within a set must be
hashable.</p>
<p>Here’s a simple example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">sets</span>
<span class="gp">>>> </span><span class="n">S</span> <span class="o">=</span> <span class="n">sets</span><span class="o">.</span><span class="n">Set</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">S</span>
<span class="go">Set([1, 2, 3])</span>
<span class="gp">>>> </span><span class="mi">1</span> <span class="ow">in</span> <span class="n">S</span>
<span class="go">True</span>
<span class="gp">>>> </span><span class="mi">0</span> <span class="ow">in</span> <span class="n">S</span>
<span class="go">False</span>
<span class="gp">>>> </span><span class="n">S</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">S</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">S</span>
<span class="go">Set([1, 2, 5])</span>
<span class="go">>>></span>
</pre></div>
</div>
<p>The union and intersection of sets can be computed with the <tt class="xref py py-meth docutils literal"><span class="pre">union()</span></tt> and
<tt class="xref py py-meth docutils literal"><span class="pre">intersection()</span></tt> methods; an alternative notation uses the bitwise operators
<tt class="docutils literal"><span class="pre">&</span></tt> and <tt class="docutils literal"><span class="pre">|</span></tt>. Mutable sets also have in-place versions of these methods,
<tt class="xref py py-meth docutils literal"><span class="pre">union_update()</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">intersection_update()</span></tt>.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">S1</span> <span class="o">=</span> <span class="n">sets</span><span class="o">.</span><span class="n">Set</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">S2</span> <span class="o">=</span> <span class="n">sets</span><span class="o">.</span><span class="n">Set</span><span class="p">([</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">6</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">S1</span><span class="o">.</span><span class="n">union</span><span class="p">(</span><span class="n">S2</span><span class="p">)</span>
<span class="go">Set([1, 2, 3, 4, 5, 6])</span>
<span class="gp">>>> </span><span class="n">S1</span> <span class="o">|</span> <span class="n">S2</span> <span class="c"># Alternative notation</span>
<span class="go">Set([1, 2, 3, 4, 5, 6])</span>
<span class="gp">>>> </span><span class="n">S1</span><span class="o">.</span><span class="n">intersection</span><span class="p">(</span><span class="n">S2</span><span class="p">)</span>
<span class="go">Set([])</span>
<span class="gp">>>> </span><span class="n">S1</span> <span class="o">&</span> <span class="n">S2</span> <span class="c"># Alternative notation</span>
<span class="go">Set([])</span>
<span class="gp">>>> </span><span class="n">S1</span><span class="o">.</span><span class="n">union_update</span><span class="p">(</span><span class="n">S2</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">S1</span>
<span class="go">Set([1, 2, 3, 4, 5, 6])</span>
<span class="go">>>></span>
</pre></div>
</div>
<p>It’s also possible to take the symmetric difference of two sets. This is the
set of all elements in the union that aren’t in the intersection. Another way
of putting it is that the symmetric difference contains all elements that are in
exactly one set. Again, there’s an alternative notation (<tt class="docutils literal"><span class="pre">^</span></tt>), and an in-
place version with the ungainly name <tt class="xref py py-meth docutils literal"><span class="pre">symmetric_difference_update()</span></tt>.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">S1</span> <span class="o">=</span> <span class="n">sets</span><span class="o">.</span><span class="n">Set</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">S2</span> <span class="o">=</span> <span class="n">sets</span><span class="o">.</span><span class="n">Set</span><span class="p">([</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">6</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">S1</span><span class="o">.</span><span class="n">symmetric_difference</span><span class="p">(</span><span class="n">S2</span><span class="p">)</span>
<span class="go">Set([1, 2, 5, 6])</span>
<span class="gp">>>> </span><span class="n">S1</span> <span class="o">^</span> <span class="n">S2</span>
<span class="go">Set([1, 2, 5, 6])</span>
<span class="go">>>></span>
</pre></div>
</div>
<p>There are also <tt class="xref py py-meth docutils literal"><span class="pre">issubset()</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">issuperset()</span></tt> methods for checking
whether one set is a subset or superset of another:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">S1</span> <span class="o">=</span> <span class="n">sets</span><span class="o">.</span><span class="n">Set</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">S2</span> <span class="o">=</span> <span class="n">sets</span><span class="o">.</span><span class="n">Set</span><span class="p">([</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">S2</span><span class="o">.</span><span class="n">issubset</span><span class="p">(</span><span class="n">S1</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">>>> </span><span class="n">S1</span><span class="o">.</span><span class="n">issubset</span><span class="p">(</span><span class="n">S2</span><span class="p">)</span>
<span class="go">False</span>
<span class="gp">>>> </span><span class="n">S1</span><span class="o">.</span><span class="n">issuperset</span><span class="p">(</span><span class="n">S2</span><span class="p">)</span>
<span class="go">True</span>
<span class="go">>>></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-0"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0218"><strong>PEP 218</strong></a> - Adding a Built-In Set Object Type</dt>
<dd>PEP written by Greg V. Wilson. Implemented by Greg V. Wilson, Alex Martelli, and
GvR.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-255-simple-generators">
<span id="section-generators"></span><h2>PEP 255: Simple Generators<a class="headerlink" href="#pep-255-simple-generators" title="Permalink to this headline">¶</a></h2>
<p>In Python 2.2, generators were added as an optional feature, to be enabled by a
<tt class="docutils literal"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">generators</span></tt> directive. In 2.3 generators no longer
need to be specially enabled, and are now always present; this means that
<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 always a keyword. The rest of this section is a copy of
the description of generators from the “What’s New in Python 2.2” document; if
you read it back when Python 2.2 came out, you can skip the rest of this
section.</p>
<p>You’re doubtless familiar with how function calls work in Python or C. When you
call a function, it gets a private namespace where its local variables are
created. When the function reaches 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, the local
variables are destroyed and the resulting value is returned to the caller. A
later call to the same function will get a fresh new set of local variables.
But, what if the local variables weren’t thrown away on exiting a function?
What if you could later resume the function where it left off? This is what
generators provide; they can be thought of as resumable functions.</p>
<p>Here’s the simplest example of a generator function:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">generate_ints</span><span class="p">(</span><span class="n">N</span><span class="p">):</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">N</span><span class="p">):</span>
<span class="k">yield</span> <span class="n">i</span>
</pre></div>
</div>
<p>A new keyword, <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 introduced for generators. Any function
containing 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> statement is a generator function; this is
detected by Python’s bytecode compiler which compiles the function specially as
a result.</p>
<p>When you call a generator function, it doesn’t return a single value; instead it
returns a generator object that supports the iterator protocol. On executing
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 generator outputs the value of <tt class="docutils literal"><span class="pre">i</span></tt>,
similar to 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. The big difference between
<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> 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 is that on reaching 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> the generator’s state of execution is suspended and local
variables are preserved. On the next call to the generator’s <tt class="docutils literal"><span class="pre">.next()</span></tt>
method, the function will resume executing immediately 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. (For complicated reasons, 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 isn’t allowed inside 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> block of a <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>...<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> statement; read <span class="target" id="index-1"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0255"><strong>PEP 255</strong></a> for a full explanation of the
interaction between <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> and exceptions.)</p>
<p>Here’s a sample usage of the <tt class="xref py py-func docutils literal"><span class="pre">generate_ints()</span></tt> generator:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">gen</span> <span class="o">=</span> <span class="n">generate_ints</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">gen</span>
<span class="go"><generator object at 0x8117f90></span>
<span class="gp">>>> </span><span class="n">gen</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">0</span>
<span class="gp">>>> </span><span class="n">gen</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">1</span>
<span class="gp">>>> </span><span class="n">gen</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">2</span>
<span class="gp">>>> </span><span class="n">gen</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">"stdin"</span>, line <span class="m">1</span>, in <span class="n">?</span>
File <span class="nb">"stdin"</span>, line <span class="m">2</span>, in <span class="n">generate_ints</span>
<span class="gr">StopIteration</span>
</pre></div>
</div>
<p>You could equally write <tt class="docutils literal"><span class="pre">for</span> <span class="pre">i</span> <span class="pre">in</span> <span class="pre">generate_ints(5)</span></tt>, or <tt class="docutils literal"><span class="pre">a,b,c</span> <span class="pre">=</span>
<span class="pre">generate_ints(3)</span></tt>.</p>
<p>Inside a generator function, the <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 can only be used
without a value, and signals the end of the procession of values; afterwards the
generator cannot return any further values. <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> with a value, such
as <tt class="docutils literal"><span class="pre">return</span> <span class="pre">5</span></tt>, is a syntax error inside a generator function. The end of the
generator’s results can also be indicated by raising <a class="reference internal" href="../library/exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><tt class="xref py py-exc docutils literal"><span class="pre">StopIteration</span></tt></a>
manually, or by just letting the flow of execution fall off the bottom of the
function.</p>
<p>You could achieve the effect of generators manually by writing your own class
and storing all the local variables of the generator as instance variables. For
example, returning a list of integers could be done by setting <tt class="docutils literal"><span class="pre">self.count</span></tt> to
0, and having the <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 increment <tt class="docutils literal"><span class="pre">self.count</span></tt> and return it.
However, for a moderately complicated generator, writing a corresponding class
would be much messier. <tt class="file docutils literal"><span class="pre">Lib/test/test_generators.py</span></tt> contains a number of
more interesting examples. The simplest one implements an in-order traversal of
a tree using generators recursively.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># A recursive generator that generates Tree leaves in in-order.</span>
<span class="k">def</span> <span class="nf">inorder</span><span class="p">(</span><span class="n">t</span><span class="p">):</span>
<span class="k">if</span> <span class="n">t</span><span class="p">:</span>
<span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">inorder</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">left</span><span class="p">):</span>
<span class="k">yield</span> <span class="n">x</span>
<span class="k">yield</span> <span class="n">t</span><span class="o">.</span><span class="n">label</span>
<span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">inorder</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">right</span><span class="p">):</span>
<span class="k">yield</span> <span class="n">x</span>
</pre></div>
</div>
<p>Two other examples in <tt class="file docutils literal"><span class="pre">Lib/test/test_generators.py</span></tt> produce solutions for
the N-Queens problem (placing $N$ queens on an $NxN$ chess board so that no
queen threatens another) and the Knight’s Tour (a route that takes a knight to
every square of an $NxN$ chessboard without visiting any square twice).</p>
<p>The idea of generators comes from other programming languages, especially Icon
(<a class="reference external" href="http://www.cs.arizona.edu/icon/">http://www.cs.arizona.edu/icon/</a>), where the idea of generators is central. In
Icon, every expression and function call behaves like a generator. One example
from “An Overview of the Icon Programming Language” at
<a class="reference external" href="http://www.cs.arizona.edu/icon/docs/ipd266.htm">http://www.cs.arizona.edu/icon/docs/ipd266.htm</a> gives an idea of what this looks
like:</p>
<div class="highlight-python"><pre>sentence := "Store it in the neighboring harbor"
if (i := find("or", sentence)) > 5 then write(i)</pre>
</div>
<p>In Icon the <tt class="xref py py-func docutils literal"><span class="pre">find()</span></tt> function returns the indexes at which the substring
“or” is found: 3, 23, 33. In the <a class="reference internal" href="../reference/compound_stmts.html#if"><tt class="xref std std-keyword docutils literal"><span class="pre">if</span></tt></a> statement, <tt class="docutils literal"><span class="pre">i</span></tt> is first
assigned a value of 3, but 3 is less than 5, so the comparison fails, and Icon
retries it with the second value of 23. 23 is greater than 5, so the comparison
now succeeds, and the code prints the value 23 to the screen.</p>
<p>Python doesn’t go nearly as far as Icon in adopting generators as a central
concept. Generators are considered part of the core Python language, but
learning or using them isn’t compulsory; if they don’t solve any problems that
you have, feel free to ignore them. One novel feature of Python’s interface as
compared to Icon’s is that a generator’s state is represented as a concrete
object (the iterator) that can be passed around to other functions or stored in
a data structure.</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-0255"><strong>PEP 255</strong></a> - Simple Generators</dt>
<dd>Written by Neil Schemenauer, Tim Peters, Magnus Lie Hetland. Implemented mostly
by Neil Schemenauer and Tim Peters, with other fixes from the Python Labs crew.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-263-source-code-encodings">
<span id="section-encodings"></span><h2>PEP 263: Source Code Encodings<a class="headerlink" href="#pep-263-source-code-encodings" title="Permalink to this headline">¶</a></h2>
<p>Python source files can now be declared as being in different character set
encodings. Encodings are declared by including a specially formatted comment in
the first or second line of the source file. For example, a UTF-8 file can be
declared with:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c">#!/usr/bin/env python</span>
<span class="c"># -*- coding: UTF-8 -*-</span>
</pre></div>
</div>
<p>Without such an encoding declaration, the default encoding used is 7-bit ASCII.
Executing or importing modules that contain string literals with 8-bit
characters and have no encoding declaration will result in a
<a class="reference internal" href="../library/exceptions.html#exceptions.DeprecationWarning" title="exceptions.DeprecationWarning"><tt class="xref py py-exc docutils literal"><span class="pre">DeprecationWarning</span></tt></a> being signalled by Python 2.3; in 2.4 this will be a
syntax error.</p>
<p>The encoding declaration only affects Unicode string literals, which will be
converted to Unicode using the specified encoding. Note that Python identifiers
are still restricted to ASCII characters, so you can’t have variable names that
use characters outside of the usual alphanumerics.</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-3"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0263"><strong>PEP 263</strong></a> - Defining Python Source Code Encodings</dt>
<dd>Written by Marc-André Lemburg and Martin von Löwis; implemented by Suzuki Hisao
and Martin von Löwis.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-273-importing-modules-from-zip-archives">
<h2>PEP 273: Importing Modules from ZIP Archives<a class="headerlink" href="#pep-273-importing-modules-from-zip-archives" title="Permalink to this headline">¶</a></h2>
<p>The new <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 adds support for importing modules from a ZIP-
format archive. You don’t need to import the module explicitly; it will be
automatically imported if a ZIP archive’s filename is added to <tt class="docutils literal"><span class="pre">sys.path</span></tt>.
For example:</p>
<div class="highlight-python"><pre>amk@nyman:~/src/python$ unzip -l /tmp/example.zip
Archive: /tmp/example.zip
Length Date Time Name
-------- ---- ---- ----
8467 11-26-02 22:30 jwzthreading.py
-------- -------
8467 1 file
amk@nyman:~/src/python$ ./python
Python 2.3 (#1, Aug 1 2003, 19:54:32)
>>> import sys
>>> sys.path.insert(0, '/tmp/example.zip') # Add .zip file to front of path
>>> import jwzthreading
>>> jwzthreading.__file__
'/tmp/example.zip/jwzthreading.py'
>>></pre>
</div>
<p>An entry in <tt class="docutils literal"><span class="pre">sys.path</span></tt> can now be the filename of a ZIP archive. The ZIP
archive can contain any kind of files, but only files named <tt class="file docutils literal"><span class="pre">*.py</span></tt>,
<tt class="file docutils literal"><span class="pre">*.pyc</span></tt>, or <tt class="file docutils literal"><span class="pre">*.pyo</span></tt> can be imported. If an archive only contains
<tt class="file docutils literal"><span class="pre">*.py</span></tt> files, Python will not attempt to modify the archive by adding the
corresponding <tt class="file docutils literal"><span class="pre">*.pyc</span></tt> file, meaning that if a ZIP archive doesn’t contain
<tt class="file docutils literal"><span class="pre">*.pyc</span></tt> files, importing may be rather slow.</p>
<p>A path within the archive can also be specified to only import from a
subdirectory; for example, the path <tt class="file docutils literal"><span class="pre">/tmp/example.zip/lib/</span></tt> would only
import from the <tt class="file docutils literal"><span class="pre">lib/</span></tt> subdirectory within 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-4"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0273"><strong>PEP 273</strong></a> - Import Modules from Zip Archives</dt>
<dd>Written by James C. Ahlstrom, who also provided an implementation. Python 2.3
follows the specification in <span class="target" id="index-5"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0273"><strong>PEP 273</strong></a>, but uses an implementation written by
Just van Rossum that uses the import hooks described in <span class="target" id="index-6"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a>. See section
<a class="reference internal" href="#section-pep302"><em>PEP 302: New Import Hooks</em></a> for a description of the new import hooks.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-277-unicode-file-name-support-for-windows-nt">
<h2>PEP 277: Unicode file name support for Windows NT<a class="headerlink" href="#pep-277-unicode-file-name-support-for-windows-nt" title="Permalink to this headline">¶</a></h2>
<p>On Windows NT, 2000, and XP, the system stores file names as Unicode strings.
Traditionally, Python has represented file names as byte strings, which is
inadequate because it renders some file names inaccessible.</p>
<p>Python now allows using arbitrary Unicode strings (within the limitations of the
file system) for all functions that expect file names, most notably the
<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> built-in function. If a Unicode string is passed to
<a class="reference internal" href="../library/os.html#os.listdir" title="os.listdir"><tt class="xref py py-func docutils literal"><span class="pre">os.listdir()</span></tt></a>, Python now returns a list of Unicode strings. A new
function, <a class="reference internal" href="../library/os.html#os.getcwdu" title="os.getcwdu"><tt class="xref py py-func docutils literal"><span class="pre">os.getcwdu()</span></tt></a>, returns the current directory as a Unicode string.</p>
<p>Byte strings still work as file names, and on Windows Python will transparently
convert them to Unicode using the <tt class="docutils literal"><span class="pre">mbcs</span></tt> encoding.</p>
<p>Other systems also allow Unicode strings as file names but convert them to byte
strings before passing them to the system, which can cause a <a class="reference internal" href="../library/exceptions.html#exceptions.UnicodeError" title="exceptions.UnicodeError"><tt class="xref py py-exc docutils literal"><span class="pre">UnicodeError</span></tt></a>
to be raised. Applications can test whether arbitrary Unicode strings are
supported as file names by checking <a class="reference internal" href="../library/os.path.html#os.path.supports_unicode_filenames" title="os.path.supports_unicode_filenames"><tt class="xref py py-attr docutils literal"><span class="pre">os.path.supports_unicode_filenames</span></tt></a>,
a Boolean value.</p>
<p>Under MacOS, <a class="reference internal" href="../library/os.html#os.listdir" title="os.listdir"><tt class="xref py py-func docutils literal"><span class="pre">os.listdir()</span></tt></a> may now return Unicode filenames.</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-0277"><strong>PEP 277</strong></a> - Unicode file name support for Windows NT</dt>
<dd>Written by Neil Hodgson; implemented by Neil Hodgson, Martin von Löwis, and Mark
Hammond.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-278-universal-newline-support">
<span id="index-8"></span><h2>PEP 278: Universal Newline Support<a class="headerlink" href="#pep-278-universal-newline-support" title="Permalink to this headline">¶</a></h2>
<p>The three major operating systems used today are Microsoft Windows, Apple’s
Macintosh OS, and the various Unix derivatives. A minor irritation of cross-
platform work is that these three platforms all use different characters to
mark the ends of lines in text files. Unix uses the linefeed (ASCII character
10), MacOS uses the carriage return (ASCII character 13), and Windows uses a
two-character sequence of a carriage return plus a newline.</p>
<p>Python’s file objects can now support end of line conventions other than the
one followed by the platform on which Python is running. Opening a file with
the mode <tt class="docutils literal"><span class="pre">'U'</span></tt> or <tt class="docutils literal"><span class="pre">'rU'</span></tt> will open a file for reading in <a class="reference internal" href="../glossary.html#term-universal-newlines"><em class="xref std std-term">universal
newlines</em></a> mode. All three line ending conventions will be translated to a
<tt class="docutils literal"><span class="pre">'\n'</span></tt> in the strings returned by the various file methods such as
<tt class="xref py py-meth docutils literal"><span class="pre">read()</span></tt> and <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>.</p>
<p>Universal newline support is also used when importing modules and when executing
a file with the <a class="reference internal" href="../library/functions.html#execfile" title="execfile"><tt class="xref py py-func docutils literal"><span class="pre">execfile()</span></tt></a> function. This means that Python modules can
be shared between all three operating systems without needing to convert the
line-endings.</p>
<p>This feature can be disabled when compiling Python by specifying the
<em class="xref std std-option">--without-universal-newlines</em> switch when running Python’s
<strong class="program">configure</strong> script.</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-0278"><strong>PEP 278</strong></a> - Universal Newline Support</dt>
<dd>Written and implemented by Jack Jansen.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-279-enumerate">
<span id="section-enumerate"></span><h2>PEP 279: enumerate()<a class="headerlink" href="#pep-279-enumerate" title="Permalink to this headline">¶</a></h2>
<p>A new built-in function, <a class="reference internal" href="../library/functions.html#enumerate" title="enumerate"><tt class="xref py py-func docutils literal"><span class="pre">enumerate()</span></tt></a>, will make certain loops a bit
clearer. <tt class="docutils literal"><span class="pre">enumerate(thing)</span></tt>, where <em>thing</em> is either an iterator or a
sequence, returns a iterator that will return <tt class="docutils literal"><span class="pre">(0,</span> <span class="pre">thing[0])</span></tt>, <tt class="docutils literal"><span class="pre">(1,</span>
<span class="pre">thing[1])</span></tt>, <tt class="docutils literal"><span class="pre">(2,</span> <span class="pre">thing[2])</span></tt>, and so forth.</p>
<p>A common idiom to change every element of a list looks like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">L</span><span class="p">)):</span>
<span class="n">item</span> <span class="o">=</span> <span class="n">L</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
<span class="c"># ... compute some result based on item ...</span>
<span class="n">L</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="n">result</span>
</pre></div>
</div>
<p>This can be rewritten using <a class="reference internal" href="../library/functions.html#enumerate" title="enumerate"><tt class="xref py py-func docutils literal"><span class="pre">enumerate()</span></tt></a> as:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">item</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">L</span><span class="p">):</span>
<span class="c"># ... compute some result based on item ...</span>
<span class="n">L</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="n">result</span>
</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-10"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0279"><strong>PEP 279</strong></a> - The enumerate() built-in function</dt>
<dd>Written and implemented by Raymond D. Hettinger.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-282-the-logging-package">
<h2>PEP 282: The logging Package<a class="headerlink" href="#pep-282-the-logging-package" title="Permalink to this headline">¶</a></h2>
<p>A standard package for writing logs, <a class="reference internal" href="../library/logging.html#module-logging" title="logging: Flexible event logging system for applications."><tt class="xref py py-mod docutils literal"><span class="pre">logging</span></tt></a>, has been added to Python
2.3. It provides a powerful and flexible mechanism for generating logging
output which can then be filtered and processed in various ways. A
configuration file written in a standard format can be used to control the
logging behavior of a program. Python includes handlers that will write log
records to standard error or to a file or socket, send them to the system log,
or even e-mail them to a particular address; of course, it’s also possible to
write your own handler classes.</p>
<p>The <tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt> class is the primary class. Most application code will deal
with one or more <tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt> objects, each one used by a particular
subsystem of the application. Each <tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt> is identified by a name, and
names are organized into a hierarchy using <tt class="docutils literal"><span class="pre">.</span></tt> as the component separator.
For example, you might have <tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt> instances named <tt class="docutils literal"><span class="pre">server</span></tt>,
<tt class="docutils literal"><span class="pre">server.auth</span></tt> and <tt class="docutils literal"><span class="pre">server.network</span></tt>. The latter two instances are below
<tt class="docutils literal"><span class="pre">server</span></tt> in the hierarchy. This means that if you turn up the verbosity for
<tt class="docutils literal"><span class="pre">server</span></tt> or direct <tt class="docutils literal"><span class="pre">server</span></tt> messages to a different handler, the changes
will also apply to records logged to <tt class="docutils literal"><span class="pre">server.auth</span></tt> and <tt class="docutils literal"><span class="pre">server.network</span></tt>.
There’s also a root <tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt> that’s the parent of all other loggers.</p>
<p>For simple uses, the <a class="reference internal" href="../library/logging.html#module-logging" title="logging: Flexible event logging system for applications."><tt class="xref py py-mod docutils literal"><span class="pre">logging</span></tt></a> package contains some convenience functions
that always use the root log:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">logging</span>
<span class="n">logging</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s">'Debugging information'</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">'Informational message'</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s">'Warning:config file </span><span class="si">%s</span><span class="s"> not found'</span><span class="p">,</span> <span class="s">'server.conf'</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s">'Error occurred'</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s">'Critical error -- shutting down'</span><span class="p">)</span>
</pre></div>
</div>
<p>This produces the following output:</p>
<div class="highlight-python"><pre>WARNING:root:Warning:config file server.conf not found
ERROR:root:Error occurred
CRITICAL:root:Critical error -- shutting down</pre>
</div>
<p>In the default configuration, informational and debugging messages are
suppressed and the output is sent to standard error. You can enable the display
of informational and debugging messages by calling the <tt class="xref py py-meth docutils literal"><span class="pre">setLevel()</span></tt> method
on the root logger.</p>
<p>Notice the <tt class="xref py py-func docutils literal"><span class="pre">warning()</span></tt> call’s use of string formatting operators; all of the
functions for logging messages take the arguments <tt class="docutils literal"><span class="pre">(msg,</span> <span class="pre">arg1,</span> <span class="pre">arg2,</span> <span class="pre">...)</span></tt> and
log the string resulting from <tt class="docutils literal"><span class="pre">msg</span> <span class="pre">%</span> <span class="pre">(arg1,</span> <span class="pre">arg2,</span> <span class="pre">...)</span></tt>.</p>
<p>There’s also an <tt class="xref py py-func docutils literal"><span class="pre">exception()</span></tt> function that records the most recent
traceback. Any of the other functions will also record the traceback if you
specify a true value for the keyword argument <em>exc_info</em>.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">f</span><span class="p">():</span>
<span class="k">try</span><span class="p">:</span> <span class="mi">1</span><span class="o">/</span><span class="mi">0</span>
<span class="k">except</span><span class="p">:</span> <span class="n">logging</span><span class="o">.</span><span class="n">exception</span><span class="p">(</span><span class="s">'Problem recorded'</span><span class="p">)</span>
<span class="n">f</span><span class="p">()</span>
</pre></div>
</div>
<p>This produces the following output:</p>
<div class="highlight-python"><pre>ERROR:root:Problem recorded
Traceback (most recent call last):
File "t.py", line 6, in f
1/0
ZeroDivisionError: integer division or modulo by zero</pre>
</div>
<p>Slightly more advanced programs will use a logger other than the root logger.
The <tt class="xref py py-func docutils literal"><span class="pre">getLogger(name)()</span></tt> function is used to get a particular log, creating
it if it doesn’t exist yet. <tt class="xref py py-func docutils literal"><span class="pre">getLogger(None)()</span></tt> returns the root logger.</p>
<div class="highlight-python"><pre>log = logging.getLogger('server')
...
log.info('Listening on port %i', port)
...
log.critical('Disk full')
...</pre>
</div>
<p>Log records are usually propagated up the hierarchy, so a message logged to
<tt class="docutils literal"><span class="pre">server.auth</span></tt> is also seen by <tt class="docutils literal"><span class="pre">server</span></tt> and <tt class="docutils literal"><span class="pre">root</span></tt>, but a <tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt>
can prevent this by setting its <tt class="xref py py-attr docutils literal"><span class="pre">propagate</span></tt> attribute to <a class="reference internal" href="../library/constants.html#False" title="False"><tt class="xref py py-const docutils literal"><span class="pre">False</span></tt></a>.</p>
<p>There are more classes provided by the <a class="reference internal" href="../library/logging.html#module-logging" title="logging: Flexible event logging system for applications."><tt class="xref py py-mod docutils literal"><span class="pre">logging</span></tt></a> package that can be
customized. When a <tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt> instance is told to log a message, it
creates a <tt class="xref py py-class docutils literal"><span class="pre">LogRecord</span></tt> instance that is sent to any number of different
<tt class="xref py py-class docutils literal"><span class="pre">Handler</span></tt> instances. Loggers and handlers can also have an attached list
of filters, and each filter can cause the <tt class="xref py py-class docutils literal"><span class="pre">LogRecord</span></tt> to be ignored or
can modify the record before passing it along. When they’re finally output,
<tt class="xref py py-class docutils literal"><span class="pre">LogRecord</span></tt> instances are converted to text by a <tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt>
class. All of these classes can be replaced by your own specially-written
classes.</p>
<p>With all of these features the <a class="reference internal" href="../library/logging.html#module-logging" title="logging: Flexible event logging system for applications."><tt class="xref py py-mod docutils literal"><span class="pre">logging</span></tt></a> package should provide enough
flexibility for even the most complicated applications. This is only an
incomplete overview of its features, so please see the package’s reference
documentation for all of the details. Reading <span class="target" id="index-11"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0282"><strong>PEP 282</strong></a> will also be helpful.</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-12"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0282"><strong>PEP 282</strong></a> - A Logging System</dt>
<dd>Written by Vinay Sajip and Trent Mick; implemented by Vinay Sajip.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-285-a-boolean-type">
<span id="section-bool"></span><h2>PEP 285: A Boolean Type<a class="headerlink" href="#pep-285-a-boolean-type" title="Permalink to this headline">¶</a></h2>
<p>A Boolean type was added to Python 2.3. Two new constants were added to the
<a class="reference internal" href="../library/__builtin__.html#module-__builtin__" title="__builtin__: The module that provides the built-in namespace."><tt class="xref py py-mod docutils literal"><span class="pre">__builtin__</span></tt></a> module, <a class="reference internal" href="../library/constants.html#True" title="True"><tt class="xref py py-const docutils literal"><span class="pre">True</span></tt></a> and <a class="reference internal" href="../library/constants.html#False" title="False"><tt class="xref py py-const docutils literal"><span class="pre">False</span></tt></a>. (<a class="reference internal" href="../library/constants.html#True" title="True"><tt class="xref py py-const docutils literal"><span class="pre">True</span></tt></a> and
<a class="reference internal" href="../library/constants.html#False" title="False"><tt class="xref py py-const docutils literal"><span class="pre">False</span></tt></a> constants were added to the built-ins in Python 2.2.1, but the
2.2.1 versions are simply set to integer values of 1 and 0 and aren’t a
different type.)</p>
<p>The type object for this new type is named <a class="reference internal" href="../library/functions.html#bool" title="bool"><tt class="xref py py-class docutils literal"><span class="pre">bool</span></tt></a>; the constructor for it
takes any Python value and converts it to <a class="reference internal" href="../library/constants.html#True" title="True"><tt class="xref py py-const docutils literal"><span class="pre">True</span></tt></a> or <a class="reference internal" href="../library/constants.html#False" title="False"><tt class="xref py py-const docutils literal"><span class="pre">False</span></tt></a>.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="nb">bool</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">>>> </span><span class="nb">bool</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="go">False</span>
<span class="gp">>>> </span><span class="nb">bool</span><span class="p">([])</span>
<span class="go">False</span>
<span class="gp">>>> </span><span class="nb">bool</span><span class="p">(</span> <span class="p">(</span><span class="mi">1</span><span class="p">,)</span> <span class="p">)</span>
<span class="go">True</span>
</pre></div>
</div>
<p>Most of the standard library modules and built-in functions have been changed to
return Booleans.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">obj</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">>>> </span><span class="nb">hasattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="s">'append'</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">>>> </span><span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="nb">list</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">>>> </span><span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="nb">tuple</span><span class="p">)</span>
<span class="go">False</span>
</pre></div>
</div>
<p>Python’s Booleans were added with the primary goal of making code clearer. For
example, if you’re reading a function and encounter the statement <tt class="docutils literal"><span class="pre">return</span> <span class="pre">1</span></tt>,
you might wonder whether the <tt class="docutils literal"><span class="pre">1</span></tt> represents a Boolean truth value, an index,
or a coefficient that multiplies some other quantity. If the statement is
<tt class="docutils literal"><span class="pre">return</span> <span class="pre">True</span></tt>, however, the meaning of the return value is quite clear.</p>
<p>Python’s Booleans were <em>not</em> added for the sake of strict type-checking. A very
strict language such as Pascal would also prevent you performing arithmetic with
Booleans, and would require that the expression in an <a class="reference internal" href="../reference/compound_stmts.html#if"><tt class="xref std std-keyword docutils literal"><span class="pre">if</span></tt></a> statement
always evaluate to a Boolean result. Python is not this strict and never will
be, as <span class="target" id="index-13"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0285"><strong>PEP 285</strong></a> explicitly says. This means you can still use any expression
in an <a class="reference internal" href="../reference/compound_stmts.html#if"><tt class="xref std std-keyword docutils literal"><span class="pre">if</span></tt></a> statement, even ones that evaluate to a list or tuple or
some random object. The Boolean type is a subclass of the <a class="reference internal" href="../library/functions.html#int" title="int"><tt class="xref py py-class docutils literal"><span class="pre">int</span></tt></a> class so
that arithmetic using a Boolean still works.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="bp">True</span> <span class="o">+</span> <span class="mi">1</span>
<span class="go">2</span>
<span class="gp">>>> </span><span class="bp">False</span> <span class="o">+</span> <span class="mi">1</span>
<span class="go">1</span>
<span class="gp">>>> </span><span class="bp">False</span> <span class="o">*</span> <span class="mi">75</span>
<span class="go">0</span>
<span class="gp">>>> </span><span class="bp">True</span> <span class="o">*</span> <span class="mi">75</span>
<span class="go">75</span>
</pre></div>
</div>
<p>To sum up <a class="reference internal" href="../library/constants.html#True" title="True"><tt class="xref py py-const docutils literal"><span class="pre">True</span></tt></a> and <a class="reference internal" href="../library/constants.html#False" title="False"><tt class="xref py py-const docutils literal"><span class="pre">False</span></tt></a> in a sentence: they’re alternative
ways to spell the integer values 1 and 0, with the single difference that
<a class="reference internal" href="../library/functions.html#str" title="str"><tt class="xref py py-func docutils literal"><span class="pre">str()</span></tt></a> and <a class="reference internal" href="../library/repr.html#module-repr" title="repr: Alternate repr() implementation with size limits."><tt class="xref py py-func docutils literal"><span class="pre">repr()</span></tt></a> return the strings <tt class="docutils literal"><span class="pre">'True'</span></tt> and <tt class="docutils literal"><span class="pre">'False'</span></tt>
instead of <tt class="docutils literal"><span class="pre">'1'</span></tt> and <tt class="docutils literal"><span class="pre">'0'</span></tt>.</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-14"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0285"><strong>PEP 285</strong></a> - Adding a bool type</dt>
<dd>Written and implemented by GvR.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-293-codec-error-handling-callbacks">
<h2>PEP 293: Codec Error Handling Callbacks<a class="headerlink" href="#pep-293-codec-error-handling-callbacks" title="Permalink to this headline">¶</a></h2>
<p>When encoding a Unicode string into a byte string, unencodable characters may be
encountered. So far, Python has allowed specifying the error processing as
either “strict” (raising <a class="reference internal" href="../library/exceptions.html#exceptions.UnicodeError" title="exceptions.UnicodeError"><tt class="xref py py-exc docutils literal"><span class="pre">UnicodeError</span></tt></a>), “ignore” (skipping the
character), or “replace” (using a question mark in the output string), with
“strict” being the default behavior. It may be desirable to specify alternative
processing of such errors, such as inserting an XML character reference or HTML
entity reference into the converted string.</p>
<p>Python now has a flexible framework to add different processing strategies. New
error handlers can be added with <a class="reference internal" href="../library/codecs.html#codecs.register_error" title="codecs.register_error"><tt class="xref py py-func docutils literal"><span class="pre">codecs.register_error()</span></tt></a>, and codecs then
can access the error handler with <a class="reference internal" href="../library/codecs.html#codecs.lookup_error" title="codecs.lookup_error"><tt class="xref py py-func docutils literal"><span class="pre">codecs.lookup_error()</span></tt></a>. An equivalent C
API has been added for codecs written in C. The error handler gets the necessary
state information such as the string being converted, the position in the string
where the error was detected, and the target encoding. The handler can then
either raise an exception or return a replacement string.</p>
<p>Two additional error handlers have been implemented using this framework:
“backslashreplace” uses Python backslash quoting to represent unencodable
characters and “xmlcharrefreplace” emits XML character references.</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-0293"><strong>PEP 293</strong></a> - Codec Error Handling Callbacks</dt>
<dd>Written and implemented by Walter Dörwald.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-301-package-index-and-metadata-for-distutils">
<span id="section-pep301"></span><h2>PEP 301: Package Index and Metadata for Distutils<a class="headerlink" href="#pep-301-package-index-and-metadata-for-distutils" title="Permalink to this headline">¶</a></h2>
<p>Support for the long-requested Python catalog makes its first appearance in 2.3.</p>
<p>The heart of the catalog is the new Distutils <strong class="command">register</strong> command.
Running <tt class="docutils literal"><span class="pre">python</span> <span class="pre">setup.py</span> <span class="pre">register</span></tt> will collect the metadata describing a
package, such as its name, version, maintainer, description, &c., and send it to
a central catalog server. The resulting catalog is available from
<a class="reference external" href="http://www.python.org/pypi">http://www.python.org/pypi</a>.</p>
<p>To make the catalog a bit more useful, a new optional <em>classifiers</em> keyword
argument has been added to the Distutils <tt class="xref py py-func docutils literal"><span class="pre">setup()</span></tt> function. A list of
<a class="reference external" href="http://catb.org/~esr/trove/">Trove</a>-style strings can be supplied to help
classify the software.</p>
<p>Here’s an example <tt class="file docutils literal"><span class="pre">setup.py</span></tt> with classifiers, written to be compatible
with older versions of the Distutils:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">distutils</span> <span class="kn">import</span> <span class="n">core</span>
<span class="n">kw</span> <span class="o">=</span> <span class="p">{</span><span class="s">'name'</span><span class="p">:</span> <span class="s">"Quixote"</span><span class="p">,</span>
<span class="s">'version'</span><span class="p">:</span> <span class="s">"0.5.1"</span><span class="p">,</span>
<span class="s">'description'</span><span class="p">:</span> <span class="s">"A highly Pythonic Web application framework"</span><span class="p">,</span>
<span class="c"># ...</span>
<span class="p">}</span>
<span class="k">if</span> <span class="p">(</span><span class="nb">hasattr</span><span class="p">(</span><span class="n">core</span><span class="p">,</span> <span class="s">'setup_keywords'</span><span class="p">)</span> <span class="ow">and</span>
<span class="s">'classifiers'</span> <span class="ow">in</span> <span class="n">core</span><span class="o">.</span><span class="n">setup_keywords</span><span class="p">):</span>
<span class="n">kw</span><span class="p">[</span><span class="s">'classifiers'</span><span class="p">]</span> <span class="o">=</span> \
<span class="p">[</span><span class="s">'Topic :: Internet :: WWW/HTTP :: Dynamic Content'</span><span class="p">,</span>
<span class="s">'Environment :: No Input/Output (Daemon)'</span><span class="p">,</span>
<span class="s">'Intended Audience :: Developers'</span><span class="p">],</span>
<span class="n">core</span><span class="o">.</span><span class="n">setup</span><span class="p">(</span><span class="o">**</span><span class="n">kw</span><span class="p">)</span>
</pre></div>
</div>
<p>The full list of classifiers can be obtained by running <tt class="docutils literal"><span class="pre">python</span> <span class="pre">setup.py</span>
<span class="pre">register</span> <span class="pre">--list-classifiers</span></tt>.</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-0301"><strong>PEP 301</strong></a> - Package Index and Metadata for Distutils</dt>
<dd>Written and implemented by Richard Jones.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-302-new-import-hooks">
<span id="section-pep302"></span><h2>PEP 302: New Import Hooks<a class="headerlink" href="#pep-302-new-import-hooks" title="Permalink to this headline">¶</a></h2>
<p>While it’s been possible to write custom import hooks ever since the
<tt class="xref py py-mod docutils literal"><span class="pre">ihooks</span></tt> module was introduced in Python 1.3, no one has ever been really
happy with it because writing new import hooks is difficult and messy. There
have been various proposed alternatives such as the <a class="reference internal" href="../library/imputil.html#module-imputil" title="imputil: Manage and augment the import process. (deprecated)"><tt class="xref py py-mod docutils literal"><span class="pre">imputil</span></tt></a> and <tt class="xref py py-mod docutils literal"><span class="pre">iu</span></tt>
modules, but none of them has ever gained much acceptance, and none of them were
easily usable from C code.</p>
<p><span class="target" id="index-17"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> borrows ideas from its predecessors, especially from Gordon
McMillan’s <tt class="xref py py-mod docutils literal"><span class="pre">iu</span></tt> module. Three new items are added to the <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><tt class="xref py py-mod docutils literal"><span class="pre">sys</span></tt></a>
module:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">sys.path_hooks</span></tt> is a list of callable objects; most often they’ll be
classes. Each callable takes a string containing a path and either returns an
importer object that will handle imports from this path or raises an
<a class="reference internal" href="../library/exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><tt class="xref py py-exc docutils literal"><span class="pre">ImportError</span></tt></a> exception if it can’t handle this path.</li>
<li><tt class="docutils literal"><span class="pre">sys.path_importer_cache</span></tt> caches importer objects for each path, so
<tt class="docutils literal"><span class="pre">sys.path_hooks</span></tt> will only need to be traversed once for each path.</li>
<li><tt class="docutils literal"><span class="pre">sys.meta_path</span></tt> is a list of importer objects that will be traversed before
<tt class="docutils literal"><span class="pre">sys.path</span></tt> is checked. This list is initially empty, but user code can add
objects to it. Additional built-in and frozen modules can be imported by an
object added to this list.</li>
</ul>
<p>Importer objects must have a single method, <tt class="xref py py-meth docutils literal"><span class="pre">find_module(fullname,</span>
<span class="pre">path=None)()</span></tt>. <em>fullname</em> will be a module or package name, e.g. <tt class="docutils literal"><span class="pre">string</span></tt> or
<tt class="docutils literal"><span class="pre">distutils.core</span></tt>. <tt class="xref py py-meth docutils literal"><span class="pre">find_module()</span></tt> must return a loader object that has a
single method, <tt class="xref py py-meth docutils literal"><span class="pre">load_module(fullname)()</span></tt>, that creates and returns the
corresponding module object.</p>
<p>Pseudo-code for Python’s new import logic, therefore, looks something like this
(simplified a bit; see <span class="target" id="index-18"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> for the full details):</p>
<div class="highlight-python"><pre>for mp in sys.meta_path:
loader = mp(fullname)
if loader is not None:
<module> = loader.load_module(fullname)
for path in sys.path:
for hook in sys.path_hooks:
try:
importer = hook(path)
except ImportError:
# ImportError, so try the other path hooks
pass
else:
loader = importer.find_module(fullname)
<module> = loader.load_module(fullname)
# Not found!
raise ImportError</pre>
</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-19"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> - New Import Hooks</dt>
<dd>Written by Just van Rossum and Paul Moore. Implemented by Just van Rossum.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-305-comma-separated-files">
<span id="section-pep305"></span><h2>PEP 305: Comma-separated Files<a class="headerlink" href="#pep-305-comma-separated-files" title="Permalink to this headline">¶</a></h2>
<p>Comma-separated files are a format frequently used for exporting data from
databases and spreadsheets. Python 2.3 adds a parser for comma-separated files.</p>
<p>Comma-separated format is deceptively simple at first glance:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Costs</span><span class="p">,</span><span class="mi">150</span><span class="p">,</span><span class="mi">200</span><span class="p">,</span><span class="mf">3.95</span>
</pre></div>
</div>
<p>Read a line and call <tt class="docutils literal"><span class="pre">line.split(',')</span></tt>: what could be simpler? But toss in
string data that can contain commas, and things get more complicated:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="s">"Costs"</span><span class="p">,</span><span class="mi">150</span><span class="p">,</span><span class="mi">200</span><span class="p">,</span><span class="mf">3.95</span><span class="p">,</span><span class="s">"Includes taxes, shipping, and sundry items"</span>
</pre></div>
</div>
<p>A big ugly regular expression can parse this, but using the new <a class="reference internal" href="../library/csv.html#module-csv" title="csv: Write and read tabular data to and from delimited files."><tt class="xref py py-mod docutils literal"><span class="pre">csv</span></tt></a>
package is much simpler:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">csv</span>
<span class="nb">input</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s">'datafile'</span><span class="p">,</span> <span class="s">'rb'</span><span class="p">)</span>
<span class="n">reader</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">(</span><span class="nb">input</span><span class="p">)</span>
<span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">reader</span><span class="p">:</span>
<span class="k">print</span> <span class="n">line</span>
</pre></div>
</div>
<p>The <tt class="xref py py-func docutils literal"><span class="pre">reader()</span></tt> function takes a number of different options. The field
separator isn’t limited to the comma and can be changed to any character, and so
can the quoting and line-ending characters.</p>
<p>Different dialects of comma-separated files can be defined and registered;
currently there are two dialects, both used by Microsoft Excel. A separate
<a class="reference internal" href="../library/csv.html#csv.writer" title="csv.writer"><tt class="xref py py-class docutils literal"><span class="pre">csv.writer</span></tt></a> class will generate comma-separated files from a succession
of tuples or lists, quoting strings that contain the delimiter.</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-20"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0305"><strong>PEP 305</strong></a> - CSV File API</dt>
<dd>Written and implemented by Kevin Altis, Dave Cole, Andrew McNamara, Skip
Montanaro, Cliff Wells.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-307-pickle-enhancements">
<span id="section-pep307"></span><h2>PEP 307: Pickle Enhancements<a class="headerlink" href="#pep-307-pickle-enhancements" title="Permalink to this headline">¶</a></h2>
<p>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 <a class="reference internal" href="../library/pickle.html#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><tt class="xref py py-mod docutils literal"><span class="pre">cPickle</span></tt></a> modules received some attention during the
2.3 development cycle. In 2.2, new-style classes could be pickled without
difficulty, but they weren’t pickled very compactly; <span class="target" id="index-21"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0307"><strong>PEP 307</strong></a> quotes a trivial
example where a new-style class results in a pickled string three times longer
than that for a classic class.</p>
<p>The solution was to invent a new pickle protocol. The <a class="reference internal" href="../library/pickle.html#pickle.dumps" title="pickle.dumps"><tt class="xref py py-func docutils literal"><span class="pre">pickle.dumps()</span></tt></a>
function has supported a text-or-binary flag for a long time. In 2.3, this
flag is redefined from a Boolean to an integer: 0 is the old text-mode pickle
format, 1 is the old binary format, and now 2 is a new 2.3-specific format. A
new constant, <a class="reference internal" href="../library/pickle.html#pickle.HIGHEST_PROTOCOL" title="pickle.HIGHEST_PROTOCOL"><tt class="xref py py-const docutils literal"><span class="pre">pickle.HIGHEST_PROTOCOL</span></tt></a>, can be used to select the
fanciest protocol available.</p>
<p>Unpickling is no longer considered a safe operation. 2.2’s <a class="reference internal" href="../library/pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><tt class="xref py py-mod docutils literal"><span class="pre">pickle</span></tt></a>
provided hooks for trying to prevent unsafe classes from being unpickled
(specifically, a <tt class="xref py py-attr docutils literal"><span class="pre">__safe_for_unpickling__</span></tt> attribute), but none of this
code was ever audited and therefore it’s all been ripped out in 2.3. You should
not unpickle untrusted data in any version of Python.</p>
<p>To reduce the pickling overhead for new-style classes, a new interface for
customizing pickling was added using three special methods:
<a class="reference internal" href="../library/pickle.html#object.__getstate__" title="object.__getstate__"><tt class="xref py py-meth docutils literal"><span class="pre">__getstate__()</span></tt></a>, <a class="reference internal" href="../library/pickle.html#object.__setstate__" title="object.__setstate__"><tt class="xref py py-meth docutils literal"><span class="pre">__setstate__()</span></tt></a>, and <a class="reference internal" href="../library/pickle.html#object.__getnewargs__" title="object.__getnewargs__"><tt class="xref py py-meth docutils literal"><span class="pre">__getnewargs__()</span></tt></a>. Consult
<span class="target" id="index-22"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0307"><strong>PEP 307</strong></a> for the full semantics of these methods.</p>
<p>As a way to compress pickles yet further, it’s now possible to use integer codes
instead of long strings to identify pickled classes. The Python Software
Foundation will maintain a list of standardized codes; there’s also a range of
codes for private use. Currently no codes have been specified.</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-23"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0307"><strong>PEP 307</strong></a> - Extensions to the pickle protocol</dt>
<dd>Written and implemented by Guido van Rossum and Tim Peters.</dd>
</dl>
</div>
</div>
<div class="section" id="extended-slices">
<span id="section-slices"></span><h2>Extended Slices<a class="headerlink" href="#extended-slices" title="Permalink to this headline">¶</a></h2>
<p>Ever since Python 1.4, the slicing syntax has supported an optional third “step”
or “stride” argument. For example, these are all legal Python syntax:
<tt class="docutils literal"><span class="pre">L[1:10:2]</span></tt>, <tt class="docutils literal"><span class="pre">L[:-1:1]</span></tt>, <tt class="docutils literal"><span class="pre">L[::-1]</span></tt>. This was added to Python at the
request of the developers of Numerical Python, which uses the third argument
extensively. However, Python’s built-in list, tuple, and string sequence types
have never supported this feature, raising a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><tt class="xref py py-exc docutils literal"><span class="pre">TypeError</span></tt></a> if you tried it.
Michael Hudson contributed a patch to fix this shortcoming.</p>
<p>For example, you can now easily extract the elements of a list that have even
indexes:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">L</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">L</span><span class="p">[::</span><span class="mi">2</span><span class="p">]</span>
<span class="go">[0, 2, 4, 6, 8]</span>
</pre></div>
</div>
<p>Negative values also work to make a copy of the same list in reverse order:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">L</span><span class="p">[::</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
<span class="go">[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]</span>
</pre></div>
</div>
<p>This also works for tuples, arrays, and strings:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">s</span><span class="o">=</span><span class="s">'abcd'</span>
<span class="gp">>>> </span><span class="n">s</span><span class="p">[::</span><span class="mi">2</span><span class="p">]</span>
<span class="go">'ac'</span>
<span class="gp">>>> </span><span class="n">s</span><span class="p">[::</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
<span class="go">'dcba'</span>
</pre></div>
</div>
<p>If you have a mutable sequence such as a list or an array you can assign to or
delete an extended slice, but there are some differences between assignment to
extended and regular slices. Assignment to a regular slice can be used to
change the length of the sequence:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">a</span>
<span class="go">[0, 1, 2]</span>
<span class="gp">>>> </span><span class="n">a</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">3</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">]</span>
<span class="gp">>>> </span><span class="n">a</span>
<span class="go">[0, 4, 5, 6]</span>
</pre></div>
</div>
<p>Extended slices aren’t this flexible. When assigning to an extended slice, the
list on the right hand side of the statement must contain the same number of
items as the slice it is replacing:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">a</span>
<span class="go">[0, 1, 2, 3]</span>
<span class="gp">>>> </span><span class="n">a</span><span class="p">[::</span><span class="mi">2</span><span class="p">]</span>
<span class="go">[0, 2]</span>
<span class="gp">>>> </span><span class="n">a</span><span class="p">[::</span><span class="mi">2</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">]</span>
<span class="gp">>>> </span><span class="n">a</span>
<span class="go">[0, 1, -1, 3]</span>
<span class="gp">>>> </span><span class="n">a</span><span class="p">[::</span><span class="mi">2</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">]</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n">?</span>
<span class="gr">ValueError</span>: <span class="n">attempt to assign sequence of size 3 to extended slice of size 2</span>
</pre></div>
</div>
<p>Deletion is more straightforward:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">a</span>
<span class="go">[0, 1, 2, 3]</span>
<span class="gp">>>> </span><span class="n">a</span><span class="p">[::</span><span class="mi">2</span><span class="p">]</span>
<span class="go">[0, 2]</span>
<span class="gp">>>> </span><span class="k">del</span> <span class="n">a</span><span class="p">[::</span><span class="mi">2</span><span class="p">]</span>
<span class="gp">>>> </span><span class="n">a</span>
<span class="go">[1, 3]</span>
</pre></div>
</div>
<p>One can also now pass slice objects to the <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a> methods of the
built-in sequences:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span><span class="o">.</span><span class="n">__getitem__</span><span class="p">(</span><span class="nb">slice</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span>
<span class="go">[0, 2, 4]</span>
</pre></div>
</div>
<p>Or use slice objects directly in subscripts:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)[</span><span class="nb">slice</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">2</span><span class="p">)]</span>
<span class="go">[0, 2, 4]</span>
</pre></div>
</div>
<p>To simplify implementing sequences that support extended slicing, slice objects
now have a method <tt class="xref py py-meth docutils literal"><span class="pre">indices(length)()</span></tt> which, given the length of a sequence,
returns a <tt class="docutils literal"><span class="pre">(start,</span> <span class="pre">stop,</span> <span class="pre">step)</span></tt> tuple that can be passed directly to
<a class="reference internal" href="../library/functions.html#range" title="range"><tt class="xref py py-func docutils literal"><span class="pre">range()</span></tt></a>. <tt class="xref py py-meth docutils literal"><span class="pre">indices()</span></tt> handles omitted and out-of-bounds indices in a
manner consistent with regular slices (and this innocuous phrase hides a welter
of confusing details!). The method is intended to be used like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">FakeSeq</span><span class="p">:</span>
<span class="o">...</span>
<span class="k">def</span> <span class="nf">calc_item</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">i</span><span class="p">):</span>
<span class="o">...</span>
<span class="k">def</span> <span class="nf">__getitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">item</span><span class="p">):</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">item</span><span class="p">,</span> <span class="nb">slice</span><span class="p">):</span>
<span class="n">indices</span> <span class="o">=</span> <span class="n">item</span><span class="o">.</span><span class="n">indices</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="p">))</span>
<span class="k">return</span> <span class="n">FakeSeq</span><span class="p">([</span><span class="bp">self</span><span class="o">.</span><span class="n">calc_item</span><span class="p">(</span><span class="n">i</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="o">*</span><span class="n">indices</span><span class="p">)])</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">calc_item</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
</pre></div>
</div>
<p>From this example you can also see that the built-in <a class="reference internal" href="../library/functions.html#slice" title="slice"><tt class="xref py py-class docutils literal"><span class="pre">slice</span></tt></a> object is
now the type object for the slice type, and is no longer a function. This is
consistent with Python 2.2, where <a class="reference internal" href="../library/functions.html#int" title="int"><tt class="xref py py-class docutils literal"><span class="pre">int</span></tt></a>, <a class="reference internal" href="../library/functions.html#str" title="str"><tt class="xref py py-class docutils literal"><span class="pre">str</span></tt></a>, etc., underwent
the same change.</p>
</div>
<div class="section" id="other-language-changes">
<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.3 makes to the core Python language.</p>
<ul>
<li><p class="first">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 is now always a keyword, as described in
section <a class="reference internal" href="#section-generators"><em>PEP 255: Simple Generators</em></a> of this document.</p>
</li>
<li><p class="first">A new built-in function <a class="reference internal" href="../library/functions.html#enumerate" title="enumerate"><tt class="xref py py-func docutils literal"><span class="pre">enumerate()</span></tt></a> was added, as described in section
<a class="reference internal" href="#section-enumerate"><em>PEP 279: enumerate()</em></a> of this document.</p>
</li>
<li><p class="first">Two new constants, <a class="reference internal" href="../library/constants.html#True" title="True"><tt class="xref py py-const docutils literal"><span class="pre">True</span></tt></a> and <a class="reference internal" href="../library/constants.html#False" title="False"><tt class="xref py py-const docutils literal"><span class="pre">False</span></tt></a> were added along with the
built-in <a class="reference internal" href="../library/functions.html#bool" title="bool"><tt class="xref py py-class docutils literal"><span class="pre">bool</span></tt></a> type, as described in section <a class="reference internal" href="#section-bool"><em>PEP 285: A Boolean Type</em></a> of this
document.</p>
</li>
<li><p class="first">The <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> type constructor will now return a long integer instead of
raising an <a class="reference internal" href="../library/exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><tt class="xref py py-exc docutils literal"><span class="pre">OverflowError</span></tt></a> when a string or floating-point number is too
large to fit into an integer. This can lead to the paradoxical result that
<tt class="docutils literal"><span class="pre">isinstance(int(expression),</span> <span class="pre">int)</span></tt> is false, but that seems unlikely to cause
problems in practice.</p>
</li>
<li><p class="first">Built-in types now support the extended slicing syntax, as described in
section <a class="reference internal" href="#section-slices"><em>Extended Slices</em></a> of this document.</p>
</li>
<li><p class="first">A new built-in function, <tt class="xref py py-func docutils literal"><span class="pre">sum(iterable,</span> <span class="pre">start=0)()</span></tt>, adds up the numeric
items in the iterable object and returns their sum. <a class="reference internal" href="../library/functions.html#sum" title="sum"><tt class="xref py py-func docutils literal"><span class="pre">sum()</span></tt></a> only accepts
numbers, meaning that you can’t use it to concatenate a bunch of strings.
(Contributed by Alex Martelli.)</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">list.insert(pos,</span> <span class="pre">value)</span></tt> used to insert <em>value</em> at the front of the list
when <em>pos</em> was negative. The behaviour has now been changed to be consistent
with slice indexing, so when <em>pos</em> is -1 the value will be inserted before the
last element, and so forth.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">list.index(value)</span></tt>, which searches for <em>value</em> within the list and returns
its index, now takes optional <em>start</em> and <em>stop</em> arguments to limit the search
to only part of the list.</p>
</li>
<li><p class="first">Dictionaries have a new method, <tt class="xref py py-meth docutils literal"><span class="pre">pop(key[,</span> <span class="pre">*default*])()</span></tt>, that returns
the value corresponding to <em>key</em> and removes that key/value pair from the
dictionary. If the requested key isn’t present in the dictionary, <em>default</em> is
returned if it’s specified and <a class="reference internal" href="../library/exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><tt class="xref py py-exc docutils literal"><span class="pre">KeyError</span></tt></a> raised if it isn’t.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">d</span> <span class="o">=</span> <span class="p">{</span><span class="mi">1</span><span class="p">:</span><span class="mi">2</span><span class="p">}</span>
<span class="gp">>>> </span><span class="n">d</span>
<span class="go">{1: 2}</span>
<span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">"stdin"</span>, line <span class="m">1</span>, in <span class="n">?</span>
<span class="gr">KeyError</span>: <span class="n">4</span>
<span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">2</span>
<span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">"stdin"</span>, line <span class="m">1</span>, in <span class="n">?</span>
<span class="gr">KeyError: 'pop()</span>: <span class="n">dictionary is empty'</span>
<span class="gp">>>> </span><span class="n">d</span>
<span class="go">{}</span>
<span class="go">>>></span>
</pre></div>
</div>
<p>There’s also a new class method, <tt class="xref py py-meth docutils literal"><span class="pre">dict.fromkeys(iterable,</span> <span class="pre">value)()</span></tt>, that
creates a dictionary with keys taken from the supplied iterator <em>iterable</em> and
all values set to <em>value</em>, defaulting to <tt class="docutils literal"><span class="pre">None</span></tt>.</p>
<p>(Patches contributed by Raymond Hettinger.)</p>
<p>Also, the <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><tt class="xref py py-func docutils literal"><span class="pre">dict()</span></tt></a> constructor now accepts keyword arguments to simplify
creating small dictionaries:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="nb">dict</span><span class="p">(</span><span class="n">red</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">blue</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">green</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">black</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
<span class="go">{'blue': 2, 'black': 4, 'green': 3, 'red': 1}</span>
</pre></div>
</div>
<p>(Contributed by Just van Rossum.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../reference/simple_stmts.html#assert"><tt class="xref std std-keyword docutils literal"><span class="pre">assert</span></tt></a> statement no longer checks the <tt class="docutils literal"><span class="pre">__debug__</span></tt> flag, so
you can no longer disable assertions by assigning to <tt class="docutils literal"><span class="pre">__debug__</span></tt>. Running
Python with the <a class="reference internal" href="../using/cmdline.html#cmdoption-O"><em class="xref std std-option">-O</em></a> switch will still generate code that doesn’t
execute any assertions.</p>
</li>
<li><p class="first">Most type objects are now callable, so you can use them to create new objects
such as functions, classes, and modules. (This means that the <a class="reference internal" href="../library/new.html#module-new" title="new: Interface to the creation of runtime implementation objects. (deprecated)"><tt class="xref py py-mod docutils literal"><span class="pre">new</span></tt></a> module
can be deprecated in a future Python version, because you can now use the type
objects available in the <a class="reference internal" href="../library/types.html#module-types" title="types: Names for built-in types."><tt class="xref py py-mod docutils literal"><span class="pre">types</span></tt></a> module.) For example, you can create a new
module object with the following code:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">types</span>
<span class="gp">>>> </span><span class="n">m</span> <span class="o">=</span> <span class="n">types</span><span class="o">.</span><span class="n">ModuleType</span><span class="p">(</span><span class="s">'abc'</span><span class="p">,</span><span class="s">'docstring'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">m</span>
<span class="go"><module 'abc' (built-in)></span>
<span class="gp">>>> </span><span class="n">m</span><span class="o">.</span><span class="n">__doc__</span>
<span class="go">'docstring'</span>
</pre></div>
</div>
</li>
<li><p class="first">A new warning, <a class="reference internal" href="../library/exceptions.html#exceptions.PendingDeprecationWarning" title="exceptions.PendingDeprecationWarning"><tt class="xref py py-exc docutils literal"><span class="pre">PendingDeprecationWarning</span></tt></a> was added to indicate features
which are in the process of being deprecated. The warning will <em>not</em> be printed
by default. To check for use of features that will be deprecated in the future,
supply <em class="xref std std-option">-Walways::PendingDeprecationWarning::</em> on the command line or
use <a class="reference internal" href="../library/warnings.html#warnings.filterwarnings" title="warnings.filterwarnings"><tt class="xref py py-func docutils literal"><span class="pre">warnings.filterwarnings()</span></tt></a>.</p>
</li>
<li><p class="first">The process of deprecating string-based exceptions, as in <tt class="docutils literal"><span class="pre">raise</span> <span class="pre">"Error</span>
<span class="pre">occurred"</span></tt>, has begun. Raising a string will now trigger
<a class="reference internal" href="../library/exceptions.html#exceptions.PendingDeprecationWarning" title="exceptions.PendingDeprecationWarning"><tt class="xref py py-exc docutils literal"><span class="pre">PendingDeprecationWarning</span></tt></a>.</p>
</li>
<li><p class="first">Using <tt class="docutils literal"><span class="pre">None</span></tt> as a variable name will now result in a <a class="reference internal" href="../library/exceptions.html#exceptions.SyntaxWarning" title="exceptions.SyntaxWarning"><tt class="xref py py-exc docutils literal"><span class="pre">SyntaxWarning</span></tt></a>
warning. In a future version of Python, <tt class="docutils literal"><span class="pre">None</span></tt> may finally become a keyword.</p>
</li>
<li><p class="first">The <tt class="xref py py-meth docutils literal"><span class="pre">xreadlines()</span></tt> method of file objects, introduced in Python 2.1, is no
longer necessary because files now behave as their own iterator.
<tt class="xref py py-meth docutils literal"><span class="pre">xreadlines()</span></tt> was originally introduced as a faster way to loop over all
the lines in a file, but now you can simply write <tt class="docutils literal"><span class="pre">for</span> <span class="pre">line</span> <span class="pre">in</span> <span class="pre">file_obj</span></tt>.
File objects also have a new read-only <tt class="xref py py-attr docutils literal"><span class="pre">encoding</span></tt> attribute that gives the
encoding used by the file; Unicode strings written to the file will be
automatically converted to bytes using the given encoding.</p>
</li>
<li><p class="first">The method resolution order used by new-style classes has changed, though
you’ll only notice the difference if you have a really complicated inheritance
hierarchy. Classic classes are unaffected by this change. Python 2.2
originally used a topological sort of a class’s ancestors, but 2.3 now uses the
C3 algorithm as described in the paper <a class="reference external" href="http://www.webcom.com/haahr/dylan/linearization-oopsla96.html">“A Monotonic Superclass Linearization
for Dylan”</a>. To
understand the motivation for this change, read Michele Simionato’s article
<a class="reference external" href="http://www.python.org/2.3/mro.html">“Python 2.3 Method Resolution Order”</a>, or
read the thread on python-dev starting with the message at
<a class="reference external" href="http://mail.python.org/pipermail/python-dev/2002-October/029035.html">http://mail.python.org/pipermail/python-dev/2002-October/029035.html</a>. Samuele
Pedroni first pointed out the problem and also implemented the fix by coding the
C3 algorithm.</p>
</li>
<li><p class="first">Python runs multithreaded programs by switching between threads after
executing N bytecodes. The default value for N has been increased from 10 to
100 bytecodes, speeding up single-threaded applications by reducing the
switching overhead. Some multithreaded applications may suffer slower response
time, but that’s easily fixed by setting the limit back to a lower number using
<tt class="xref py py-func docutils literal"><span class="pre">sys.setcheckinterval(N)()</span></tt>. The limit can be retrieved with the new
<a class="reference internal" href="../library/sys.html#sys.getcheckinterval" title="sys.getcheckinterval"><tt class="xref py py-func docutils literal"><span class="pre">sys.getcheckinterval()</span></tt></a> function.</p>
</li>
<li><p class="first">One minor but far-reaching change is that the names of extension types defined
by the modules included with Python now contain the module and a <tt class="docutils literal"><span class="pre">'.'</span></tt> in
front of the type name. For example, in Python 2.2, if you created a socket and
printed its <tt class="xref py py-attr docutils literal"><span class="pre">__class__</span></tt>, you’d get this output:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">s</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">()</span>
<span class="gp">>>> </span><span class="n">s</span><span class="o">.</span><span class="n">__class__</span>
<span class="go"><type 'socket'></span>
</pre></div>
</div>
<p>In 2.3, you get this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">s</span><span class="o">.</span><span class="n">__class__</span>
<span class="go"><type '_socket.socket'></span>
</pre></div>
</div>
</li>
<li><p class="first">One of the noted incompatibilities between old- and new-style classes has been
removed: you can now assign to the <tt class="xref py py-attr docutils literal"><span class="pre">__name__</span></tt> and <tt class="xref py py-attr docutils literal"><span class="pre">__bases__</span></tt>
attributes of new-style classes. There are some restrictions on what can be
assigned to <tt class="xref py py-attr docutils literal"><span class="pre">__bases__</span></tt> along the lines of those relating to assigning to
an instance’s <tt class="xref py py-attr docutils literal"><span class="pre">__class__</span></tt> attribute.</p>
</li>
</ul>
<div class="section" id="string-changes">
<h3>String Changes<a class="headerlink" href="#string-changes" title="Permalink to this headline">¶</a></h3>
<ul>
<li><p class="first">The <a class="reference internal" href="../reference/expressions.html#in"><tt class="xref std std-keyword docutils literal"><span class="pre">in</span></tt></a> operator now works differently for strings. Previously, when
evaluating <tt class="docutils literal"><span class="pre">X</span> <span class="pre">in</span> <span class="pre">Y</span></tt> where <em>X</em> and <em>Y</em> are strings, <em>X</em> could only be a single
character. That’s now changed; <em>X</em> can be a string of any length, and <tt class="docutils literal"><span class="pre">X</span> <span class="pre">in</span> <span class="pre">Y</span></tt>
will return <a class="reference internal" href="../library/constants.html#True" title="True"><tt class="xref py py-const docutils literal"><span class="pre">True</span></tt></a> if <em>X</em> is a substring of <em>Y</em>. If <em>X</em> is the empty
string, the result is always <a class="reference internal" href="../library/constants.html#True" title="True"><tt class="xref py py-const docutils literal"><span class="pre">True</span></tt></a>.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="s">'ab'</span> <span class="ow">in</span> <span class="s">'abcd'</span>
<span class="go">True</span>
<span class="gp">>>> </span><span class="s">'ad'</span> <span class="ow">in</span> <span class="s">'abcd'</span>
<span class="go">False</span>
<span class="gp">>>> </span><span class="s">''</span> <span class="ow">in</span> <span class="s">'abcd'</span>
<span class="go">True</span>
</pre></div>
</div>
<p>Note that this doesn’t tell you where the substring starts; if you need that
information, use the <tt class="xref py py-meth docutils literal"><span class="pre">find()</span></tt> string method.</p>
</li>
<li><p class="first">The <tt class="xref py py-meth docutils literal"><span class="pre">strip()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">lstrip()</span></tt>, and <tt class="xref py py-meth docutils literal"><span class="pre">rstrip()</span></tt> string methods now have
an optional argument for specifying the characters to strip. The default is
still to remove all whitespace characters:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="s">' abc '</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span>
<span class="go">'abc'</span>
<span class="gp">>>> </span><span class="s">'><><abc<><><>'</span><span class="o">.</span><span class="n">strip</span><span class="p">(</span><span class="s">'<>'</span><span class="p">)</span>
<span class="go">'abc'</span>
<span class="gp">>>> </span><span class="s">'><><abc<><><></span><span class="se">\n</span><span class="s">'</span><span class="o">.</span><span class="n">strip</span><span class="p">(</span><span class="s">'<>'</span><span class="p">)</span>
<span class="go">'abc<><><>\n'</span>
<span class="gp">>>> </span><span class="s">u'</span><span class="se">\u4000\u4001</span><span class="s">abc</span><span class="se">\u4000</span><span class="s">'</span><span class="o">.</span><span class="n">strip</span><span class="p">(</span><span class="s">u'</span><span class="se">\u4000</span><span class="s">'</span><span class="p">)</span>
<span class="go">u'\u4001abc'</span>
<span class="go">>>></span>
</pre></div>
</div>
<p>(Suggested by Simon Brunning and implemented by Walter Dörwald.)</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> string methods now accept negative
numbers for the <em>start</em> and <em>end</em> parameters.</p>
</li>
<li><p class="first">Another new string method is <tt class="xref py py-meth docutils literal"><span class="pre">zfill()</span></tt>, originally a function in 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. <tt class="xref py py-meth docutils literal"><span class="pre">zfill()</span></tt> pads a numeric string with zeros on the
left until it’s the specified width. Note that the <tt class="docutils literal"><span class="pre">%</span></tt> operator is still more
flexible and powerful than <tt class="xref py py-meth docutils literal"><span class="pre">zfill()</span></tt>.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="s">'45'</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
<span class="go">'0045'</span>
<span class="gp">>>> </span><span class="s">'12345'</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
<span class="go">'12345'</span>
<span class="gp">>>> </span><span class="s">'goofy'</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">6</span><span class="p">)</span>
<span class="go">'0goofy'</span>
</pre></div>
</div>
<p>(Contributed by Walter Dörwald.)</p>
</li>
<li><p class="first">A new type object, <a class="reference internal" href="../library/functions.html#basestring" title="basestring"><tt class="xref py py-class docutils literal"><span class="pre">basestring</span></tt></a>, has been added. Both 8-bit strings and
Unicode strings inherit from this type, so <tt class="docutils literal"><span class="pre">isinstance(obj,</span> <span class="pre">basestring)</span></tt> will
return <a class="reference internal" href="../library/constants.html#True" title="True"><tt class="xref py py-const docutils literal"><span class="pre">True</span></tt></a> for either kind of string. It’s a completely abstract
type, so you can’t create <a class="reference internal" href="../library/functions.html#basestring" title="basestring"><tt class="xref py py-class docutils literal"><span class="pre">basestring</span></tt></a> instances.</p>
</li>
<li><p class="first">Interned strings are no longer immortal and will now be garbage-collected in
the usual way when the only reference to them is from the internal dictionary of
interned strings. (Implemented by Oren Tirosh.)</p>
</li>
</ul>
</div>
<div class="section" id="optimizations">
<h3>Optimizations<a class="headerlink" href="#optimizations" title="Permalink to this headline">¶</a></h3>
<ul class="simple">
<li>The creation of new-style class instances has been made much faster; they’re
now faster than classic classes!</li>
<li>The <tt class="xref py py-meth docutils literal"><span class="pre">sort()</span></tt> method of list objects has been extensively rewritten by Tim
Peters, and the implementation is significantly faster.</li>
<li>Multiplication of large long integers is now much faster thanks to an
implementation of Karatsuba multiplication, an algorithm that scales better than
the O(n*n) required for the grade-school multiplication algorithm. (Original
patch by Christopher A. Craig, and significantly reworked by Tim Peters.)</li>
<li>The <tt class="docutils literal"><span class="pre">SET_LINENO</span></tt> opcode is now gone. This may provide a small speed
increase, depending on your compiler’s idiosyncrasies. See section
<a class="reference internal" href="#section-other"><em>Other Changes and Fixes</em></a> for a longer explanation. (Removed by Michael Hudson.)</li>
<li><a class="reference internal" href="../library/functions.html#xrange" title="xrange"><tt class="xref py py-func docutils literal"><span class="pre">xrange()</span></tt></a> objects now have their own iterator, making <tt class="docutils literal"><span class="pre">for</span> <span class="pre">i</span> <span class="pre">in</span>
<span class="pre">xrange(n)</span></tt> slightly faster than <tt class="docutils literal"><span class="pre">for</span> <span class="pre">i</span> <span class="pre">in</span> <span class="pre">range(n)</span></tt>. (Patch by Raymond
Hettinger.)</li>
<li>A number of small rearrangements have been made in various hotspots to improve
performance, such as inlining a function or removing some code. (Implemented
mostly by GvR, but lots of people have contributed single changes.)</li>
</ul>
<p>The net result of the 2.3 optimizations is that Python 2.3 runs the pystone
benchmark around 25% faster than Python 2.2.</p>
</div>
</div>
<div class="section" id="new-improved-and-deprecated-modules">
<h2>New, Improved, and Deprecated Modules<a class="headerlink" href="#new-improved-and-deprecated-modules" title="Permalink to this headline">¶</a></h2>
<p>As usual, Python’s standard library received a number of enhancements and bug
fixes. Here’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 CVS logs for all the details.</p>
<ul>
<li><p class="first">The <a class="reference internal" href="../library/array.html#module-array" title="array: Space efficient arrays of uniformly typed numeric values."><tt class="xref py py-mod docutils literal"><span class="pre">array</span></tt></a> module now supports arrays of Unicode characters using the
<tt class="docutils literal"><span class="pre">'u'</span></tt> format character. Arrays also now support using the <tt class="docutils literal"><span class="pre">+=</span></tt> assignment
operator to add another array’s contents, and the <tt class="docutils literal"><span class="pre">*=</span></tt> assignment operator to
repeat an array. (Contributed by Jason Orendorff.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/bsddb.html#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><tt class="xref py py-mod docutils literal"><span class="pre">bsddb</span></tt></a> module has been replaced by version 4.1.6 of the <a class="reference external" href="http://pybsddb.sourceforge.net">PyBSDDB</a> package, providing a more complete interface
to the transactional features of the BerkeleyDB library.</p>
<p>The old version of the module has been renamed to <tt class="xref py py-mod docutils literal"><span class="pre">bsddb185</span></tt> and is no
longer built automatically; you’ll have to edit <tt class="file docutils literal"><span class="pre">Modules/Setup</span></tt> to enable
it. Note that the new <a class="reference internal" href="../library/bsddb.html#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><tt class="xref py py-mod docutils literal"><span class="pre">bsddb</span></tt></a> package is intended to be compatible with
the old module, so be sure to file bugs if you discover any incompatibilities.
When upgrading to Python 2.3, if the new interpreter is compiled with a new
version of the underlying BerkeleyDB library, you will almost certainly have to
convert your database files to the new version. You can do this fairly easily
with the new scripts <tt class="file docutils literal"><span class="pre">db2pickle.py</span></tt> and <tt class="file docutils literal"><span class="pre">pickle2db.py</span></tt> which you
will find in the distribution’s <tt class="file docutils literal"><span class="pre">Tools/scripts</span></tt> directory. If you’ve
already been using the PyBSDDB package and importing it as <tt class="xref py py-mod docutils literal"><span class="pre">bsddb3</span></tt>, you
will have to change your <tt class="docutils literal"><span class="pre">import</span></tt> statements to import it as <a class="reference internal" href="../library/bsddb.html#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><tt class="xref py py-mod docutils literal"><span class="pre">bsddb</span></tt></a>.</p>
</li>
<li><p class="first">The new <a class="reference internal" href="../library/bz2.html#module-bz2" title="bz2: Interface to compression and decompression routines compatible with bzip2."><tt class="xref py py-mod docutils literal"><span class="pre">bz2</span></tt></a> module is an interface to the bz2 data compression library.
bz2-compressed data is usually smaller than corresponding <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>-compressed data. (Contributed by Gustavo Niemeyer.)</p>
</li>
<li><p class="first">A set of standard date/time types has been added in the new <a class="reference internal" href="../library/datetime.html#module-datetime" title="datetime: Basic date and time types."><tt class="xref py py-mod docutils literal"><span class="pre">datetime</span></tt></a>
module. See the following section for more details.</p>
</li>
<li><p class="first">The Distutils <tt class="xref py py-class docutils literal"><span class="pre">Extension</span></tt> class now supports an extra constructor
argument named <em>depends</em> for listing additional source files that an extension
depends on. This lets Distutils recompile the module if any of the dependency
files are modified. For example, if <tt class="file docutils literal"><span class="pre">sampmodule.c</span></tt> includes the header
file <tt class="file docutils literal"><span class="pre">sample.h</span></tt>, you would create the <tt class="xref py py-class docutils literal"><span class="pre">Extension</span></tt> object like
this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">ext</span> <span class="o">=</span> <span class="n">Extension</span><span class="p">(</span><span class="s">"samp"</span><span class="p">,</span>
<span class="n">sources</span><span class="o">=</span><span class="p">[</span><span class="s">"sampmodule.c"</span><span class="p">],</span>
<span class="n">depends</span><span class="o">=</span><span class="p">[</span><span class="s">"sample.h"</span><span class="p">])</span>
</pre></div>
</div>
<p>Modifying <tt class="file docutils literal"><span class="pre">sample.h</span></tt> would then cause the module to be recompiled.
(Contributed by Jeremy Hylton.)</p>
</li>
<li><p class="first">Other minor changes to Distutils: it now checks for the <span class="target" id="index-24"></span><tt class="xref std std-envvar docutils literal"><span class="pre">CC</span></tt>,
<span class="target" id="index-25"></span><tt class="xref std std-envvar docutils literal"><span class="pre">CFLAGS</span></tt>, <span class="target" id="index-26"></span><tt class="xref std std-envvar docutils literal"><span class="pre">CPP</span></tt>, <span class="target" id="index-27"></span><tt class="xref std std-envvar docutils literal"><span class="pre">LDFLAGS</span></tt>, and <span class="target" id="index-28"></span><tt class="xref std std-envvar docutils literal"><span class="pre">CPPFLAGS</span></tt>
environment variables, using them to override the settings in Python’s
configuration (contributed by Robert Weber).</p>
</li>
<li><p class="first">Previously 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 would only search the docstrings of
public methods and functions for test cases, but it now also examines private
ones as well. The <tt class="xref py py-func docutils literal"><span class="pre">DocTestSuite(()</span></tt> function creates a
<a class="reference internal" href="../library/unittest.html#unittest.TestSuite" title="unittest.TestSuite"><tt class="xref py py-class docutils literal"><span class="pre">unittest.TestSuite</span></tt></a> object from a set of <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> tests.</p>
</li>
<li><p class="first">The new <tt class="xref py py-func docutils literal"><span class="pre">gc.get_referents(object)()</span></tt> function returns a list of all the
objects referenced by <em>object</em>.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/getopt.html#module-getopt" title="getopt: Portable parser for command line options; support both short and long option names."><tt class="xref py py-mod docutils literal"><span class="pre">getopt</span></tt></a> module gained a new function, <tt class="xref py py-func docutils literal"><span class="pre">gnu_getopt()</span></tt>, that
supports the same arguments as the existing <a class="reference internal" href="../library/getopt.html#module-getopt" title="getopt: Portable parser for command line options; support both short and long option names."><tt class="xref py py-func docutils literal"><span class="pre">getopt()</span></tt></a> function but uses
GNU-style scanning mode. The existing <a class="reference internal" href="../library/getopt.html#module-getopt" title="getopt: Portable parser for command line options; support both short and long option names."><tt class="xref py py-func docutils literal"><span class="pre">getopt()</span></tt></a> stops processing options as
soon as a non-option argument is encountered, but in GNU-style mode processing
continues, meaning that options and arguments can be mixed. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">getopt</span><span class="o">.</span><span class="n">getopt</span><span class="p">([</span><span class="s">'-f'</span><span class="p">,</span> <span class="s">'filename'</span><span class="p">,</span> <span class="s">'output'</span><span class="p">,</span> <span class="s">'-v'</span><span class="p">],</span> <span class="s">'f:v'</span><span class="p">)</span>
<span class="go">([('-f', 'filename')], ['output', '-v'])</span>
<span class="gp">>>> </span><span class="n">getopt</span><span class="o">.</span><span class="n">gnu_getopt</span><span class="p">([</span><span class="s">'-f'</span><span class="p">,</span> <span class="s">'filename'</span><span class="p">,</span> <span class="s">'output'</span><span class="p">,</span> <span class="s">'-v'</span><span class="p">],</span> <span class="s">'f:v'</span><span class="p">)</span>
<span class="go">([('-f', 'filename'), ('-v', '')], ['output'])</span>
</pre></div>
</div>
<p>(Contributed by Peter Åstrand.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/grp.html#module-grp" title="grp: The group database (getgrnam() and friends). (Unix)"><tt class="xref py py-mod docutils literal"><span class="pre">grp</span></tt></a>, <a class="reference internal" href="../library/pwd.html#module-pwd" title="pwd: The password database (getpwnam() and friends). (Unix)"><tt class="xref py py-mod docutils literal"><span class="pre">pwd</span></tt></a>, and <a class="reference internal" href="../library/resource.html#module-resource" title="resource: An interface to provide resource usage information on the current process. (Unix)"><tt class="xref py py-mod docutils literal"><span class="pre">resource</span></tt></a> modules now return enhanced
tuples:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">grp</span>
<span class="gp">>>> </span><span class="n">g</span> <span class="o">=</span> <span class="n">grp</span><span class="o">.</span><span class="n">getgrnam</span><span class="p">(</span><span class="s">'amk'</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">g</span><span class="o">.</span><span class="n">gr_name</span><span class="p">,</span> <span class="n">g</span><span class="o">.</span><span class="n">gr_gid</span>
<span class="go">('amk', 500)</span>
</pre></div>
</div>
</li>
<li><p class="first">The <a class="reference internal" href="../library/gzip.html#module-gzip" title="gzip: Interfaces for gzip compression and decompression using file objects."><tt class="xref py py-mod docutils literal"><span class="pre">gzip</span></tt></a> module can now handle files exceeding 2 GiB.</p>
</li>
<li><p class="first">The new <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 contains an implementation of a heap queue
algorithm. A heap is an array-like data structure that keeps items in a
partially sorted order such that, for every index <em>k</em>, <tt class="docutils literal"><span class="pre">heap[k]</span> <span class="pre"><=</span>
<span class="pre">heap[2*k+1]</span></tt> and <tt class="docutils literal"><span class="pre">heap[k]</span> <span class="pre"><=</span> <span class="pre">heap[2*k+2]</span></tt>. This makes it quick to remove the
smallest item, and inserting a new item while maintaining the heap property is
O(lg n). (See <a class="reference external" href="http://www.nist.gov/dads/HTML/priorityque.html">http://www.nist.gov/dads/HTML/priorityque.html</a> for more
information about the priority queue data structure.)</p>
<p>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 provides <tt class="xref py py-func docutils literal"><span class="pre">heappush()</span></tt> and <tt class="xref py py-func docutils literal"><span class="pre">heappop()</span></tt> functions
for adding and removing items while maintaining the heap property on top of some
other mutable Python sequence type. Here’s an example that uses a Python list:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">heapq</span>
<span class="gp">>>> </span><span class="n">heap</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">>>> </span><span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">11</span><span class="p">,</span> <span class="mi">1</span><span class="p">]:</span>
<span class="gp">... </span> <span class="n">heapq</span><span class="o">.</span><span class="n">heappush</span><span class="p">(</span><span class="n">heap</span><span class="p">,</span> <span class="n">item</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">>>> </span><span class="n">heap</span>
<span class="go">[1, 3, 5, 11, 7]</span>
<span class="gp">>>> </span><span class="n">heapq</span><span class="o">.</span><span class="n">heappop</span><span class="p">(</span><span class="n">heap</span><span class="p">)</span>
<span class="go">1</span>
<span class="gp">>>> </span><span class="n">heapq</span><span class="o">.</span><span class="n">heappop</span><span class="p">(</span><span class="n">heap</span><span class="p">)</span>
<span class="go">3</span>
<span class="gp">>>> </span><span class="n">heap</span>
<span class="go">[5, 7, 11]</span>
</pre></div>
</div>
<p>(Contributed by Kevin O’Connor.)</p>
</li>
<li><p class="first">The IDLE integrated development environment has been updated using the code
from the IDLEfork project (<a class="reference external" href="http://idlefork.sf.net">http://idlefork.sf.net</a>). The most notable feature is
that the code being developed is now executed in a subprocess, meaning that
there’s no longer any need for manual <tt class="docutils literal"><span class="pre">reload()</span></tt> operations. IDLE’s core code
has been incorporated into the standard library as the <tt class="xref py py-mod docutils literal"><span class="pre">idlelib</span></tt> package.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/imaplib.html#module-imaplib" title="imaplib: IMAP4 protocol client (requires sockets)."><tt class="xref py py-mod docutils literal"><span class="pre">imaplib</span></tt></a> module now supports IMAP over SSL. (Contributed by Piers
Lauder and Tino Lange.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/itertools.html#module-itertools" title="itertools: Functions creating iterators for efficient looping."><tt class="xref py py-mod docutils literal"><span class="pre">itertools</span></tt></a> contains a number of useful functions for use with
iterators, inspired by various functions provided by the ML and Haskell
languages. For example, <tt class="docutils literal"><span class="pre">itertools.ifilter(predicate,</span> <span class="pre">iterator)</span></tt> returns all
elements in the iterator for which the function <tt class="xref py py-func docutils literal"><span class="pre">predicate()</span></tt> returns
<a class="reference internal" href="../library/constants.html#True" title="True"><tt class="xref py py-const docutils literal"><span class="pre">True</span></tt></a>, and <tt class="docutils literal"><span class="pre">itertools.repeat(obj,</span> <span class="pre">N)</span></tt> returns <tt class="docutils literal"><span class="pre">obj</span></tt> <em>N</em> times.
There are a number of other functions in the module; see the package’s reference
documentation for details.
(Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">Two new functions in the <a class="reference internal" href="../library/math.html#module-math" title="math: Mathematical functions (sin() etc.)."><tt class="xref py py-mod docutils literal"><span class="pre">math</span></tt></a> module, <tt class="xref py py-func docutils literal"><span class="pre">degrees(rads)()</span></tt> and
<tt class="xref py py-func docutils literal"><span class="pre">radians(degs)()</span></tt>, convert between radians and degrees. Other functions in
the <a class="reference internal" href="../library/math.html#module-math" title="math: Mathematical functions (sin() etc.)."><tt class="xref py py-mod docutils literal"><span class="pre">math</span></tt></a> module such as <a class="reference internal" href="../library/math.html#math.sin" title="math.sin"><tt class="xref py py-func docutils literal"><span class="pre">math.sin()</span></tt></a> and <a class="reference internal" href="../library/math.html#math.cos" title="math.cos"><tt class="xref py py-func docutils literal"><span class="pre">math.cos()</span></tt></a> have always
required input values measured in radians. Also, an optional <em>base</em> argument
was added to <a class="reference internal" href="../library/math.html#math.log" title="math.log"><tt class="xref py py-func docutils literal"><span class="pre">math.log()</span></tt></a> to make it easier to compute logarithms for bases
other than <tt class="docutils literal"><span class="pre">e</span></tt> and <tt class="docutils literal"><span class="pre">10</span></tt>. (Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">Several new POSIX functions (<tt class="xref py py-func docutils literal"><span class="pre">getpgid()</span></tt>, <tt class="xref py py-func docutils literal"><span class="pre">killpg()</span></tt>, <tt class="xref py py-func docutils literal"><span class="pre">lchown()</span></tt>,
<tt class="xref py py-func docutils literal"><span class="pre">loadavg()</span></tt>, <tt class="xref py py-func docutils literal"><span class="pre">major()</span></tt>, <tt class="xref py py-func docutils literal"><span class="pre">makedev()</span></tt>, <tt class="xref py py-func docutils literal"><span class="pre">minor()</span></tt>, and
<tt class="xref py py-func docutils literal"><span class="pre">mknod()</span></tt>) were added to the <a class="reference internal" href="../library/posix.html#module-posix" title="posix: The most common POSIX system calls (normally used via module os). (Unix)"><tt class="xref py py-mod docutils literal"><span class="pre">posix</span></tt></a> module that underlies 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. (Contributed by Gustavo Niemeyer, Geert Jansen, and Denis S.
Otkidach.)</p>
</li>
<li><p class="first">In 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, the <tt class="xref py py-func docutils literal"><span class="pre">*stat()</span></tt> family of functions can now report
fractions of a second in a timestamp. Such time stamps are represented as
floats, similar to the value returned by <a class="reference internal" href="../library/time.html#time.time" title="time.time"><tt class="xref py py-func docutils literal"><span class="pre">time.time()</span></tt></a>.</p>
<p>During testing, it was found that some applications will break if time stamps
are floats. For compatibility, when using the tuple interface of the
<tt class="xref py py-class docutils literal"><span class="pre">stat_result</span></tt> time stamps will be represented as integers. When using
named fields (a feature first introduced in Python 2.2), time stamps are still
represented as integers, unless <a class="reference internal" href="../library/os.html#os.stat_float_times" title="os.stat_float_times"><tt class="xref py py-func docutils literal"><span class="pre">os.stat_float_times()</span></tt></a> is invoked to enable
float return values:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">os</span><span class="o">.</span><span class="n">stat</span><span class="p">(</span><span class="s">"/tmp"</span><span class="p">)</span><span class="o">.</span><span class="n">st_mtime</span>
<span class="go">1034791200</span>
<span class="gp">>>> </span><span class="n">os</span><span class="o">.</span><span class="n">stat_float_times</span><span class="p">(</span><span class="bp">True</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">os</span><span class="o">.</span><span class="n">stat</span><span class="p">(</span><span class="s">"/tmp"</span><span class="p">)</span><span class="o">.</span><span class="n">st_mtime</span>
<span class="go">1034791200.6335014</span>
</pre></div>
</div>
<p>In Python 2.4, the default will change to always returning floats.</p>
<p>Application developers should enable this feature only if all their libraries
work properly when confronted with floating point time stamps, or if they use
the tuple API. If used, the feature should be activated on an application level
instead of trying to enable it on a per-use basis.</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 contains a new parser for command-line arguments
that can convert option values to a particular Python type and will
automatically generate a usage message. See the following section for more
details.</p>
</li>
<li><p class="first">The old and never-documented <tt class="xref py py-mod docutils literal"><span class="pre">linuxaudiodev</span></tt> module has been deprecated,
and a new version named <a class="reference internal" href="../library/ossaudiodev.html#module-ossaudiodev" title="ossaudiodev: Access to OSS-compatible audio devices. (Linux, FreeBSD)"><tt class="xref py py-mod docutils literal"><span class="pre">ossaudiodev</span></tt></a> has been added. The module was
renamed because the OSS sound drivers can be used on platforms other than Linux,
and the interface has also been tidied and brought up to date in various ways.
(Contributed by Greg Ward and Nicholas FitzRoy-Dale.)</p>
</li>
<li><p class="first">The new <a class="reference internal" href="../library/platform.html#module-platform" title="platform: Retrieves as much platform identifying data as possible."><tt class="xref py py-mod docutils literal"><span class="pre">platform</span></tt></a> module contains a number of functions that try to
determine various properties of the platform you’re running on. There are
functions for getting the architecture, CPU type, the Windows OS version, and
even the Linux distribution version. (Contributed by Marc-André Lemburg.)</p>
</li>
<li><p class="first">The parser objects provided by the <tt class="xref py py-mod docutils literal"><span class="pre">pyexpat</span></tt> module can now optionally
buffer character data, resulting in fewer calls to your character data handler
and therefore faster performance. Setting the parser object’s
<tt class="xref py py-attr docutils literal"><span class="pre">buffer_text</span></tt> attribute to <a class="reference internal" href="../library/constants.html#True" title="True"><tt class="xref py py-const docutils literal"><span class="pre">True</span></tt></a> will enable buffering.</p>
</li>
<li><p class="first">The <tt class="xref py py-func docutils literal"><span class="pre">sample(population,</span> <span class="pre">k)()</span></tt> function was added to the <a class="reference internal" href="../library/random.html#module-random" title="random: Generate pseudo-random numbers with various common distributions."><tt class="xref py py-mod docutils literal"><span class="pre">random</span></tt></a>
module. <em>population</em> is a sequence or <a class="reference internal" href="../library/functions.html#xrange" title="xrange"><tt class="xref py py-class docutils literal"><span class="pre">xrange</span></tt></a> object containing the
elements of a population, and <tt class="xref py py-func docutils literal"><span class="pre">sample()</span></tt> chooses <em>k</em> elements from the
population without replacing chosen elements. <em>k</em> can be any value up to
<tt class="docutils literal"><span class="pre">len(population)</span></tt>. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">days</span> <span class="o">=</span> <span class="p">[</span><span class="s">'Mo'</span><span class="p">,</span> <span class="s">'Tu'</span><span class="p">,</span> <span class="s">'We'</span><span class="p">,</span> <span class="s">'Th'</span><span class="p">,</span> <span class="s">'Fr'</span><span class="p">,</span> <span class="s">'St'</span><span class="p">,</span> <span class="s">'Sn'</span><span class="p">]</span>
<span class="gp">>>> </span><span class="n">random</span><span class="o">.</span><span class="n">sample</span><span class="p">(</span><span class="n">days</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="c"># Choose 3 elements</span>
<span class="go">['St', 'Sn', 'Th']</span>
<span class="gp">>>> </span><span class="n">random</span><span class="o">.</span><span class="n">sample</span><span class="p">(</span><span class="n">days</span><span class="p">,</span> <span class="mi">7</span><span class="p">)</span> <span class="c"># Choose 7 elements</span>
<span class="go">['Tu', 'Th', 'Mo', 'We', 'St', 'Fr', 'Sn']</span>
<span class="gp">>>> </span><span class="n">random</span><span class="o">.</span><span class="n">sample</span><span class="p">(</span><span class="n">days</span><span class="p">,</span> <span class="mi">7</span><span class="p">)</span> <span class="c"># Choose 7 again</span>
<span class="go">['We', 'Mo', 'Sn', 'Fr', 'Tu', 'St', 'Th']</span>
<span class="gp">>>> </span><span class="n">random</span><span class="o">.</span><span class="n">sample</span><span class="p">(</span><span class="n">days</span><span class="p">,</span> <span class="mi">8</span><span class="p">)</span> <span class="c"># Can't choose eight</span>
<span class="gt">Traceback (most recent call last):</span>
File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n">?</span>
File <span class="nb">"random.py"</span>, line <span class="m">414</span>, in <span class="n">sample</span>
<span class="k">raise</span> <span class="ne">ValueError</span><span class="p">,</span> <span class="s">"sample larger than population"</span>
<span class="gr">ValueError</span>: <span class="n">sample larger than population</span>
<span class="gp">>>> </span><span class="n">random</span><span class="o">.</span><span class="n">sample</span><span class="p">(</span><span class="nb">xrange</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">10000</span><span class="p">,</span><span class="mi">2</span><span class="p">),</span> <span class="mi">10</span><span class="p">)</span> <span class="c"># Choose ten odd nos. under 10000</span>
<span class="go">[3407, 3805, 1505, 7023, 2401, 2267, 9733, 3151, 8083, 9195]</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/random.html#module-random" title="random: Generate pseudo-random numbers with various common distributions."><tt class="xref py py-mod docutils literal"><span class="pre">random</span></tt></a> module now uses a new algorithm, the Mersenne Twister,
implemented in C. It’s faster and more extensively studied than the previous
algorithm.</p>
<p>(All changes contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">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 also gained a number of new functions:
<tt class="xref py py-func docutils literal"><span class="pre">get_history_item()</span></tt>, <tt class="xref py py-func docutils literal"><span class="pre">get_current_history_length()</span></tt>, and
<tt class="xref py py-func docutils literal"><span class="pre">redisplay()</span></tt>.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/rexec.html#module-rexec" title="rexec: Basic restricted execution framework. (deprecated)"><tt class="xref py py-mod docutils literal"><span class="pre">rexec</span></tt></a> and <a class="reference internal" href="../library/bastion.html#module-Bastion" title="Bastion: Providing restricted access to objects. (deprecated)"><tt class="xref py py-mod docutils literal"><span class="pre">Bastion</span></tt></a> modules have been declared dead, and
attempts to import them will fail with a <a class="reference internal" href="../library/exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><tt class="xref py py-exc docutils literal"><span class="pre">RuntimeError</span></tt></a>. New-style classes
provide new ways to break out of the restricted execution environment provided
by <a class="reference internal" href="../library/rexec.html#module-rexec" title="rexec: Basic restricted execution framework. (deprecated)"><tt class="xref py py-mod docutils literal"><span class="pre">rexec</span></tt></a>, and no one has interest in fixing them or time to do so. If
you have applications using <a class="reference internal" href="../library/rexec.html#module-rexec" title="rexec: Basic restricted execution framework. (deprecated)"><tt class="xref py py-mod docutils literal"><span class="pre">rexec</span></tt></a>, rewrite them to use something else.</p>
<p>(Sticking with Python 2.2 or 2.1 will not make your applications any safer
because there are known bugs in the <a class="reference internal" href="../library/rexec.html#module-rexec" title="rexec: Basic restricted execution framework. (deprecated)"><tt class="xref py py-mod docutils literal"><span class="pre">rexec</span></tt></a> module in those versions. To
repeat: if you’re using <a class="reference internal" href="../library/rexec.html#module-rexec" title="rexec: Basic restricted execution framework. (deprecated)"><tt class="xref py py-mod docutils literal"><span class="pre">rexec</span></tt></a>, stop using it immediately.)</p>
</li>
<li><p class="first">The <tt class="xref py py-mod docutils literal"><span class="pre">rotor</span></tt> module has been deprecated because the algorithm it uses for
encryption is not believed to be secure. If you need encryption, use one of the
several AES Python modules that are available separately.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/shutil.html#module-shutil" title="shutil: High-level file operations, including copying."><tt class="xref py py-mod docutils literal"><span class="pre">shutil</span></tt></a> module gained a <tt class="xref py py-func docutils literal"><span class="pre">move(src,</span> <span class="pre">dest)()</span></tt> function that
recursively moves a file or directory to a new location.</p>
</li>
<li><p class="first">Support for more advanced POSIX signal handling was added to the <a class="reference internal" href="../library/signal.html#module-signal" title="signal: Set handlers for asynchronous events."><tt class="xref py py-mod docutils literal"><span class="pre">signal</span></tt></a>
but then removed again as it proved impossible to make it work reliably across
platforms.</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 timeouts. You can call the
<tt class="xref py py-meth docutils literal"><span class="pre">settimeout(t)()</span></tt> method on a socket object to set a timeout of <em>t</em> seconds.
Subsequent socket operations that take longer than <em>t</em> seconds to complete will
abort and raise a <a class="reference internal" href="../library/socket.html#socket.timeout" title="socket.timeout"><tt class="xref py py-exc docutils literal"><span class="pre">socket.timeout</span></tt></a> exception.</p>
<p>The original timeout implementation was by Tim O’Malley. Michael Gilfix
integrated it into the Python <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 and shepherded it through a
lengthy review. After the code was checked in, Guido van Rossum rewrote parts
of it. (This is a good example of a collaborative development process in
action.)</p>
</li>
<li><p class="first">On Windows, 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 ships with Secure Sockets Layer
(SSL) support.</p>
</li>
<li><p class="first">The value of the C <tt class="xref py py-const docutils literal"><span class="pre">PYTHON_API_VERSION</span></tt> macro is now exposed at the
Python level as <tt class="docutils literal"><span class="pre">sys.api_version</span></tt>. The current exception can be cleared by
calling the new <a class="reference internal" href="../library/sys.html#sys.exc_clear" title="sys.exc_clear"><tt class="xref py py-func docutils literal"><span class="pre">sys.exc_clear()</span></tt></a> function.</p>
</li>
<li><p class="first">The new <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 allows reading from and writing to
<strong class="program">tar</strong>-format archive files. (Contributed by Lars Gustäbel.)</p>
</li>
<li><p class="first">The new <a class="reference internal" href="../library/textwrap.html#module-textwrap" title="textwrap: Text wrapping and filling"><tt class="xref py py-mod docutils literal"><span class="pre">textwrap</span></tt></a> module contains functions for wrapping strings
containing paragraphs of text. The <tt class="xref py py-func docutils literal"><span class="pre">wrap(text,</span> <span class="pre">width)()</span></tt> function takes a
string and returns a list containing the text split into lines of no more than
the chosen width. The <tt class="xref py py-func docutils literal"><span class="pre">fill(text,</span> <span class="pre">width)()</span></tt> function returns a single
string, reformatted to fit into lines no longer than the chosen width. (As you
can guess, <tt class="xref py py-func docutils literal"><span class="pre">fill()</span></tt> is built on top of <tt class="xref py py-func docutils literal"><span class="pre">wrap()</span></tt>. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">textwrap</span>
<span class="gp">>>> </span><span class="n">paragraph</span> <span class="o">=</span> <span class="s">"Not a whit, we defy augury: ... more text ..."</span>
<span class="gp">>>> </span><span class="n">textwrap</span><span class="o">.</span><span class="n">wrap</span><span class="p">(</span><span class="n">paragraph</span><span class="p">,</span> <span class="mi">60</span><span class="p">)</span>
<span class="go">["Not a whit, we defy augury: there's a special providence in",</span>
<span class="go"> "the fall of a sparrow. If it be now, 'tis not to come; if it",</span>
<span class="go"> ...]</span>
<span class="gp">>>> </span><span class="k">print</span> <span class="n">textwrap</span><span class="o">.</span><span class="n">fill</span><span class="p">(</span><span class="n">paragraph</span><span class="p">,</span> <span class="mi">35</span><span class="p">)</span>
<span class="go">Not a whit, we defy augury: there's</span>
<span class="go">a special providence in the fall of</span>
<span class="go">a sparrow. If it be now, 'tis not</span>
<span class="go">to come; if it be not to come, it</span>
<span class="go">will be now; if it be not now, yet</span>
<span class="go">it will come: the readiness is all.</span>
<span class="go">>>></span>
</pre></div>
</div>
<p>The module also contains a <tt class="xref py py-class docutils literal"><span class="pre">TextWrapper</span></tt> class that actually implements
the text wrapping strategy. Both the <tt class="xref py py-class docutils literal"><span class="pre">TextWrapper</span></tt> class and the
<tt class="xref py py-func docutils literal"><span class="pre">wrap()</span></tt> and <tt class="xref py py-func docutils literal"><span class="pre">fill()</span></tt> functions support a number of additional keyword
arguments for fine-tuning the formatting; consult the module’s documentation
for details. (Contributed by Greg Ward.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/thread.html#module-thread" title="thread: Create multiple threads of control within one interpreter."><tt class="xref py py-mod docutils literal"><span class="pre">thread</span></tt></a> and <a class="reference internal" href="../library/threading.html#module-threading" title="threading: Higher-level threading interface."><tt class="xref py py-mod docutils literal"><span class="pre">threading</span></tt></a> modules now have companion modules,
<a class="reference internal" href="../library/dummy_thread.html#module-dummy_thread" title="dummy_thread: Drop-in replacement for the thread module."><tt class="xref py py-mod docutils literal"><span class="pre">dummy_thread</span></tt></a> and <a class="reference internal" href="../library/dummy_threading.html#module-dummy_threading" title="dummy_threading: Drop-in replacement for the threading module."><tt class="xref py py-mod docutils literal"><span class="pre">dummy_threading</span></tt></a>, that provide a do-nothing
implementation of the <a class="reference internal" href="../library/thread.html#module-thread" title="thread: Create multiple threads of control within one interpreter."><tt class="xref py py-mod docutils literal"><span class="pre">thread</span></tt></a> module’s interface for platforms where
threads are not supported. The intention is to simplify thread-aware modules
(ones that <em>don’t</em> rely on threads to run) by putting the following code at the
top:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">try</span><span class="p">:</span>
<span class="kn">import</span> <span class="nn">threading</span> <span class="kn">as</span> <span class="nn">_threading</span>
<span class="k">except</span> <span class="ne">ImportError</span><span class="p">:</span>
<span class="kn">import</span> <span class="nn">dummy_threading</span> <span class="kn">as</span> <span class="nn">_threading</span>
</pre></div>
</div>
<p>In this example, <tt class="xref py py-mod docutils literal"><span class="pre">_threading</span></tt> is used as the module name to make it clear
that the module being used is not necessarily the actual <a class="reference internal" href="../library/threading.html#module-threading" title="threading: Higher-level threading interface."><tt class="xref py py-mod docutils literal"><span class="pre">threading</span></tt></a>
module. Code can call functions and use classes in <tt class="xref py py-mod docutils literal"><span class="pre">_threading</span></tt> whether or
not threads are supported, avoiding an <a class="reference internal" href="../reference/compound_stmts.html#if"><tt class="xref std std-keyword docutils literal"><span class="pre">if</span></tt></a> statement and making the
code slightly clearer. This module will not magically make multithreaded code
run without threads; code that waits for another thread to return or to do
something will simply hang forever.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/time.html#module-time" title="time: Time access and conversions."><tt class="xref py py-mod docutils literal"><span class="pre">time</span></tt></a> module’s <tt class="xref py py-func docutils literal"><span class="pre">strptime()</span></tt> function has long been an annoyance
because it uses the platform C library’s <tt class="xref py py-func docutils literal"><span class="pre">strptime()</span></tt> implementation, and
different platforms sometimes have odd bugs. Brett Cannon contributed a
portable implementation that’s written in pure Python and should behave
identically on all platforms.</p>
</li>
<li><p class="first">The new <a class="reference internal" href="../library/timeit.html#module-timeit" title="timeit: Measure the execution time of small code snippets."><tt class="xref py py-mod docutils literal"><span class="pre">timeit</span></tt></a> module helps measure how long snippets of Python code
take to execute. The <tt class="file docutils literal"><span class="pre">timeit.py</span></tt> file can be run directly from the
command line, or the module’s <tt class="xref py py-class docutils literal"><span class="pre">Timer</span></tt> class can be imported and used
directly. Here’s a short example that figures out whether it’s faster to
convert an 8-bit string to Unicode by appending an empty Unicode string to it or
by using the <a class="reference internal" href="../library/functions.html#unicode" title="unicode"><tt class="xref py py-func docutils literal"><span class="pre">unicode()</span></tt></a> function:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">timeit</span>
<span class="n">timer1</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">Timer</span><span class="p">(</span><span class="s">'unicode("abc")'</span><span class="p">)</span>
<span class="n">timer2</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">Timer</span><span class="p">(</span><span class="s">'"abc" + u""'</span><span class="p">)</span>
<span class="c"># Run three trials</span>
<span class="k">print</span> <span class="n">timer1</span><span class="o">.</span><span class="n">repeat</span><span class="p">(</span><span class="n">repeat</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">number</span><span class="o">=</span><span class="mi">100000</span><span class="p">)</span>
<span class="k">print</span> <span class="n">timer2</span><span class="o">.</span><span class="n">repeat</span><span class="p">(</span><span class="n">repeat</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">number</span><span class="o">=</span><span class="mi">100000</span><span class="p">)</span>
<span class="c"># On my laptop this outputs:</span>
<span class="c"># [0.36831796169281006, 0.37441694736480713, 0.35304892063140869]</span>
<span class="c"># [0.17574405670166016, 0.18193507194519043, 0.17565798759460449]</span>
</pre></div>
</div>
</li>
<li><p class="first">The <a class="reference internal" href="../library/tix.html#module-Tix" title="Tix: Tk Extension Widgets for Tkinter"><tt class="xref py py-mod docutils literal"><span class="pre">Tix</span></tt></a> module has received various bug fixes and updates for the
current version of the Tix package.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/tkinter.html#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><tt class="xref py py-mod docutils literal"><span class="pre">Tkinter</span></tt></a> module now works with a thread-enabled version of Tcl.
Tcl’s threading model requires that widgets only be accessed from the thread in
which they’re created; accesses from another thread can cause Tcl to panic. For
certain Tcl interfaces, <a class="reference internal" href="../library/tkinter.html#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><tt class="xref py py-mod docutils literal"><span class="pre">Tkinter</span></tt></a> will now automatically avoid this when a
widget is accessed from a different thread by marshalling a command, passing it
to the correct thread, and waiting for the results. Other interfaces can’t be
handled automatically but <a class="reference internal" href="../library/tkinter.html#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><tt class="xref py py-mod docutils literal"><span class="pre">Tkinter</span></tt></a> will now raise an exception on such an
access so that you can at least find out about the problem. See
<a class="reference external" href="http://mail.python.org/pipermail/python-dev/2002-December/031107.html">http://mail.python.org/pipermail/python-dev/2002-December/031107.html</a> for a more
detailed explanation of this change. (Implemented by Martin von Löwis.)</p>
</li>
<li><p class="first">Calling Tcl methods through <tt class="xref py py-mod docutils literal"><span class="pre">_tkinter</span></tt> no longer returns only strings.
Instead, if Tcl returns other objects those objects are converted to their
Python equivalent, if one exists, or wrapped with a <tt class="xref py py-class docutils literal"><span class="pre">_tkinter.Tcl_Obj</span></tt>
object if no Python equivalent exists. This behavior can be controlled through
the <tt class="xref py py-meth docutils literal"><span class="pre">wantobjects()</span></tt> method of <tt class="xref py py-class docutils literal"><span class="pre">tkapp</span></tt> objects.</p>
<p>When using <tt class="xref py py-mod docutils literal"><span class="pre">_tkinter</span></tt> through the <a class="reference internal" href="../library/tkinter.html#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><tt class="xref py py-mod docutils literal"><span class="pre">Tkinter</span></tt></a> module (as most Tkinter
applications will), this feature is always activated. It should not cause
compatibility problems, since Tkinter would always convert string results to
Python types where possible.</p>
<p>If any incompatibilities are found, the old behavior can be restored by setting
the <tt class="xref py py-attr docutils literal"><span class="pre">wantobjects</span></tt> variable in the <a class="reference internal" href="../library/tkinter.html#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><tt class="xref py py-mod docutils literal"><span class="pre">Tkinter</span></tt></a> module to false before
creating the first <tt class="xref py py-class docutils literal"><span class="pre">tkapp</span></tt> object.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">Tkinter</span>
<span class="n">Tkinter</span><span class="o">.</span><span class="n">wantobjects</span> <span class="o">=</span> <span class="mi">0</span>
</pre></div>
</div>
<p>Any breakage caused by this change should be reported as a bug.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/userdict.html#module-UserDict" title="UserDict: Class wrapper for dictionary objects."><tt class="xref py py-mod docutils literal"><span class="pre">UserDict</span></tt></a> module has a new <tt class="xref py py-class docutils literal"><span class="pre">DictMixin</span></tt> class which defines
all dictionary methods for classes that already have a minimum mapping
interface. This greatly simplifies writing classes that need to be
substitutable for dictionaries, such as the classes in the <a class="reference internal" href="../library/shelve.html#module-shelve" title="shelve: Python object persistence."><tt class="xref py py-mod docutils literal"><span class="pre">shelve</span></tt></a>
module.</p>
<p>Adding the mix-in as a superclass provides the full dictionary interface
whenever the class defines <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a>, <a class="reference internal" href="../reference/datamodel.html#object.__setitem__" title="object.__setitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__setitem__()</span></tt></a>,
<a class="reference internal" href="../reference/datamodel.html#object.__delitem__" title="object.__delitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__delitem__()</span></tt></a>, and <tt class="xref py py-meth docutils literal"><span class="pre">keys()</span></tt>. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">UserDict</span>
<span class="gp">>>> </span><span class="k">class</span> <span class="nc">SeqDict</span><span class="p">(</span><span class="n">UserDict</span><span class="o">.</span><span class="n">DictMixin</span><span class="p">):</span>
<span class="gp">... </span> <span class="sd">"""Dictionary lookalike implemented with lists."""</span>
<span class="gp">... </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="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">keylist</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">valuelist</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">... </span> <span class="k">def</span> <span class="nf">__getitem__</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="gp">... </span> <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span> <span class="n">i</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">keylist</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
<span class="gp">... </span> <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">raise</span> <span class="ne">KeyError</span>
<span class="gp">... </span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">valuelist</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
<span class="gp">... </span> <span class="k">def</span> <span class="nf">__setitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
<span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span> <span class="n">i</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">keylist</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
<span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">valuelist</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="n">value</span>
<span class="gp">... </span> <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
<span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">keylist</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
<span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">valuelist</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
<span class="gp">... </span> <span class="k">def</span> <span class="nf">__delitem__</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="gp">... </span> <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span> <span class="n">i</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">keylist</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
<span class="gp">... </span> <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">raise</span> <span class="ne">KeyError</span>
<span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">keylist</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
<span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">valuelist</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
<span class="gp">... </span> <span class="k">def</span> <span class="nf">keys</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span> <span class="k">return</span> <span class="nb">list</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">keylist</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">>>> </span><span class="n">s</span> <span class="o">=</span> <span class="n">SeqDict</span><span class="p">()</span>
<span class="gp">>>> </span><span class="nb">dir</span><span class="p">(</span><span class="n">s</span><span class="p">)</span> <span class="c"># See that other dictionary methods are implemented</span>
<span class="go">['__cmp__', '__contains__', '__delitem__', '__doc__', '__getitem__',</span>
<span class="go"> '__init__', '__iter__', '__len__', '__module__', '__repr__',</span>
<span class="go"> '__setitem__', 'clear', 'get', 'has_key', 'items', 'iteritems',</span>
<span class="go"> 'iterkeys', 'itervalues', 'keylist', 'keys', 'pop', 'popitem',</span>
<span class="go"> 'setdefault', 'update', 'valuelist', 'values']</span>
</pre></div>
</div>
<p>(Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">The DOM implementation in <a class="reference internal" href="../library/xml.dom.minidom.html#module-xml.dom.minidom" title="xml.dom.minidom: Minimal Document Object Model (DOM) implementation."><tt class="xref py py-mod docutils literal"><span class="pre">xml.dom.minidom</span></tt></a> can now generate XML output
in a particular encoding by providing an optional encoding argument to the
<tt class="xref py py-meth docutils literal"><span class="pre">toxml()</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">toprettyxml()</span></tt> methods of DOM nodes.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/xmlrpclib.html#module-xmlrpclib" title="xmlrpclib: XML-RPC client access."><tt class="xref py py-mod docutils literal"><span class="pre">xmlrpclib</span></tt></a> module now supports an XML-RPC extension for handling nil
data values such as Python’s <tt class="docutils literal"><span class="pre">None</span></tt>. Nil values are always supported on
unmarshalling an XML-RPC response. To generate requests containing <tt class="docutils literal"><span class="pre">None</span></tt>,
you must supply a true value for the <em>allow_none</em> parameter when creating a
<tt class="xref py py-class docutils literal"><span class="pre">Marshaller</span></tt> instance.</p>
</li>
<li><p class="first">The new <a class="reference internal" href="../library/docxmlrpcserver.html#module-DocXMLRPCServer" title="DocXMLRPCServer: Self-documenting XML-RPC server implementation."><tt class="xref py py-mod docutils literal"><span class="pre">DocXMLRPCServer</span></tt></a> module allows writing self-documenting XML-RPC
servers. Run it in demo mode (as a program) to see it in action. Pointing the
Web browser to the RPC server produces pydoc-style documentation; pointing
xmlrpclib to the server allows invoking the actual methods. (Contributed by
Brian Quinlan.)</p>
</li>
<li><p class="first">Support for internationalized domain names (RFCs 3454, 3490, 3491, and 3492)
has been added. The “idna” encoding can be used to convert between a Unicode
domain name and the ASCII-compatible encoding (ACE) of that name.</p>
<div class="highlight-python"><pre>>{}>{}> u"www.Alliancefrançaise.nu".encode("idna")
'www.xn--alliancefranaise-npb.nu'</pre>
</div>
<p>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 has also been extended to transparently convert
Unicode hostnames to the ACE version before passing them to the C library.
Modules that deal with hostnames such as <a class="reference internal" href="../library/httplib.html#module-httplib" title="httplib: HTTP and HTTPS protocol client (requires sockets)."><tt class="xref py py-mod docutils literal"><span class="pre">httplib</span></tt></a> and <a class="reference internal" href="../library/ftplib.html#module-ftplib" title="ftplib: FTP protocol client (requires sockets)."><tt class="xref py py-mod docutils literal"><span class="pre">ftplib</span></tt></a>)
also support Unicode host names; <a class="reference internal" href="../library/httplib.html#module-httplib" title="httplib: HTTP and HTTPS protocol client (requires sockets)."><tt class="xref py py-mod docutils literal"><span class="pre">httplib</span></tt></a> also sends HTTP <tt class="docutils literal"><span class="pre">Host</span></tt>
headers using the ACE version of the domain name. <a class="reference internal" href="../library/urllib.html#module-urllib" title="urllib: Open an arbitrary network resource by URL (requires sockets)."><tt class="xref py py-mod docutils literal"><span class="pre">urllib</span></tt></a> supports
Unicode URLs with non-ASCII host names as long as the <tt class="docutils literal"><span class="pre">path</span></tt> part of the URL
is ASCII only.</p>
<p>To implement this change, the <a class="reference internal" href="../library/stringprep.html#module-stringprep" title="stringprep: String preparation, as per RFC 3453 (deprecated)"><tt class="xref py py-mod docutils literal"><span class="pre">stringprep</span></tt></a> module, the <tt class="docutils literal"><span class="pre">mkstringprep</span></tt>
tool and the <tt class="docutils literal"><span class="pre">punycode</span></tt> encoding have been added.</p>
</li>
</ul>
<div class="section" id="date-time-type">
<h3>Date/Time Type<a class="headerlink" href="#date-time-type" title="Permalink to this headline">¶</a></h3>
<p>Date and time types suitable for expressing timestamps were added as 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. The types don’t support different calendars or many
fancy features, and just stick to the basics of representing time.</p>
<p>The three primary types are: <tt class="xref py py-class docutils literal"><span class="pre">date</span></tt>, representing a day, month, and year;
<a class="reference internal" href="../library/time.html#module-time" title="time: Time access and conversions."><tt class="xref py py-class docutils literal"><span class="pre">time</span></tt></a>, consisting of hour, minute, and second; and <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>,
which contains all the attributes of both <tt class="xref py py-class docutils literal"><span class="pre">date</span></tt> and <a class="reference internal" href="../library/time.html#module-time" title="time: Time access and conversions."><tt class="xref py py-class docutils literal"><span class="pre">time</span></tt></a>.
There’s also a <tt class="xref py py-class docutils literal"><span class="pre">timedelta</span></tt> class representing differences between two
points in time, and time zone logic is implemented by classes inheriting from
the abstract <tt class="xref py py-class docutils literal"><span class="pre">tzinfo</span></tt> class.</p>
<p>You can create instances of <tt class="xref py py-class docutils literal"><span class="pre">date</span></tt> and <a class="reference internal" href="../library/time.html#module-time" title="time: Time access and conversions."><tt class="xref py py-class docutils literal"><span class="pre">time</span></tt></a> by either supplying
keyword arguments to the appropriate constructor, e.g.
<tt class="docutils literal"><span class="pre">datetime.date(year=1972,</span> <span class="pre">month=10,</span> <span class="pre">day=15)</span></tt>, or by using one of a number of
class methods. For example, the <tt class="xref py py-meth docutils literal"><span class="pre">date.today()</span></tt> class method returns the
current local date.</p>
<p>Once created, instances of the date/time classes are all immutable. There are a
number of methods for producing formatted strings from objects:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">datetime</span>
<span class="gp">>>> </span><span class="n">now</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">()</span>
<span class="gp">>>> </span><span class="n">now</span><span class="o">.</span><span class="n">isoformat</span><span class="p">()</span>
<span class="go">'2002-12-30T21:27:03.994956'</span>
<span class="gp">>>> </span><span class="n">now</span><span class="o">.</span><span class="n">ctime</span><span class="p">()</span> <span class="c"># Only available on date, datetime</span>
<span class="go">'Mon Dec 30 21:27:03 2002'</span>
<span class="gp">>>> </span><span class="n">now</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s">'%Y </span><span class="si">%d</span><span class="s"> %b'</span><span class="p">)</span>
<span class="go">'2002 30 Dec'</span>
</pre></div>
</div>
<p>The <tt class="xref py py-meth docutils literal"><span class="pre">replace()</span></tt> method allows modifying one or more fields of a
<tt class="xref py py-class docutils literal"><span class="pre">date</span></tt> or <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> instance, returning a new instance:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">d</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">()</span>
<span class="gp">>>> </span><span class="n">d</span>
<span class="go">datetime.datetime(2002, 12, 30, 22, 15, 38, 827738)</span>
<span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="n">year</span><span class="o">=</span><span class="mi">2001</span><span class="p">,</span> <span class="n">hour</span> <span class="o">=</span> <span class="mi">12</span><span class="p">)</span>
<span class="go">datetime.datetime(2001, 12, 30, 12, 15, 38, 827738)</span>
<span class="go">>>></span>
</pre></div>
</div>
<p>Instances can be compared, hashed, and converted to strings (the result is the
same as that of <tt class="xref py py-meth docutils literal"><span class="pre">isoformat()</span></tt>). <tt class="xref py py-class docutils literal"><span class="pre">date</span></tt> and <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>
instances can be subtracted from each other, and added to <tt class="xref py py-class docutils literal"><span class="pre">timedelta</span></tt>
instances. The largest missing feature is that there’s no standard library
support for parsing strings and getting back a <tt class="xref py py-class docutils literal"><span class="pre">date</span></tt> or
<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>.</p>
<p>For more information, refer to the module’s reference documentation.
(Contributed by Tim Peters.)</p>
</div>
<div class="section" id="the-optparse-module">
<h3>The optparse Module<a class="headerlink" href="#the-optparse-module" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="../library/getopt.html#module-getopt" title="getopt: Portable parser for command line options; support both short and long option names."><tt class="xref py py-mod docutils literal"><span class="pre">getopt</span></tt></a> module provides simple parsing of command-line arguments. The
new <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 (originally named Optik) provides more elaborate
command-line parsing that follows the Unix conventions, automatically creates
the output for <a class="reference internal" href="../using/cmdline.html#cmdoption--help"><em class="xref std std-option">--help</em></a>, and can perform different actions for different
options.</p>
<p>You start by creating an instance of <tt class="xref py py-class docutils literal"><span class="pre">OptionParser</span></tt> and telling it what
your program’s options are.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">sys</span>
<span class="kn">from</span> <span class="nn">optparse</span> <span class="kn">import</span> <span class="n">OptionParser</span>
<span class="n">op</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">()</span>
<span class="n">op</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">'-i'</span><span class="p">,</span> <span class="s">'--input'</span><span class="p">,</span>
<span class="n">action</span><span class="o">=</span><span class="s">'store'</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s">'string'</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">'input'</span><span class="p">,</span>
<span class="n">help</span><span class="o">=</span><span class="s">'set input filename'</span><span class="p">)</span>
<span class="n">op</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">'-l'</span><span class="p">,</span> <span class="s">'--length'</span><span class="p">,</span>
<span class="n">action</span><span class="o">=</span><span class="s">'store'</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s">'int'</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">'length'</span><span class="p">,</span>
<span class="n">help</span><span class="o">=</span><span class="s">'set maximum length of output'</span><span class="p">)</span>
</pre></div>
</div>
<p>Parsing a command line is then done by calling the <tt class="xref py py-meth docutils literal"><span class="pre">parse_args()</span></tt> method.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">options</span><span class="p">,</span> <span class="n">args</span> <span class="o">=</span> <span class="n">op</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">:])</span>
<span class="k">print</span> <span class="n">options</span>
<span class="k">print</span> <span class="n">args</span>
</pre></div>
</div>
<p>This returns an object containing all of the option values, and a list of
strings containing the remaining arguments.</p>
<p>Invoking the script with the various arguments now works as you’d expect it to.
Note that the length argument is automatically converted to an integer.</p>
<div class="highlight-python"><pre>$ ./python opt.py -i data arg1
<Values at 0x400cad4c: {'input': 'data', 'length': None}>
['arg1']
$ ./python opt.py --input=data --length=4
<Values at 0x400cad2c: {'input': 'data', 'length': 4}>
[]
$</pre>
</div>
<p>The help message is automatically generated for you:</p>
<div class="highlight-python"><pre>$ ./python opt.py --help
usage: opt.py [options]
options:
-h, --help show this help message and exit
-iINPUT, --input=INPUT
set input filename
-lLENGTH, --length=LENGTH
set maximum length of output
$</pre>
</div>
<p>See the module’s documentation for more details.</p>
<p>Optik was written by Greg Ward, with suggestions from the readers of the Getopt
SIG.</p>
</div>
</div>
<div class="section" id="pymalloc-a-specialized-object-allocator">
<span id="section-pymalloc"></span><h2>Pymalloc: A Specialized Object Allocator<a class="headerlink" href="#pymalloc-a-specialized-object-allocator" title="Permalink to this headline">¶</a></h2>
<p>Pymalloc, a specialized object allocator written by Vladimir Marangozov, was a
feature added to Python 2.1. Pymalloc is intended to be faster than the system
<tt class="xref c c-func docutils literal"><span class="pre">malloc()</span></tt> and to have less memory overhead for allocation patterns typical
of Python programs. The allocator uses C’s <tt class="xref c c-func docutils literal"><span class="pre">malloc()</span></tt> function to get large
pools of memory and then fulfills smaller memory requests from these pools.</p>
<p>In 2.1 and 2.2, pymalloc was an experimental feature and wasn’t enabled by
default; you had to explicitly enable it when compiling Python by providing the
<em class="xref std std-option">--with-pymalloc</em> option to the <strong class="program">configure</strong> script. In 2.3,
pymalloc has had further enhancements and is now enabled by default; you’ll have
to supply <em class="xref std std-option">--without-pymalloc</em> to disable it.</p>
<p>This change is transparent to code written in Python; however, pymalloc may
expose bugs in C extensions. Authors of C extension modules should test their
code with pymalloc enabled, because some incorrect code may cause core dumps at
runtime.</p>
<p>There’s one particularly common error that causes problems. There are a number
of memory allocation functions in Python’s C API that have previously just been
aliases for the C library’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>, meaning that if
you accidentally called mismatched functions the error wouldn’t be noticeable.
When the object allocator is enabled, these functions aren’t aliases of
<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> any more, and calling the wrong function to
free memory may get you a core dump. For example, if memory was allocated using
<tt class="xref c c-func docutils literal"><span class="pre">PyObject_Malloc()</span></tt>, it has to be freed using <tt class="xref c c-func docutils literal"><span class="pre">PyObject_Free()</span></tt>, not
<tt class="xref c c-func docutils literal"><span class="pre">free()</span></tt>. A few modules included with Python fell afoul of this and had to
be fixed; doubtless there are more third-party modules that will have the same
problem.</p>
<p>As part of this change, the confusing multiple interfaces for allocating memory
have been consolidated down into two API families. Memory allocated with one
family must not be manipulated with functions from the other family. There is
one family for allocating chunks of memory and another family of functions
specifically for allocating Python objects.</p>
<ul class="simple">
<li>To allocate and free an undistinguished chunk of memory use the “raw memory”
family: <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>.</li>
<li>The “object memory” family is the interface to the pymalloc facility described
above and is biased towards a large number of “small” allocations:
<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>.</li>
<li>To allocate and free Python objects, use the “object” family
<a class="reference internal" href="../c-api/allocation.html#PyObject_New" title="PyObject_New"><tt class="xref c c-func docutils literal"><span class="pre">PyObject_New()</span></tt></a>, <a class="reference internal" href="../c-api/allocation.html#PyObject_NewVar" title="PyObject_NewVar"><tt class="xref c c-func docutils literal"><span class="pre">PyObject_NewVar()</span></tt></a>, and <a class="reference internal" href="../c-api/allocation.html#PyObject_Del" title="PyObject_Del"><tt class="xref c c-func docutils literal"><span class="pre">PyObject_Del()</span></tt></a>.</li>
</ul>
<p>Thanks to lots of work by Tim Peters, pymalloc in 2.3 also provides debugging
features to catch memory overwrites and doubled frees in both extension modules
and in the interpreter itself. To enable this support, compile a debugging
version of the Python interpreter by running <strong class="program">configure</strong> with
<em class="xref std std-option">--with-pydebug</em>.</p>
<p>To aid extension writers, a header file <tt class="file docutils literal"><span class="pre">Misc/pymemcompat.h</span></tt> is
distributed with the source to Python 2.3 that allows Python extensions to use
the 2.3 interfaces to memory allocation while compiling against any version of
Python since 1.5.2. You would copy the file from Python’s source distribution
and bundle it with the source of your extension.</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://svn.python.org/view/python/trunk/Objects/obmalloc.c">http://svn.python.org/view/python/trunk/Objects/obmalloc.c</a></dt>
<dd>For the full details of the pymalloc implementation, see the comments at
the top of the file <tt class="file docutils literal"><span class="pre">Objects/obmalloc.c</span></tt> in the Python source code.
The above link points to the file within the python.org SVN browser.</dd>
</dl>
</div>
</div>
<div class="section" id="build-and-c-api-changes">
<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’s build process and to the C API include:</p>
<ul class="simple">
<li>The cycle detection implementation used by the garbage collection has proven
to be stable, so it’s now been made mandatory. You can no longer compile Python
without it, and the <em class="xref std std-option">--with-cycle-gc</em> switch to <strong class="program">configure</strong> has
been removed.</li>
<li>Python can now optionally be built as a shared library
(<tt class="file docutils literal"><span class="pre">libpython2.3.so</span></tt>) by supplying <em class="xref std std-option">--enable-shared</em> when running
Python’s <strong class="program">configure</strong> script. (Contributed by Ondrej Palkovsky.)</li>
<li>The <tt class="xref c c-macro docutils literal"><span class="pre">DL_EXPORT</span></tt> and <tt class="xref c c-macro docutils literal"><span class="pre">DL_IMPORT</span></tt> macros are now deprecated.
Initialization functions for Python extension modules should now be declared
using the new macro <tt class="xref c c-macro docutils literal"><span class="pre">PyMODINIT_FUNC</span></tt>, while the Python core will
generally use the <tt class="xref c c-macro docutils literal"><span class="pre">PyAPI_FUNC</span></tt> and <tt class="xref c c-macro docutils literal"><span class="pre">PyAPI_DATA</span></tt> macros.</li>
<li>The interpreter can be compiled without any docstrings for the built-in
functions and modules by supplying <em class="xref std std-option">--without-doc-strings</em> to the
<strong class="program">configure</strong> script. This makes the Python executable about 10% smaller,
but will also mean that you can’t get help for Python’s built-ins. (Contributed
by Gustavo Niemeyer.)</li>
<li>The <tt class="xref c c-func docutils literal"><span class="pre">PyArg_NoArgs()</span></tt> macro is now deprecated, and code that uses it
should be changed. For Python 2.2 and later, the method definition table can
specify the <a class="reference internal" href="../c-api/structures.html#METH_NOARGS" title="METH_NOARGS"><tt class="xref py py-const docutils literal"><span class="pre">METH_NOARGS</span></tt></a> flag, signalling that there are no arguments,
and the argument checking can then be removed. If compatibility with pre-2.2
versions of Python is important, the code could use <tt class="docutils literal"><span class="pre">PyArg_ParseTuple(args,</span>
<span class="pre">"")</span></tt> instead, but this will be slower than using <a class="reference internal" href="../c-api/structures.html#METH_NOARGS" title="METH_NOARGS"><tt class="xref py py-const docutils literal"><span class="pre">METH_NOARGS</span></tt></a>.</li>
<li><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> accepts new format characters for various sizes of
unsigned integers: <tt class="docutils literal"><span class="pre">B</span></tt> for <tt class="xref c c-type docutils literal"><span class="pre">unsigned</span> <span class="pre">char</span></tt>, <tt class="docutils literal"><span class="pre">H</span></tt> for <tt class="xref c c-type docutils literal"><span class="pre">unsigned</span>
<span class="pre">short</span> <span class="pre">int</span></tt>, <tt class="docutils literal"><span class="pre">I</span></tt> for <tt class="xref c c-type docutils literal"><span class="pre">unsigned</span> <span class="pre">int</span></tt>, and <tt class="docutils literal"><span class="pre">K</span></tt> for <tt class="xref c c-type docutils literal"><span class="pre">unsigned</span>
<span class="pre">long</span> <span class="pre">long</span></tt>.</li>
<li>A new function, <tt class="xref c c-func docutils literal"><span class="pre">PyObject_DelItemString(mapping,</span> <span class="pre">char</span> <span class="pre">*key)()</span></tt> was added
as shorthand for <tt class="docutils literal"><span class="pre">PyObject_DelItem(mapping,</span> <span class="pre">PyString_New(key))</span></tt>.</li>
<li>File objects now manage their internal string buffer differently, increasing
it exponentially when needed. This results in the benchmark tests in
<tt class="file docutils literal"><span class="pre">Lib/test/test_bufio.py</span></tt> speeding up considerably (from 57 seconds to 1.7
seconds, according to one measurement).</li>
<li>It’s now possible to define class and static methods for a C extension type by
setting either the <a class="reference internal" href="../c-api/structures.html#METH_CLASS" title="METH_CLASS"><tt class="xref py py-const docutils literal"><span class="pre">METH_CLASS</span></tt></a> or <a class="reference internal" href="../c-api/structures.html#METH_STATIC" title="METH_STATIC"><tt class="xref py py-const docutils literal"><span class="pre">METH_STATIC</span></tt></a> flags in a
method’s <a class="reference internal" href="../c-api/structures.html#PyMethodDef" title="PyMethodDef"><tt class="xref c c-type docutils literal"><span class="pre">PyMethodDef</span></tt></a> structure.</li>
<li>Python now includes a copy of the Expat XML parser’s source code, removing any
dependence on a system version or local installation of Expat.</li>
<li>If you dynamically allocate type objects in your extension, you should be
aware of a change in the rules relating to the <tt class="xref py py-attr docutils literal"><span class="pre">__module__</span></tt> and
<tt class="xref py py-attr docutils literal"><span class="pre">__name__</span></tt> attributes. In summary, you will want to ensure the type’s
dictionary contains a <tt class="docutils literal"><span class="pre">'__module__'</span></tt> key; making the module name the part of
the type name leading up to the final period will no longer have the desired
effect. For more detail, read the API reference documentation or the source.</li>
</ul>
<div class="section" id="port-specific-changes">
<h3>Port-Specific Changes<a class="headerlink" href="#port-specific-changes" title="Permalink to this headline">¶</a></h3>
<p>Support for a port to IBM’s OS/2 using the EMX runtime environment was merged
into the main Python source tree. EMX is a POSIX emulation layer over the OS/2
system APIs. The Python port for EMX tries to support all the POSIX-like
capability exposed by the EMX runtime, and mostly succeeds; <tt class="xref py py-func docutils literal"><span class="pre">fork()</span></tt> and
<a class="reference internal" href="../library/fcntl.html#module-fcntl" title="fcntl: The fcntl() and ioctl() system calls. (Unix)"><tt class="xref py py-func docutils literal"><span class="pre">fcntl()</span></tt></a> are restricted by the limitations of the underlying emulation
layer. The standard OS/2 port, which uses IBM’s Visual Age compiler, also
gained support for case-sensitive import semantics as part of the integration of
the EMX port into CVS. (Contributed by Andrew MacIntyre.)</p>
<p>On MacOS, most toolbox modules have been weaklinked to improve backward
compatibility. This means that modules will no longer fail to load if a single
routine is missing on the current OS version. Instead calling the missing
routine will raise an exception. (Contributed by Jack Jansen.)</p>
<p>The RPM spec files, found in the <tt class="file docutils literal"><span class="pre">Misc/RPM/</span></tt> directory in the Python
source distribution, were updated for 2.3. (Contributed by Sean Reifschneider.)</p>
<p>Other new platforms now supported by Python include AtheOS
(<a class="reference external" href="http://www.atheos.cx/">http://www.atheos.cx/</a>), GNU/Hurd, and OpenVMS.</p>
</div>
</div>
<div class="section" id="other-changes-and-fixes">
<span id="section-other"></span><h2>Other Changes and Fixes<a class="headerlink" href="#other-changes-and-fixes" title="Permalink to this headline">¶</a></h2>
<p>As usual, there were a bunch of other improvements and bugfixes scattered
throughout the source tree. A search through the CVS change logs finds there
were 523 patches applied and 514 bugs fixed between Python 2.2 and 2.3. Both
figures are likely to be underestimates.</p>
<p>Some of the more notable changes are:</p>
<ul>
<li><p class="first">If the <span class="target" id="index-29"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONINSPECT"><tt class="xref std std-envvar docutils literal"><span class="pre">PYTHONINSPECT</span></tt></a> environment variable is set, the Python
interpreter will enter the interactive prompt after running a Python program, as
if Python had been invoked with the <a class="reference internal" href="../using/cmdline.html#cmdoption-i"><em class="xref std std-option">-i</em></a> option. The environment
variable can be set before running the Python interpreter, or it can be set by
the Python program as part of its execution.</p>
</li>
<li><p class="first">The <tt class="file docutils literal"><span class="pre">regrtest.py</span></tt> script now provides a way to allow “all resources
except <em>foo</em>.” A resource name passed to the <a class="reference internal" href="../using/cmdline.html#cmdoption-u"><em class="xref std std-option">-u</em></a> option can now be
prefixed with a hyphen (<tt class="docutils literal"><span class="pre">'-'</span></tt>) to mean “remove this resource.” For example,
the option ‘<tt class="docutils literal"><span class="pre">-uall,-bsddb</span></tt>‘ could be used to enable the use of all resources
except <tt class="docutils literal"><span class="pre">bsddb</span></tt>.</p>
</li>
<li><p class="first">The tools used to build the documentation now work under Cygwin as well as
Unix.</p>
</li>
<li><p class="first">The <tt class="docutils literal"><span class="pre">SET_LINENO</span></tt> opcode has been removed. Back in the mists of time, this
opcode was needed to produce line numbers in tracebacks and support trace
functions (for, e.g., <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>). Since Python 1.5, the line numbers in
tracebacks have been computed using a different mechanism that works with
“python -O”. For Python 2.3 Michael Hudson implemented a similar scheme to
determine when to call the trace function, removing the need for <tt class="docutils literal"><span class="pre">SET_LINENO</span></tt>
entirely.</p>
<p>It would be difficult to detect any resulting difference from Python code, apart
from a slight speed up when Python is run without <a class="reference internal" href="../using/cmdline.html#cmdoption-O"><em class="xref std std-option">-O</em></a>.</p>
<p>C extensions that access the <tt class="xref py py-attr docutils literal"><span class="pre">f_lineno</span></tt> field of frame objects should
instead call <tt class="docutils literal"><span class="pre">PyCode_Addr2Line(f->f_code,</span> <span class="pre">f->f_lasti)</span></tt>. This will have the
added effect of making the code work as desired under “python -O” in earlier
versions of Python.</p>
<p>A nifty new feature is that trace functions can now assign to the
<tt class="xref py py-attr docutils literal"><span class="pre">f_lineno</span></tt> attribute of frame objects, changing the line that will be
executed next. A <tt class="docutils literal"><span class="pre">jump</span></tt> command has been added to 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> debugger
taking advantage of this new feature. (Implemented by Richie Hindle.)</p>
</li>
</ul>
</div>
<div class="section" id="porting-to-python-2-3">
<h2>Porting to Python 2.3<a class="headerlink" href="#porting-to-python-2-3" title="Permalink to this headline">¶</a></h2>
<p>This section lists previously described changes that may require changes to your
code:</p>
<ul>
<li><p class="first"><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 always a keyword; if it’s used as a variable name in
your code, a different name must be chosen.</p>
</li>
<li><p class="first">For strings <em>X</em> and <em>Y</em>, <tt class="docutils literal"><span class="pre">X</span> <span class="pre">in</span> <span class="pre">Y</span></tt> now works if <em>X</em> is more than one
character long.</p>
</li>
<li><p class="first">The <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> type constructor will now return a long integer instead of
raising an <a class="reference internal" href="../library/exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><tt class="xref py py-exc docutils literal"><span class="pre">OverflowError</span></tt></a> when a string or floating-point number is too
large to fit into an integer.</p>
</li>
<li><p class="first">If you have Unicode strings that contain 8-bit characters, you must declare
the file’s encoding (UTF-8, Latin-1, or whatever) by adding a comment to the top
of the file. See section <a class="reference internal" href="#section-encodings"><em>PEP 263: Source Code Encodings</em></a> for more information.</p>
</li>
<li><p class="first">Calling Tcl methods through <tt class="xref py py-mod docutils literal"><span class="pre">_tkinter</span></tt> no longer returns only strings.
Instead, if Tcl returns other objects those objects are converted to their
Python equivalent, if one exists, or wrapped with a <tt class="xref py py-class docutils literal"><span class="pre">_tkinter.Tcl_Obj</span></tt>
object if no Python equivalent exists.</p>
</li>
<li><p class="first">Large octal and hex literals such as <tt class="docutils literal"><span class="pre">0xffffffff</span></tt> now trigger a
<a class="reference internal" href="../library/exceptions.html#exceptions.FutureWarning" title="exceptions.FutureWarning"><tt class="xref py py-exc docutils literal"><span class="pre">FutureWarning</span></tt></a>. Currently they’re stored as 32-bit numbers and result in a
negative value, but in Python 2.4 they’ll become positive long integers.</p>
<p>There are a few ways to fix this warning. If you really need a positive number,
just add an <tt class="docutils literal"><span class="pre">L</span></tt> to the end of the literal. If you’re trying to get a 32-bit
integer with low bits set and have previously used an expression such as <tt class="docutils literal"><span class="pre">~(1</span>
<span class="pre"><<</span> <span class="pre">31)</span></tt>, it’s probably clearest to start with all bits set and clear the
desired upper bits. For example, to clear just the top bit (bit 31), you could
write <tt class="docutils literal"><span class="pre">0xffffffffL</span> <span class="pre">&~(1L<<31)</span></tt>.</p>
</li>
<li><p class="first">You can no longer disable assertions by assigning to <tt class="docutils literal"><span class="pre">__debug__</span></tt>.</p>
</li>
<li><p class="first">The Distutils <tt class="xref py py-func docutils literal"><span class="pre">setup()</span></tt> function has gained various new keyword arguments
such as <em>depends</em>. Old versions of the Distutils will abort if passed unknown
keywords. A solution is to check for the presence of the new
<tt class="xref py py-func docutils literal"><span class="pre">get_distutil_options()</span></tt> function in your <tt class="file docutils literal"><span class="pre">setup.py</span></tt> and only uses the
new keywords with a version of the Distutils that supports them:</p>
<div class="highlight-python"><pre>from distutils import core
kw = {'sources': 'foo.c', ...}
if hasattr(core, 'get_distutil_options'):
kw['depends'] = ['foo.h']
ext = Extension(**kw)</pre>
</div>
</li>
<li><p class="first">Using <tt class="docutils literal"><span class="pre">None</span></tt> as a variable name will now result in a <a class="reference internal" href="../library/exceptions.html#exceptions.SyntaxWarning" title="exceptions.SyntaxWarning"><tt class="xref py py-exc docutils literal"><span class="pre">SyntaxWarning</span></tt></a>
warning.</p>
</li>
<li><p class="first">Names of extension types defined by the modules included with Python now
contain the module and a <tt class="docutils literal"><span class="pre">'.'</span></tt> in front of the type name.</p>
</li>
</ul>
</div>
<div class="section" id="acknowledgements">
<span id="acks"></span><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: Jeff Bauer,
Simon Brunning, Brett Cannon, Michael Chermside, Andrew Dalke, Scott David
Daniels, Fred L. Drake, Jr., David Fraser, Kelly Gerber, Raymond Hettinger,
Michael Hudson, Chris Lambert, Detlef Lannert, Martin von Löwis, Andrew
MacIntyre, Lalo Martins, Chad Netzer, Gustavo Niemeyer, Neal Norwitz, Hans
Nowak, Chris Reedy, Francesco Ricciardi, Vinay Sajip, Neil Schemenauer, Roman
Suzi, Jason Tishler, Just van Rossum.</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’s New in Python 2.3</a><ul>
<li><a class="reference internal" href="#pep-218-a-standard-set-datatype">PEP 218: A Standard Set Datatype</a></li>
<li><a class="reference internal" href="#pep-255-simple-generators">PEP 255: Simple Generators</a></li>
<li><a class="reference internal" href="#pep-263-source-code-encodings">PEP 263: Source Code Encodings</a></li>
<li><a class="reference internal" href="#pep-273-importing-modules-from-zip-archives">PEP 273: Importing Modules from ZIP Archives</a></li>
<li><a class="reference internal" href="#pep-277-unicode-file-name-support-for-windows-nt">PEP 277: Unicode file name support for Windows NT</a></li>
<li><a class="reference internal" href="#pep-278-universal-newline-support">PEP 278: Universal Newline Support</a></li>
<li><a class="reference internal" href="#pep-279-enumerate">PEP 279: enumerate()</a></li>
<li><a class="reference internal" href="#pep-282-the-logging-package">PEP 282: The logging Package</a></li>
<li><a class="reference internal" href="#pep-285-a-boolean-type">PEP 285: A Boolean Type</a></li>
<li><a class="reference internal" href="#pep-293-codec-error-handling-callbacks">PEP 293: Codec Error Handling Callbacks</a></li>
<li><a class="reference internal" href="#pep-301-package-index-and-metadata-for-distutils">PEP 301: Package Index and Metadata for Distutils</a></li>
<li><a class="reference internal" href="#pep-302-new-import-hooks">PEP 302: New Import Hooks</a></li>
<li><a class="reference internal" href="#pep-305-comma-separated-files">PEP 305: Comma-separated Files</a></li>
<li><a class="reference internal" href="#pep-307-pickle-enhancements">PEP 307: Pickle Enhancements</a></li>
<li><a class="reference internal" href="#extended-slices">Extended Slices</a></li>
<li><a class="reference internal" href="#other-language-changes">Other Language Changes</a><ul>
<li><a class="reference internal" href="#string-changes">String Changes</a></li>
<li><a class="reference internal" href="#optimizations">Optimizations</a></li>
</ul>
</li>
<li><a class="reference internal" href="#new-improved-and-deprecated-modules">New, Improved, and Deprecated Modules</a><ul>
<li><a class="reference internal" href="#date-time-type">Date/Time Type</a></li>
<li><a class="reference internal" href="#the-optparse-module">The optparse Module</a></li>
</ul>
</li>
<li><a class="reference internal" href="#pymalloc-a-specialized-object-allocator">Pymalloc: A Specialized Object Allocator</a></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="#other-changes-and-fixes">Other Changes and Fixes</a></li>
<li><a class="reference internal" href="#porting-to-python-2-3">Porting to Python 2.3</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.4.html"
title="previous chapter">What’s New in Python 2.4</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="2.2.html"
title="next chapter">What’s New in Python 2.2</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.3.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" />
<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.2.html" title="What’s New in Python 2.2"
>next</a> |</li>
<li class="right" >
<a href="2.4.html" title="What’s New in Python 2.4"
>previous</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="http://www.python.org/">Python</a> »</li>
<li>
<a href="../index.html">Python 2.7.5 documentation</a> »
</li>
<li><a href="index.html" >What’s New in Python</a> »</li>
</ul>
</div>
<div class="footer">
© <a href="../copyright.html">Copyright</a> 1990-2020, 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 Oct 13, 2020.
<a href="../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.3.
</div>
</body>
</html>
SEA-GHOST - SHELL CODING BY SEA-GHOST