Linux server.nvwebsoft.co.in 3.10.0-1160.114.2.el7.x86_64 #1 SMP Wed Mar 20 15:54:52 UTC 2024 x86_64
Apache
: 162.240.12.249 | : 52.14.66.242
202 Domain
8.1.31
nbspublicschool
www.github.com/MadExploits
Terminal
AUTO ROOT
Adminer
Backdoor Destroyer
Linux Exploit
Lock Shell
Lock File
Create User
CREATE RDP
PHP Mailer
BACKCONNECT
UNLOCK SHELL
HASH IDENTIFIER
CPANEL RESET
CREATE WP USER
README
+ Create Folder
+ Create File
/
usr /
share /
doc /
python-docs-2.7.5 /
html /
whatsnew /
[ HOME SHELL ]
Name
Size
Permission
Action
2.0.html
121.13
KB
-rw-r--r--
2.1.html
74.86
KB
-rw-r--r--
2.2.html
129.31
KB
-rw-r--r--
2.3.html
214.29
KB
-rw-r--r--
2.4.html
155.06
KB
-rw-r--r--
2.5.html
231.71
KB
-rw-r--r--
2.6.html
329.35
KB
-rw-r--r--
2.7.html
276.15
KB
-rw-r--r--
index.html
24.76
KB
-rw-r--r--
Delete
Unzip
Zip
${this.title}
Close
Code Editor : 2.4.html
<!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.4 — 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.3" href="2.3.html" /> <link rel="prev" title="What’s New in Python 2.5" href="2.5.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.3.html" title="What’s New in Python 2.3" accesskey="N">next</a> |</li> <li class="right" > <a href="2.5.html" title="What’s New in Python 2.5" 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-4"> <h1>What’s New in Python 2.4<a class="headerlink" href="#what-s-new-in-python-2-4" 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.4.1, released on March 30, 2005.</p> <p>Python 2.4 is a medium-sized release. It doesn’t introduce as many changes as the radical Python 2.2, but introduces more features than the conservative 2.3 release. The most significant new language features are function decorators and generator expressions; most other changes are to the standard library.</p> <p>According to the CVS change logs, there were 481 patches applied and 502 bugs fixed between Python 2.3 and 2.4. Both figures are likely to be underestimates.</p> <p>This article doesn’t attempt to provide a complete specification of every single new feature, but instead provides a brief introduction to each feature. For full details, you should refer to the documentation for Python 2.4, such as the Python Library Reference and the Python Reference Manual. Often you will be referred to the PEP for a particular new feature for explanations of the implementation and design rationale.</p> <div class="section" id="pep-218-built-in-set-objects"> <h2>PEP 218: Built-In Set Objects<a class="headerlink" href="#pep-218-built-in-set-objects" title="Permalink to this headline">¶</a></h2> <p>Python 2.3 introduced the <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. C implementations of set data types have now been added to the Python core as two new built-in types, <tt class="xref py py-func docutils literal"><span class="pre">set(iterable)()</span></tt> and <tt class="xref py py-func docutils literal"><span class="pre">frozenset(iterable)()</span></tt>. They provide high speed operations for membership testing, for eliminating duplicates from sequences, and for mathematical operations like unions, intersections, differences, and symmetric differences.</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">set</span><span class="p">(</span><span class="s">'abracadabra'</span><span class="p">)</span> <span class="c"># form a set from a string</span> <span class="gp">>>> </span><span class="s">'z'</span> <span class="ow">in</span> <span class="n">a</span> <span class="c"># fast membership testing</span> <span class="go">False</span> <span class="gp">>>> </span><span class="n">a</span> <span class="c"># unique letters in a</span> <span class="go">set(['a', 'r', 'b', 'c', 'd'])</span> <span class="gp">>>> </span><span class="s">''</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">a</span><span class="p">)</span> <span class="c"># convert back into a string</span> <span class="go">'arbcd'</span> <span class="gp">>>> </span><span class="n">b</span> <span class="o">=</span> <span class="nb">set</span><span class="p">(</span><span class="s">'alacazam'</span><span class="p">)</span> <span class="c"># form a second set</span> <span class="gp">>>> </span><span class="n">a</span> <span class="o">-</span> <span class="n">b</span> <span class="c"># letters in a but not in b</span> <span class="go">set(['r', 'd', 'b'])</span> <span class="gp">>>> </span><span class="n">a</span> <span class="o">|</span> <span class="n">b</span> <span class="c"># letters in either a or b</span> <span class="go">set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])</span> <span class="gp">>>> </span><span class="n">a</span> <span class="o">&</span> <span class="n">b</span> <span class="c"># letters in both a and b</span> <span class="go">set(['a', 'c'])</span> <span class="gp">>>> </span><span class="n">a</span> <span class="o">^</span> <span class="n">b</span> <span class="c"># letters in a or b but not both</span> <span class="go">set(['r', 'd', 'b', 'm', 'z', 'l'])</span> <span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="s">'z'</span><span class="p">)</span> <span class="c"># add a new element</span> <span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="s">'wxy'</span><span class="p">)</span> <span class="c"># add multiple new elements</span> <span class="gp">>>> </span><span class="n">a</span> <span class="go">set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'x', 'z'])</span> <span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="s">'x'</span><span class="p">)</span> <span class="c"># take one element out</span> <span class="gp">>>> </span><span class="n">a</span> <span class="go">set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'z'])</span> </pre></div> </div> <p>The <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><tt class="xref py py-func docutils literal"><span class="pre">frozenset()</span></tt></a> type is an immutable version of <a class="reference internal" href="../library/stdtypes.html#set" title="set"><tt class="xref py py-func docutils literal"><span class="pre">set()</span></tt></a>. Since it is immutable and hashable, it may be used as a dictionary key or as a member of another set.</p> <p>The <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 remains in the standard library, and may be useful if you wish to subclass the <tt class="xref py py-class docutils literal"><span class="pre">Set</span></tt> or <tt class="xref py py-class docutils literal"><span class="pre">ImmutableSet</span></tt> classes. There are currently no plans to deprecate the module.</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-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>Originally proposed by Greg Wilson and ultimately implemented by Raymond Hettinger.</dd> </dl> </div> </div> <div class="section" id="pep-237-unifying-long-integers-and-integers"> <h2>PEP 237: Unifying Long Integers and Integers<a class="headerlink" href="#pep-237-unifying-long-integers-and-integers" title="Permalink to this headline">¶</a></h2> <p>The lengthy transition process for this PEP, begun in Python 2.2, takes another step forward in Python 2.4. In 2.3, certain integer operations that would behave differently after int/long unification triggered <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> warnings and returned values limited to 32 or 64 bits (depending on your platform). In 2.4, these expressions no longer produce a warning and instead produce a different result that’s usually a long integer.</p> <p>The problematic expressions are primarily left shifts and lengthy hexadecimal and octal constants. For example, <tt class="docutils literal"><span class="pre">2</span> <span class="pre"><<</span> <span class="pre">32</span></tt> results in a warning in 2.3, evaluating to 0 on 32-bit platforms. In Python 2.4, this expression now returns the correct answer, 8589934592.</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-1"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0237"><strong>PEP 237</strong></a> - Unifying Long Integers and Integers</dt> <dd>Original PEP written by Moshe Zadka and GvR. The changes for 2.4 were implemented by Kalle Svensson.</dd> </dl> </div> </div> <div class="section" id="pep-289-generator-expressions"> <h2>PEP 289: Generator Expressions<a class="headerlink" href="#pep-289-generator-expressions" title="Permalink to this headline">¶</a></h2> <p>The iterator feature introduced in Python 2.2 and 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> module make it easier to write programs that loop through large data sets without having the entire data set in memory at one time. List comprehensions don’t fit into this picture very well because they produce a Python list object containing all of the items. This unavoidably pulls all of the objects into memory, which can be a problem if your data set is very large. When trying to write a functionally-styled program, it would be natural to write something like:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">links</span> <span class="o">=</span> <span class="p">[</span><span class="n">link</span> <span class="k">for</span> <span class="n">link</span> <span class="ow">in</span> <span class="n">get_all_links</span><span class="p">()</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">link</span><span class="o">.</span><span class="n">followed</span><span class="p">]</span> <span class="k">for</span> <span class="n">link</span> <span class="ow">in</span> <span class="n">links</span><span class="p">:</span> <span class="o">...</span> </pre></div> </div> <p>instead of</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">for</span> <span class="n">link</span> <span class="ow">in</span> <span class="n">get_all_links</span><span class="p">():</span> <span class="k">if</span> <span class="n">link</span><span class="o">.</span><span class="n">followed</span><span class="p">:</span> <span class="k">continue</span> <span class="o">...</span> </pre></div> </div> <p>The first form is more concise and perhaps more readable, but if you’re dealing with a large number of link objects you’d have to write the second form to avoid having all link objects in memory at the same time.</p> <p>Generator expressions work similarly to list comprehensions but don’t materialize the entire list; instead they create a generator that will return elements one by one. The above example could be written as:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">links</span> <span class="o">=</span> <span class="p">(</span><span class="n">link</span> <span class="k">for</span> <span class="n">link</span> <span class="ow">in</span> <span class="n">get_all_links</span><span class="p">()</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">link</span><span class="o">.</span><span class="n">followed</span><span class="p">)</span> <span class="k">for</span> <span class="n">link</span> <span class="ow">in</span> <span class="n">links</span><span class="p">:</span> <span class="o">...</span> </pre></div> </div> <p>Generator expressions always have to be written inside parentheses, as in the above example. The parentheses signalling a function call also count, so if you want to create an iterator that will be immediately passed to a function you could write:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">print</span> <span class="nb">sum</span><span class="p">(</span><span class="n">obj</span><span class="o">.</span><span class="n">count</span> <span class="k">for</span> <span class="n">obj</span> <span class="ow">in</span> <span class="n">list_all_objects</span><span class="p">())</span> </pre></div> </div> <p>Generator expressions differ from list comprehensions in various small ways. Most notably, the loop variable (<em>obj</em> in the above example) is not accessible outside of the generator expression. List comprehensions leave the variable assigned to its last value; future versions of Python will change this, making list comprehensions match generator expressions in this respect.</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-0289"><strong>PEP 289</strong></a> - Generator Expressions</dt> <dd>Proposed by Raymond Hettinger and implemented by Jiwon Seo with early efforts steered by Hye-Shik Chang.</dd> </dl> </div> </div> <div class="section" id="pep-292-simpler-string-substitutions"> <h2>PEP 292: Simpler String Substitutions<a class="headerlink" href="#pep-292-simpler-string-substitutions" title="Permalink to this headline">¶</a></h2> <p>Some new classes in the standard library provide an alternative mechanism for substituting variables into strings; this style of substitution may be better for applications where untrained users need to edit templates.</p> <p>The usual way of substituting variables by name is the <tt class="docutils literal"><span class="pre">%</span></tt> operator:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="s">'</span><span class="si">%(page)i</span><span class="s">: </span><span class="si">%(title)s</span><span class="s">'</span> <span class="o">%</span> <span class="p">{</span><span class="s">'page'</span><span class="p">:</span><span class="mi">2</span><span class="p">,</span> <span class="s">'title'</span><span class="p">:</span> <span class="s">'The Best of Times'</span><span class="p">}</span> <span class="go">'2: The Best of Times'</span> </pre></div> </div> <p>When writing the template string, it can be easy to forget the <tt class="docutils literal"><span class="pre">i</span></tt> or <tt class="docutils literal"><span class="pre">s</span></tt> after the closing parenthesis. This isn’t a big problem if the template is in a Python module, because you run the code, get an “Unsupported format character” <a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a>, and fix the problem. However, consider an application such as Mailman where template strings or translations are being edited by users who aren’t aware of the Python language. The format string’s syntax is complicated to explain to such users, and if they make a mistake, it’s difficult to provide helpful feedback to them.</p> <p>PEP 292 adds a <tt class="xref py py-class docutils literal"><span class="pre">Template</span></tt> class to 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 that uses <tt class="docutils literal"><span class="pre">$</span></tt> to indicate a substitution:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">string</span> <span class="gp">>>> </span><span class="n">t</span> <span class="o">=</span> <span class="n">string</span><span class="o">.</span><span class="n">Template</span><span class="p">(</span><span class="s">'$page: $title'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">t</span><span class="o">.</span><span class="n">substitute</span><span class="p">({</span><span class="s">'page'</span><span class="p">:</span><span class="mi">2</span><span class="p">,</span> <span class="s">'title'</span><span class="p">:</span> <span class="s">'The Best of Times'</span><span class="p">})</span> <span class="go">'2: The Best of Times'</span> </pre></div> </div> <p>If a key is missing from the dictionary, the <tt class="xref py py-meth docutils literal"><span class="pre">substitute()</span></tt> method will raise a <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>. There’s also a <tt class="xref py py-meth docutils literal"><span class="pre">safe_substitute()</span></tt> method that ignores missing keys:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">t</span> <span class="o">=</span> <span class="n">string</span><span class="o">.</span><span class="n">Template</span><span class="p">(</span><span class="s">'$page: $title'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">t</span><span class="o">.</span><span class="n">safe_substitute</span><span class="p">({</span><span class="s">'page'</span><span class="p">:</span><span class="mi">3</span><span class="p">})</span> <span class="go">'3: $title'</span> </pre></div> </div> <div class="admonition-see-also admonition seealso"> <p class="first admonition-title">See also</p> <dl class="last docutils"> <dt><span class="target" id="index-3"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0292"><strong>PEP 292</strong></a> - Simpler String Substitutions</dt> <dd>Written and implemented by Barry Warsaw.</dd> </dl> </div> </div> <div class="section" id="pep-318-decorators-for-functions-and-methods"> <h2>PEP 318: Decorators for Functions and Methods<a class="headerlink" href="#pep-318-decorators-for-functions-and-methods" title="Permalink to this headline">¶</a></h2> <p>Python 2.2 extended Python’s object model by adding static methods and class methods, but it didn’t extend Python’s syntax to provide any new way of defining static or class methods. Instead, you had to write a <a class="reference internal" href="../reference/compound_stmts.html#def"><tt class="xref std std-keyword docutils literal"><span class="pre">def</span></tt></a> statement in the usual way, and pass the resulting method to a <a class="reference internal" href="../library/functions.html#staticmethod" title="staticmethod"><tt class="xref py py-func docutils literal"><span class="pre">staticmethod()</span></tt></a> or <a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><tt class="xref py py-func docutils literal"><span class="pre">classmethod()</span></tt></a> function that would wrap up the function as a method of the new type. Your code would look like this:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">C</span><span class="p">:</span> <span class="k">def</span> <span class="nf">meth</span> <span class="p">(</span><span class="n">cls</span><span class="p">):</span> <span class="o">...</span> <span class="n">meth</span> <span class="o">=</span> <span class="nb">classmethod</span><span class="p">(</span><span class="n">meth</span><span class="p">)</span> <span class="c"># Rebind name to wrapped-up class method</span> </pre></div> </div> <p>If the method was very long, it would be easy to miss or forget the <a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><tt class="xref py py-func docutils literal"><span class="pre">classmethod()</span></tt></a> invocation after the function body.</p> <p>The intention was always to add some syntax to make such definitions more readable, but at the time of 2.2’s release a good syntax was not obvious. Today a good syntax <em>still</em> isn’t obvious but users are asking for easier access to the feature; a new syntactic feature has been added to meet this need.</p> <p>The new feature is called “function decorators”. The name comes from the idea that <a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><tt class="xref py py-func docutils literal"><span class="pre">classmethod()</span></tt></a>, <a class="reference internal" href="../library/functions.html#staticmethod" title="staticmethod"><tt class="xref py py-func docutils literal"><span class="pre">staticmethod()</span></tt></a>, and friends are storing additional information on a function object; they’re <em>decorating</em> functions with more details.</p> <p>The notation borrows from Java and uses the <tt class="docutils literal"><span class="pre">'@'</span></tt> character as an indicator. Using the new syntax, the example above would be written:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">C</span><span class="p">:</span> <span class="nd">@classmethod</span> <span class="k">def</span> <span class="nf">meth</span> <span class="p">(</span><span class="n">cls</span><span class="p">):</span> <span class="o">...</span> </pre></div> </div> <p>The <tt class="docutils literal"><span class="pre">@classmethod</span></tt> is shorthand for the <tt class="docutils literal"><span class="pre">meth=classmethod(meth)</span></tt> assignment. More generally, if you have the following:</p> <div class="highlight-python"><div class="highlight"><pre><span class="nd">@A</span> <span class="nd">@B</span> <span class="nd">@C</span> <span class="k">def</span> <span class="nf">f</span> <span class="p">():</span> <span class="o">...</span> </pre></div> </div> <p>It’s equivalent to the following pre-decorator code:</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="o">...</span> <span class="n">f</span> <span class="o">=</span> <span class="n">A</span><span class="p">(</span><span class="n">B</span><span class="p">(</span><span class="n">C</span><span class="p">(</span><span class="n">f</span><span class="p">)))</span> </pre></div> </div> <p>Decorators must come on the line before a function definition, one decorator per line, and can’t be on the same line as the def statement, meaning that <tt class="docutils literal"><span class="pre">@A</span> <span class="pre">def</span> <span class="pre">f():</span> <span class="pre">...</span></tt> is illegal. You can only decorate function definitions, either at the module level or inside a class; you can’t decorate class definitions.</p> <p>A decorator is just a function that takes the function to be decorated as an argument and returns either the same function or some new object. The return value of the decorator need not be callable (though it typically is), unless further decorators will be applied to the result. It’s easy to write your own decorators. The following simple example just sets an attribute on the function object:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="k">def</span> <span class="nf">deco</span><span class="p">(</span><span class="n">func</span><span class="p">):</span> <span class="gp">... </span> <span class="n">func</span><span class="o">.</span><span class="n">attr</span> <span class="o">=</span> <span class="s">'decorated'</span> <span class="gp">... </span> <span class="k">return</span> <span class="n">func</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="nd">@deco</span> <span class="gp">... </span><span class="k">def</span> <span class="nf">f</span><span class="p">():</span> <span class="k">pass</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">f</span> <span class="go"><function f at 0x402ef0d4></span> <span class="gp">>>> </span><span class="n">f</span><span class="o">.</span><span class="n">attr</span> <span class="go">'decorated'</span> <span class="go">>>></span> </pre></div> </div> <p>As a slightly more realistic example, the following decorator checks that the supplied argument is an integer:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">require_int</span> <span class="p">(</span><span class="n">func</span><span class="p">):</span> <span class="k">def</span> <span class="nf">wrapper</span> <span class="p">(</span><span class="n">arg</span><span class="p">):</span> <span class="k">assert</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">arg</span><span class="p">,</span> <span class="nb">int</span><span class="p">)</span> <span class="k">return</span> <span class="n">func</span><span class="p">(</span><span class="n">arg</span><span class="p">)</span> <span class="k">return</span> <span class="n">wrapper</span> <span class="nd">@require_int</span> <span class="k">def</span> <span class="nf">p1</span> <span class="p">(</span><span class="n">arg</span><span class="p">):</span> <span class="k">print</span> <span class="n">arg</span> <span class="nd">@require_int</span> <span class="k">def</span> <span class="nf">p2</span><span class="p">(</span><span class="n">arg</span><span class="p">):</span> <span class="k">print</span> <span class="n">arg</span><span class="o">*</span><span class="mi">2</span> </pre></div> </div> <p>An example in <span class="target" id="index-4"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0318"><strong>PEP 318</strong></a> contains a fancier version of this idea that lets you both specify the required type and check the returned type.</p> <p>Decorator functions can take arguments. If arguments are supplied, your decorator function is called with only those arguments and must return a new decorator function; this function must take a single function and return a function, as previously described. In other words, <tt class="docutils literal"><span class="pre">@A</span> <span class="pre">@B</span> <span class="pre">@C(args)</span></tt> becomes:</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="o">...</span> <span class="n">_deco</span> <span class="o">=</span> <span class="n">C</span><span class="p">(</span><span class="n">args</span><span class="p">)</span> <span class="n">f</span> <span class="o">=</span> <span class="n">A</span><span class="p">(</span><span class="n">B</span><span class="p">(</span><span class="n">_deco</span><span class="p">(</span><span class="n">f</span><span class="p">)))</span> </pre></div> </div> <p>Getting this right can be slightly brain-bending, but it’s not too difficult.</p> <p>A small related change makes the <tt class="xref py py-attr docutils literal"><span class="pre">func_name</span></tt> attribute of functions writable. This attribute is used to display function names in tracebacks, so decorators should change the name of any new function that’s constructed and returned.</p> <div class="admonition-see-also admonition seealso"> <p class="first admonition-title">See also</p> <dl class="last docutils"> <dt><span class="target" id="index-5"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0318"><strong>PEP 318</strong></a> - Decorators for Functions, Methods and Classes</dt> <dd>Written by Kevin D. Smith, Jim Jewett, and Skip Montanaro. Several people wrote patches implementing function decorators, but the one that was actually checked in was patch #979728, written by Mark Russell.</dd> <dt><a class="reference external" href="http://www.python.org/moin/PythonDecoratorLibrary">http://www.python.org/moin/PythonDecoratorLibrary</a></dt> <dd>This Wiki page contains several examples of decorators.</dd> </dl> </div> </div> <div class="section" id="pep-322-reverse-iteration"> <h2>PEP 322: Reverse Iteration<a class="headerlink" href="#pep-322-reverse-iteration" title="Permalink to this headline">¶</a></h2> <p>A new built-in function, <tt class="xref py py-func docutils literal"><span class="pre">reversed(seq)()</span></tt>, takes a sequence and returns an iterator that loops over the elements of the sequence in reverse order.</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">reversed</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">4</span><span class="p">)):</span> <span class="gp">... </span> <span class="k">print</span> <span class="n">i</span> <span class="gp">...</span> <span class="go">3</span> <span class="go">2</span> <span class="go">1</span> </pre></div> </div> <p>Compared to extended slicing, such as <tt class="docutils literal"><span class="pre">range(1,4)[::-1]</span></tt>, <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><tt class="xref py py-func docutils literal"><span class="pre">reversed()</span></tt></a> is easier to read, runs faster, and uses substantially less memory.</p> <p>Note that <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><tt class="xref py py-func docutils literal"><span class="pre">reversed()</span></tt></a> only accepts sequences, not arbitrary iterators. If you want to reverse an iterator, first convert it to a list with <a class="reference internal" href="../library/functions.html#list" title="list"><tt class="xref py py-func docutils literal"><span class="pre">list()</span></tt></a>.</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="nb">input</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s">'/etc/passwd'</span><span class="p">,</span> <span class="s">'r'</span><span class="p">)</span> <span class="gp">>>> </span><span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="nb">reversed</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="nb">input</span><span class="p">)):</span> <span class="gp">... </span> <span class="k">print</span> <span class="n">line</span> <span class="gp">...</span> <span class="go">root:*:0:0:System Administrator:/var/root:/bin/tcsh</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-6"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0322"><strong>PEP 322</strong></a> - Reverse Iteration</dt> <dd>Written and implemented by Raymond Hettinger.</dd> </dl> </div> </div> <div class="section" id="pep-324-new-subprocess-module"> <h2>PEP 324: New subprocess Module<a class="headerlink" href="#pep-324-new-subprocess-module" title="Permalink to this headline">¶</a></h2> <p>The standard library provides a number of ways to execute a subprocess, offering different features and different levels of complexity. <tt class="xref py py-func docutils literal"><span class="pre">os.system(command)()</span></tt> is easy to use, but slow (it runs a shell process which executes the command) and dangerous (you have to be careful about escaping the shell’s metacharacters). The <a class="reference internal" href="../library/popen2.html#module-popen2" title="popen2: Subprocesses with accessible standard I/O streams. (deprecated)"><tt class="xref py py-mod docutils literal"><span class="pre">popen2</span></tt></a> module offers classes that can capture standard output and standard error from the subprocess, but the naming is confusing. The <a class="reference internal" href="../library/subprocess.html#module-subprocess" title="subprocess: Subprocess management."><tt class="xref py py-mod docutils literal"><span class="pre">subprocess</span></tt></a> module cleans this up, providing a unified interface that offers all the features you might need.</p> <p>Instead of <a class="reference internal" href="../library/popen2.html#module-popen2" title="popen2: Subprocesses with accessible standard I/O streams. (deprecated)"><tt class="xref py py-mod docutils literal"><span class="pre">popen2</span></tt></a>‘s collection of classes, <a class="reference internal" href="../library/subprocess.html#module-subprocess" title="subprocess: Subprocess management."><tt class="xref py py-mod docutils literal"><span class="pre">subprocess</span></tt></a> contains a single class called <tt class="xref py py-class docutils literal"><span class="pre">Popen</span></tt> whose constructor supports a number of different keyword arguments.</p> <div class="highlight-python"><pre>class Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0):</pre> </div> <p><em>args</em> is commonly a sequence of strings that will be the arguments to the program executed as the subprocess. (If the <em>shell</em> argument is true, <em>args</em> can be a string which will then be passed on to the shell for interpretation, just as <a class="reference internal" href="../library/os.html#os.system" title="os.system"><tt class="xref py py-func docutils literal"><span class="pre">os.system()</span></tt></a> does.)</p> <p><em>stdin</em>, <em>stdout</em>, and <em>stderr</em> specify what the subprocess’s input, output, and error streams will be. You can provide a file object or a file descriptor, or you can use the constant <tt class="docutils literal"><span class="pre">subprocess.PIPE</span></tt> to create a pipe between the subprocess and the parent.</p> <p id="index-7">The constructor has a number of handy options:</p> <ul class="simple"> <li><em>close_fds</em> requests that all file descriptors be closed before running the subprocess.</li> <li><em>cwd</em> specifies the working directory in which the subprocess will be executed (defaulting to whatever the parent’s working directory is).</li> <li><em>env</em> is a dictionary specifying environment variables.</li> <li><em>preexec_fn</em> is a function that gets called before the child is started.</li> <li><em>universal_newlines</em> opens the child’s input and output using Python’s <a class="reference internal" href="../glossary.html#term-universal-newlines"><em class="xref std std-term">universal newlines</em></a> feature.</li> </ul> <p>Once you’ve created the <tt class="xref py py-class docutils literal"><span class="pre">Popen</span></tt> instance, you can call its <tt class="xref py py-meth docutils literal"><span class="pre">wait()</span></tt> method to pause until the subprocess has exited, <tt class="xref py py-meth docutils literal"><span class="pre">poll()</span></tt> to check if it’s exited without pausing, or <tt class="xref py py-meth docutils literal"><span class="pre">communicate(data)()</span></tt> to send the string <em>data</em> to the subprocess’s standard input. <tt class="xref py py-meth docutils literal"><span class="pre">communicate(data)()</span></tt> then reads any data that the subprocess has sent to its standard output or standard error, returning a tuple <tt class="docutils literal"><span class="pre">(stdout_data,</span> <span class="pre">stderr_data)</span></tt>.</p> <p><tt class="xref py py-func docutils literal"><span class="pre">call()</span></tt> is a shortcut that passes its arguments along to the <tt class="xref py py-class docutils literal"><span class="pre">Popen</span></tt> constructor, waits for the command to complete, and returns the status code of the subprocess. It can serve as a safer analog to <a class="reference internal" href="../library/os.html#os.system" title="os.system"><tt class="xref py py-func docutils literal"><span class="pre">os.system()</span></tt></a>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">sts</span> <span class="o">=</span> <span class="n">subprocess</span><span class="o">.</span><span class="n">call</span><span class="p">([</span><span class="s">'dpkg'</span><span class="p">,</span> <span class="s">'-i'</span><span class="p">,</span> <span class="s">'/tmp/new-package.deb'</span><span class="p">])</span> <span class="k">if</span> <span class="n">sts</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span> <span class="c"># Success</span> <span class="o">...</span> <span class="k">else</span><span class="p">:</span> <span class="c"># dpkg returned an error</span> <span class="o">...</span> </pre></div> </div> <p>The command is invoked without use of the shell. If you really do want to use the shell, you can add <tt class="docutils literal"><span class="pre">shell=True</span></tt> as a keyword argument and provide a string instead of a sequence:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">sts</span> <span class="o">=</span> <span class="n">subprocess</span><span class="o">.</span><span class="n">call</span><span class="p">(</span><span class="s">'dpkg -i /tmp/new-package.deb'</span><span class="p">,</span> <span class="n">shell</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> </pre></div> </div> <p>The PEP takes various examples of shell and Python code and shows how they’d be translated into Python code that uses <a class="reference internal" href="../library/subprocess.html#module-subprocess" title="subprocess: Subprocess management."><tt class="xref py py-mod docutils literal"><span class="pre">subprocess</span></tt></a>. Reading this section of the PEP is highly recommended.</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-8"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0324"><strong>PEP 324</strong></a> - subprocess - New process module</dt> <dd>Written and implemented by Peter Åstrand, with assistance from Fredrik Lundh and others.</dd> </dl> </div> </div> <div class="section" id="pep-327-decimal-data-type"> <h2>PEP 327: Decimal Data Type<a class="headerlink" href="#pep-327-decimal-data-type" title="Permalink to this headline">¶</a></h2> <p>Python has always supported floating-point (FP) numbers, based on the underlying C <tt class="xref c c-type docutils literal"><span class="pre">double</span></tt> type, as a data type. However, while most programming languages provide a floating-point type, many people (even programmers) are unaware that floating-point numbers don’t represent certain decimal fractions accurately. The new <tt class="xref py py-class docutils literal"><span class="pre">Decimal</span></tt> type can represent these fractions accurately, up to a user-specified precision limit.</p> <div class="section" id="why-is-decimal-needed"> <h3>Why is Decimal needed?<a class="headerlink" href="#why-is-decimal-needed" title="Permalink to this headline">¶</a></h3> <p>The limitations arise from the representation used for floating-point numbers. FP numbers are made up of three components:</p> <ul class="simple"> <li>The sign, which is positive or negative.</li> <li>The mantissa, which is a single-digit binary number followed by a fractional part. For example, <tt class="docutils literal"><span class="pre">1.01</span></tt> in base-2 notation is <tt class="docutils literal"><span class="pre">1</span> <span class="pre">+</span> <span class="pre">0/2</span> <span class="pre">+</span> <span class="pre">1/4</span></tt>, or 1.25 in decimal notation.</li> <li>The exponent, which tells where the decimal point is located in the number represented.</li> </ul> <p>For example, the number 1.25 has positive sign, a mantissa value of 1.01 (in binary), and an exponent of 0 (the decimal point doesn’t need to be shifted). The number 5 has the same sign and mantissa, but the exponent is 2 because the mantissa is multiplied by 4 (2 to the power of the exponent 2); 1.25 * 4 equals 5.</p> <p>Modern systems usually provide floating-point support that conforms to a standard called IEEE 754. C’s <tt class="xref c c-type docutils literal"><span class="pre">double</span></tt> type is usually implemented as a 64-bit IEEE 754 number, which uses 52 bits of space for the mantissa. This means that numbers can only be specified to 52 bits of precision. If you’re trying to represent numbers whose expansion repeats endlessly, the expansion is cut off after 52 bits. Unfortunately, most software needs to produce output in base 10, and common fractions in base 10 are often repeating decimals in binary. For example, 1.1 decimal is binary <tt class="docutils literal"><span class="pre">1.0001100110011</span> <span class="pre">...</span></tt>; .1 = 1/16 + 1/32 + 1/256 plus an infinite number of additional terms. IEEE 754 has to chop off that infinitely repeated decimal after 52 digits, so the representation is slightly inaccurate.</p> <p>Sometimes you can see this inaccuracy when the number is printed:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="mf">1.1</span> <span class="go">1.1000000000000001</span> </pre></div> </div> <p>The inaccuracy isn’t always visible when you print the number because the FP-to- decimal-string conversion is provided by the C library, and most C libraries try to produce sensible output. Even if it’s not displayed, however, the inaccuracy is still there and subsequent operations can magnify the error.</p> <p>For many applications this doesn’t matter. If I’m plotting points and displaying them on my monitor, the difference between 1.1 and 1.1000000000000001 is too small to be visible. Reports often limit output to a certain number of decimal places, and if you round the number to two or three or even eight decimal places, the error is never apparent. However, for applications where it does matter, it’s a lot of work to implement your own custom arithmetic routines.</p> <p>Hence, the <tt class="xref py py-class docutils literal"><span class="pre">Decimal</span></tt> type was created.</p> </div> <div class="section" id="the-decimal-type"> <h3>The <tt class="xref py py-class docutils literal"><span class="pre">Decimal</span></tt> type<a class="headerlink" href="#the-decimal-type" title="Permalink to this headline">¶</a></h3> <p>A new module, <a class="reference internal" href="../library/decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic Specification."><tt class="xref py py-mod docutils literal"><span class="pre">decimal</span></tt></a>, was added to Python’s standard library. It contains two classes, <tt class="xref py py-class docutils literal"><span class="pre">Decimal</span></tt> and <tt class="xref py py-class docutils literal"><span class="pre">Context</span></tt>. <tt class="xref py py-class docutils literal"><span class="pre">Decimal</span></tt> instances represent numbers, and <tt class="xref py py-class docutils literal"><span class="pre">Context</span></tt> instances are used to wrap up various settings such as the precision and default rounding mode.</p> <p><tt class="xref py py-class docutils literal"><span class="pre">Decimal</span></tt> instances are immutable, like regular Python integers and FP numbers; once it’s been created, you can’t change the value an instance represents. <tt class="xref py py-class docutils literal"><span class="pre">Decimal</span></tt> instances can be created from integers or strings:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">decimal</span> <span class="gp">>>> </span><span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1972</span><span class="p">)</span> <span class="go">Decimal("1972")</span> <span class="gp">>>> </span><span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="s">"1.1"</span><span class="p">)</span> <span class="go">Decimal("1.1")</span> </pre></div> </div> <p>You can also provide tuples containing the sign, the mantissa represented as a tuple of decimal digits, and the exponent:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">((</span><span class="mi">1</span><span class="p">,</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">4</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="o">-</span><span class="mi">2</span><span class="p">))</span> <span class="go">Decimal("-14.75")</span> </pre></div> </div> <p>Cautionary note: the sign bit is a Boolean value, so 0 is positive and 1 is negative.</p> <p>Converting from floating-point numbers poses a bit of a problem: should the FP number representing 1.1 turn into the decimal number for exactly 1.1, or for 1.1 plus whatever inaccuracies are introduced? The decision was to dodge the issue and leave such a conversion out of the API. Instead, you should convert the floating-point number into a string using the desired precision and pass the string to the <tt class="xref py py-class docutils literal"><span class="pre">Decimal</span></tt> constructor:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">f</span> <span class="o">=</span> <span class="mf">1.1</span> <span class="gp">>>> </span><span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">f</span><span class="p">))</span> <span class="go">Decimal("1.1")</span> <span class="gp">>>> </span><span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="s">'</span><span class="si">%.12f</span><span class="s">'</span> <span class="o">%</span> <span class="n">f</span><span class="p">)</span> <span class="go">Decimal("1.100000000000")</span> </pre></div> </div> <p>Once you have <tt class="xref py py-class docutils literal"><span class="pre">Decimal</span></tt> instances, you can perform the usual mathematical operations on them. One limitation: exponentiation requires an integer exponent:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="s">'35.72'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">b</span> <span class="o">=</span> <span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="s">'1.73'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">a</span><span class="o">+</span><span class="n">b</span> <span class="go">Decimal("37.45")</span> <span class="gp">>>> </span><span class="n">a</span><span class="o">-</span><span class="n">b</span> <span class="go">Decimal("33.99")</span> <span class="gp">>>> </span><span class="n">a</span><span class="o">*</span><span class="n">b</span> <span class="go">Decimal("61.7956")</span> <span class="gp">>>> </span><span class="n">a</span><span class="o">/</span><span class="n">b</span> <span class="go">Decimal("20.64739884393063583815028902")</span> <span class="gp">>>> </span><span class="n">a</span> <span class="o">**</span> <span class="mi">2</span> <span class="go">Decimal("1275.9184")</span> <span class="gp">>>> </span><span class="n">a</span><span class="o">**</span><span class="n">b</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">decimal.InvalidOperation</span>: <span class="n">x ** (non-integer)</span> </pre></div> </div> <p>You can combine <tt class="xref py py-class docutils literal"><span class="pre">Decimal</span></tt> instances with integers, but not with floating- point numbers:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">a</span> <span class="o">+</span> <span class="mi">4</span> <span class="go">Decimal("39.72")</span> <span class="gp">>>> </span><span class="n">a</span> <span class="o">+</span> <span class="mf">4.5</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">TypeError</span>: <span class="n">You can interact Decimal only with int, long or Decimal data types.</span> <span class="go">>>></span> </pre></div> </div> <p><tt class="xref py py-class docutils literal"><span class="pre">Decimal</span></tt> numbers can be used with 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> and <a class="reference internal" href="../library/cmath.html#module-cmath" title="cmath: Mathematical functions for complex numbers."><tt class="xref py py-mod docutils literal"><span class="pre">cmath</span></tt></a> modules, but note that they’ll be immediately converted to floating-point numbers before the operation is performed, resulting in a possible loss of precision and accuracy. You’ll also get back a regular floating-point number and not a <tt class="xref py py-class docutils literal"><span class="pre">Decimal</span></tt>.</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">math</span><span class="o">,</span> <span class="nn">cmath</span> <span class="gp">>>> </span><span class="n">d</span> <span class="o">=</span> <span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="s">'123456789012.345'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">math</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">d</span><span class="p">)</span> <span class="go">351364.18288201344</span> <span class="gp">>>> </span><span class="n">cmath</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="o">-</span><span class="n">d</span><span class="p">)</span> <span class="go">351364.18288201344j</span> </pre></div> </div> <p><tt class="xref py py-class docutils literal"><span class="pre">Decimal</span></tt> instances have a <tt class="xref py py-meth docutils literal"><span class="pre">sqrt()</span></tt> method that returns a <tt class="xref py py-class docutils literal"><span class="pre">Decimal</span></tt>, but if you need other things such as trigonometric functions you’ll have to implement them.</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">sqrt</span><span class="p">()</span> <span class="go">Decimal("351364.1828820134592177245001")</span> </pre></div> </div> </div> <div class="section" id="the-context-type"> <h3>The <tt class="xref py py-class docutils literal"><span class="pre">Context</span></tt> type<a class="headerlink" href="#the-context-type" title="Permalink to this headline">¶</a></h3> <p>Instances of the <tt class="xref py py-class docutils literal"><span class="pre">Context</span></tt> class encapsulate several settings for decimal operations:</p> <ul class="simple"> <li><tt class="xref py py-attr docutils literal"><span class="pre">prec</span></tt> is the precision, the number of decimal places.</li> <li><tt class="xref py py-attr docutils literal"><span class="pre">rounding</span></tt> specifies the rounding mode. The <a class="reference internal" href="../library/decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic Specification."><tt class="xref py py-mod docutils literal"><span class="pre">decimal</span></tt></a> module has constants for the various possibilities: <tt class="xref py py-const docutils literal"><span class="pre">ROUND_DOWN</span></tt>, <tt class="xref py py-const docutils literal"><span class="pre">ROUND_CEILING</span></tt>, <tt class="xref py py-const docutils literal"><span class="pre">ROUND_HALF_EVEN</span></tt>, and various others.</li> <li><tt class="xref py py-attr docutils literal"><span class="pre">traps</span></tt> is a dictionary specifying what happens on encountering certain error conditions: either an exception is raised or a value is returned. Some examples of error conditions are division by zero, loss of precision, and overflow.</li> </ul> <p>There’s a thread-local default context available by calling <tt class="xref py py-func docutils literal"><span class="pre">getcontext()</span></tt>; you can change the properties of this context to alter the default precision, rounding, or trap handling. The following example shows the effect of changing the precision of the default context:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">decimal</span><span class="o">.</span><span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">prec</span> <span class="go">28</span> <span class="gp">>>> </span><span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">/</span> <span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span> <span class="go">Decimal("0.1428571428571428571428571429")</span> <span class="gp">>>> </span><span class="n">decimal</span><span class="o">.</span><span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">prec</span> <span class="o">=</span> <span class="mi">9</span> <span class="gp">>>> </span><span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">/</span> <span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span> <span class="go">Decimal("0.142857143")</span> </pre></div> </div> <p>The default action for error conditions is selectable; the module can either return a special value such as infinity or not-a-number, or exceptions can be raised:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">/</span> <span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="gt">Traceback (most recent call last):</span> <span class="c">...</span> <span class="gr">decimal.DivisionByZero</span>: <span class="n">x / 0</span> <span class="gp">>>> </span><span class="n">decimal</span><span class="o">.</span><span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">traps</span><span class="p">[</span><span class="n">decimal</span><span class="o">.</span><span class="n">DivisionByZero</span><span class="p">]</span> <span class="o">=</span> <span class="bp">False</span> <span class="gp">>>> </span><span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">/</span> <span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="go">Decimal("Infinity")</span> <span class="go">>>></span> </pre></div> </div> <p>The <tt class="xref py py-class docutils literal"><span class="pre">Context</span></tt> instance also has various methods for formatting numbers such as <tt class="xref py py-meth docutils literal"><span class="pre">to_eng_string()</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">to_sci_string()</span></tt>.</p> <p>For more information, see the documentation for the <a class="reference internal" href="../library/decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic Specification."><tt class="xref py py-mod docutils literal"><span class="pre">decimal</span></tt></a> module, which includes a quick-start tutorial and a reference.</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-0327"><strong>PEP 327</strong></a> - Decimal Data Type</dt> <dd>Written by Facundo Batista and implemented by Facundo Batista, Eric Price, Raymond Hettinger, Aahz, and Tim Peters.</dd> <dt><a class="reference external" href="http://www.lahey.com/float.htm">http://www.lahey.com/float.htm</a></dt> <dd>The article uses Fortran code to illustrate many of the problems that floating- point inaccuracy can cause.</dd> <dt><a class="reference external" href="http://www2.hursley.ibm.com/decimal/">http://www2.hursley.ibm.com/decimal/</a></dt> <dd>A description of a decimal-based representation. This representation is being proposed as a standard, and underlies the new Python decimal type. Much of this material was written by Mike Cowlishaw, designer of the Rexx language.</dd> </dl> </div> </div> </div> <div class="section" id="pep-328-multi-line-imports"> <h2>PEP 328: Multi-line Imports<a class="headerlink" href="#pep-328-multi-line-imports" title="Permalink to this headline">¶</a></h2> <p>One language change is a small syntactic tweak aimed at making it easier to import many names from a module. In a <tt class="docutils literal"><span class="pre">from</span> <span class="pre">module</span> <span class="pre">import</span> <span class="pre">names</span></tt> statement, <em>names</em> is a sequence of names separated by commas. If the sequence is very long, you can either write multiple imports from the same module, or you can use backslashes to escape the line endings like this:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">SimpleXMLRPCServer</span> <span class="kn">import</span> <span class="n">SimpleXMLRPCServer</span><span class="p">,</span>\ <span class="n">SimpleXMLRPCRequestHandler</span><span class="p">,</span>\ <span class="n">CGIXMLRPCRequestHandler</span><span class="p">,</span>\ <span class="n">resolve_dotted_attribute</span> </pre></div> </div> <p>The syntactic change in Python 2.4 simply allows putting the names within parentheses. Python ignores newlines within a parenthesized expression, so the backslashes are no longer needed:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">SimpleXMLRPCServer</span> <span class="kn">import</span> <span class="p">(</span><span class="n">SimpleXMLRPCServer</span><span class="p">,</span> <span class="n">SimpleXMLRPCRequestHandler</span><span class="p">,</span> <span class="n">CGIXMLRPCRequestHandler</span><span class="p">,</span> <span class="n">resolve_dotted_attribute</span><span class="p">)</span> </pre></div> </div> <p>The PEP also proposes that all <a class="reference internal" href="../reference/simple_stmts.html#import"><tt class="xref std std-keyword docutils literal"><span class="pre">import</span></tt></a> statements be absolute imports, with a leading <tt class="docutils literal"><span class="pre">.</span></tt> character to indicate a relative import. This part of the PEP was not implemented for Python 2.4, but was completed for Python 2.5.</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-10"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0328"><strong>PEP 328</strong></a> - Imports: Multi-Line and Absolute/Relative</dt> <dd>Written by Aahz. Multi-line imports were implemented by Dima Dorfman.</dd> </dl> </div> </div> <div class="section" id="pep-331-locale-independent-float-string-conversions"> <h2>PEP 331: Locale-Independent Float/String Conversions<a class="headerlink" href="#pep-331-locale-independent-float-string-conversions" title="Permalink to this headline">¶</a></h2> <p>The <a class="reference internal" href="../library/locale.html#module-locale" title="locale: Internationalization services."><tt class="xref py py-mod docutils literal"><span class="pre">locale</span></tt></a> modules lets Python software select various conversions and display conventions that are localized to a particular country or language. However, the module was careful to not change the numeric locale because various functions in Python’s implementation required that the numeric locale remain set to the <tt class="docutils literal"><span class="pre">'C'</span></tt> locale. Often this was because the code was using the C library’s <tt class="xref c c-func docutils literal"><span class="pre">atof()</span></tt> function.</p> <p>Not setting the numeric locale caused trouble for extensions that used third- party C libraries, however, because they wouldn’t have the correct locale set. The motivating example was GTK+, whose user interface widgets weren’t displaying numbers in the current locale.</p> <p>The solution described in the PEP is to add three new functions to the Python API that perform ASCII-only conversions, ignoring the locale setting:</p> <ul class="simple"> <li><tt class="xref c c-func docutils literal"><span class="pre">PyOS_ascii_strtod(str,</span> <span class="pre">ptr)()</span></tt> and <tt class="xref c c-func docutils literal"><span class="pre">PyOS_ascii_atof(str,</span> <span class="pre">ptr)()</span></tt> both convert a string to a C <tt class="xref c c-type docutils literal"><span class="pre">double</span></tt>.</li> <li><tt class="xref c c-func docutils literal"><span class="pre">PyOS_ascii_formatd(buffer,</span> <span class="pre">buf_len,</span> <span class="pre">format,</span> <span class="pre">d)()</span></tt> converts a <tt class="xref c c-type docutils literal"><span class="pre">double</span></tt> to an ASCII string.</li> </ul> <p>The code for these functions came from the GLib library (<a class="reference external" href="http://library.gnome.org/devel/glib/stable/">http://library.gnome.org/devel/glib/stable/</a>), whose developers kindly relicensed the relevant functions and donated them to the Python Software Foundation. The <a class="reference internal" href="../library/locale.html#module-locale" title="locale: Internationalization services."><tt class="xref py py-mod docutils literal"><span class="pre">locale</span></tt></a> module can now change the numeric locale, letting extensions such as GTK+ produce the correct results.</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-11"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0331"><strong>PEP 331</strong></a> - Locale-Independent Float/String Conversions</dt> <dd>Written by Christian R. Reis, and implemented by Gustavo Carneiro.</dd> </dl> </div> </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.4 makes to the core Python language.</p> <ul> <li><p class="first">Decorators for functions and methods were added (<span class="target" id="index-12"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0318"><strong>PEP 318</strong></a>).</p> </li> <li><p class="first">Built-in <a class="reference internal" href="../library/stdtypes.html#set" title="set"><tt class="xref py py-func docutils literal"><span class="pre">set()</span></tt></a> and <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><tt class="xref py py-func docutils literal"><span class="pre">frozenset()</span></tt></a> types were added (<span class="target" id="index-13"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0218"><strong>PEP 218</strong></a>). Other new built-ins include the <tt class="xref py py-func docutils literal"><span class="pre">reversed(seq)()</span></tt> function (<span class="target" id="index-14"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0322"><strong>PEP 322</strong></a>).</p> </li> <li><p class="first">Generator expressions were added (<span class="target" id="index-15"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0289"><strong>PEP 289</strong></a>).</p> </li> <li><p class="first">Certain numeric expressions no longer return values restricted to 32 or 64 bits (<span class="target" id="index-16"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0237"><strong>PEP 237</strong></a>).</p> </li> <li><p class="first">You can now put parentheses around the list of names in a <tt class="docutils literal"><span class="pre">from</span> <span class="pre">module</span> <span class="pre">import</span> <span class="pre">names</span></tt> statement (<span class="target" id="index-17"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0328"><strong>PEP 328</strong></a>).</p> </li> <li><p class="first">The <a class="reference internal" href="../library/stdtypes.html#dict.update" title="dict.update"><tt class="xref py py-meth docutils literal"><span class="pre">dict.update()</span></tt></a> method now accepts the same argument forms as the <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><tt class="xref py py-class docutils literal"><span class="pre">dict</span></tt></a> constructor. This includes any mapping, any iterable of key/value pairs, and keyword arguments. (Contributed by Raymond Hettinger.)</p> </li> <li><p class="first">The string methods <tt class="xref py py-meth docutils literal"><span class="pre">ljust()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">rjust()</span></tt>, and <tt class="xref py py-meth docutils literal"><span class="pre">center()</span></tt> now take an optional argument for specifying a fill character other than a space. (Contributed by Raymond Hettinger.)</p> </li> <li><p class="first">Strings also gained an <tt class="xref py py-meth docutils literal"><span class="pre">rsplit()</span></tt> method that works like the <tt class="xref py py-meth docutils literal"><span class="pre">split()</span></tt> method but splits from the end of the string. (Contributed by Sean Reifschneider.)</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="s">'www.python.org'</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">'.'</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span> <span class="go">['www', 'python.org']</span> <span class="go">'www.python.org'.rsplit('.', 1)</span> <span class="go">['www.python', 'org']</span> </pre></div> </div> </li> <li><p class="first">Three keyword parameters, <em>cmp</em>, <em>key</em>, and <em>reverse</em>, were added to the <tt class="xref py py-meth docutils literal"><span class="pre">sort()</span></tt> method of lists. These parameters make some common usages of <tt class="xref py py-meth docutils literal"><span class="pre">sort()</span></tt> simpler. All of these parameters are optional.</p> <p>For the <em>cmp</em> parameter, the value should be a comparison function that takes two parameters and returns -1, 0, or +1 depending on how the parameters compare. This function will then be used to sort the list. Previously this was the only parameter that could be provided to <tt class="xref py py-meth docutils literal"><span class="pre">sort()</span></tt>.</p> <p><em>key</em> should be a single-parameter function that takes a list element and returns a comparison key for the element. The list is then sorted using the comparison keys. The following example sorts a list case-insensitively:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="s">'A'</span><span class="p">,</span> <span class="s">'b'</span><span class="p">,</span> <span class="s">'c'</span><span class="p">,</span> <span class="s">'D'</span><span class="p">]</span> <span class="gp">>>> </span><span class="n">L</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span> <span class="c"># Case-sensitive sort</span> <span class="gp">>>> </span><span class="n">L</span> <span class="go">['A', 'D', 'b', 'c']</span> <span class="gp">>>> </span><span class="c"># Using 'key' parameter to sort list</span> <span class="gp">>>> </span><span class="n">L</span><span class="o">.</span><span class="n">sort</span><span class="p">(</span><span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span><span class="o">.</span><span class="n">lower</span><span class="p">())</span> <span class="gp">>>> </span><span class="n">L</span> <span class="go">['A', 'b', 'c', 'D']</span> <span class="gp">>>> </span><span class="c"># Old-fashioned way</span> <span class="gp">>>> </span><span class="n">L</span><span class="o">.</span><span class="n">sort</span><span class="p">(</span><span class="nb">cmp</span><span class="o">=</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">:</span> <span class="nb">cmp</span><span class="p">(</span><span class="n">x</span><span class="o">.</span><span class="n">lower</span><span class="p">(),</span> <span class="n">y</span><span class="o">.</span><span class="n">lower</span><span class="p">()))</span> <span class="gp">>>> </span><span class="n">L</span> <span class="go">['A', 'b', 'c', 'D']</span> </pre></div> </div> <p>The last example, which uses the <em>cmp</em> parameter, is the old way to perform a case-insensitive sort. It works but is slower than using a <em>key</em> parameter. Using <em>key</em> calls <tt class="xref py py-meth docutils literal"><span class="pre">lower()</span></tt> method once for each element in the list while using <em>cmp</em> will call it twice for each comparison, so using <em>key</em> saves on invocations of the <tt class="xref py py-meth docutils literal"><span class="pre">lower()</span></tt> method.</p> <p>For simple key functions and comparison functions, it is often possible to avoid a <a class="reference internal" href="../reference/expressions.html#lambda"><tt class="xref std std-keyword docutils literal"><span class="pre">lambda</span></tt></a> expression by using an unbound method instead. For example, the above case-insensitive sort is best written as:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">L</span><span class="o">.</span><span class="n">sort</span><span class="p">(</span><span class="n">key</span><span class="o">=</span><span class="nb">str</span><span class="o">.</span><span class="n">lower</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">L</span> <span class="go">['A', 'b', 'c', 'D']</span> </pre></div> </div> <p>Finally, the <em>reverse</em> parameter takes a Boolean value. If the value is true, the list will be sorted into reverse order. Instead of <tt class="docutils literal"><span class="pre">L.sort()</span> <span class="pre">;</span> <span class="pre">L.reverse()</span></tt>, you can now write <tt class="docutils literal"><span class="pre">L.sort(reverse=True)</span></tt>.</p> <p>The results of sorting are now guaranteed to be stable. This means that two entries with equal keys will be returned in the same order as they were input. For example, you can sort a list of people by name, and then sort the list by age, resulting in a list sorted by age where people with the same age are in name-sorted order.</p> <p>(All changes to <tt class="xref py py-meth docutils literal"><span class="pre">sort()</span></tt> contributed by Raymond Hettinger.)</p> </li> <li><p class="first">There is a new built-in function <tt class="xref py py-func docutils literal"><span class="pre">sorted(iterable)()</span></tt> that works like the in-place <tt class="xref py py-meth docutils literal"><span class="pre">list.sort()</span></tt> method but can be used in expressions. The differences are:</p> </li> <li><p class="first">the input may be any iterable;</p> </li> <li><p class="first">a newly formed copy is sorted, leaving the original intact; and</p> </li> <li><p class="first">the expression returns the new sorted copy</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="mi">9</span><span class="p">,</span><span class="mi">7</span><span class="p">,</span><span class="mi">8</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">6</span><span class="p">,</span><span class="mi">5</span><span class="p">]</span> <span class="gp">>>> </span><span class="p">[</span><span class="mi">10</span><span class="o">+</span><span class="n">i</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">L</span><span class="p">)]</span> <span class="c"># usable in a list comprehension</span> <span class="go">[11, 12, 13, 14, 15, 16, 17, 18, 19]</span> <span class="gp">>>> </span><span class="n">L</span> <span class="c"># original is left unchanged</span> <span class="go">[9,7,8,3,2,4,1,6,5]</span> <span class="gp">>>> </span><span class="nb">sorted</span><span class="p">(</span><span class="s">'Monty Python'</span><span class="p">)</span> <span class="c"># any iterable may be an input</span> <span class="go">[' ', 'M', 'P', 'h', 'n', 'n', 'o', 'o', 't', 't', 'y', 'y']</span> <span class="gp">>>> </span><span class="c"># List the contents of a dict sorted by key values</span> <span class="gp">>>> </span><span class="n">colormap</span> <span class="o">=</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="n">yellow</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span> <span class="gp">>>> </span><span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">colormap</span><span class="o">.</span><span class="n">iteritems</span><span class="p">()):</span> <span class="gp">... </span> <span class="k">print</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="gp">...</span> <span class="go">black 4</span> <span class="go">blue 2</span> <span class="go">green 3</span> <span class="go">red 1</span> <span class="go">yellow 5</span> </pre></div> </div> <p>(Contributed by Raymond Hettinger.)</p> </li> <li><p class="first">Integer operations will no longer trigger an <tt class="xref py py-exc docutils literal"><span class="pre">OverflowWarning</span></tt>. The <tt class="xref py py-exc docutils literal"><span class="pre">OverflowWarning</span></tt> warning will disappear in Python 2.5.</p> </li> <li><p class="first">The interpreter gained a new switch, <a class="reference internal" href="../using/cmdline.html#cmdoption-m"><em class="xref std std-option">-m</em></a>, that takes a name, searches for the corresponding module on <tt class="docutils literal"><span class="pre">sys.path</span></tt>, and runs the module as a script. For example, you can now run the Python profiler with <tt class="docutils literal"><span class="pre">python</span> <span class="pre">-m</span> <span class="pre">profile</span></tt>. (Contributed by Nick Coghlan.)</p> </li> <li><p class="first">The <tt class="xref py py-func docutils literal"><span class="pre">eval(expr,</span> <span class="pre">globals,</span> <span class="pre">locals)()</span></tt> and <tt class="xref py py-func docutils literal"><span class="pre">execfile(filename,</span> <span class="pre">globals,</span> <span class="pre">locals)()</span></tt> functions and the <a class="reference internal" href="../reference/simple_stmts.html#exec"><tt class="xref std std-keyword docutils literal"><span class="pre">exec</span></tt></a> statement now accept any mapping type for the <em>locals</em> parameter. Previously this had to be a regular Python dictionary. (Contributed by Raymond Hettinger.)</p> </li> <li><p class="first">The <a class="reference internal" href="../library/functions.html#zip" title="zip"><tt class="xref py py-func docutils literal"><span class="pre">zip()</span></tt></a> built-in function and <a class="reference internal" href="../library/itertools.html#itertools.izip" title="itertools.izip"><tt class="xref py py-func docutils literal"><span class="pre">itertools.izip()</span></tt></a> now return an empty list if called with no arguments. Previously they raised 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> exception. This makes them more suitable for use with variable length argument lists:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="k">def</span> <span class="nf">transpose</span><span class="p">(</span><span class="n">array</span><span class="p">):</span> <span class="gp">... </span> <span class="k">return</span> <span class="nb">zip</span><span class="p">(</span><span class="o">*</span><span class="n">array</span><span class="p">)</span> <span class="gp">...</span> <span class="gp">>>> </span><span class="n">transpose</span><span class="p">([(</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">6</span><span class="p">)])</span> <span class="go">[(1, 4), (2, 5), (3, 6)]</span> <span class="gp">>>> </span><span class="n">transpose</span><span class="p">([])</span> <span class="go">[]</span> </pre></div> </div> <p>(Contributed by Raymond Hettinger.)</p> </li> <li><p class="first">Encountering a failure while importing a module no longer leaves a partially- initialized module object in <tt class="docutils literal"><span class="pre">sys.modules</span></tt>. The incomplete module object left behind would fool further imports of the same module into succeeding, leading to confusing errors. (Fixed by Tim Peters.)</p> </li> <li><p class="first"><a class="reference internal" href="../library/constants.html#None" title="None"><tt class="xref py py-const docutils literal"><span class="pre">None</span></tt></a> is now a constant; code that binds a new value to the name <tt class="docutils literal"><span class="pre">None</span></tt> is now a syntax error. (Contributed by Raymond Hettinger.)</p> </li> </ul> <div class="section" id="optimizations"> <h3>Optimizations<a class="headerlink" href="#optimizations" title="Permalink to this headline">¶</a></h3> <ul class="simple"> <li>The inner loops for list and tuple slicing were optimized and now run about one-third faster. The inner loops for dictionaries were also optimized, resulting in performance boosts for <tt class="xref py py-meth docutils literal"><span class="pre">keys()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">values()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">items()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">iterkeys()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">itervalues()</span></tt>, and <tt class="xref py py-meth docutils literal"><span class="pre">iteritems()</span></tt>. (Contributed by Raymond Hettinger.)</li> <li>The machinery for growing and shrinking lists was optimized for speed and for space efficiency. Appending and popping from lists now runs faster due to more efficient code paths and less frequent use of the underlying system <tt class="xref c c-func docutils literal"><span class="pre">realloc()</span></tt>. List comprehensions also benefit. <tt class="xref py py-meth docutils literal"><span class="pre">list.extend()</span></tt> was also optimized and no longer converts its argument into a temporary list before extending the base list. (Contributed by Raymond Hettinger.)</li> <li><a class="reference internal" href="../library/functions.html#list" title="list"><tt class="xref py py-func docutils literal"><span class="pre">list()</span></tt></a>, <a class="reference internal" href="../library/functions.html#tuple" title="tuple"><tt class="xref py py-func docutils literal"><span class="pre">tuple()</span></tt></a>, <a class="reference internal" href="../library/functions.html#map" title="map"><tt class="xref py py-func docutils literal"><span class="pre">map()</span></tt></a>, <a class="reference internal" href="../library/functions.html#filter" title="filter"><tt class="xref py py-func docutils literal"><span class="pre">filter()</span></tt></a>, and <a class="reference internal" href="../library/functions.html#zip" title="zip"><tt class="xref py py-func docutils literal"><span class="pre">zip()</span></tt></a> now run several times faster with non-sequence arguments that supply a <a class="reference internal" href="../reference/datamodel.html#object.__len__" title="object.__len__"><tt class="xref py py-meth docutils literal"><span class="pre">__len__()</span></tt></a> method. (Contributed by Raymond Hettinger.)</li> <li>The methods <tt class="xref py py-meth docutils literal"><span class="pre">list.__getitem__()</span></tt>, <tt class="xref py py-meth docutils literal"><span class="pre">dict.__getitem__()</span></tt>, and <tt class="xref py py-meth docutils literal"><span class="pre">dict.__contains__()</span></tt> are now implemented as <tt class="xref py py-class docutils literal"><span class="pre">method_descriptor</span></tt> objects rather than <tt class="xref py py-class docutils literal"><span class="pre">wrapper_descriptor</span></tt> objects. This form of access doubles their performance and makes them more suitable for use as arguments to functionals: <tt class="docutils literal"><span class="pre">map(mydict.__getitem__,</span> <span class="pre">keylist)</span></tt>. (Contributed by Raymond Hettinger.)</li> <li>Added a new opcode, <tt class="docutils literal"><span class="pre">LIST_APPEND</span></tt>, that simplifies the generated bytecode for list comprehensions and speeds them up by about a third. (Contributed by Raymond Hettinger.)</li> <li>The peephole bytecode optimizer has been improved to produce shorter, faster bytecode; remarkably, the resulting bytecode is more readable. (Enhanced by Raymond Hettinger.)</li> <li>String concatenations in statements of the form <tt class="docutils literal"><span class="pre">s</span> <span class="pre">=</span> <span class="pre">s</span> <span class="pre">+</span> <span class="pre">"abc"</span></tt> and <tt class="docutils literal"><span class="pre">s</span> <span class="pre">+=</span> <span class="pre">"abc"</span></tt> are now performed more efficiently in certain circumstances. This optimization won’t be present in other Python implementations such as Jython, so you shouldn’t rely on it; using the <tt class="xref py py-meth docutils literal"><span class="pre">join()</span></tt> method of strings is still recommended when you want to efficiently glue a large number of strings together. (Contributed by Armin Rigo.)</li> </ul> <p>The net result of the 2.4 optimizations is that Python 2.4 runs the pystone benchmark around 5% faster than Python 2.3 and 35% faster than Python 2.2. (pystone is not a particularly good benchmark, but it’s the most commonly used measurement of Python’s performance. Your own applications may show greater or smaller benefits from Python 2.4.)</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/asyncore.html#module-asyncore" title="asyncore: A base class for developing asynchronous socket handling services."><tt class="xref py py-mod docutils literal"><span class="pre">asyncore</span></tt></a> module’s <tt class="xref py py-func docutils literal"><span class="pre">loop()</span></tt> function now has a <em>count</em> parameter that lets you perform a limited number of passes through the polling loop. The default is still to loop forever.</p> </li> <li><p class="first">The <a class="reference internal" href="../library/base64.html#module-base64" title="base64: RFC 3548: Base16, Base32, Base64 Data Encodings"><tt class="xref py py-mod docutils literal"><span class="pre">base64</span></tt></a> module now has more complete RFC 3548 support for Base64, Base32, and Base16 encoding and decoding, including optional case folding and optional alternative alphabets. (Contributed by Barry Warsaw.)</p> </li> <li><p class="first">The <a class="reference internal" href="../library/bisect.html#module-bisect" title="bisect: Array bisection algorithms for binary searching."><tt class="xref py py-mod docutils literal"><span class="pre">bisect</span></tt></a> module now has an underlying C implementation for improved performance. (Contributed by Dmitry Vasiliev.)</p> </li> <li><p class="first">The CJKCodecs collections of East Asian codecs, maintained by Hye-Shik Chang, was integrated into 2.4. The new encodings are:</p> </li> <li><p class="first">Chinese (PRC): gb2312, gbk, gb18030, big5hkscs, hz</p> </li> <li><p class="first">Chinese (ROC): big5, cp950</p> </li> <li><dl class="first docutils"> <dt>Japanese: cp932, euc-jis-2004, euc-jp, euc-jisx0213, iso-2022-jp,</dt> <dd><p class="first last">iso-2022-jp-1, iso-2022-jp-2, iso-2022-jp-3, iso-2022-jp-ext, iso-2022-jp-2004, shift-jis, shift-jisx0213, shift-jis-2004</p> </dd> </dl> </li> <li><p class="first">Korean: cp949, euc-kr, johab, iso-2022-kr</p> </li> <li><p class="first">Some other new encodings were added: HP Roman8, ISO_8859-11, ISO_8859-16, PCTP-154, and TIS-620.</p> </li> <li><p class="first">The UTF-8 and UTF-16 codecs now cope better with receiving partial input. Previously the <tt class="xref py py-class docutils literal"><span class="pre">StreamReader</span></tt> class would try to read more data, making it impossible to resume decoding from the stream. The <tt class="xref py py-meth docutils literal"><span class="pre">read()</span></tt> method will now return as much data as it can and future calls will resume decoding where previous ones left off. (Implemented by Walter Dörwald.)</p> </li> <li><p class="first">There is a new <a class="reference internal" href="../library/collections.html#module-collections" title="collections: High-performance datatypes"><tt class="xref py py-mod docutils literal"><span class="pre">collections</span></tt></a> module for various specialized collection datatypes. Currently it contains just one type, <tt class="xref py py-class docutils literal"><span class="pre">deque</span></tt>, a double- ended queue that supports efficiently adding and removing elements from either end:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">collections</span> <span class="kn">import</span> <span class="n">deque</span> <span class="gp">>>> </span><span class="n">d</span> <span class="o">=</span> <span class="n">deque</span><span class="p">(</span><span class="s">'ghi'</span><span class="p">)</span> <span class="c"># make a new deque with three items</span> <span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s">'j'</span><span class="p">)</span> <span class="c"># add a new entry to the right side</span> <span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">appendleft</span><span class="p">(</span><span class="s">'f'</span><span class="p">)</span> <span class="c"># add a new entry to the left side</span> <span class="gp">>>> </span><span class="n">d</span> <span class="c"># show the representation of the deque</span> <span class="go">deque(['f', 'g', 'h', 'i', 'j'])</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="c"># return and remove the rightmost item</span> <span class="go">'j'</span> <span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span> <span class="c"># return and remove the leftmost item</span> <span class="go">'f'</span> <span class="gp">>>> </span><span class="nb">list</span><span class="p">(</span><span class="n">d</span><span class="p">)</span> <span class="c"># list the contents of the deque</span> <span class="go">['g', 'h', 'i']</span> <span class="gp">>>> </span><span class="s">'h'</span> <span class="ow">in</span> <span class="n">d</span> <span class="c"># search the deque</span> <span class="go">True</span> </pre></div> </div> <p>Several modules, such as the <a class="reference internal" href="../library/queue.html#module-Queue" title="Queue: A synchronized queue class."><tt class="xref py py-mod docutils literal"><span class="pre">Queue</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 take advantage of <a class="reference internal" href="../library/collections.html#collections.deque" title="collections.deque"><tt class="xref py py-class docutils literal"><span class="pre">collections.deque</span></tt></a> for improved performance. (Contributed by Raymond Hettinger.)</p> </li> <li><p class="first">The <a class="reference internal" href="../library/configparser.html#module-ConfigParser" title="ConfigParser: Configuration file parser."><tt class="xref py py-mod docutils literal"><span class="pre">ConfigParser</span></tt></a> classes have been enhanced slightly. The <tt class="xref py py-meth docutils literal"><span class="pre">read()</span></tt> method now returns a list of the files that were successfully parsed, and the <a class="reference internal" href="../library/stdtypes.html#set" title="set"><tt class="xref py py-meth docutils literal"><span class="pre">set()</span></tt></a> method raises <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 passed a <em>value</em> argument that isn’t a string. (Contributed by John Belmonte and David Goodger.)</p> </li> <li><p class="first">The <a class="reference internal" href="../library/curses.html#module-curses" title="curses: An interface to the curses library, providing portable terminal handling. (Unix)"><tt class="xref py py-mod docutils literal"><span class="pre">curses</span></tt></a> module now supports the ncurses extension <tt class="xref py py-func docutils literal"><span class="pre">use_default_colors()</span></tt>. On platforms where the terminal supports transparency, this makes it possible to use a transparent background. (Contributed by Jörg Lehmann.)</p> </li> <li><p class="first">The <a class="reference internal" href="../library/difflib.html#module-difflib" title="difflib: Helpers for computing differences between objects."><tt class="xref py py-mod docutils literal"><span class="pre">difflib</span></tt></a> module now includes an <tt class="xref py py-class docutils literal"><span class="pre">HtmlDiff</span></tt> class that creates an HTML table showing a side by side comparison of two versions of a text. (Contributed by Dan Gass.)</p> </li> <li><p class="first">The <a class="reference internal" href="../library/email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><tt class="xref py py-mod docutils literal"><span class="pre">email</span></tt></a> package was updated to version 3.0, which dropped various deprecated APIs and removes support for Python versions earlier than 2.3. The 3.0 version of the package uses a new incremental parser for MIME messages, available in the <tt class="xref py py-mod docutils literal"><span class="pre">email.FeedParser</span></tt> module. The new parser doesn’t require reading the entire message into memory, and doesn’t raise exceptions if a message is malformed; instead it records any problems in the <tt class="xref py py-attr docutils literal"><span class="pre">defect</span></tt> attribute of the message. (Developed by Anthony Baxter, Barry Warsaw, Thomas Wouters, and others.)</p> </li> <li><p class="first">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 has been converted to C. The resulting tenfold improvement in speed makes the module suitable for handling high volumes of data. In addition, the module has two new functions <tt class="xref py py-func docutils literal"><span class="pre">nlargest()</span></tt> and <tt class="xref py py-func docutils literal"><span class="pre">nsmallest()</span></tt> that use heaps to find the N largest or smallest values in a dataset without the expense of a full sort. (Contributed by Raymond Hettinger.)</p> </li> <li><p class="first">The <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> module now contains constants for HTTP status codes defined in various HTTP-related RFC documents. Constants have names such as <tt class="xref py py-const docutils literal"><span class="pre">OK</span></tt>, <tt class="xref py py-const docutils literal"><span class="pre">CREATED</span></tt>, <tt class="xref py py-const docutils literal"><span class="pre">CONTINUE</span></tt>, and <tt class="xref py py-const docutils literal"><span class="pre">MOVED_PERMANENTLY</span></tt>; use pydoc to get a full list. (Contributed by Andrew Eland.)</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’s THREAD command (contributed by Yves Dionne) and new <tt class="xref py py-meth docutils literal"><span class="pre">deleteacl()</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">myrights()</span></tt> methods (contributed by Arnaud Mazin).</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> module gained a <tt class="xref py py-func docutils literal"><span class="pre">groupby(iterable[,</span> <span class="pre">*func*])()</span></tt> function. <em>iterable</em> is something that can be iterated over to return a stream of elements, and the optional <em>func</em> parameter is a function that takes an element and returns a key value; if omitted, the key is simply the element itself. <tt class="xref py py-func docutils literal"><span class="pre">groupby()</span></tt> then groups the elements into subsequences which have matching values of the key, and returns a series of 2-tuples containing the key value and an iterator over the subsequence.</p> <p>Here’s an example to make this clearer. The <em>key</em> function simply returns whether a number is even or odd, so the result of <tt class="xref py py-func docutils literal"><span class="pre">groupby()</span></tt> is to return consecutive runs of odd or even numbers.</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">itertools</span> <span class="gp">>>> </span><span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="mi">11</span><span class="p">,</span> <span class="mi">12</span><span class="p">,</span> <span class="mi">14</span><span class="p">]</span> <span class="gp">>>> </span><span class="k">for</span> <span class="n">key_val</span><span class="p">,</span> <span class="n">it</span> <span class="ow">in</span> <span class="n">itertools</span><span class="o">.</span><span class="n">groupby</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span> <span class="o">%</span> <span class="mi">2</span><span class="p">):</span> <span class="gp">... </span> <span class="k">print</span> <span class="n">key_val</span><span class="p">,</span> <span class="nb">list</span><span class="p">(</span><span class="n">it</span><span class="p">)</span> <span class="gp">...</span> <span class="go">0 [2, 4, 6]</span> <span class="go">1 [7]</span> <span class="go">0 [8]</span> <span class="go">1 [9, 11]</span> <span class="go">0 [12, 14]</span> <span class="go">>>></span> </pre></div> </div> <p><tt class="xref py py-func docutils literal"><span class="pre">groupby()</span></tt> is typically used with sorted input. The logic for <tt class="xref py py-func docutils literal"><span class="pre">groupby()</span></tt> is similar to the Unix <tt class="docutils literal"><span class="pre">uniq</span></tt> filter which makes it handy for eliminating, counting, or identifying duplicate elements:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">word</span> <span class="o">=</span> <span class="s">'abracadabra'</span> <span class="gp">>>> </span><span class="n">letters</span> <span class="o">=</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">word</span><span class="p">)</span> <span class="c"># Turn string into a sorted list of letters</span> <span class="gp">>>> </span><span class="n">letters</span> <span class="go">['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r']</span> <span class="gp">>>> </span><span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">g</span> <span class="ow">in</span> <span class="n">itertools</span><span class="o">.</span><span class="n">groupby</span><span class="p">(</span><span class="n">letters</span><span class="p">):</span> <span class="gp">... </span> <span class="k">print</span> <span class="n">k</span><span class="p">,</span> <span class="nb">list</span><span class="p">(</span><span class="n">g</span><span class="p">)</span> <span class="gp">...</span> <span class="go">a ['a', 'a', 'a', 'a', 'a']</span> <span class="go">b ['b', 'b']</span> <span class="go">c ['c']</span> <span class="go">d ['d']</span> <span class="go">r ['r', 'r']</span> <span class="gp">>>> </span><span class="c"># List unique letters</span> <span class="gp">>>> </span><span class="p">[</span><span class="n">k</span> <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">g</span> <span class="ow">in</span> <span class="n">groupby</span><span class="p">(</span><span class="n">letters</span><span class="p">)]</span> <span class="go">['a', 'b', 'c', 'd', 'r']</span> <span class="gp">>>> </span><span class="c"># Count letter occurrences</span> <span class="gp">>>> </span><span class="p">[(</span><span class="n">k</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="n">g</span><span class="p">)))</span> <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">g</span> <span class="ow">in</span> <span class="n">groupby</span><span class="p">(</span><span class="n">letters</span><span class="p">)]</span> <span class="go">[('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)]</span> </pre></div> </div> <p>(Contributed by Hye-Shik Chang.)</p> </li> <li><p class="first"><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> also gained a function named <tt class="xref py py-func docutils literal"><span class="pre">tee(iterator,</span> <span class="pre">N)()</span></tt> that returns <em>N</em> independent iterators that replicate <em>iterator</em>. If <em>N</em> is omitted, the default is 2.</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">L</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="mi">3</span><span class="p">]</span> <span class="gp">>>> </span><span class="n">i1</span><span class="p">,</span> <span class="n">i2</span> <span class="o">=</span> <span class="n">itertools</span><span class="o">.</span><span class="n">tee</span><span class="p">(</span><span class="n">L</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">i1</span><span class="p">,</span><span class="n">i2</span> <span class="go">(<itertools.tee object at 0x402c2080>, <itertools.tee object at 0x402c2090>)</span> <span class="gp">>>> </span><span class="nb">list</span><span class="p">(</span><span class="n">i1</span><span class="p">)</span> <span class="c"># Run the first iterator to exhaustion</span> <span class="go">[1, 2, 3]</span> <span class="gp">>>> </span><span class="nb">list</span><span class="p">(</span><span class="n">i2</span><span class="p">)</span> <span class="c"># Run the second iterator to exhaustion</span> <span class="go">[1, 2, 3]</span> </pre></div> </div> <p>Note that <tt class="xref py py-func docutils literal"><span class="pre">tee()</span></tt> has to keep copies of the values returned by the iterator; in the worst case, it may need to keep all of them. This should therefore be used carefully if the leading iterator can run far ahead of the trailing iterator in a long stream of inputs. If the separation is large, then you might as well use <a class="reference internal" href="../library/functions.html#list" title="list"><tt class="xref py py-func docutils literal"><span class="pre">list()</span></tt></a> instead. When the iterators track closely with one another, <tt class="xref py py-func docutils literal"><span class="pre">tee()</span></tt> is ideal. Possible applications include bookmarking, windowing, or lookahead iterators. (Contributed by Raymond Hettinger.)</p> </li> <li><p class="first">A number of functions were added to the <a class="reference internal" href="../library/locale.html#module-locale" title="locale: Internationalization services."><tt class="xref py py-mod docutils literal"><span class="pre">locale</span></tt></a> module, such as <tt class="xref py py-func docutils literal"><span class="pre">bind_textdomain_codeset()</span></tt> to specify a particular encoding and a family of <tt class="xref py py-func docutils literal"><span class="pre">l*gettext()</span></tt> functions that return messages in the chosen encoding. (Contributed by Gustavo Niemeyer.)</p> </li> <li><p class="first">Some keyword arguments were added to 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’s <tt class="xref py py-func docutils literal"><span class="pre">basicConfig()</span></tt> function to simplify log configuration. The default behavior is to log messages to standard error, but various keyword arguments can be specified to log to a particular file, change the logging format, or set the logging level. For example:</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">basicConfig</span><span class="p">(</span><span class="n">filename</span><span class="o">=</span><span class="s">'/var/log/application.log'</span><span class="p">,</span> <span class="n">level</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="c"># Log all messages</span> <span class="n">format</span><span class="o">=</span><span class="s">'%(levelname):%(process):%(thread):%(message)'</span><span class="p">)</span> </pre></div> </div> <p>Other additions to 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 include a <tt class="xref py py-meth docutils literal"><span class="pre">log(level,</span> <span class="pre">msg)()</span></tt> convenience method, as well as a <tt class="xref py py-class docutils literal"><span class="pre">TimedRotatingFileHandler</span></tt> class that rotates its log files at a timed interval. The module already had <tt class="xref py py-class docutils literal"><span class="pre">RotatingFileHandler</span></tt>, which rotated logs once the file exceeded a certain size. Both classes derive from a new <tt class="xref py py-class docutils literal"><span class="pre">BaseRotatingHandler</span></tt> class that can be used to implement other rotating handlers.</p> <p>(Changes implemented by Vinay Sajip.)</p> </li> <li><p class="first">The <a class="reference internal" href="../library/marshal.html#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><tt class="xref py py-mod docutils literal"><span class="pre">marshal</span></tt></a> module now shares interned strings on unpacking a data structure. This may shrink the size of certain pickle strings, but the primary effect is to make <tt class="file docutils literal"><span class="pre">.pyc</span></tt> files significantly smaller. (Contributed by Martin von Löwis.)</p> </li> <li><p class="first">The <a class="reference internal" href="../library/nntplib.html#module-nntplib" title="nntplib: NNTP protocol client (requires sockets)."><tt class="xref py py-mod docutils literal"><span class="pre">nntplib</span></tt></a> module’s <tt class="xref py py-class docutils literal"><span class="pre">NNTP</span></tt> class gained <tt class="xref py py-meth docutils literal"><span class="pre">description()</span></tt> and <tt class="xref py py-meth docutils literal"><span class="pre">descriptions()</span></tt> methods to retrieve newsgroup descriptions for a single group or for a range of groups. (Contributed by Jürgen A. Erhard.)</p> </li> <li><p class="first">Two new functions were added to the <a class="reference internal" href="../library/operator.html#module-operator" title="operator: Functions corresponding to the standard operators."><tt class="xref py py-mod docutils literal"><span class="pre">operator</span></tt></a> module, <tt class="xref py py-func docutils literal"><span class="pre">attrgetter(attr)()</span></tt> and <tt class="xref py py-func docutils literal"><span class="pre">itemgetter(index)()</span></tt>. Both functions return callables that take a single argument and return the corresponding attribute or item; these callables make excellent data extractors when used with <a class="reference internal" href="../library/functions.html#map" title="map"><tt class="xref py py-func docutils literal"><span class="pre">map()</span></tt></a> or <a class="reference internal" href="../library/functions.html#sorted" title="sorted"><tt class="xref py py-func docutils literal"><span class="pre">sorted()</span></tt></a>. For example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">L</span> <span class="o">=</span> <span class="p">[(</span><span class="s">'c'</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="s">'d'</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s">'a'</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="s">'b'</span><span class="p">,</span> <span class="mi">3</span><span class="p">)]</span> <span class="gp">>>> </span><span class="nb">map</span><span class="p">(</span><span class="n">operator</span><span class="o">.</span><span class="n">itemgetter</span><span class="p">(</span><span class="mi">0</span><span class="p">),</span> <span class="n">L</span><span class="p">)</span> <span class="go">['c', 'd', 'a', 'b']</span> <span class="gp">>>> </span><span class="nb">map</span><span class="p">(</span><span class="n">operator</span><span class="o">.</span><span class="n">itemgetter</span><span class="p">(</span><span class="mi">1</span><span class="p">),</span> <span class="n">L</span><span class="p">)</span> <span class="go">[2, 1, 4, 3]</span> <span class="gp">>>> </span><span class="nb">sorted</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">operator</span><span class="o">.</span><span class="n">itemgetter</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span> <span class="c"># Sort list by second tuple item</span> <span class="go">[('d', 1), ('c', 2), ('b', 3), ('a', 4)]</span> </pre></div> </div> <p>(Contributed by Raymond Hettinger.)</p> </li> <li><p class="first">The <a class="reference internal" href="../library/optparse.html#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><tt class="xref py py-mod docutils literal"><span class="pre">optparse</span></tt></a> module was updated in various ways. The module now passes its messages through <a class="reference internal" href="../library/gettext.html#gettext.gettext" title="gettext.gettext"><tt class="xref py py-func docutils literal"><span class="pre">gettext.gettext()</span></tt></a>, making it possible to internationalize Optik’s help and error messages. Help messages for options can now include the string <tt class="docutils literal"><span class="pre">'%default'</span></tt>, which will be replaced by the option’s default value. (Contributed by Greg Ward.)</p> </li> <li><p class="first">The long-term plan is to deprecate the <a class="reference internal" href="../library/rfc822.html#module-rfc822" title="rfc822: Parse 2822 style mail messages. (deprecated)"><tt class="xref py py-mod docutils literal"><span class="pre">rfc822</span></tt></a> module in some future Python release in favor of the <a class="reference internal" href="../library/email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><tt class="xref py py-mod docutils literal"><span class="pre">email</span></tt></a> package. To this end, the <tt class="xref py py-func docutils literal"><span class="pre">email.Utils.formatdate()</span></tt> function has been changed to make it usable as a replacement for <tt class="xref py py-func docutils literal"><span class="pre">rfc822.formatdate()</span></tt>. You may want to write new e-mail processing code with this in mind. (Change implemented by Anthony Baxter.)</p> </li> <li><p class="first">A new <tt class="xref py py-func docutils literal"><span class="pre">urandom(n)()</span></tt> function was added to 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, returning a string containing <em>n</em> bytes of random data. This function provides access to platform-specific sources of randomness such as <tt class="file docutils literal"><span class="pre">/dev/urandom</span></tt> on Linux or the Windows CryptoAPI. (Contributed by Trevor Perrin.)</p> </li> <li><p class="first">Another new function: <tt class="xref py py-func docutils literal"><span class="pre">os.path.lexists(path)()</span></tt> returns true if the file specified by <em>path</em> exists, whether or not it’s a symbolic link. This differs from the existing <tt class="xref py py-func docutils literal"><span class="pre">os.path.exists(path)()</span></tt> function, which returns false if <em>path</em> is a symlink that points to a destination that doesn’t exist. (Contributed by Beni Cherniavsky.)</p> </li> <li><p class="first">A new <tt class="xref py py-func docutils literal"><span class="pre">getsid()</span></tt> function was 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 J. Raynor.)</p> </li> <li><p class="first">The <a class="reference internal" href="../library/poplib.html#module-poplib" title="poplib: POP3 protocol client (requires sockets)."><tt class="xref py py-mod docutils literal"><span class="pre">poplib</span></tt></a> module now supports POP over SSL. (Contributed by Hector Urtubia.)</p> </li> <li><p class="first">The <a class="reference internal" href="../library/profile.html#module-profile" title="profile: Python source profiler."><tt class="xref py py-mod docutils literal"><span class="pre">profile</span></tt></a> module can now profile C extension functions. (Contributed by Nick Bastin.)</p> </li> <li><p class="first">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 has a new method called <tt class="xref py py-meth docutils literal"><span class="pre">getrandbits(N)()</span></tt> that returns a long integer <em>N</em> bits in length. The existing <tt class="xref py py-meth docutils literal"><span class="pre">randrange()</span></tt> method now uses <tt class="xref py py-meth docutils literal"><span class="pre">getrandbits()</span></tt> where appropriate, making generation of arbitrarily large random numbers more efficient. (Contributed by Raymond Hettinger.)</p> </li> <li><p class="first">The regular expression language accepted by the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><tt class="xref py py-mod docutils literal"><span class="pre">re</span></tt></a> module was extended with simple conditional expressions, written as <tt class="docutils literal"><span class="pre">(?(group)A|B)</span></tt>. <em>group</em> is either a numeric group ID or a group name defined with <tt class="docutils literal"><span class="pre">(?P<group>...)</span></tt> earlier in the expression. If the specified group matched, the regular expression pattern <em>A</em> will be tested against the string; if the group didn’t match, the pattern <em>B</em> will be used instead. (Contributed by Gustavo Niemeyer.)</p> </li> <li><p class="first">The <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><tt class="xref py py-mod docutils literal"><span class="pre">re</span></tt></a> module is also no longer recursive, thanks to a massive amount of work by Gustavo Niemeyer. In a recursive regular expression engine, certain patterns result in a large amount of C stack space being consumed, and it was possible to overflow the stack. For example, if you matched a 30000-byte string of <tt class="docutils literal"><span class="pre">a</span></tt> characters against the expression <tt class="docutils literal"><span class="pre">(a|b)+</span></tt>, one stack frame was consumed per character. Python 2.3 tried to check for stack overflow and raise 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> exception, but certain patterns could sidestep the checking and if you were unlucky Python could segfault. Python 2.4’s regular expression engine can match this pattern without problems.</p> </li> <li><p class="first">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> module now performs tighter error-checking on the parameters to the <a class="reference internal" href="../library/signal.html#signal.signal" title="signal.signal"><tt class="xref py py-func docutils literal"><span class="pre">signal.signal()</span></tt></a> function. For example, you can’t set a handler on the <tt class="xref py py-const docutils literal"><span class="pre">SIGKILL</span></tt> signal; previous versions of Python would quietly accept this, but 2.4 will raise 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> exception.</p> </li> <li><p class="first">Two new functions were added to 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. <tt class="xref py py-func docutils literal"><span class="pre">socketpair()</span></tt> returns a pair of connected sockets and <tt class="xref py py-func docutils literal"><span class="pre">getservbyport(port)()</span></tt> looks up the service name for a given port number. (Contributed by Dave Cole and Barry Warsaw.)</p> </li> <li><p class="first">The <a class="reference internal" href="../library/sys.html#sys.exitfunc" title="sys.exitfunc"><tt class="xref py py-func docutils literal"><span class="pre">sys.exitfunc()</span></tt></a> function has been deprecated. Code should be using the existing <a class="reference internal" href="../library/atexit.html#module-atexit" title="atexit: Register and execute cleanup functions."><tt class="xref py py-mod docutils literal"><span class="pre">atexit</span></tt></a> module, which correctly handles calling multiple exit functions. Eventually <a class="reference internal" href="../library/sys.html#sys.exitfunc" title="sys.exitfunc"><tt class="xref py py-func docutils literal"><span class="pre">sys.exitfunc()</span></tt></a> will become a purely internal interface, accessed only by <a class="reference internal" href="../library/atexit.html#module-atexit" title="atexit: Register and execute cleanup functions."><tt class="xref py py-mod docutils literal"><span class="pre">atexit</span></tt></a>.</p> </li> <li><p class="first">The <a class="reference internal" href="../library/tarfile.html#module-tarfile" title="tarfile: Read and write tar-format archive files."><tt class="xref py py-mod docutils literal"><span class="pre">tarfile</span></tt></a> module now generates GNU-format tar files by default. (Contributed by Lars Gustaebel.)</p> </li> <li><p class="first">The <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 now has an elegantly simple way to support thread-local data. The module contains a <tt class="xref py py-class docutils literal"><span class="pre">local</span></tt> class whose attribute values are local to different threads.</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">threading</span> <span class="n">data</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">local</span><span class="p">()</span> <span class="n">data</span><span class="o">.</span><span class="n">number</span> <span class="o">=</span> <span class="mi">42</span> <span class="n">data</span><span class="o">.</span><span class="n">url</span> <span class="o">=</span> <span class="p">(</span><span class="s">'www.python.org'</span><span class="p">,</span> <span class="mi">80</span><span class="p">)</span> </pre></div> </div> <p>Other threads can assign and retrieve their own values for the <tt class="xref py py-attr docutils literal"><span class="pre">number</span></tt> and <tt class="xref py py-attr docutils literal"><span class="pre">url</span></tt> attributes. You can subclass <tt class="xref py py-class docutils literal"><span class="pre">local</span></tt> to initialize attributes or to add methods. (Contributed by Jim Fulton.)</p> </li> <li><p class="first">The <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 now automatically disables periodic garbage collection during the timing loop. This change makes consecutive timings more comparable. (Contributed by Raymond Hettinger.)</p> </li> <li><p class="first">The <a class="reference internal" href="../library/weakref.html#module-weakref" title="weakref: Support for weak references and weak dictionaries."><tt class="xref py py-mod docutils literal"><span class="pre">weakref</span></tt></a> module now supports a wider variety of objects including Python functions, class instances, sets, frozensets, deques, arrays, files, sockets, and regular expression pattern objects. (Contributed by Raymond Hettinger.)</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 a multi-call extension for transmitting multiple XML-RPC calls in a single HTTP operation. (Contributed by Brian Quinlan.)</p> </li> <li><p class="first">The <tt class="xref py py-mod docutils literal"><span class="pre">mpz</span></tt>, <tt class="xref py py-mod docutils literal"><span class="pre">rotor</span></tt>, and <tt class="xref py py-mod docutils literal"><span class="pre">xreadlines</span></tt> modules have been removed.</p> </li> </ul> <div class="section" id="cookielib"> <h3>cookielib<a class="headerlink" href="#cookielib" title="Permalink to this headline">¶</a></h3> <p>The <a class="reference internal" href="../library/cookielib.html#module-cookielib" title="cookielib: Classes for automatic handling of HTTP cookies."><tt class="xref py py-mod docutils literal"><span class="pre">cookielib</span></tt></a> library supports client-side handling for HTTP cookies, mirroring the <a class="reference internal" href="../library/cookie.html#module-Cookie" title="Cookie: Support for HTTP state management (cookies)."><tt class="xref py py-mod docutils literal"><span class="pre">Cookie</span></tt></a> module’s server-side cookie support. Cookies are stored in cookie jars; the library transparently stores cookies offered by the web server in the cookie jar, and fetches the cookie from the jar when connecting to the server. As in web browsers, policy objects control whether cookies are accepted or not.</p> <p>In order to store cookies across sessions, two implementations of cookie jars are provided: one that stores cookies in the Netscape format so applications can use the Mozilla or Lynx cookie files, and one that stores cookies in the same format as the Perl libwww library.</p> <p><a class="reference internal" href="../library/urllib2.html#module-urllib2" title="urllib2: Next generation URL opening library."><tt class="xref py py-mod docutils literal"><span class="pre">urllib2</span></tt></a> has been changed to interact with <a class="reference internal" href="../library/cookielib.html#module-cookielib" title="cookielib: Classes for automatic handling of HTTP cookies."><tt class="xref py py-mod docutils literal"><span class="pre">cookielib</span></tt></a>: <tt class="xref py py-class docutils literal"><span class="pre">HTTPCookieProcessor</span></tt> manages a cookie jar that is used when accessing URLs.</p> <p>This module was contributed by John J. Lee.</p> </div> <div class="section" id="doctest"> <h3>doctest<a class="headerlink" href="#doctest" title="Permalink to this headline">¶</a></h3> <p>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 underwent considerable refactoring thanks to Edward Loper and Tim Peters. Testing can still be as simple as running <a class="reference internal" href="../library/doctest.html#doctest.testmod" title="doctest.testmod"><tt class="xref py py-func docutils literal"><span class="pre">doctest.testmod()</span></tt></a>, but the refactorings allow customizing the module’s operation in various ways</p> <p>The new <tt class="xref py py-class docutils literal"><span class="pre">DocTestFinder</span></tt> class extracts the tests from a given object’s docstrings:</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="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span> <span class="sd">""">>> f(2,2)</span> <span class="sd">4</span> <span class="sd">>>> f(3,2)</span> <span class="sd">6</span> <span class="sd"> """</span> <span class="k">return</span> <span class="n">x</span><span class="o">*</span><span class="n">y</span> <span class="n">finder</span> <span class="o">=</span> <span class="n">doctest</span><span class="o">.</span><span class="n">DocTestFinder</span><span class="p">()</span> <span class="c"># Get list of DocTest instances</span> <span class="n">tests</span> <span class="o">=</span> <span class="n">finder</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="n">f</span><span class="p">)</span> </pre></div> </div> <p>The new <tt class="xref py py-class docutils literal"><span class="pre">DocTestRunner</span></tt> class then runs individual tests and can produce a summary of the results:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">runner</span> <span class="o">=</span> <span class="n">doctest</span><span class="o">.</span><span class="n">DocTestRunner</span><span class="p">()</span> <span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="n">tests</span><span class="p">:</span> <span class="n">tried</span><span class="p">,</span> <span class="n">failed</span> <span class="o">=</span> <span class="n">runner</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">t</span><span class="p">)</span> <span class="n">runner</span><span class="o">.</span><span class="n">summarize</span><span class="p">(</span><span class="n">verbose</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span> </pre></div> </div> <p>The above example produces the following output:</p> <div class="highlight-python"><pre>1 items passed all tests: 2 tests in f 2 tests in 1 items. 2 passed and 0 failed. Test passed.</pre> </div> <p><tt class="xref py py-class docutils literal"><span class="pre">DocTestRunner</span></tt> uses an instance of the <tt class="xref py py-class docutils literal"><span class="pre">OutputChecker</span></tt> class to compare the expected output with the actual output. This class takes a number of different flags that customize its behaviour; ambitious users can also write a completely new subclass of <tt class="xref py py-class docutils literal"><span class="pre">OutputChecker</span></tt>.</p> <p>The default output checker provides a number of handy features. For example, with the <a class="reference internal" href="../library/doctest.html#doctest.ELLIPSIS" title="doctest.ELLIPSIS"><tt class="xref py py-const docutils literal"><span class="pre">doctest.ELLIPSIS</span></tt></a> option flag, an ellipsis (<tt class="docutils literal"><span class="pre">...</span></tt>) in the expected output matches any substring, making it easier to accommodate outputs that vary in minor ways:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">o</span> <span class="p">(</span><span class="n">n</span><span class="p">):</span> <span class="sd">""">>> o(1)</span> <span class="sd"><__main__.C instance at 0x...></span> <span class="sd">>>></span> <span class="sd">"""</span> </pre></div> </div> <p>Another special string, <tt class="docutils literal"><span class="pre"><BLANKLINE></span></tt>, matches a blank line:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">p</span> <span class="p">(</span><span class="n">n</span><span class="p">):</span> <span class="sd">""">>> p(1)</span> <span class="sd"><BLANKLINE></span> <span class="sd">>>></span> <span class="sd">"""</span> </pre></div> </div> <p>Another new capability is producing a diff-style display of the output by specifying the <a class="reference internal" href="../library/doctest.html#doctest.REPORT_UDIFF" title="doctest.REPORT_UDIFF"><tt class="xref py py-const docutils literal"><span class="pre">doctest.REPORT_UDIFF</span></tt></a> (unified diffs), <a class="reference internal" href="../library/doctest.html#doctest.REPORT_CDIFF" title="doctest.REPORT_CDIFF"><tt class="xref py py-const docutils literal"><span class="pre">doctest.REPORT_CDIFF</span></tt></a> (context diffs), or <a class="reference internal" href="../library/doctest.html#doctest.REPORT_NDIFF" title="doctest.REPORT_NDIFF"><tt class="xref py py-const docutils literal"><span class="pre">doctest.REPORT_NDIFF</span></tt></a> (delta-style) option flags. For example:</p> <div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">g</span> <span class="p">(</span><span class="n">n</span><span class="p">):</span> <span class="sd">""">>> g(4)</span> <span class="sd">here</span> <span class="sd">is</span> <span class="sd">a</span> <span class="sd">lengthy</span> <span class="sd">>>>"""</span> <span class="n">L</span> <span class="o">=</span> <span class="s">'here is a rather lengthy list of words'</span><span class="o">.</span><span class="n">split</span><span class="p">()</span> <span class="k">for</span> <span class="n">word</span> <span class="ow">in</span> <span class="n">L</span><span class="p">[:</span><span class="n">n</span><span class="p">]:</span> <span class="k">print</span> <span class="n">word</span> </pre></div> </div> <p>Running the above function’s tests with <a class="reference internal" href="../library/doctest.html#doctest.REPORT_UDIFF" title="doctest.REPORT_UDIFF"><tt class="xref py py-const docutils literal"><span class="pre">doctest.REPORT_UDIFF</span></tt></a> specified, you get the following output:</p> <div class="highlight-python"><pre>********************************************************************** File "t.py", line 15, in g Failed example: g(4) Differences (unified diff with -expected +actual): @@ -2,3 +2,3 @@ is a -lengthy +rather **********************************************************************</pre> </div> </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>Some of the changes to Python’s build process and to the C API are:</p> <ul class="simple"> <li>Three new convenience macros were added for common return values from extension functions: <a class="reference internal" href="../c-api/none.html#Py_RETURN_NONE" title="Py_RETURN_NONE"><tt class="xref c c-macro docutils literal"><span class="pre">Py_RETURN_NONE</span></tt></a>, <a class="reference internal" href="../c-api/bool.html#Py_RETURN_TRUE" title="Py_RETURN_TRUE"><tt class="xref c c-macro docutils literal"><span class="pre">Py_RETURN_TRUE</span></tt></a>, and <a class="reference internal" href="../c-api/bool.html#Py_RETURN_FALSE" title="Py_RETURN_FALSE"><tt class="xref c c-macro docutils literal"><span class="pre">Py_RETURN_FALSE</span></tt></a>. (Contributed by Brett Cannon.)</li> <li>Another new macro, <tt class="xref c c-macro docutils literal"><span class="pre">Py_CLEAR(obj)</span></tt>, decreases the reference count of <em>obj</em> and sets <em>obj</em> to the null pointer. (Contributed by Jim Fulton.)</li> <li>A new function, <tt class="xref c c-func docutils literal"><span class="pre">PyTuple_Pack(N,</span> <span class="pre">obj1,</span> <span class="pre">obj2,</span> <span class="pre">...,</span> <span class="pre">objN)()</span></tt>, constructs tuples from a variable length argument list of Python objects. (Contributed by Raymond Hettinger.)</li> <li>A new function, <tt class="xref c c-func docutils literal"><span class="pre">PyDict_Contains(d,</span> <span class="pre">k)()</span></tt>, implements fast dictionary lookups without masking exceptions raised during the look-up process. (Contributed by Raymond Hettinger.)</li> <li>The <tt class="xref c c-macro docutils literal"><span class="pre">Py_IS_NAN(X)</span></tt> macro returns 1 if its float or double argument <em>X</em> is a NaN. (Contributed by Tim Peters.)</li> <li>C code can avoid unnecessary locking by using the new <a class="reference internal" href="../c-api/init.html#PyEval_ThreadsInitialized" title="PyEval_ThreadsInitialized"><tt class="xref c c-func docutils literal"><span class="pre">PyEval_ThreadsInitialized()</span></tt></a> function to tell if any thread operations have been performed. If this function returns false, no lock operations are needed. (Contributed by Nick Coghlan.)</li> <li>A new function, <a class="reference internal" href="../c-api/arg.html#PyArg_VaParseTupleAndKeywords" title="PyArg_VaParseTupleAndKeywords"><tt class="xref c c-func docutils literal"><span class="pre">PyArg_VaParseTupleAndKeywords()</span></tt></a>, is the same as <a class="reference internal" href="../c-api/arg.html#PyArg_ParseTupleAndKeywords" title="PyArg_ParseTupleAndKeywords"><tt class="xref c c-func docutils literal"><span class="pre">PyArg_ParseTupleAndKeywords()</span></tt></a> but takes a <tt class="xref c c-type docutils literal"><span class="pre">va_list</span></tt> instead of a number of arguments. (Contributed by Greg Chapman.)</li> <li>A new method flag, <tt class="xref py py-const docutils literal"><span class="pre">METH_COEXISTS</span></tt>, allows a function defined in slots to co-exist with a <a class="reference internal" href="../c-api/structures.html#PyCFunction" title="PyCFunction"><tt class="xref c c-type docutils literal"><span class="pre">PyCFunction</span></tt></a> having the same name. This can halve the access time for a method such as <tt class="xref py py-meth docutils literal"><span class="pre">set.__contains__()</span></tt>. (Contributed by Raymond Hettinger.)</li> <li>Python can now be built with additional profiling for the interpreter itself, intended as an aid to people developing the Python core. Providing <em class="xref std std-option">----enable-profiling</em> to the <strong class="program">configure</strong> script will let you profile the interpreter with <strong class="program">gprof</strong>, and providing the <em class="xref std std-option">----with-tsc</em> switch enables profiling using the Pentium’s Time-Stamp- Counter register. Note that the <em class="xref std std-option">----with-tsc</em> switch is slightly misnamed, because the profiling feature also works on the PowerPC platform, though that processor architecture doesn’t call that register “the TSC register”. (Contributed by Jeremy Hylton.)</li> <li>The <tt class="xref c c-type docutils literal"><span class="pre">tracebackobject</span></tt> type has been renamed to <tt class="xref c c-type docutils literal"><span class="pre">PyTracebackObject</span></tt>.</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> <ul class="simple"> <li>The Windows port now builds under MSVC++ 7.1 as well as version 6. (Contributed by Martin von Löwis.)</li> </ul> </div> </div> <div class="section" id="porting-to-python-2-4"> <h2>Porting to Python 2.4<a class="headerlink" href="#porting-to-python-2-4" title="Permalink to this headline">¶</a></h2> <p>This section lists previously described changes that may require changes to your code:</p> <ul class="simple"> <li>Left shifts and hexadecimal/octal constants that are too large no longer 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> and return a value limited to 32 or 64 bits; instead they return a long integer.</li> <li>Integer operations will no longer trigger an <tt class="xref py py-exc docutils literal"><span class="pre">OverflowWarning</span></tt>. The <tt class="xref py py-exc docutils literal"><span class="pre">OverflowWarning</span></tt> warning will disappear in Python 2.5.</li> <li>The <a class="reference internal" href="../library/functions.html#zip" title="zip"><tt class="xref py py-func docutils literal"><span class="pre">zip()</span></tt></a> built-in function and <a class="reference internal" href="../library/itertools.html#itertools.izip" title="itertools.izip"><tt class="xref py py-func docutils literal"><span class="pre">itertools.izip()</span></tt></a> now return an empty list instead of 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> exception if called with no arguments.</li> <li>You can no longer compare the <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 provided by 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. Two instances of different classes will now always be unequal, and relative comparisons (<tt class="docutils literal"><span class="pre"><</span></tt>, <tt class="docutils literal"><span class="pre">></span></tt>) will raise 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>.</li> <li><a class="reference internal" href="../library/dircache.html#dircache.listdir" title="dircache.listdir"><tt class="xref py py-func docutils literal"><span class="pre">dircache.listdir()</span></tt></a> now passes exceptions to the caller instead of returning empty lists.</li> <li><tt class="xref py py-func docutils literal"><span class="pre">LexicalHandler.startDTD()</span></tt> used to receive the public and system IDs in the wrong order. This has been corrected; applications relying on the wrong order need to be fixed.</li> <li><a class="reference internal" href="../library/fcntl.html#fcntl.ioctl" title="fcntl.ioctl"><tt class="xref py py-func docutils literal"><span class="pre">fcntl.ioctl()</span></tt></a> now warns if the <em>mutate</em> argument is omitted and relevant.</li> <li>The <a class="reference internal" href="../library/tarfile.html#module-tarfile" title="tarfile: Read and write tar-format archive files."><tt class="xref py py-mod docutils literal"><span class="pre">tarfile</span></tt></a> module now generates GNU-format tar files by default.</li> <li>Encountering a failure while importing a module no longer leaves a partially- initialized module object in <tt class="docutils literal"><span class="pre">sys.modules</span></tt>.</li> <li><a class="reference internal" href="../library/constants.html#None" title="None"><tt class="xref py py-const docutils literal"><span class="pre">None</span></tt></a> is now a constant; code that binds a new value to the name <tt class="docutils literal"><span class="pre">None</span></tt> is now a syntax error.</li> <li>The <tt class="xref py py-func docutils literal"><span class="pre">signals.signal()</span></tt> function now raises 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> exception for certain illegal values; previously these errors would pass silently. For example, you can no longer set a handler on the <tt class="xref py py-const docutils literal"><span class="pre">SIGKILL</span></tt> signal.</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: Koray Can, Hye-Shik Chang, Michael Dyck, Raymond Hettinger, Brian Hurt, Hamish Lawson, Fredrik Lundh, Sean Reifschneider, Sadruddin Rejeb.</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.4</a><ul> <li><a class="reference internal" href="#pep-218-built-in-set-objects">PEP 218: Built-In Set Objects</a></li> <li><a class="reference internal" href="#pep-237-unifying-long-integers-and-integers">PEP 237: Unifying Long Integers and Integers</a></li> <li><a class="reference internal" href="#pep-289-generator-expressions">PEP 289: Generator Expressions</a></li> <li><a class="reference internal" href="#pep-292-simpler-string-substitutions">PEP 292: Simpler String Substitutions</a></li> <li><a class="reference internal" href="#pep-318-decorators-for-functions-and-methods">PEP 318: Decorators for Functions and Methods</a></li> <li><a class="reference internal" href="#pep-322-reverse-iteration">PEP 322: Reverse Iteration</a></li> <li><a class="reference internal" href="#pep-324-new-subprocess-module">PEP 324: New subprocess Module</a></li> <li><a class="reference internal" href="#pep-327-decimal-data-type">PEP 327: Decimal Data Type</a><ul> <li><a class="reference internal" href="#why-is-decimal-needed">Why is Decimal needed?</a></li> <li><a class="reference internal" href="#the-decimal-type">The <tt class="docutils literal"><span class="pre">Decimal</span></tt> type</a></li> <li><a class="reference internal" href="#the-context-type">The <tt class="docutils literal"><span class="pre">Context</span></tt> type</a></li> </ul> </li> <li><a class="reference internal" href="#pep-328-multi-line-imports">PEP 328: Multi-line Imports</a></li> <li><a class="reference internal" href="#pep-331-locale-independent-float-string-conversions">PEP 331: Locale-Independent Float/String Conversions</a></li> <li><a class="reference internal" href="#other-language-changes">Other Language Changes</a><ul> <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="#cookielib">cookielib</a></li> <li><a class="reference internal" href="#doctest">doctest</a></li> </ul> </li> <li><a class="reference internal" href="#build-and-c-api-changes">Build and C API Changes</a><ul> <li><a class="reference internal" href="#port-specific-changes">Port-Specific Changes</a></li> </ul> </li> <li><a class="reference internal" href="#porting-to-python-2-4">Porting to Python 2.4</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.5.html" title="previous chapter">What’s New in Python 2.5</a></p> <h4>Next topic</h4> <p class="topless"><a href="2.3.html" title="next chapter">What’s New in Python 2.3</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.4.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.3.html" title="What’s New in Python 2.3" >next</a> |</li> <li class="right" > <a href="2.5.html" title="What’s New in Python 2.5" >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>
Close