Initial commit of OpenSPARC T2 architecture model.
[OpenSPARC-T2-SAM] / sam-t2 / devtools / v9 / html / python / whatsnew / node13.html
CommitLineData
920dae64
AT
1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2<html>
3<head>
4<link rel="STYLESHEET" href="whatsnew24.css" type='text/css' />
5<link rel="SHORTCUT ICON" href="../icons/pyfav.png" type="image/png" />
6<link rel='start' href='../index.html' title='Python Documentation Index' />
7<link rel="first" href="whatsnew24.html" title='What's New in Python 2.4' />
8<link rel='contents' href='contents.html' title="Contents" />
9<link rel='last' href='about.html' title='About this document...' />
10<link rel='help' href='about.html' title='About this document...' />
11<link rel="next" href="node14.html" />
12<link rel="prev" href="node12.html" />
13<link rel="parent" href="whatsnew24.html" />
14<link rel="next" href="node14.html" />
15<meta name='aesop' content='information' />
16<title>12 New, Improved, and Deprecated Modules</title>
17</head>
18<body>
19<DIV CLASS="navigation">
20<div id='top-navigation-panel' xml:id='top-navigation-panel'>
21<table align="center" width="100%" cellpadding="0" cellspacing="2">
22<tr>
23<td class='online-navigation'><a rel="prev" title="11 Other Language Changes"
24 href="node12.html"><img src='../icons/previous.png'
25 border='0' height='32' alt='Previous Page' width='32' /></A></td>
26<td class='online-navigation'><a rel="parent" title="What's New in Python"
27 href="whatsnew24.html"><img src='../icons/up.png'
28 border='0' height='32' alt='Up One Level' width='32' /></A></td>
29<td class='online-navigation'><a rel="next" title="13 Build and C"
30 href="node14.html"><img src='../icons/next.png'
31 border='0' height='32' alt='Next Page' width='32' /></A></td>
32<td align="center" width="100%">What's New in Python 2.4</td>
33<td class='online-navigation'><a rel="contents" title="Table of Contents"
34 href="contents.html"><img src='../icons/contents.png'
35 border='0' height='32' alt='Contents' width='32' /></A></td>
36<td class='online-navigation'><img src='../icons/blank.png'
37 border='0' height='32' alt='' width='32' /></td>
38<td class='online-navigation'><img src='../icons/blank.png'
39 border='0' height='32' alt='' width='32' /></td>
40</tr></table>
41<div class='online-navigation'>
42<b class="navlabel">Previous:</b>
43<a class="sectref" rel="prev" href="node12.html">11 Other Language Changes</A>
44<b class="navlabel">Up:</b>
45<a class="sectref" rel="parent" href="whatsnew24.html">What's New in Python</A>
46<b class="navlabel">Next:</b>
47<a class="sectref" rel="next" href="node14.html">13 Build and C</A>
48</div>
49<hr /></div>
50</DIV>
51<!--End of Navigation Panel-->
52<div class='online-navigation'>
53<!--Table of Child-Links-->
54<A NAME="CHILD_LINKS"><STRONG>Subsections</STRONG></a>
55
56<UL CLASS="ChildLinks">
57<LI><A href="node13.html#SECTION0001310000000000000000">12.1 cookielib</a>
58<LI><A href="node13.html#SECTION0001320000000000000000">12.2 doctest</a>
59</ul>
60<!--End of Table of Child-Links-->
61</div>
62<HR>
63
64<H1><A NAME="SECTION0001300000000000000000">
6512 New, Improved, and Deprecated Modules</A>
66</H1>
67
68<P>
69As usual, Python's standard library received a number of enhancements and
70bug fixes. Here's a partial list of the most notable changes, sorted
71alphabetically by module name. Consult the
72<span class="file">Misc/NEWS</span> file in the source tree for a more
73complete list of changes, or look through the CVS logs for all the
74details.
75
76<P>
77
78<UL>
79<LI>The <tt class="module">asyncore</tt> module's <tt class="function">loop()</tt> function now
80 has a <var>count</var> parameter that lets you perform a limited number
81 of passes through the polling loop. The default is still to loop
82 forever.
83
84<P>
85</LI>
86<LI>The <tt class="module">base64</tt> module now has more complete RFC 3548 support
87 for Base64, Base32, and Base16 encoding and decoding, including
88 optional case folding and optional alternative alphabets.
89 (Contributed by Barry Warsaw.)
90
91<P>
92</LI>
93<LI>The <tt class="module">bisect</tt> module now has an underlying C implementation
94 for improved performance.
95 (Contributed by Dmitry Vasiliev.)
96
97<P>
98</LI>
99<LI>The CJKCodecs collections of East Asian codecs, maintained
100by Hye-Shik Chang, was integrated into 2.4.
101The new encodings are:
102
103<P>
104
105<UL>
106<LI>Chinese (PRC): gb2312, gbk, gb18030, big5hkscs, hz
107</LI>
108<LI>Chinese (ROC): big5, cp950
109</LI>
110<LI>Japanese: cp932, euc-jis-2004, euc-jp,
111euc-jisx0213, iso-2022-jp, iso-2022-jp-1, iso-2022-jp-2,
112 iso-2022-jp-3, iso-2022-jp-ext, iso-2022-jp-2004,
113 shift-jis, shift-jisx0213, shift-jis-2004
114</LI>
115<LI>Korean: cp949, euc-kr, johab, iso-2022-kr
116</LI>
117</UL>
118
119<P>
120</LI>
121<LI>Some other new encodings were added: HP Roman8,
122ISO_8859-11, ISO_8859-16, PCTP-154, and TIS-620.
123
124<P>
125</LI>
126<LI>The UTF-8 and UTF-16 codecs now cope better with receiving partial input.
127Previously the <tt class="class">StreamReader</tt> class would try to read more data,
128making it impossible to resume decoding from the stream. The
129<tt class="method">read()</tt> method will now return as much data as it can and future
130calls will resume decoding where previous ones left off.
131(Implemented by Walter D&#246;rwald.)
132
133<P>
134</LI>
135<LI>There is a new <tt class="module">collections</tt> module for
136 various specialized collection datatypes.
137 Currently it contains just one type, <tt class="class">deque</tt>,
138 a double-ended queue that supports efficiently adding and removing
139 elements from either end:
140
141<P>
142<div class="verbatim"><pre>
143&gt;&gt;&gt; from collections import deque
144&gt;&gt;&gt; d = deque('ghi') # make a new deque with three items
145&gt;&gt;&gt; d.append('j') # add a new entry to the right side
146&gt;&gt;&gt; d.appendleft('f') # add a new entry to the left side
147&gt;&gt;&gt; d # show the representation of the deque
148deque(['f', 'g', 'h', 'i', 'j'])
149&gt;&gt;&gt; d.pop() # return and remove the rightmost item
150'j'
151&gt;&gt;&gt; d.popleft() # return and remove the leftmost item
152'f'
153&gt;&gt;&gt; list(d) # list the contents of the deque
154['g', 'h', 'i']
155&gt;&gt;&gt; 'h' in d # search the deque
156True
157</pre></div>
158
159<P>
160Several modules, such as the <tt class="module">Queue</tt> and <tt class="module">threading</tt>
161modules, now take advantage of <tt class="class">collections.deque</tt> for improved
162performance. (Contributed by Raymond Hettinger.)
163
164<P>
165</LI>
166<LI>The <tt class="module">ConfigParser</tt> classes have been enhanced slightly.
167 The <tt class="method">read()</tt> method now returns a list of the files that
168 were successfully parsed, and the <tt class="method">set()</tt> method raises
169 <tt class="exception">TypeError</tt> if passed a <var>value</var> argument that isn't a
170 string. (Contributed by John Belmonte and David Goodger.)
171
172<P>
173</LI>
174<LI>The <tt class="module">curses</tt> module now supports the ncurses extension
175 <tt class="function">use_default_colors()</tt>. On platforms where the terminal
176 supports transparency, this makes it possible to use a transparent
177 background. (Contributed by J&#246;rg Lehmann.)
178
179<P>
180</LI>
181<LI>The <tt class="module">difflib</tt> module now includes an <tt class="class">HtmlDiff</tt> class
182that creates an HTML table showing a side by side comparison
183of two versions of a text. (Contributed by Dan Gass.)
184
185<P>
186</LI>
187<LI>The <tt class="module">email</tt> package was updated to version 3.0,
188which dropped various deprecated APIs and removes support for Python
189versions earlier than 2.3. The 3.0 version of the package uses a new
190incremental parser for MIME messages, available in the
191<tt class="module">email.FeedParser</tt> module. The new parser doesn't require
192reading the entire message into memory, and doesn't throw exceptions
193if a message is malformed; instead it records any problems in the
194<tt class="member">defect</tt> attribute of the message. (Developed by Anthony
195Baxter, Barry Warsaw, Thomas Wouters, and others.)
196
197<P>
198</LI>
199<LI>The <tt class="module">heapq</tt> module has been converted to C. The resulting
200 tenfold improvement in speed makes the module suitable for handling
201 high volumes of data. In addition, the module has two new functions
202 <tt class="function">nlargest()</tt> and <tt class="function">nsmallest()</tt> that use heaps to
203 find the N largest or smallest values in a dataset without the
204 expense of a full sort. (Contributed by Raymond Hettinger.)
205
206<P>
207</LI>
208<LI>The <tt class="module">httplib</tt> module now contains constants for HTTP
209status codes defined in various HTTP-related RFC documents. Constants
210have names such as <tt class="constant">OK</tt>, <tt class="constant">CREATED</tt>,
211<tt class="constant">CONTINUE</tt>, and <tt class="constant">MOVED_PERMANENTLY</tt>; use pydoc to
212get a full list. (Contributed by Andrew Eland.)
213
214<P>
215</LI>
216<LI>The <tt class="module">imaplib</tt> module now supports IMAP's THREAD command
217(contributed by Yves Dionne) and new <tt class="method">deleteacl()</tt> and
218<tt class="method">myrights()</tt> methods (contributed by Arnaud Mazin).
219
220<P>
221</LI>
222<LI>The <tt class="module">itertools</tt> module gained a
223 <tt class="function">groupby(<var>iterable</var><big>[</big>, <var>func</var><big>]</big>)</tt> function.
224 <var>iterable</var> is something that can be iterated over to return a
225 stream of elements, and the optional <var>func</var> parameter is a
226 function that takes an element and returns a key value; if omitted,
227 the key is simply the element itself. <tt class="function">groupby()</tt> then
228 groups the elements into subsequences which have matching values of
229 the key, and returns a series of 2-tuples containing the key value
230 and an iterator over the subsequence.
231
232<P>
233Here's an example to make this clearer. The <var>key</var> function simply
234returns whether a number is even or odd, so the result of
235<tt class="function">groupby()</tt> is to return consecutive runs of odd or even
236numbers.
237
238<P>
239<div class="verbatim"><pre>
240&gt;&gt;&gt; import itertools
241&gt;&gt;&gt; L = [2, 4, 6, 7, 8, 9, 11, 12, 14]
242&gt;&gt;&gt; for key_val, it in itertools.groupby(L, lambda x: x % 2):
243... print key_val, list(it)
244...
2450 [2, 4, 6]
2461 [7]
2470 [8]
2481 [9, 11]
2490 [12, 14]
250&gt;&gt;&gt;
251</pre></div>
252
253<P>
254<tt class="function">groupby()</tt> is typically used with sorted input. The logic
255for <tt class="function">groupby()</tt> is similar to the <span class="Unix">Unix</span> <code>uniq</code> filter
256which makes it handy for eliminating, counting, or identifying
257duplicate elements:
258
259<P>
260<div class="verbatim"><pre>
261&gt;&gt;&gt; word = 'abracadabra'
262&gt;&gt;&gt; letters = sorted(word) # Turn string into a sorted list of letters
263&gt;&gt;&gt; letters
264['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r']
265&gt;&gt;&gt; for k, g in itertools.groupby(letters):
266... print k, list(g)
267...
268a ['a', 'a', 'a', 'a', 'a']
269b ['b', 'b']
270c ['c']
271d ['d']
272r ['r', 'r']
273&gt;&gt;&gt; # List unique letters
274&gt;&gt;&gt; [k for k, g in groupby(letters)]
275['a', 'b', 'c', 'd', 'r']
276&gt;&gt;&gt; # Count letter occurrences
277&gt;&gt;&gt; [(k, len(list(g))) for k, g in groupby(letters)]
278[('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)]
279</pre></div>
280
281<P>
282(Contributed by Hye-Shik Chang.)
283
284<P>
285</LI>
286<LI><tt class="module">itertools</tt> also gained a function named
287<tt class="function">tee(<var>iterator</var>, <var>N</var>)</tt> that returns <var>N</var> independent
288iterators that replicate <var>iterator</var>. If <var>N</var> is omitted, the
289default is 2.
290
291<P>
292<div class="verbatim"><pre>
293&gt;&gt;&gt; L = [1,2,3]
294&gt;&gt;&gt; i1, i2 = itertools.tee(L)
295&gt;&gt;&gt; i1,i2
296(&lt;itertools.tee object at 0x402c2080&gt;, &lt;itertools.tee object at 0x402c2090&gt;)
297&gt;&gt;&gt; list(i1) # Run the first iterator to exhaustion
298[1, 2, 3]
299&gt;&gt;&gt; list(i2) # Run the second iterator to exhaustion
300[1, 2, 3]
301&gt;
302</pre></div>
303
304<P>
305Note that <tt class="function">tee()</tt> has to keep copies of the values returned
306by the iterator; in the worst case, it may need to keep all of them.
307This should therefore be used carefully if the leading iterator
308can run far ahead of the trailing iterator in a long stream of inputs.
309If the separation is large, then you might as well use
310<tt class="function">list()</tt> instead. When the iterators track closely with one
311another, <tt class="function">tee()</tt> is ideal. Possible applications include
312bookmarking, windowing, or lookahead iterators.
313(Contributed by Raymond Hettinger.)
314
315<P>
316</LI>
317<LI>A number of functions were added to the <tt class="module">locale</tt>
318module, such as <tt class="function">bind_textdomain_codeset()</tt> to specify a
319particular encoding and a family of <tt class="function">l*gettext()</tt> functions
320that return messages in the chosen encoding.
321(Contributed by Gustavo Niemeyer.)
322
323<P>
324</LI>
325<LI>Some keyword arguments were added to the <tt class="module">logging</tt>
326package's <tt class="function">basicConfig</tt> function to simplify log
327configuration. The default behavior is to log messages to standard
328error, but various keyword arguments can be specified to log to a
329particular file, change the logging format, or set the logging level.
330For example:
331
332<P>
333<div class="verbatim"><pre>
334import logging
335logging.basicConfig(filename='/var/log/application.log',
336 level=0, # Log all messages
337 format='%(levelname):%(process):%(thread):%(message)')
338</pre></div>
339
340<P>
341Other additions to the <tt class="module">logging</tt> package include a
342<tt class="method">log(<var>level</var>, <var>msg</var>)</tt> convenience method, as well as a
343<tt class="class">TimedRotatingFileHandler</tt> class that rotates its log files at a
344timed interval. The module already had <tt class="class">RotatingFileHandler</tt>,
345which rotated logs once the file exceeded a certain size. Both
346classes derive from a new <tt class="class">BaseRotatingHandler</tt> class that can
347be used to implement other rotating handlers.
348
349<P>
350(Changes implemented by Vinay Sajip.)
351
352<P>
353</LI>
354<LI>The <tt class="module">marshal</tt> module now shares interned strings on unpacking a
355data structure. This may shrink the size of certain pickle strings,
356but the primary effect is to make <span class="file">.pyc</span> files significantly smaller.
357(Contributed by Martin von Loewis.)
358
359<P>
360</LI>
361<LI>The <tt class="module">nntplib</tt> module's <tt class="class">NNTP</tt> class gained
362<tt class="method">description()</tt> and <tt class="method">descriptions()</tt> methods to retrieve
363newsgroup descriptions for a single group or for a range of groups.
364(Contributed by J&#252;rgen A. Erhard.)
365
366<P>
367</LI>
368<LI>Two new functions were added to the <tt class="module">operator</tt> module,
369<tt class="function">attrgetter(<var>attr</var>)</tt> and <tt class="function">itemgetter(<var>index</var>)</tt>.
370Both functions return callables that take a single argument and return
371the corresponding attribute or item; these callables make excellent
372data extractors when used with <tt class="function">map()</tt> or
373<tt class="function">sorted()</tt>. For example:
374
375<P>
376<div class="verbatim"><pre>
377&gt;&gt;&gt; L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
378&gt;&gt;&gt; map(operator.itemgetter(0), L)
379['c', 'd', 'a', 'b']
380&gt;&gt;&gt; map(operator.itemgetter(1), L)
381[2, 1, 4, 3]
382&gt;&gt;&gt; sorted(L, key=operator.itemgetter(1)) # Sort list by second tuple item
383[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
384</pre></div>
385
386<P>
387(Contributed by Raymond Hettinger.)
388
389<P>
390</LI>
391<LI>The <tt class="module">optparse</tt> module was updated in various ways. The
392module now passes its messages through <tt class="function">gettext.gettext()</tt>,
393making it possible to internationalize Optik's help and error
394messages. Help messages for options can now include the string
395<code>'%default'</code>, which will be replaced by the option's default
396value. (Contributed by Greg Ward.)
397
398<P>
399</LI>
400<LI>The long-term plan is to deprecate the <tt class="module">rfc822</tt> module
401in some future Python release in favor of the <tt class="module">email</tt> package.
402To this end, the <tt class="function">email.Utils.formatdate()</tt> function has been
403changed to make it usable as a replacement for
404<tt class="function">rfc822.formatdate()</tt>. You may want to write new e-mail
405processing code with this in mind. (Change implemented by Anthony
406Baxter.)
407
408<P>
409</LI>
410<LI>A new <tt class="function">urandom(<var>n</var>)</tt> function was added to the
411<tt class="module">os</tt> module, returning a string containing <var>n</var> bytes of
412random data. This function provides access to platform-specific
413sources of randomness such as <span class="file">/dev/urandom</span> on Linux or the
414Windows CryptoAPI. (Contributed by Trevor Perrin.)
415
416<P>
417</LI>
418<LI>Another new function: <tt class="function">os.path.lexists(<var>path</var>)</tt>
419returns true if the file specified by <var>path</var> exists, whether or
420not it's a symbolic link. This differs from the existing
421<tt class="function">os.path.exists(<var>path</var>)</tt> function, which returns false if
422<var>path</var> is a symlink that points to a destination that doesn't exist.
423(Contributed by Beni Cherniavsky.)
424
425<P>
426</LI>
427<LI>A new <tt class="function">getsid()</tt> function was added to the
428<tt class="module">posix</tt> module that underlies the <tt class="module">os</tt> module.
429(Contributed by J. Raynor.)
430
431<P>
432</LI>
433<LI>The <tt class="module">poplib</tt> module now supports POP over SSL. (Contributed by
434Hector Urtubia.)
435
436<P>
437</LI>
438<LI>The <tt class="module">profile</tt> module can now profile C extension functions.
439(Contributed by Nick Bastin.)
440
441<P>
442</LI>
443<LI>The <tt class="module">random</tt> module has a new method called
444 <tt class="method">getrandbits(<var>N</var>)</tt> that returns a long integer <var>N</var>
445 bits in length. The existing <tt class="method">randrange()</tt> method now uses
446 <tt class="method">getrandbits()</tt> where appropriate, making generation of
447 arbitrarily large random numbers more efficient. (Contributed by
448 Raymond Hettinger.)
449
450<P>
451</LI>
452<LI>The regular expression language accepted by the <tt class="module">re</tt> module
453 was extended with simple conditional expressions, written as
454 <tt class="regexp">(?(<var>group</var>)<var>A</var>|<var>B</var>)</tt>. <var>group</var> is either a
455 numeric group ID or a group name defined with <tt class="regexp">(?P&lt;group&gt;...)</tt>
456 earlier in the expression. If the specified group matched, the
457 regular expression pattern <var>A</var> will be tested against the string; if
458 the group didn't match, the pattern <var>B</var> will be used instead.
459 (Contributed by Gustavo Niemeyer.)
460
461<P>
462</LI>
463<LI>The <tt class="module">re</tt> module is also no longer recursive, thanks to a
464massive amount of work by Gustavo Niemeyer. In a recursive regular
465expression engine, certain patterns result in a large amount of C
466stack space being consumed, and it was possible to overflow the stack.
467For example, if you matched a 30000-byte string of "<tt class="samp">a</tt>" characters
468against the expression <tt class="regexp">(a|b)+</tt>, one stack frame was consumed
469per character. Python 2.3 tried to check for stack overflow and raise
470a <tt class="exception">RuntimeError</tt> exception, but certain patterns could
471sidestep the checking and if you were unlucky Python could segfault.
472Python 2.4's regular expression engine can match this pattern without
473problems.
474
475<P>
476</LI>
477<LI>A new <tt class="function">socketpair()</tt> function, returning a pair of
478connected sockets, was added to the <tt class="module">socket</tt> module.
479(Contributed by Dave Cole.)
480
481<P>
482</LI>
483<LI>The <tt class="function">sys.exitfunc()</tt> function has been deprecated. Code
484should be using the existing <tt class="module">atexit</tt> module, which correctly
485handles calling multiple exit functions. Eventually
486<tt class="function">sys.exitfunc()</tt> will become a purely internal interface,
487accessed only by <tt class="module">atexit</tt>.
488
489<P>
490</LI>
491<LI>The <tt class="module">tarfile</tt> module now generates GNU-format tar files
492by default. (Contributed by Lars Gustaebel.)
493
494<P>
495</LI>
496<LI>The <tt class="module">threading</tt> module now has an elegantly simple way to support
497thread-local data. The module contains a <tt class="class">local</tt> class whose
498attribute values are local to different threads.
499
500<P>
501<div class="verbatim"><pre>
502import threading
503
504data = threading.local()
505data.number = 42
506data.url = ('www.python.org', 80)
507</pre></div>
508
509<P>
510Other threads can assign and retrieve their own values for the
511<tt class="member">number</tt> and <tt class="member">url</tt> attributes. You can subclass
512<tt class="class">local</tt> to initialize attributes or to add methods.
513(Contributed by Jim Fulton.)
514
515<P>
516</LI>
517<LI>The <tt class="module">timeit</tt> module now automatically disables periodic
518 garbarge collection during the timing loop. This change makes
519 consecutive timings more comparable. (Contributed by Raymond Hettinger.)
520
521<P>
522</LI>
523<LI>The <tt class="module">weakref</tt> module now supports a wider variety of objects
524 including Python functions, class instances, sets, frozensets, deques,
525 arrays, files, sockets, and regular expression pattern objects.
526 (Contributed by Raymond Hettinger.)
527
528<P>
529</LI>
530<LI>The <tt class="module">xmlrpclib</tt> module now supports a multi-call extension for
531transmitting multiple XML-RPC calls in a single HTTP operation.
532(Contributed by Brian Quinlan.)
533
534<P>
535</LI>
536<LI>The <tt class="module">mpz</tt>, <tt class="module">rotor</tt>, and <tt class="module">xreadlines</tt> modules have
537been removed.
538
539<P>
540</LI>
541</UL>
542
543<P>
544
545<H2><A NAME="SECTION0001310000000000000000">
54612.1 cookielib</A>
547</H2>
548
549<P>
550The <tt class="module">cookielib</tt> library supports client-side handling for HTTP
551cookies, mirroring the <tt class="module">Cookie</tt> module's server-side cookie
552support. Cookies are stored in cookie jars; the library transparently
553stores cookies offered by the web server in the cookie jar, and
554fetches the cookie from the jar when connecting to the server. As in
555web browsers, policy objects control whether cookies are accepted or
556not.
557
558<P>
559In order to store cookies across sessions, two implementations of
560cookie jars are provided: one that stores cookies in the Netscape
561format so applications can use the Mozilla or Lynx cookie files, and
562one that stores cookies in the same format as the Perl libwww library.
563
564<P>
565<tt class="module">urllib2</tt> has been changed to interact with <tt class="module">cookielib</tt>:
566<tt class="class">HTTPCookieProcessor</tt> manages a cookie jar that is used when
567accessing URLs.
568
569<P>
570This module was contributed by John J. Lee.
571
572<P>
573
574<H2><A NAME="SECTION0001320000000000000000">
57512.2 doctest</A>
576</H2>
577
578<P>
579The <tt class="module">doctest</tt> module underwent considerable refactoring thanks
580to Edward Loper and Tim Peters. Testing can still be as simple as
581running <tt class="function">doctest.testmod()</tt>, but the refactorings allow
582customizing the module's operation in various ways
583
584<P>
585The new <tt class="class">DocTestFinder</tt> class extracts the tests from a given
586object's docstrings:
587
588<P>
589<div class="verbatim"><pre>
590def f (x, y):
591 """&gt;&gt;&gt; f(2,2)
5924
593&gt;&gt;&gt; f(3,2)
5946
595 """
596 return x*y
597
598finder = doctest.DocTestFinder()
599
600# Get list of DocTest instances
601tests = finder.find(f)
602</pre></div>
603
604<P>
605The new <tt class="class">DocTestRunner</tt> class then runs individual tests and can
606produce a summary of the results:
607
608<P>
609<div class="verbatim"><pre>
610runner = doctest.DocTestRunner()
611for t in tests:
612 tried, failed = runner.run(t)
613
614runner.summarize(verbose=1)
615</pre></div>
616
617<P>
618The above example produces the following output:
619
620<P>
621<div class="verbatim"><pre>
6221 items passed all tests:
623 2 tests in f
6242 tests in 1 items.
6252 passed and 0 failed.
626Test passed.
627</pre></div>
628
629<P>
630<tt class="class">DocTestRunner</tt> uses an instance of the <tt class="class">OutputChecker</tt>
631class to compare the expected output with the actual output. This
632class takes a number of different flags that customize its behaviour;
633ambitious users can also write a completely new subclass of
634<tt class="class">OutputChecker</tt>.
635
636<P>
637The default output checker provides a number of handy features.
638For example, with the <tt class="constant">doctest.ELLIPSIS</tt> option flag,
639an ellipsis ("<tt class="samp">...</tt>") in the expected output matches any substring,
640making it easier to accommodate outputs that vary in minor ways:
641
642<P>
643<div class="verbatim"><pre>
644def o (n):
645 """&gt;&gt;&gt; o(1)
646&lt;__main__.C instance at 0x...&gt;
647&gt;&gt;&gt;
648"""
649</pre></div>
650
651<P>
652Another special string, "<tt class="samp">&lt;BLANKLINE&gt;</tt>", matches a blank line:
653
654<P>
655<div class="verbatim"><pre>
656def p (n):
657 """&gt;&gt;&gt; p(1)
658&lt;BLANKLINE&gt;
659&gt;&gt;&gt;
660"""
661</pre></div>
662
663<P>
664Another new capability is producing a diff-style display of the output
665by specifying the <tt class="constant">doctest.REPORT_UDIFF</tt> (unified diffs),
666<tt class="constant">doctest.REPORT_CDIFF</tt> (context diffs), or
667<tt class="constant">doctest.REPORT_NDIFF</tt> (delta-style) option flags. For example:
668
669<P>
670<div class="verbatim"><pre>
671def g (n):
672 """&gt;&gt;&gt; g(4)
673here
674is
675a
676lengthy
677&gt;&gt;&gt;"""
678 L = 'here is a rather lengthy list of words'.split()
679 for word in L[:n]:
680 print word
681</pre></div>
682
683<P>
684Running the above function's tests with
685<tt class="constant">doctest.REPORT_UDIFF</tt> specified, you get the following output:
686
687<P>
688<div class="verbatim"><pre>
689**********************************************************************
690File ``t.py'', line 15, in g
691Failed example:
692 g(4)
693Differences (unified diff with -expected +actual):
694 @@ -2,3 +2,3 @@
695 is
696 a
697 -lengthy
698 +rather
699**********************************************************************
700</pre></div>
701
702<P>
703
704<DIV CLASS="navigation">
705<div class='online-navigation'>
706<p></p><hr />
707<table align="center" width="100%" cellpadding="0" cellspacing="2">
708<tr>
709<td class='online-navigation'><a rel="prev" title="11 Other Language Changes"
710 href="node12.html"><img src='../icons/previous.png'
711 border='0' height='32' alt='Previous Page' width='32' /></A></td>
712<td class='online-navigation'><a rel="parent" title="What's New in Python"
713 href="whatsnew24.html"><img src='../icons/up.png'
714 border='0' height='32' alt='Up One Level' width='32' /></A></td>
715<td class='online-navigation'><a rel="next" title="13 Build and C"
716 href="node14.html"><img src='../icons/next.png'
717 border='0' height='32' alt='Next Page' width='32' /></A></td>
718<td align="center" width="100%">What's New in Python 2.4</td>
719<td class='online-navigation'><a rel="contents" title="Table of Contents"
720 href="contents.html"><img src='../icons/contents.png'
721 border='0' height='32' alt='Contents' width='32' /></A></td>
722<td class='online-navigation'><img src='../icons/blank.png'
723 border='0' height='32' alt='' width='32' /></td>
724<td class='online-navigation'><img src='../icons/blank.png'
725 border='0' height='32' alt='' width='32' /></td>
726</tr></table>
727<div class='online-navigation'>
728<b class="navlabel">Previous:</b>
729<a class="sectref" rel="prev" href="node12.html">11 Other Language Changes</A>
730<b class="navlabel">Up:</b>
731<a class="sectref" rel="parent" href="whatsnew24.html">What's New in Python</A>
732<b class="navlabel">Next:</b>
733<a class="sectref" rel="next" href="node14.html">13 Build and C</A>
734</div>
735</div>
736<hr />
737<span class="release-info">Release 1.01.</span>
738</DIV>
739<!--End of Navigation Panel-->
740<ADDRESS>
741See <i><a href="about.html">About this document...</a></i> for information on suggesting changes.
742</ADDRESS>
743</BODY>
744</HTML>