blob: 1607cc78fac60d1a6f70230f91b5dc1811b8bb60 [file] [log] [blame]
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001\documentclass{howto}
2\usepackage{distutils}
3% $Id$
4
5\title{What's New in Python 2.4}
6\release{0.0}
7\author{A.M.\ Kuchling}
Fred Drakeb914ef02004-01-02 06:57:50 +00008\authoraddress{
9 \strong{Python Software Foundation}\\
10 Email: \email{amk@amk.ca}
11}
Fred Drakeed0fa3d2003-07-30 19:14:09 +000012
13\begin{document}
14\maketitle
15\tableofcontents
16
17This article explains the new features in Python 2.4. No release date
Raymond Hettingerd4462302003-11-26 17:52:45 +000018for Python 2.4 has been set; expect that this will happen mid-2004.
Fred Drakeed0fa3d2003-07-30 19:14:09 +000019
20While Python 2.3 was primarily a library development release, Python
212.4 may extend the core language and interpreter in
22as-yet-undetermined ways.
23
24This article doesn't attempt to provide a complete specification of
25the new features, but instead provides a convenient overview. For
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +000026full details, you should refer to the documentation for Python 2.4,
27such as the \citetitle[../lib/lib.html]{Python Library Reference} and
28the \citetitle[../ref/ref.html]{Python Reference Manual}.
Fred Drakeed0fa3d2003-07-30 19:14:09 +000029If you want to understand the complete implementation and design
30rationale, refer to the PEP for a particular new feature.
31
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +000032
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000033%======================================================================
34\section{PEP 218: Built-In Set Objects}
35
36Two new built-in types, \function{set(iterable)} and
37\function{frozenset(iterable)} provide high speed data types for
38membership testing, for eliminating duplicates from sequences, and
39for mathematical operations like unions, intersections, differences,
40and symmetric differences.
41
42\begin{verbatim}
43>>> a = set('abracadabra') # form a set from a string
44>>> 'z' in a # fast membership testing
45False
46>>> a # unique letters in a
47set(['a', 'r', 'b', 'c', 'd'])
48>>> ''.join(a) # convert back into a string
49'arbcd'
Raymond Hettingerd4462302003-11-26 17:52:45 +000050
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000051>>> b = set('alacazam') # form a second set
52>>> a - b # letters in a but not in b
53set(['r', 'd', 'b'])
54>>> a | b # letters in either a or b
55set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
56>>> a & b # letters in both a and b
57set(['a', 'c'])
58>>> a ^ b # letters in a or b but not both
59set(['r', 'd', 'b', 'm', 'z', 'l'])
Raymond Hettingerd4462302003-11-26 17:52:45 +000060
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000061>>> a.add('z') # add a new element
62>>> a.update('wxy') # add multiple new elements
63>>> a
64set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'x', 'z'])
65>>> a.remove('x') # take one element out
66>>> a
67set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'z'])
68\end{verbatim}
69
70The type \function{frozenset()} is an immutable version of \function{set()}.
71Since it is immutable and hashable, it may be used as a dictionary key or
72as a member of another set. Accordingly, it does not have methods
73like \method{add()} and \method{remove()} which could alter its contents.
74
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +000075% XXX what happens to the sets module?
Raymond Hettingered54d912003-12-31 01:59:18 +000076% The current thinking is that the sets module will be left alone.
77% That way, existing code will continue to run without alteration.
78% Also, the module provides an autoconversion feature not supported by set()
79% and frozenset().
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +000080
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000081\begin{seealso}
82\seepep{218}{Adding a Built-In Set Object Type}{Originally proposed by
83Greg Wilson and ultimately implemented by Raymond Hettinger.}
84\end{seealso}
Fred Drakeed0fa3d2003-07-30 19:14:09 +000085
86%======================================================================
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +000087\section{PEP 237: Unifying Long Integers and Integers}
88
89XXX write this.
90
91%======================================================================
Andrew M. Kuchling1a420252003-11-08 15:58:49 +000092\section{PEP 322: Reverse Iteration}
Fred Drakeed0fa3d2003-07-30 19:14:09 +000093
Andrew M. Kuchling1a420252003-11-08 15:58:49 +000094A new built-in function, \function{reversed(seq)}, takes a sequence
95and returns an iterator that returns the elements of the sequence
96in reverse order.
97
98\begin{verbatim}
Raymond Hettingerbc3cba22003-11-12 16:39:30 +000099>>> for i in reversed(xrange(1,4)):
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000100... print i
101...
1023
1032
1041
105\end{verbatim}
106
Raymond Hettingerbc3cba22003-11-12 16:39:30 +0000107Compared to extended slicing, \code{range(1,4)[::-1]}, \function{reversed()}
108is easier to read, runs faster, and uses substantially less memory.
109
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000110Note that \function{reversed()} only accepts sequences, not arbitrary
Raymond Hettingerbc3cba22003-11-12 16:39:30 +0000111iterators. If you want to reverse an iterator, first convert it to
112a list with \function{list()}.
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000113
114\begin{verbatim}
Andrew M. Kuchling44a31e12004-01-01 18:33:34 +0000115>>> input= open('/etc/passwd', 'r')
116>>> for line in reversed(list(input)):
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000117... print line
118...
119root:*:0:0:System Administrator:/var/root:/bin/tcsh
120 ...
121\end{verbatim}
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000122
Andrew M. Kuchlingf7a6b672003-11-08 16:05:37 +0000123\begin{seealso}
124\seepep{322}{Reverse Iteration}{Written and implemented by Raymond Hettinger.}
125
126\end{seealso}
127
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000128
129%======================================================================
130\section{Other Language Changes}
131
132Here are all of the changes that Python 2.4 makes to the core Python
133language.
134
135\begin{itemize}
Raymond Hettingerd4462302003-11-26 17:52:45 +0000136
Raymond Hettinger31017ae2004-03-04 08:25:44 +0000137\item The \method{dict.update()} method now accepts the same
138argument forms as the \class{dict} constructor. This includes any
139mapping, any iterable of key/value pairs, and/or keyword arguments.
140
Raymond Hettingerd4462302003-11-26 17:52:45 +0000141\item The string methods, \method{ljust()}, \method{rjust()}, and
Andrew M. Kuchling67087562003-11-26 18:03:48 +0000142\method{center()} now take an optional argument for specifying a
Raymond Hettingerd4462302003-11-26 17:52:45 +0000143fill character other than a space.
144
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000145\item Strings also gained an \method{rsplit()} method that
Raymond Hettingered54d912003-12-31 01:59:18 +0000146works like the \method{split()} method but splits from the end of
Andrew M. Kuchling44a31e12004-01-01 18:33:34 +0000147the string.
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000148
149\begin{verbatim}
Raymond Hettinger7a6d2972004-02-13 19:00:07 +0000150>>> 'www.python.org'.split('.', 1)
151['www', 'python.org']
152'www.python.org'.rsplit('.', 1)
153['www.python', 'org']
154\end{verbatim}
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000155
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000156\item The \method{sort()} method of lists gained three keyword
157arguments, \var{cmp}, \var{key}, and \var{reverse}. These arguments
158make some common usages of \method{sort()} simpler. All are optional.
159
160\var{cmp} is the same as the previous single argument to
161\method{sort()}; if provided, the value should be a comparison
162function that takes two arguments and returns -1, 0, or +1 depending
163on how the arguments compare.
164
165\var{key} should be a single-argument function that takes a list
166element and returns a comparison key for the element. The list is
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000167then sorted using the comparison keys. The following example sorts a
168list case-insensitively:
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000169
170\begin{verbatim}
171>>> L = ['A', 'b', 'c', 'D']
172>>> L.sort() # Case-sensitive sort
173>>> L
174['A', 'D', 'b', 'c']
175>>> L.sort(key=lambda x: x.lower())
176>>> L
177['A', 'b', 'c', 'D']
178>>> L.sort(cmp=lambda x,y: cmp(x.lower(), y.lower()))
179>>> L
180['A', 'b', 'c', 'D']
181\end{verbatim}
182
183The last example, which uses the \var{cmp} parameter, is the old way
Raymond Hettingered54d912003-12-31 01:59:18 +0000184to perform a case-insensitive sort. It works but is slower than
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000185using a \var{key} parameter. Using \var{key} results in calling the
186\method{lower()} method once for each element in the list while using
187\var{cmp} will call the method twice for each comparison.
188
Andrew M. Kuchling981a9182003-11-13 21:33:26 +0000189For simple key functions and comparison functions, it is often
190possible to avoid a \keyword{lambda} expression by using an unbound
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000191method instead. For example, the above case-insensitive sort is best
192coded as:
193
194\begin{verbatim}
195>>> L.sort(key=str.lower)
196>>> L
197['A', 'b', 'c', 'D']
198\end{verbatim}
199
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000200The \var{reverse} parameter should have a Boolean value. If the value is
201\constant{True}, the list will be sorted into reverse order. Instead
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000202of \code{L.sort(lambda x,y: cmp(y.score, x.score))}, you can now write:
203\code{L.sort(key = lambda x: x.score, reverse=True)}.
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000204
Andrew M. Kuchling981a9182003-11-13 21:33:26 +0000205The results of sorting are now guaranteed to be stable. This means
206that two entries with equal keys will be returned in the same order as
207they were input. For example, you can sort a list of people by name,
208and then sort the list by age, resulting in a list sorted by age where
209people with the same age are in name-sorted order.
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000210
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000211\item There is a new built-in function \function{sorted(iterable)} that works
Raymond Hettinger64958a12003-12-17 20:43:33 +0000212like the in-place \method{list.sort()} method but has been made suitable
213for use in expressions. The differences are:
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000214 \begin{itemize}
Raymond Hettinger7d1dd042003-11-12 16:42:10 +0000215 \item the input may be any iterable;
216 \item a newly formed copy is sorted, leaving the original intact; and
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000217 \item the expression returns the new sorted copy
218 \end{itemize}
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000219
220\begin{verbatim}
221>>> L = [9,7,8,3,2,4,1,6,5]
Raymond Hettinger64958a12003-12-17 20:43:33 +0000222>>> [10+i for i in sorted(L)] # usable in a list comprehension
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000223[11, 12, 13, 14, 15, 16, 17, 18, 19]
224>>> L = [9,7,8,3,2,4,1,6,5] # original is left unchanged
225[9,7,8,3,2,4,1,6,5]
Raymond Hettingerd4462302003-11-26 17:52:45 +0000226
Raymond Hettinger64958a12003-12-17 20:43:33 +0000227>>> sorted('Monte Python') # any iterable may be an input
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000228[' ', 'M', 'P', 'e', 'h', 'n', 'n', 'o', 'o', 't', 't', 'y']
Raymond Hettingerd4462302003-11-26 17:52:45 +0000229
230>>> # List the contents of a dict sorted by key values
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000231>>> colormap = dict(red=1, blue=2, green=3, black=4, yellow=5)
Raymond Hettinger64958a12003-12-17 20:43:33 +0000232>>> for k, v in sorted(colormap.iteritems()):
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000233... print k, v
234...
235black 4
236blue 2
237green 3
238red 1
239yellow 5
240
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000241\end{verbatim}
242
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000243\item The \function{zip()} built-in function and \function{itertools.izip()}
Andrew M. Kuchling67087562003-11-26 18:03:48 +0000244 now return an empty list instead of raising a \exception{TypeError}
Andrew M. Kuchling44a31e12004-01-01 18:33:34 +0000245 exception if called with no arguments. This makes them more
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000246 suitable for use with variable length argument lists:
247
248\begin{verbatim}
249>>> def transpose(array):
250... return zip(*array)
251...
252>>> transpose([(1,2,3), (4,5,6)])
253[(1, 4), (2, 5), (3, 6)]
254>>> transpose([])
255[]
256\end{verbatim}
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +0000257
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000258\end{itemize}
259
260
261%======================================================================
262\subsection{Optimizations}
263
264\begin{itemize}
265
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000266\item The inner loops for \class{list} and \class{tuple} slicing
267 were optimized and now run about one-third faster.
268
Raymond Hettinger7a6d2972004-02-13 19:00:07 +0000269\item The machinery for growing and shrinking lists was optimized
Raymond Hettingerab517d22004-02-14 18:34:46 +0000270 for speed and for space efficiency. Small lists (under eight elements)
271 never over-allocate by more than three elements. Large lists do not
Raymond Hettinger7a6d2972004-02-13 19:00:07 +0000272 over-allocate by more than 1/8th. Appending and popping from lists
273 now runs faster due to more efficient code paths and less frequent
274 use of the underlying system realloc(). List comprehensions also
275 benefit. The amount of improvement varies between systems and shows
276 the greatest improvement on systems with poor realloc() implementations.
Raymond Hettinger79b5cf12004-02-17 10:46:32 +0000277 \method{list.extend()} was also optimized and no longer converts its
278 argument into a temporary list prior to extending the base list.
Raymond Hettinger7a6d2972004-02-13 19:00:07 +0000279
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000280\item \function{list()}, \function{tuple()}, \function{map()},
281 \function{filter()}, and \function{zip()} now run several times
282 faster with non-sequence arguments that supply a \method{__len__()}
283 method. Previously, the pre-sizing optimization only applied to
284 sequence arguments.
285
Raymond Hettinger23a0f4e2004-01-05 08:15:20 +0000286\item The methods \method{list.__getitem__()},
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000287 \method{dict.__getitem__()}, and \method{dict.__contains__()} are
288 are now implemented as \class{method_descriptor} objects rather
289 than \class{wrapper_descriptor} objects. This form of optimized
290 access doubles their performance and makes them more suitable for
Raymond Hettinger23a0f4e2004-01-05 08:15:20 +0000291 use as arguments to functionals:
292 \samp{map(mydict.__getitem__, keylist)}.
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000293
Raymond Hettingerdd80f762004-03-07 07:31:06 +0000294\item Added an newcode opcode, \code{LIST_APPEND}, that simplifies
295 the generated bytecode for list comprehensions and speeds them up
296 by about a third.
297
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000298\end{itemize}
299
300The net result of the 2.4 optimizations is that Python 2.4 runs the
301pystone benchmark around XX\% faster than Python 2.3 and YY\% faster
302than Python 2.2.
303
304
305%======================================================================
306\section{New, Improved, and Deprecated Modules}
307
308As usual, Python's standard library received a number of enhancements and
309bug fixes. Here's a partial list of the most notable changes, sorted
310alphabetically by module name. Consult the
311\file{Misc/NEWS} file in the source tree for a more
312complete list of changes, or look through the CVS logs for all the
313details.
314
315\begin{itemize}
316
Andrew M. Kuchling69f31eb2003-08-13 23:11:04 +0000317\item The \module{curses} modules now supports the ncurses extension
318 \function{use_default_colors()}. On platforms where the terminal
319 supports transparency, this makes it possible to use a transparent background.
320 (Contributed by J\"org Lehmann.)
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +0000321
Raymond Hettinger0c410272004-01-05 10:13:35 +0000322\item The \module{bisect} module now has an underlying C implementation
323 for improved performance.
324 (Contributed by Dmitry Vasiliev.)
325
Andrew M. Kuchling5303a962004-01-18 15:55:51 +0000326\item The CJKCodecs collections of East Asian codecs, maintained
327by Hye-Shik Chang, was integrated into 2.4.
328The new encodings are:
329
330\begin{itemize}
331 \item Chinese (PRC): gb2312, gbk, gb18030, hz
332 \item Chinese (ROC): big5, cp950
333 \item Japanese: cp932, shift-jis, shift-jisx0213, euc-jp,
334euc-jisx0213, iso-2022-jp, iso-2022-jp-1, iso-2022-jp-2,
335 iso-2022-jp-3, iso-2022-jp-ext
336 \item Korean: cp949, euc-kr, johab, iso-2022-kr
337\end{itemize}
338
Andrew M. Kuchlingfd0e4942004-02-09 13:23:34 +0000339\item There is a new \module{collections} module for
340 various specialized collection datatypes.
341 Currently it contains just one type, \class{deque},
342 a double-ended queue that supports efficiently adding and removing
343 elements from either end.
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000344
345\begin{verbatim}
346>>> from collections import deque
347>>> d = deque('ghi') # make a new deque with three items
348>>> d.append('j') # add a new entry to the right side
349>>> d.appendleft('f') # add a new entry to the left side
350>>> d # show the representation of the deque
351deque(['f', 'g', 'h', 'i', 'j'])
352>>> d.pop() # return and remove the rightmost item
353'j'
354>>> d.popleft() # return and remove the leftmost item
355'f'
356>>> list(d) # list the contents of the deque
357['g', 'h', 'i']
358>>> 'h' in d # search the deque
359True
360\end{verbatim}
361
Andrew M. Kuchlingfd0e4942004-02-09 13:23:34 +0000362Several modules now take advantage of \class{collections.deque} for
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000363improved performance: \module{Queue}, \module{mutex}, \module{shlex}
364\module{threading}, and \module{pydoc}.
Andrew M. Kuchling5303a962004-01-18 15:55:51 +0000365
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000366\item The \module{heapq} module has been converted to C. The resulting
Andrew M. Kuchlingfd0e4942004-02-09 13:23:34 +0000367 tenfold improvement in speed makes the module suitable for handling
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000368 high volumes of data.
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000369
Andrew M. Kuchlingdff9dbd2003-11-20 22:22:19 +0000370\item The \module{imaplib} module now supports IMAP's THREAD command.
371(Contributed by Yves Dionne.)
372
Andrew M. Kuchlingad809552003-12-06 23:19:23 +0000373\item The \module{itertools} module gained a
374 \function{groupby(\var{iterable}\optional{, \var{func}})} function,
375 inspired by the GROUP BY clause from SQL.
376 \var{iterable} returns a succession of elements, and the optional
377 \var{func} is a function that takes an element and returns a key
378 value; if omitted, the key is simply the element itself.
379 \function{groupby()} then groups the elements into subsequences
380 which have matching values of the key, and returns a series of 2-tuples
381 containing the key value and an iterator over the subsequence.
382
383Here's an example. The \var{key} function simply returns whether a
384number is even or odd, so the result of \function{groupby()} is to
385return consecutive runs of odd or even numbers.
386
387\begin{verbatim}
388>>> import itertools
389>>> L = [2,4,6, 7,8,9,11, 12, 14]
390>>> for key_val, it in itertools.groupby(L, lambda x: x % 2):
391... print key_val, list(it)
392...
3930 [2, 4, 6]
3941 [7]
3950 [8]
3961 [9, 11]
3970 [12, 14]
398>>>
399\end{verbatim}
400
Raymond Hettingerfeb78c92003-12-12 13:13:47 +0000401Like its SQL counterpart, \function{groupby()} is typically used with
402sorted input. The logic for \function{groupby()} is similar to the
403\UNIX{} \code{uniq} filter which makes it handy for eliminating,
404counting, or identifying duplicate elements:
405
406\begin{verbatim}
407>>> word = 'abracadabra'
Raymond Hettingered54d912003-12-31 01:59:18 +0000408>>> letters = sorted(word) # Turn string into a sorted list of letters
Raymond Hettinger64958a12003-12-17 20:43:33 +0000409>>> letters
Andrew M. Kuchling4612bc52003-12-16 20:59:37 +0000410['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r']
Raymond Hettingered54d912003-12-31 01:59:18 +0000411>>> [k for k, g in groupby(letters)] # List unique letters
Raymond Hettingerfeb78c92003-12-12 13:13:47 +0000412['a', 'b', 'c', 'd', 'r']
Raymond Hettingered54d912003-12-31 01:59:18 +0000413>>> [(k, len(list(g))) for k, g in groupby(letters)] # Count letter occurences
Raymond Hettingerfeb78c92003-12-12 13:13:47 +0000414[('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)]
Raymond Hettingered54d912003-12-31 01:59:18 +0000415>>> [k for k, g in groupby(letters) if len(list(g)) > 1] # List duplicated letters
Raymond Hettingerfeb78c92003-12-12 13:13:47 +0000416['a', 'b', 'r']
417\end{verbatim}
418
Raymond Hettingered54d912003-12-31 01:59:18 +0000419\item \module{itertools} also gained a function named
420\function{tee(\var{iterator}, \var{N})} that returns \var{N} independent
421iterators that replicate \var{iterator}. If \var{N} is omitted, the
422default is 2.
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000423
424\begin{verbatim}
425>>> L = [1,2,3]
426>>> i1, i2 = itertools.tee(L)
427>>> i1,i2
428(<itertools.tee object at 0x402c2080>, <itertools.tee object at 0x402c2090>)
Raymond Hettingered54d912003-12-31 01:59:18 +0000429>>> list(i1) # Run the first iterator to exhaustion
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000430[1, 2, 3]
Raymond Hettingered54d912003-12-31 01:59:18 +0000431>>> list(i2) # Run the second iterator to exhaustion
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000432[1, 2, 3]
433>\end{verbatim}
434
435Note that \function{tee()} has to keep copies of the values returned
Raymond Hettingered54d912003-12-31 01:59:18 +0000436by the iterator; in the worst case, it may need to keep all of them.
Andrew M. Kuchling44a31e12004-01-01 18:33:34 +0000437This should therefore be used carefully if the leading iterator
Raymond Hettingered54d912003-12-31 01:59:18 +0000438can run far ahead of the trailing iterator in a long stream of inputs.
Andrew M. Kuchling44a31e12004-01-01 18:33:34 +0000439If the separation is large, then it becomes preferable to use
Raymond Hettingered54d912003-12-31 01:59:18 +0000440\function{list()} instead. When the iterators track closely with one
441another, \function{tee()} is ideal. Possible applications include
442bookmarking, windowing, or lookahead iterators.
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000443
Andrew M. Kuchlingdff9dbd2003-11-20 22:22:19 +0000444\item A new \function{getsid()} function was added to the
445\module{posix} module that underlies the \module{os} module.
446(Contributed by J. Raynor.)
447
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000448\item The \module{operator} module gained two new functions,
449\function{attrgetter(\var{attr})} and \function{itemgetter(\var{index})}.
450Both functions return callables that take a single argument and return
Raymond Hettingered54d912003-12-31 01:59:18 +0000451the corresponding attribute or item; these callables make excellent
452data extractors when used with \function{map()} or \function{sorted()}.
453For example:
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000454
455\begin{verbatim}
Raymond Hettingered54d912003-12-31 01:59:18 +0000456>>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000457>>> map(operator.itemgetter(0), L)
458['c', 'd', 'a', 'b']
459>>> map(operator.itemgetter(1), L)
Raymond Hettingered54d912003-12-31 01:59:18 +0000460[2, 1, 4, 3]
461>>> sorted(L, key=operator.itemgetter(1)) # Sort list by second tuple item
462[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000463\end{verbatim}
464
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +0000465\item The \module{random} module has a new method called \method{getrandbits(N)}
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000466 which returns an N-bit long integer. This method supports the existing
467 \method{randrange()} method, making it possible to efficiently generate
Andrew M. Kuchling44a31e12004-01-01 18:33:34 +0000468 arbitrarily large random numbers.
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +0000469
470\item The regular expression language accepted by the \module{re} module
471 was extended with simple conditional expressions, written as
472 \code{(?(\var{group})\var{A}|\var{B})}. \var{group} is either a
473 numeric group ID or a group name defined with \code{(?P<group>...)}
474 earlier in the expression. If the specified group matched, the
475 regular expression pattern \var{A} will be tested against the string; if
476 the group didn't match, the pattern \var{B} will be used instead.
Andrew M. Kuchling69f31eb2003-08-13 23:11:04 +0000477
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000478\end{itemize}
479
480
481%======================================================================
482% whole new modules get described in \subsections here
483
484
485% ======================================================================
486\section{Build and C API Changes}
487
488Changes to Python's build process and to the C API include:
489
490\begin{itemize}
491
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +0000492 \item Three new convenience macros were added for common return
493 values from extension functions: \csimplemacro{Py_RETURN_NONE},
494 \csimplemacro{Py_RETURN_TRUE}, and \csimplemacro{Py_RETURN_FALSE}.
495
Fred Drakece3caf22004-02-12 18:13:12 +0000496 \item A new function, \cfunction{PyTuple_Pack(\var{N}, \var{obj1},
497 \var{obj2}, ..., \var{objN})}, constructs tuples from a variable
498 length argument list of Python objects.
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000499
Fred Drakece3caf22004-02-12 18:13:12 +0000500 \item A new function, \cfunction{PyDict_Contains(\var{d}, \var{k})},
501 implements fast dictionary lookups without masking exceptions raised
502 during the look-up process.
Raymond Hettingerd4462302003-11-26 17:52:45 +0000503
Fred Drakece3caf22004-02-12 18:13:12 +0000504 \item A new method flag, \constant{METH_COEXISTS}, allows a function
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000505 defined in slots to co-exist with a PyCFunction having the same name.
506 This can halve the access to time to a method such as
507 \method{set.__contains__()}
508
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000509\end{itemize}
510
511
512%======================================================================
513\subsection{Port-Specific Changes}
514
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000515\begin{itemize}
516
517\item The Windows port now builds under MSVC++ 7.1 as well as version 6.
518
519\end{itemize}
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000520
521
522%======================================================================
523\section{Other Changes and Fixes \label{section-other}}
524
525As usual, there were a bunch of other improvements and bugfixes
526scattered throughout the source tree. A search through the CVS change
527logs finds there were XXX patches applied and YYY bugs fixed between
528Python 2.3 and 2.4. Both figures are likely to be underestimates.
529
530Some of the more notable changes are:
531
532\begin{itemize}
533
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000534\item The \module{timeit} module now automatically disables periodic
535 garbarge collection during the timing loop. This change makes
536 consecutive timings more comparable.
537
538\item The \module{base64} module now has more complete RFC 3548 support
539 for Base64, Base32, and Base16 encoding and decoding, including
540 optional case folding and optional alternative alphabets.
541 (Contributed by Barry Warsaw.)
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000542
543\end{itemize}
544
545
546%======================================================================
547\section{Porting to Python 2.4}
548
549This section lists previously described changes that may require
550changes to your code:
551
552\begin{itemize}
553
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000554\item The \function{zip()} built-in function and \function{itertools.izip()}
555 now return an empty list instead of raising a \exception{TypeError}
556 exception if called with no arguments.
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +0000557
558\item \function{dircache.listdir()} now passes exceptions to the caller
559 instead of returning empty lists.
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000560
561\end{itemize}
562
563
564%======================================================================
565\section{Acknowledgements \label{acks}}
566
567The author would like to thank the following people for offering
568suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchling981a9182003-11-13 21:33:26 +0000569article: Raymond Hettinger.
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000570
571\end{document}