<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <link rel="STYLESHEET" href="whatsnew23.css" type='text/css' /> <link rel="SHORTCUT ICON" href="../icons/pyfav.gif" /> <link rel='start' href='../index.html' title='Python Documentation Index' /> <link rel="first" href="whatsnew23.html" title='What's New in Python 2.3' /> <link rel='contents' href='contents.html' title="Contents" /> <link rel='last' href='about.html' title='About this document...' /> <link rel='help' href='about.html' title='About this document...' /> <LINK rel="next" href="section-pymalloc.html"> <LINK rel="prev" href="node17.html"> <LINK rel="parent" href="whatsnew23.html"> <LINK rel="next" href="section-pymalloc.html"> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <meta name='aesop' content='information' /> <META name="description" content="New, Improved, and Deprecated Modules"> <META name="keywords" content="whatsnew23"> <META name="resource-type" content="document"> <META name="distribution" content="global"> <title>17 New, Improved, and Deprecated Modules</title> </head> <body> <DIV CLASS="navigation"> <div id='top-navigation-panel'> <table align="center" width="100%" cellpadding="0" cellspacing="2"> <tr> <td class='online-navigation'><a rel="prev" title="16 Other Language Changes" href="node17.html"><img src='../icons/previous.png' border='0' height='32' alt='Previous Page' width='32' /></A></td> <td class='online-navigation'><a rel="parent" title="What's New in Python" href="whatsnew23.html"><img src='../icons/up.png' border='0' height='32' alt='Up One Level' width='32' /></A></td> <td class='online-navigation'><a rel="next" title="18 Pymalloc: A Specialized" href="section-pymalloc.html"><img src='../icons/next.png' border='0' height='32' alt='Next Page' width='32' /></A></td> <td align="center" width="100%">What's New in Python 2.3</td> <td class='online-navigation'><a rel="contents" title="Table of Contents" href="contents.html"><img src='../icons/contents.png' border='0' height='32' alt='Contents' width='32' /></A></td> <td class='online-navigation'><img src='../icons/blank.png' border='0' height='32' alt='' width='32' /></td> <td class='online-navigation'><img src='../icons/blank.png' border='0' height='32' alt='' width='32' /></td> </tr></table> <div class='online-navigation'> <b class="navlabel">Previous:</b> <a class="sectref" rel="prev" href="node17.html">16 Other Language Changes</A> <b class="navlabel">Up:</b> <a class="sectref" rel="parent" href="whatsnew23.html">What's New in Python</A> <b class="navlabel">Next:</b> <a class="sectref" rel="next" href="section-pymalloc.html">18 Pymalloc: A Specialized</A> </div> <hr /></div> </DIV> <!--End of Navigation Panel--> <div class='online-navigation'> <!--Table of Child-Links--> <A NAME="CHILD_LINKS"><STRONG>Subsections</STRONG></a> <UL CLASS="ChildLinks"> <LI><A href="node18.html#SECTION0001810000000000000000">17.1 Date/Time Type</a> <LI><A href="node18.html#SECTION0001820000000000000000">17.2 The optparse Module</a> </ul> <!--End of Table of Child-Links--> </div> <HR> <H1><A NAME="SECTION0001800000000000000000"> 17 New, Improved, and Deprecated Modules</A> </H1> <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 <span class="file">Misc/NEWS</span> 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>The <tt class="module">array</tt> module now supports arrays of Unicode characters using the "<tt class="character">u</tt>" format character. Arrays also now support using the <code>+=</code> assignment operator to add another array's contents, and the <code>*=</code> assignment operator to repeat an array. (Contributed by Jason Orendorff.) <P> </LI> <LI>The <tt class="module">bsddb</tt> module has been replaced by version 4.1.6 of the <a class="ulink" href="http://pybsddb.sourceforge.net" >PyBSDDB</a> package, providing a more complete interface to the transactional features of the BerkeleyDB library. <P> The old version of the module has been renamed to <tt class="module">bsddb185</tt> and is no longer built automatically; you'll have to edit <span class="file">Modules/Setup</span> to enable it. Note that the new <tt class="module">bsddb</tt> package is intended to be compatible with the old module, so be sure to file bugs if you discover any incompatibilities. When upgrading to Python 2.3, if the new interpreter is compiled with a new version of the underlying BerkeleyDB library, you will almost certainly have to convert your database files to the new version. You can do this fairly easily with the new scripts <span class="file">db2pickle.py</span> and <span class="file">pickle2db.py</span> which you will find in the distribution's <span class="file">Tools/scripts</span> directory. If you've already been using the PyBSDDB package and importing it as <tt class="module">bsddb3</tt>, you will have to change your <code>import</code> statements to import it as <tt class="module">bsddb</tt>. <P> </LI> <LI>The new <tt class="module">bz2</tt> module is an interface to the bz2 data compression library. bz2-compressed data is usually smaller than corresponding <tt class="module">zlib</tt>-compressed data. (Contributed by Gustavo Niemeyer.) <P> </LI> <LI>A set of standard date/time types has been added in the new <tt class="module">datetime</tt> module. See the following section for more details. <P> </LI> <LI>The Distutils <tt class="class">Extension</tt> class now supports an extra constructor argument named <var>depends</var> for listing additional source files that an extension depends on. This lets Distutils recompile the module if any of the dependency files are modified. For example, if <span class="file">sampmodule.c</span> includes the header file <span class="file">sample.h</span>, you would create the <tt class="class">Extension</tt> object like this: <P> <div class="verbatim"><pre> ext = Extension("samp", sources=["sampmodule.c"], depends=["sample.h"]) </pre></div> <P> Modifying <span class="file">sample.h</span> would then cause the module to be recompiled. (Contributed by Jeremy Hylton.) <P> </LI> <LI>Other minor changes to Distutils: it now checks for the <a class="envvar" id='l2h-1'>CC</a>, <a class="envvar" id='l2h-2'>CFLAGS</a>, <a class="envvar" id='l2h-3'>CPP</a>, <a class="envvar" id='l2h-4'>LDFLAGS</a>, and <a class="envvar" id='l2h-5'>CPPFLAGS</a> environment variables, using them to override the settings in Python's configuration (contributed by Robert Weber). <P> </LI> <LI>Previously the <tt class="module">doctest</tt> module would only search the docstrings of public methods and functions for test cases, but it now also examines private ones as well. The <tt class="function">DocTestSuite(</tt> function creates a <tt class="class">unittest.TestSuite</tt> object from a set of <tt class="module">doctest</tt> tests. <P> </LI> <LI>The new <tt class="function">gc.get_referents(<var>object</var>)</tt> function returns a list of all the objects referenced by <var>object</var>. <P> </LI> <LI>The <tt class="module">getopt</tt> module gained a new function, <tt class="function">gnu_getopt()</tt>, that supports the same arguments as the existing <tt class="function">getopt()</tt> function but uses GNU-style scanning mode. The existing <tt class="function">getopt()</tt> stops processing options as soon as a non-option argument is encountered, but in GNU-style mode processing continues, meaning that options and arguments can be mixed. For example: <P> <div class="verbatim"><pre> >>> getopt.getopt(['-f', 'filename', 'output', '-v'], 'f:v') ([('-f', 'filename')], ['output', '-v']) >>> getopt.gnu_getopt(['-f', 'filename', 'output', '-v'], 'f:v') ([('-f', 'filename'), ('-v', '')], ['output']) </pre></div> <P> (Contributed by Peter Åstrand.) <P> </LI> <LI>The <tt class="module">grp</tt>, <tt class="module">pwd</tt>, and <tt class="module">resource</tt> modules now return enhanced tuples: <P> <div class="verbatim"><pre> >>> import grp >>> g = grp.getgrnam('amk') >>> g.gr_name, g.gr_gid ('amk', 500) </pre></div> <P> </LI> <LI>The <tt class="module">gzip</tt> module can now handle files exceeding 2 Gb. <P> </LI> <LI>The new <tt class="module">heapq</tt> module contains an implementation of a heap queue algorithm. A heap is an array-like data structure that keeps items in a partially sorted order such that, for every index <var>k</var>, <code>heap[<var>k</var>] <= heap[2*<var>k</var>+1]</code> and <code>heap[<var>k</var>] <= heap[2*<var>k</var>+2]</code>. This makes it quick to remove the smallest item, and inserting a new item while maintaining the heap property is O(lg n). (See <a class="url" href="http://www.nist.gov/dads/HTML/priorityque.html">http://www.nist.gov/dads/HTML/priorityque.html</a> for more information about the priority queue data structure.) <P> The <tt class="module">heapq</tt> module provides <tt class="function">heappush()</tt> and <tt class="function">heappop()</tt> functions for adding and removing items while maintaining the heap property on top of some other mutable Python sequence type. Here's an example that uses a Python list: <P> <div class="verbatim"><pre> >>> import heapq >>> heap = [] >>> for item in [3, 7, 5, 11, 1]: ... heapq.heappush(heap, item) ... >>> heap [1, 3, 5, 11, 7] >>> heapq.heappop(heap) 1 >>> heapq.heappop(heap) 3 >>> heap [5, 7, 11] </pre></div> <P> (Contributed by Kevin O'Connor.) <P> </LI> <LI>The IDLE integrated development environment has been updated using the code from the IDLEfork project (<a class="url" href="http://idlefork.sf.net">http://idlefork.sf.net</a>). The most notable feature is that the code being developed is now executed in a subprocess, meaning that there's no longer any need for manual <code>reload()</code> operations. IDLE's core code has been incorporated into the standard library as the <tt class="module">idlelib</tt> package. <P> </LI> <LI>The <tt class="module">imaplib</tt> module now supports IMAP over SSL. (Contributed by Piers Lauder and Tino Lange.) <P> </LI> <LI>The <tt class="module">itertools</tt> contains a number of useful functions for use with iterators, inspired by various functions provided by the ML and Haskell languages. For example, <code>itertools.ifilter(predicate, iterator)</code> returns all elements in the iterator for which the function <tt class="function">predicate()</tt> returns <tt class="constant">True</tt>, and <code>itertools.repeat(obj, <var>N</var>)</code> returns <code>obj</code> <var>N</var> times. There are a number of other functions in the module; see the <a class="ulink" href="../lib/module-itertools.html" >package's reference documentation</a> for details. (Contributed by Raymond Hettinger.) <P> </LI> <LI>Two new functions in the <tt class="module">math</tt> module, <tt class="function">degrees(<var>rads</var>)</tt> and <tt class="function">radians(<var>degs</var>)</tt>, convert between radians and degrees. Other functions in the <tt class="module">math</tt> module such as <tt class="function">math.sin()</tt> and <tt class="function">math.cos()</tt> have always required input values measured in radians. Also, an optional <var>base</var> argument was added to <tt class="function">math.log()</tt> to make it easier to compute logarithms for bases other than <code>e</code> and <code>10</code>. (Contributed by Raymond Hettinger.) <P> </LI> <LI>Several new POSIX functions (<tt class="function">getpgid()</tt>, <tt class="function">killpg()</tt>, <tt class="function">lchown()</tt>, <tt class="function">loadavg()</tt>, <tt class="function">major()</tt>, <tt class="function">makedev()</tt>, <tt class="function">minor()</tt>, and <tt class="function">mknod()</tt>) were added to the <tt class="module">posix</tt> module that underlies the <tt class="module">os</tt> module. (Contributed by Gustavo Niemeyer, Geert Jansen, and Denis S. Otkidach.) <P> </LI> <LI>In the <tt class="module">os</tt> module, the <tt class="function">*stat()</tt> family of functions can now report fractions of a second in a timestamp. Such time stamps are represented as floats, similar to the value returned by <tt class="function">time.time()</tt>. <P> During testing, it was found that some applications will break if time stamps are floats. For compatibility, when using the tuple interface of the <tt class="class">stat_result</tt> time stamps will be represented as integers. When using named fields (a feature first introduced in Python 2.2), time stamps are still represented as integers, unless <tt class="function">os.stat_float_times()</tt> is invoked to enable float return values: <P> <div class="verbatim"><pre> >>> os.stat("/tmp").st_mtime 1034791200 >>> os.stat_float_times(True) >>> os.stat("/tmp").st_mtime 1034791200.6335014 </pre></div> <P> In Python 2.4, the default will change to always returning floats. <P> Application developers should enable this feature only if all their libraries work properly when confronted with floating point time stamps, or if they use the tuple API. If used, the feature should be activated on an application level instead of trying to enable it on a per-use basis. <P> </LI> <LI>The <tt class="module">optparse</tt> module contains a new parser for command-line arguments that can convert option values to a particular Python type and will automatically generate a usage message. See the following section for more details. <P> </LI> <LI>The old and never-documented <tt class="module">linuxaudiodev</tt> module has been deprecated, and a new version named <tt class="module">ossaudiodev</tt> has been added. The module was renamed because the OSS sound drivers can be used on platforms other than Linux, and the interface has also been tidied and brought up to date in various ways. (Contributed by Greg Ward and Nicholas FitzRoy-Dale.) <P> </LI> <LI>The new <tt class="module">platform</tt> module contains a number of functions that try to determine various properties of the platform you're running on. There are functions for getting the architecture, CPU type, the Windows OS version, and even the Linux distribution version. (Contributed by Marc-André Lemburg.) <P> </LI> <LI>The parser objects provided by the <tt class="module">pyexpat</tt> module can now optionally buffer character data, resulting in fewer calls to your character data handler and therefore faster performance. Setting the parser object's <tt class="member">buffer_text</tt> attribute to <tt class="constant">True</tt> will enable buffering. <P> </LI> <LI>The <tt class="function">sample(<var>population</var>, <var>k</var>)</tt> function was added to the <tt class="module">random</tt> module. <var>population</var> is a sequence or <tt class="class">xrange</tt> object containing the elements of a population, and <tt class="function">sample()</tt> chooses <var>k</var> elements from the population without replacing chosen elements. <var>k</var> can be any value up to <code>len(<var>population</var>)</code>. For example: <P> <div class="verbatim"><pre> >>> days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'St', 'Sn'] >>> random.sample(days, 3) # Choose 3 elements ['St', 'Sn', 'Th'] >>> random.sample(days, 7) # Choose 7 elements ['Tu', 'Th', 'Mo', 'We', 'St', 'Fr', 'Sn'] >>> random.sample(days, 7) # Choose 7 again ['We', 'Mo', 'Sn', 'Fr', 'Tu', 'St', 'Th'] >>> random.sample(days, 8) # Can't choose eight Traceback (most recent call last): File "<stdin>", line 1, in ? File "random.py", line 414, in sample raise ValueError, "sample larger than population" ValueError: sample larger than population >>> random.sample(xrange(1,10000,2), 10) # Choose ten odd nos. under 10000 [3407, 3805, 1505, 7023, 2401, 2267, 9733, 3151, 8083, 9195] </pre></div> <P> The <tt class="module">random</tt> module now uses a new algorithm, the Mersenne Twister, implemented in C. It's faster and more extensively studied than the previous algorithm. <P> (All changes contributed by Raymond Hettinger.) <P> </LI> <LI>The <tt class="module">readline</tt> module also gained a number of new functions: <tt class="function">get_history_item()</tt>, <tt class="function">get_current_history_length()</tt>, and <tt class="function">redisplay()</tt>. <P> </LI> <LI>The <tt class="module">rexec</tt> and <tt class="module">Bastion</tt> modules have been declared dead, and attempts to import them will fail with a <tt class="exception">RuntimeError</tt>. New-style classes provide new ways to break out of the restricted execution environment provided by <tt class="module">rexec</tt>, and no one has interest in fixing them or time to do so. If you have applications using <tt class="module">rexec</tt>, rewrite them to use something else. <P> (Sticking with Python 2.2 or 2.1 will not make your applications any safer because there are known bugs in the <tt class="module">rexec</tt> module in those versions. To repeat: if you're using <tt class="module">rexec</tt>, stop using it immediately.) <P> </LI> <LI>The <tt class="module">rotor</tt> module has been deprecated because the algorithm it uses for encryption is not believed to be secure. If you need encryption, use one of the several AES Python modules that are available separately. <P> </LI> <LI>The <tt class="module">shutil</tt> module gained a <tt class="function">move(<var>src</var>, <var>dest</var>)</tt> function that recursively moves a file or directory to a new location. <P> </LI> <LI>Support for more advanced POSIX signal handling was added to the <tt class="module">signal</tt> but then removed again as it proved impossible to make it work reliably across platforms. <P> </LI> <LI>The <tt class="module">socket</tt> module now supports timeouts. You can call the <tt class="method">settimeout(<var>t</var>)</tt> method on a socket object to set a timeout of <var>t</var> seconds. Subsequent socket operations that take longer than <var>t</var> seconds to complete will abort and raise a <tt class="exception">socket.timeout</tt> exception. <P> The original timeout implementation was by Tim O'Malley. Michael Gilfix integrated it into the Python <tt class="module">socket</tt> module and shepherded it through a lengthy review. After the code was checked in, Guido van Rossum rewrote parts of it. (This is a good example of a collaborative development process in action.) <P> </LI> <LI>On Windows, the <tt class="module">socket</tt> module now ships with Secure Sockets Layer (SSL) support. <P> </LI> <LI>The value of the C <tt class="constant">PYTHON_API_VERSION</tt> macro is now exposed at the Python level as <code>sys.api_version</code>. The current exception can be cleared by calling the new <tt class="function">sys.exc_clear()</tt> function. <P> </LI> <LI>The new <tt class="module">tarfile</tt> module allows reading from and writing to <b class="program">tar</b>-format archive files. (Contributed by Lars Gustäbel.) <P> </LI> <LI>The new <tt class="module">textwrap</tt> module contains functions for wrapping strings containing paragraphs of text. The <tt class="function">wrap(<var>text</var>, <var>width</var>)</tt> function takes a string and returns a list containing the text split into lines of no more than the chosen width. The <tt class="function">fill(<var>text</var>, <var>width</var>)</tt> function returns a single string, reformatted to fit into lines no longer than the chosen width. (As you can guess, <tt class="function">fill()</tt> is built on top of <tt class="function">wrap()</tt>. For example: <P> <div class="verbatim"><pre> >>> import textwrap >>> paragraph = "Not a whit, we defy augury: ... more text ..." >>> textwrap.wrap(paragraph, 60) ["Not a whit, we defy augury: there's a special providence in", "the fall of a sparrow. If it be now, 'tis not to come; if it", ...] >>> print textwrap.fill(paragraph, 35) Not a whit, we defy augury: there's a special providence in the fall of a sparrow. If it be now, 'tis not to come; if it be not to come, it will be now; if it be not now, yet it will come: the readiness is all. >>> </pre></div> <P> The module also contains a <tt class="class">TextWrapper</tt> class that actually implements the text wrapping strategy. Both the <tt class="class">TextWrapper</tt> class and the <tt class="function">wrap()</tt> and <tt class="function">fill()</tt> functions support a number of additional keyword arguments for fine-tuning the formatting; consult the <a class="ulink" href="../lib/module-textwrap.html" >module's documentation</a> for details. (Contributed by Greg Ward.) <P> </LI> <LI>The <tt class="module">thread</tt> and <tt class="module">threading</tt> modules now have companion modules, <tt class="module">dummy_thread</tt> and <tt class="module">dummy_threading</tt>, that provide a do-nothing implementation of the <tt class="module">thread</tt> module's interface for platforms where threads are not supported. The intention is to simplify thread-aware modules (ones that <i>don't</i> rely on threads to run) by putting the following code at the top: <P> <div class="verbatim"><pre> try: import threading as _threading except ImportError: import dummy_threading as _threading </pre></div> <P> In this example, <tt class="module">_threading</tt> is used as the module name to make it clear that the module being used is not necessarily the actual <tt class="module">threading</tt> module. Code can call functions and use classes in <tt class="module">_threading</tt> whether or not threads are supported, avoiding an <tt class="keyword">if</tt> statement and making the code slightly clearer. This module will not magically make multithreaded code run without threads; code that waits for another thread to return or to do something will simply hang forever. <P> </LI> <LI>The <tt class="module">time</tt> module's <tt class="function">strptime()</tt> function has long been an annoyance because it uses the platform C library's <tt class="function">strptime()</tt> implementation, and different platforms sometimes have odd bugs. Brett Cannon contributed a portable implementation that's written in pure Python and should behave identically on all platforms. <P> </LI> <LI>The new <tt class="module">timeit</tt> module helps measure how long snippets of Python code take to execute. The <span class="file">timeit.py</span> file can be run directly from the command line, or the module's <tt class="class">Timer</tt> class can be imported and used directly. Here's a short example that figures out whether it's faster to convert an 8-bit string to Unicode by appending an empty Unicode string to it or by using the <tt class="function">unicode()</tt> function: <P> <div class="verbatim"><pre> import timeit timer1 = timeit.Timer('unicode("abc")') timer2 = timeit.Timer('"abc" + u""') # Run three trials print timer1.repeat(repeat=3, number=100000) print timer2.repeat(repeat=3, number=100000) # On my laptop this outputs: # [0.36831796169281006, 0.37441694736480713, 0.35304892063140869] # [0.17574405670166016, 0.18193507194519043, 0.17565798759460449] </pre></div> <P> </LI> <LI>The <tt class="module">Tix</tt> module has received various bug fixes and updates for the current version of the Tix package. <P> </LI> <LI>The <tt class="module">Tkinter</tt> module now works with a thread-enabled version of Tcl. Tcl's threading model requires that widgets only be accessed from the thread in which they're created; accesses from another thread can cause Tcl to panic. For certain Tcl interfaces, <tt class="module">Tkinter</tt> will now automatically avoid this when a widget is accessed from a different thread by marshalling a command, passing it to the correct thread, and waiting for the results. Other interfaces can't be handled automatically but <tt class="module">Tkinter</tt> will now raise an exception on such an access so that you can at least find out about the problem. See <a class="url" href="http://mail.python.org/pipermail/python-dev/2002-December/031107.html">http://mail.python.org/pipermail/python-dev/2002-December/031107.html</a> for a more detailed explanation of this change. (Implemented by Martin von Löwis.) <P> </LI> <LI>Calling Tcl methods through <tt class="module">_tkinter</tt> no longer returns only strings. Instead, if Tcl returns other objects those objects are converted to their Python equivalent, if one exists, or wrapped with a <tt class="class">_tkinter.Tcl_Obj</tt> object if no Python equivalent exists. This behavior can be controlled through the <tt class="method">wantobjects()</tt> method of <tt class="class">tkapp</tt> objects. <P> When using <tt class="module">_tkinter</tt> through the <tt class="module">Tkinter</tt> module (as most Tkinter applications will), this feature is always activated. It should not cause compatibility problems, since Tkinter would always convert string results to Python types where possible. <P> If any incompatibilities are found, the old behavior can be restored by setting the <tt class="member">wantobjects</tt> variable in the <tt class="module">Tkinter</tt> module to false before creating the first <tt class="class">tkapp</tt> object. <P> <div class="verbatim"><pre> import Tkinter Tkinter.wantobjects = 0 </pre></div> <P> Any breakage caused by this change should be reported as a bug. <P> </LI> <LI>The <tt class="module">UserDict</tt> module has a new <tt class="class">DictMixin</tt> class which defines all dictionary methods for classes that already have a minimum mapping interface. This greatly simplifies writing classes that need to be substitutable for dictionaries, such as the classes in the <tt class="module">shelve</tt> module. <P> Adding the mix-in as a superclass provides the full dictionary interface whenever the class defines <tt class="method">__getitem__</tt>, <tt class="method">__setitem__</tt>, <tt class="method">__delitem__</tt>, and <tt class="method">keys</tt>. For example: <P> <div class="verbatim"><pre> >>> import UserDict >>> class SeqDict(UserDict.DictMixin): ... """Dictionary lookalike implemented with lists.""" ... def __init__(self): ... self.keylist = [] ... self.valuelist = [] ... def __getitem__(self, key): ... try: ... i = self.keylist.index(key) ... except ValueError: ... raise KeyError ... return self.valuelist[i] ... def __setitem__(self, key, value): ... try: ... i = self.keylist.index(key) ... self.valuelist[i] = value ... except ValueError: ... self.keylist.append(key) ... self.valuelist.append(value) ... def __delitem__(self, key): ... try: ... i = self.keylist.index(key) ... except ValueError: ... raise KeyError ... self.keylist.pop(i) ... self.valuelist.pop(i) ... def keys(self): ... return list(self.keylist) ... >>> s = SeqDict() >>> dir(s) # See that other dictionary methods are implemented ['__cmp__', '__contains__', '__delitem__', '__doc__', '__getitem__', '__init__', '__iter__', '__len__', '__module__', '__repr__', '__setitem__', 'clear', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keylist', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'valuelist', 'values'] </pre></div> <P> (Contributed by Raymond Hettinger.) <P> </LI> <LI>The DOM implementation in <tt class="module">xml.dom.minidom</tt> can now generate XML output in a particular encoding by providing an optional encoding argument to the <tt class="method">toxml()</tt> and <tt class="method">toprettyxml()</tt> methods of DOM nodes. <P> </LI> <LI>The <tt class="module">xmlrpclib</tt> module now supports an XML-RPC extension for handling nil data values such as Python's <code>None</code>. Nil values are always supported on unmarshalling an XML-RPC response. To generate requests containing <code>None</code>, you must supply a true value for the <var>allow_none</var> parameter when creating a <tt class="class">Marshaller</tt> instance. <P> </LI> <LI>The new <tt class="module">DocXMLRPCServer</tt> module allows writing self-documenting XML-RPC servers. Run it in demo mode (as a program) to see it in action. Pointing the Web browser to the RPC server produces pydoc-style documentation; pointing xmlrpclib to the server allows invoking the actual methods. (Contributed by Brian Quinlan.) <P> </LI> <LI>Support for internationalized domain names (RFCs 3454, 3490, 3491, and 3492) has been added. The ``idna'' encoding can be used to convert between a Unicode domain name and the ASCII-compatible encoding (ACE) of that name. <P> <div class="verbatim"><pre><TT> >>> u"www.Alliancefran¸ caise.nu".encode("idna") 'www.xn--alliancefranaise-npb.nu' </TT></pre></div> <P> The <tt class="module">socket</tt> module has also been extended to transparently convert Unicode hostnames to the ACE version before passing them to the C library. Modules that deal with hostnames such as <tt class="module">httplib</tt> and <tt class="module">ftplib</tt>) also support Unicode host names; <tt class="module">httplib</tt> also sends HTTP "<tt class="samp">Host</tt>" headers using the ACE version of the domain name. <tt class="module">urllib</tt> supports Unicode URLs with non-ASCII host names as long as the <code>path</code> part of the URL is ASCII only. <P> To implement this change, the <tt class="module">stringprep</tt> module, the <code>mkstringprep</code> tool and the <code>punycode</code> encoding have been added. <P> </LI> </UL> <P> <H2><A NAME="SECTION0001810000000000000000"> 17.1 Date/Time Type</A> </H2> <P> Date and time types suitable for expressing timestamps were added as the <tt class="module">datetime</tt> module. The types don't support different calendars or many fancy features, and just stick to the basics of representing time. <P> The three primary types are: <tt class="class">date</tt>, representing a day, month, and year; <tt class="class">time</tt>, consisting of hour, minute, and second; and <tt class="class">datetime</tt>, which contains all the attributes of both <tt class="class">date</tt> and <tt class="class">time</tt>. There's also a <tt class="class">timedelta</tt> class representing differences between two points in time, and time zone logic is implemented by classes inheriting from the abstract <tt class="class">tzinfo</tt> class. <P> You can create instances of <tt class="class">date</tt> and <tt class="class">time</tt> by either supplying keyword arguments to the appropriate constructor, e.g. <code>datetime.date(year=1972, month=10, day=15)</code>, or by using one of a number of class methods. For example, the <tt class="method">date.today()</tt> class method returns the current local date. <P> Once created, instances of the date/time classes are all immutable. There are a number of methods for producing formatted strings from objects: <P> <div class="verbatim"><pre> >>> import datetime >>> now = datetime.datetime.now() >>> now.isoformat() '2002-12-30T21:27:03.994956' >>> now.ctime() # Only available on date, datetime 'Mon Dec 30 21:27:03 2002' >>> now.strftime('%Y %d %b') '2002 30 Dec' </pre></div> <P> The <tt class="method">replace()</tt> method allows modifying one or more fields of a <tt class="class">date</tt> or <tt class="class">datetime</tt> instance, returning a new instance: <P> <div class="verbatim"><pre> >>> d = datetime.datetime.now() >>> d datetime.datetime(2002, 12, 30, 22, 15, 38, 827738) >>> d.replace(year=2001, hour = 12) datetime.datetime(2001, 12, 30, 12, 15, 38, 827738) >>> </pre></div> <P> Instances can be compared, hashed, and converted to strings (the result is the same as that of <tt class="method">isoformat()</tt>). <tt class="class">date</tt> and <tt class="class">datetime</tt> instances can be subtracted from each other, and added to <tt class="class">timedelta</tt> instances. The largest missing feature is that there's no standard library support for parsing strings and getting back a <tt class="class">date</tt> or <tt class="class">datetime</tt>. <P> For more information, refer to the <a class="ulink" href="../lib/module-datetime.html" >module's reference documentation</a>. (Contributed by Tim Peters.) <P> <H2><A NAME="SECTION0001820000000000000000"> 17.2 The optparse Module</A> </H2> <P> The <tt class="module">getopt</tt> module provides simple parsing of command-line arguments. The new <tt class="module">optparse</tt> module (originally named Optik) provides more elaborate command-line parsing that follows the Unix conventions, automatically creates the output for <b class="programopt">--help</b>, and can perform different actions for different options. <P> You start by creating an instance of <tt class="class">OptionParser</tt> and telling it what your program's options are. <P> <div class="verbatim"><pre> import sys from optparse import OptionParser op = OptionParser() op.add_option('-i', '--input', action='store', type='string', dest='input', help='set input filename') op.add_option('-l', '--length', action='store', type='int', dest='length', help='set maximum length of output') </pre></div> <P> Parsing a command line is then done by calling the <tt class="method">parse_args()</tt> method. <P> <div class="verbatim"><pre> options, args = op.parse_args(sys.argv[1:]) print options print args </pre></div> <P> This returns an object containing all of the option values, and a list of strings containing the remaining arguments. <P> Invoking the script with the various arguments now works as you'd expect it to. Note that the length argument is automatically converted to an integer. <P> <div class="verbatim"><pre> $ ./python opt.py -i data arg1 <Values at 0x400cad4c: {'input': 'data', 'length': None}> ['arg1'] $ ./python opt.py --input=data --length=4 <Values at 0x400cad2c: {'input': 'data', 'length': 4}> [] $ </pre></div> <P> The help message is automatically generated for you: <P> <div class="verbatim"><pre> $ ./python opt.py --help usage: opt.py [options] options: -h, --help show this help message and exit -iINPUT, --input=INPUT set input filename -lLENGTH, --length=LENGTH set maximum length of output $ </pre></div> <P> See the <a class="ulink" href="../lib/module-optparse.html" >module's documentation</a> for more details. <P> Optik was written by Greg Ward, with suggestions from the readers of the Getopt SIG. <P> <DIV CLASS="navigation"> <div class='online-navigation'><hr /> <table align="center" width="100%" cellpadding="0" cellspacing="2"> <tr> <td class='online-navigation'><a rel="prev" title="16 Other Language Changes" rel="prev" title="16 Other Language Changes" href="node17.html"><img src='../icons/previous.png' border='0' height='32' alt='Previous Page' width='32' /></A></td> <td class='online-navigation'><a rel="parent" title="What's New in Python" rel="parent" title="What's New in Python" href="whatsnew23.html"><img src='../icons/up.png' border='0' height='32' alt='Up One Level' width='32' /></A></td> <td class='online-navigation'><a rel="next" title="18 Pymalloc: A Specialized" rel="next" title="18 Pymalloc: A Specialized" href="section-pymalloc.html"><img src='../icons/next.png' border='0' height='32' alt='Next Page' width='32' /></A></td> <td align="center" width="100%">What's New in Python 2.3</td> <td class='online-navigation'><a rel="contents" title="Table of Contents" rel="contents" title="Table of Contents" href="contents.html"><img src='../icons/contents.png' border='0' height='32' alt='Contents' width='32' /></A></td> <td class='online-navigation'><img src='../icons/blank.png' border='0' height='32' alt='' width='32' /></td> <td class='online-navigation'><img src='../icons/blank.png' border='0' height='32' alt='' width='32' /></td> </tr></table> <div class='online-navigation'> <b class="navlabel">Previous:</b> <a class="sectref" rel="prev" href="node17.html">16 Other Language Changes</A> <b class="navlabel">Up:</b> <a class="sectref" rel="parent" href="whatsnew23.html">What's New in Python</A> <b class="navlabel">Next:</b> <a class="sectref" rel="next" href="section-pymalloc.html">18 Pymalloc: A Specialized</A> </div> </div> <hr /> <span class="release-info">Release 1.00.</span> </DIV> <!--End of Navigation Panel--> <ADDRESS> See <i><a href="about.html">About this document...</a></i> for information on suggesting changes. </ADDRESS> </BODY> </HTML>