blob: 6b2d0f8d87c029418fdf3c8e8b73f2ceed1ddcc8 [file] [log] [blame]
Andrew M. Kuchling23406892004-07-15 11:44:42 +00001
Fred Drakeed0fa3d2003-07-30 19:14:09 +00002\documentclass{howto}
3\usepackage{distutils}
4% $Id$
5
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +00006% Don't write extensive text for new sections; I'll do that.
7% Feel free to add commented-out reminders of things that need
8% to be covered. --amk
9
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +000010% XXX pydoc can display links to module docs -- but when?
11%
12
Fred Drakeed0fa3d2003-07-30 19:14:09 +000013\title{What's New in Python 2.4}
Andrew M. Kuchling89ba1ff2004-07-14 21:56:19 +000014\release{0.2}
Fred Drakeed0fa3d2003-07-30 19:14:09 +000015\author{A.M.\ Kuchling}
Fred Drakeb914ef02004-01-02 06:57:50 +000016\authoraddress{
17 \strong{Python Software Foundation}\\
18 Email: \email{amk@amk.ca}
19}
Fred Drakeed0fa3d2003-07-30 19:14:09 +000020
21\begin{document}
22\maketitle
23\tableofcontents
24
Andrew M. Kuchling89ba1ff2004-07-14 21:56:19 +000025This article explains the new features in Python 2.4 alpha2, scheduled
26for release in late July 2004. The final version of Python 2.4 is
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +000027expected to be released around September 2004.
Fred Drakeed0fa3d2003-07-30 19:14:09 +000028
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +000029Python 2.4 is a medium-sized release. It doesn't introduce as many
Andrew M. Kuchling3b790912004-07-04 16:39:40 +000030changes as the radical Python 2.2, but introduces more features than
31the conservative 2.3 release did. The most significant new language
32feature (as of this writing) is the addition of generator expressions;
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +000033most other changes are to the standard library.
Fred Drakeed0fa3d2003-07-30 19:14:09 +000034
35This article doesn't attempt to provide a complete specification of
Andrew M. Kuchling3b790912004-07-04 16:39:40 +000036every single new feature, but instead provides a convenient overview.
37For full details, you should refer to the documentation for Python
382.4, such as the \citetitle[../lib/lib.html]{Python Library Reference}
39and the \citetitle[../ref/ref.html]{Python Reference Manual}. If you
40want to understand the complete implementation and design rationale,
41refer to the PEP for a particular new feature or to the module
42documentation.
Fred Drakeed0fa3d2003-07-30 19:14:09 +000043
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +000044
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000045%======================================================================
46\section{PEP 218: Built-In Set Objects}
47
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +000048Python 2.3 introduced the \module{sets} module. C implementations of
49set data types have now been added to the Python core as two new
50built-in types, \function{set(\var{iterable})} and
51\function{frozenset(\var{iterable})}. They provide high speed
52operations for membership testing, for eliminating duplicates from
53sequences, and for mathematical operations like unions, intersections,
54differences, and symmetric differences.
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000055
56\begin{verbatim}
57>>> a = set('abracadabra') # form a set from a string
58>>> 'z' in a # fast membership testing
59False
60>>> a # unique letters in a
61set(['a', 'r', 'b', 'c', 'd'])
62>>> ''.join(a) # convert back into a string
63'arbcd'
Raymond Hettingerd4462302003-11-26 17:52:45 +000064
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000065>>> b = set('alacazam') # form a second set
66>>> a - b # letters in a but not in b
67set(['r', 'd', 'b'])
68>>> a | b # letters in either a or b
69set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
70>>> a & b # letters in both a and b
71set(['a', 'c'])
72>>> a ^ b # letters in a or b but not both
73set(['r', 'd', 'b', 'm', 'z', 'l'])
Raymond Hettingerd4462302003-11-26 17:52:45 +000074
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000075>>> a.add('z') # add a new element
76>>> a.update('wxy') # add multiple new elements
77>>> a
78set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'x', 'z'])
79>>> a.remove('x') # take one element out
80>>> a
81set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'z'])
82\end{verbatim}
83
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +000084The \function{frozenset} type is an immutable version of \function{set}.
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000085Since it is immutable and hashable, it may be used as a dictionary key or
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +000086as a member of another set.
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000087
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +000088The \module{sets} module remains in the standard library, and may be
89useful if you wish to subclass the \class{Set} or \class{ImmutableSet}
90classes. There are currently no plans to deprecate the module.
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +000091
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000092\begin{seealso}
93\seepep{218}{Adding a Built-In Set Object Type}{Originally proposed by
94Greg Wilson and ultimately implemented by Raymond Hettinger.}
95\end{seealso}
Fred Drakeed0fa3d2003-07-30 19:14:09 +000096
97%======================================================================
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +000098\section{PEP 237: Unifying Long Integers and Integers}
99
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000100The lengthy transition process for this PEP, begun in Python 2.2,
Andrew M. Kuchlingd4be86c2004-07-04 01:44:04 +0000101takes another step forward in Python 2.4. In 2.3, certain integer
102operations that would behave differently after int/long unification
103triggered \exception{FutureWarning} warnings and returned values
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000104limited to 32 or 64 bits (depending on your platform). In 2.4, these
105expressions no longer produce a warning and instead produce a
106different result that's usually a long integer.
Andrew M. Kuchlingd4be86c2004-07-04 01:44:04 +0000107
108The problematic expressions are primarily left shifts and lengthy
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000109hexadecimal and octal constants. For example,
110\code{2 \textless{}\textless{} 32} results
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000111in a warning in 2.3, evaluating to 0 on 32-bit platforms. In Python
1122.4, this expression now returns the correct answer, 8589934592.
Andrew M. Kuchlingd4be86c2004-07-04 01:44:04 +0000113
114\begin{seealso}
115\seepep{237}{Unifying Long Integers and Integers}{Original PEP
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000116written by Moshe Zadka and GvR. The changes for 2.4 were implemented by
Andrew M. Kuchlingd4be86c2004-07-04 01:44:04 +0000117Kalle Svensson.}
118\end{seealso}
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000119
120%======================================================================
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000121\section{PEP 289: Generator Expressions}
Raymond Hettinger354433a2004-05-19 08:20:33 +0000122
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000123The iterator feature introduced in Python 2.2 makes it easier to write
124programs that loop through large data sets without having the entire
125data set in memory at one time. Programmers can use iterators and the
126\module{itertools} module to write code in a fairly functional style.
127
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000128% XXX avoid metaphor
129List comprehensions have been the fly in the ointment because they
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000130produce a Python list object containing all of the items, unavoidably
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000131pulling them all into memory. When trying to write a
132functionally-styled program, it would be natural to write something
133like:
Raymond Hettinger354433a2004-05-19 08:20:33 +0000134
135\begin{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000136links = [link for link in get_all_links() if not link.followed]
137for link in links:
138 ...
Raymond Hettinger354433a2004-05-19 08:20:33 +0000139\end{verbatim}
140
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000141instead of
Raymond Hettinger354433a2004-05-19 08:20:33 +0000142
143\begin{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000144for link in get_all_links():
145 if link.followed:
146 continue
147 ...
148\end{verbatim}
Raymond Hettinger354433a2004-05-19 08:20:33 +0000149
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000150The first form is more concise and perhaps more readable, but if
151you're dealing with a large number of link objects the second form
152would have to be used.
Raymond Hettinger354433a2004-05-19 08:20:33 +0000153
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000154Generator expressions work similarly to list comprehensions but don't
155materialize the entire list; instead they create a generator that will
156return elements one by one. The above example could be written as:
Raymond Hettinger354433a2004-05-19 08:20:33 +0000157
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000158\begin{verbatim}
159links = (link for link in get_all_links() if not link.followed)
160for link in links:
161 ...
162\end{verbatim}
Raymond Hettinger170a6222004-05-19 19:45:19 +0000163
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000164Generator expressions always have to be written inside parentheses, as
165in the above example. The parentheses signalling a function call also
166count, so if you want to create a iterator that will be immediately
167passed to a function you could write:
Raymond Hettinger170a6222004-05-19 19:45:19 +0000168
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000169\begin{verbatim}
170print sum(obj.count for obj in list_all_objects())
171\end{verbatim}
Raymond Hettinger170a6222004-05-19 19:45:19 +0000172
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000173Generator expressions differ from list comprehensions in various small
174ways. Most notably, the loop variable (\var{obj} in the above
175example) is not accessible outside of the generator expression. List
176comprehensions leave the variable assigned to its last value; future
177versions of Python will change this, making list comprehensions match
178generator expressions in this respect.
Raymond Hettinger354433a2004-05-19 08:20:33 +0000179
180\begin{seealso}
181\seepep{289}{Generator Expressions}{Proposed by Raymond Hettinger and
182implemented by Jiwon Seo with early efforts steered by Hye-Shik Chang.}
183\end{seealso}
184
185%======================================================================
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000186\section{PEP 322: Reverse Iteration}
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000187
Fred Drake56fcc232004-05-06 02:55:35 +0000188A new built-in function, \function{reversed(\var{seq})}, takes a sequence
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000189and returns an iterator that loops over the elements of the sequence
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000190in reverse order.
191
192\begin{verbatim}
Raymond Hettingerbc3cba22003-11-12 16:39:30 +0000193>>> for i in reversed(xrange(1,4)):
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000194... print i
195...
1963
1972
1981
199\end{verbatim}
200
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000201Compared to extended slicing, such as \code{range(1,4)[::-1]},
202\function{reversed()} is easier to read, runs faster, and uses
203substantially less memory.
Raymond Hettingerbc3cba22003-11-12 16:39:30 +0000204
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000205Note that \function{reversed()} only accepts sequences, not arbitrary
Raymond Hettingerbc3cba22003-11-12 16:39:30 +0000206iterators. If you want to reverse an iterator, first convert it to
207a list with \function{list()}.
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000208
209\begin{verbatim}
Andrew M. Kuchling44a31e12004-01-01 18:33:34 +0000210>>> input= open('/etc/passwd', 'r')
211>>> for line in reversed(list(input)):
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000212... print line
213...
214root:*:0:0:System Administrator:/var/root:/bin/tcsh
215 ...
216\end{verbatim}
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000217
Andrew M. Kuchlingf7a6b672003-11-08 16:05:37 +0000218\begin{seealso}
219\seepep{322}{Reverse Iteration}{Written and implemented by Raymond Hettinger.}
220
221\end{seealso}
222
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000223
224%======================================================================
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000225\section{PEP 327: Decimal Data Type}
226
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000227Python has always supported floating-point (FP) numbers as a data
228type, based on the underlying C \ctype{double} type. However, while
229most programming languages provide a floating-point type, most people
230(even programmers) are unaware that computing with floating-point
231numbers entails certain unavoidable inaccuracies. The new decimal
232type provides a way to avoid these inaccuracies.
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000233
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000234\subsection{Why is Decimal needed?}
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000235
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000236The limitations arise from the representation used for floating-point numbers.
237FP numbers are made up of three components:
238
239\begin{itemize}
240\item The sign, which is -1 or +1.
241\item The mantissa, which is a single-digit binary number
242followed by a fractional part. For example, \code{1.01} in base-2 notation
243is \code{1 + 0/2 + 1/4}, or 1.25 in decimal notation.
244\item The exponent, which tells where the decimal point is located in the number represented.
245\end{itemize}
246
247For example, the number 1.25 has sign +1, mantissa 1.01 (in binary),
248and exponent of 0 (the decimal point doesn't need to be shifted). The
249number 5 has the same sign and mantissa, but the exponent is 2
250because the mantissa is multiplied by 4 (2 to the power of the exponent 2).
251
252Modern systems usually provide floating-point support that conforms to
253a relevant standard called IEEE 754. C's \ctype{double} type is
254usually implemented as a 64-bit IEEE 754 number, which uses 52 bits of
255space for the mantissa. This means that numbers can only be specified
256to 52 bits of precision. If you're trying to represent numbers whose
257expansion repeats endlessly, the expansion is cut off after 52 bits.
258Unfortunately, most software needs to produce output in base 10, and
259base 10 often gives rise to such repeating decimals. For example, 1.1
260decimal is binary \code{1.0001100110011 ...}; .1 = 1/16 + 1/32 + 1/256
261plus an infinite number of additional terms. IEEE 754 has to chop off
262that infinitely repeated decimal after 52 digits, so the
263representation is slightly inaccurate.
264
265Sometimes you can see this inaccuracy when the number is printed:
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000266\begin{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000267>>> 1.1
2681.1000000000000001
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000269\end{verbatim}
270
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000271The inaccuracy isn't always visible when you print the number because
272the FP-to-decimal-string conversion is provided by the C library, and
273most C libraries try to produce sensible output, but the inaccuracy is
274still there and subsequent operations can magnify the error.
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000275
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000276For many applications this doesn't matter. If I'm plotting points and
277displaying them on my monitor, the difference between 1.1 and
2781.1000000000000001 is too small to be visible. Reports often limit
279output to a certain number of decimal places, and if you round the
280number to two or three or even eight decimal places, the error is
281never apparent. However, for applications where it does matter,
282it's a lot of work to implement your own custom arithmetic routines.
283
284\subsection{The \class{Decimal} type}
285
286A new module, \module{decimal}, was added to Python's standard library.
287It contains two classes, \class{Decimal} and \class{Context}.
288\class{Decimal} instances represent numbers, and
289\class{Context} instances are used to wrap up various settings such as the precision and default rounding mode.
290
291\class{Decimal} instances, like regular Python integers and FP numbers, are immutable; once they've been created, you can't change the value it represents.
292\class{Decimal} instances can be created from integers or strings:
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000293
294\begin{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000295>>> import decimal
296>>> decimal.Decimal(1972)
297Decimal("1972")
298>>> decimal.Decimal("1.1")
299Decimal("1.1")
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000300\end{verbatim}
301
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000302You can also provide tuples containing the sign, mantissa represented
303as a tuple of decimal digits, and exponent:
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000304
305\begin{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000306>>> decimal.Decimal((1, (1, 4, 7, 5), -2))
307Decimal("-14.75")
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000308\end{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000309
310Cautionary note: the sign bit is a Boolean value, so 0 is positive and 1 is negative.
311
312Floating-point numbers posed a bit of a problem: should the FP number
313representing 1.1 turn into the decimal number for exactly 1.1, or for
3141.1 plus whatever inaccuracies are introduced? The decision was to
315leave such a conversion out of the API. Instead, you should convert
316the floating-point number into a string using the desired precision and
317pass the string to the \class{Decimal} constructor:
318
319\begin{verbatim}
320>>> f = 1.1
321>>> decimal.Decimal(str(f))
322Decimal("1.1")
323>>> decimal.Decimal(repr(f))
324Decimal("1.1000000000000001")
325\end{verbatim}
326
327Once you have \class{Decimal} instances, you can perform the usual
328mathematical operations on them. One limitation: exponentiation
329requires an integer exponent:
330
331\begin{verbatim}
332>>> a = decimal.Decimal('35.72')
333>>> b = decimal.Decimal('1.73')
334>>> a+b
335Decimal("37.45")
336>>> a-b
337Decimal("33.99")
338>>> a*b
339Decimal("61.7956")
340>>> a/b
341Decimal("20.6473988")
342>>> a ** 2
343Decimal("1275.9184")
344>>> a ** b
345Decimal("NaN")
346\end{verbatim}
347
348You can combine \class{Decimal} instances with integers, but not with
349floating-point numbers:
350
351\begin{verbatim}
352>>> a + 4
353Decimal("39.72")
354>>> a + 4.5
355Traceback (most recent call last):
356 ...
357TypeError: You can interact Decimal only with int, long or Decimal data types.
358>>>
359\end{verbatim}
360
361\class{Decimal} numbers can be used with the \module{math} and
362\module{cmath} modules, though you'll get back a regular
363floating-point number and not a \class{Decimal}. Instances also have a \method{sqrt()} method:
364
365\begin{verbatim}
366>>> import math, cmath
367>>> d = decimal.Decimal('123456789012.345')
368>>> math.sqrt(d)
369351364.18288201344
370>>> cmath.sqrt(-d)
371351364.18288201344j
372>>> d.sqrt()
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000373Decimal("351364.1828820134592177245001")
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000374\end{verbatim}
375
376
377\subsection{The \class{Context} type}
378
379Instances of the \class{Context} class encapsulate several settings for
380decimal operations:
381
382\begin{itemize}
383 \item \member{prec} is the precision, the number of decimal places.
384 \item \member{rounding} specifies the rounding mode. The \module{decimal}
385 module has constants for the various possibilities:
386 \constant{ROUND_DOWN}, \constant{ROUND_CEILING}, \constant{ROUND_HALF_EVEN}, and various others.
387 \item \member{trap_enablers} is a dictionary specifying what happens on
388encountering certain error conditions: either an exception is raised or
389a value is returned. Some examples of error conditions are
390division by zero, loss of precision, and overflow.
391\end{itemize}
392
393There's a thread-local default context available by calling
394\function{getcontext()}; you can change the properties of this context
395to alter the default precision, rounding, or trap handling.
396
397\begin{verbatim}
398>>> decimal.getcontext().prec
39928
400>>> decimal.Decimal(1) / decimal.Decimal(7)
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000401Decimal("0.1428571428571428571428571429")
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000402>>> decimal.getcontext().prec = 9
403>>> decimal.Decimal(1) / decimal.Decimal(7)
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000404Decimal("0.142857143")
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000405\end{verbatim}
406
407The default action for error conditions is to return a special value
408such as infinity or not-a-number, but you can request that exceptions
409be raised:
410
411\begin{verbatim}
412>>> decimal.Decimal(1) / decimal.Decimal(0)
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000413Decimal("Infinity")
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000414>>> decimal.getcontext().trap_enablers[decimal.DivisionByZero] = True
415>>> decimal.Decimal(1) / decimal.Decimal(0)
416Traceback (most recent call last):
417 ...
418decimal.DivisionByZero: x / 0
419>>>
420\end{verbatim}
421
422The \class{Context} instance also has various methods for formatting
423numbers such as \method{to_eng_string()} and \method{to_sci_string()}.
424
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000425
426\begin{seealso}
427\seepep{327}{Decimal Data Type}{Written by Facundo Batista and implemented
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000428 by Facundo Batista, Eric Price, Raymond Hettinger, Aahz, and Tim Peters.}
429
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000430\seeurl{http://research.microsoft.com/\textasciitilde hollasch/cgindex/coding/ieeefloat.html}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000431{A more detailed overview of the IEEE-754 representation.}
432
433\seeurl{http://www.lahey.com/float.htm}
434{The article uses Fortran code to illustrate many of the problems
435that floating-point inaccuracy can cause.}
436
437\seeurl{http://www2.hursley.ibm.com/decimal/}
438{A description of a decimal-based representation. This representation
439is being proposed as a standard, and underlies the new Python decimal
440type. Much of this material was written by Mike Cowlishaw, designer of the
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000441Rexx language.}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000442
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000443\end{seealso}
444
445
446%======================================================================
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000447\section{Other Language Changes}
448
449Here are all of the changes that Python 2.4 makes to the core Python
450language.
451
452\begin{itemize}
Raymond Hettingerd4462302003-11-26 17:52:45 +0000453
Raymond Hettinger31017ae2004-03-04 08:25:44 +0000454\item The \method{dict.update()} method now accepts the same
455argument forms as the \class{dict} constructor. This includes any
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +0000456mapping, any iterable of key/value pairs, and keyword arguments.
Raymond Hettinger31017ae2004-03-04 08:25:44 +0000457
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000458\item The string methods \method{ljust()}, \method{rjust()}, and
Andrew M. Kuchling67087562003-11-26 18:03:48 +0000459\method{center()} now take an optional argument for specifying a
Raymond Hettingerd4462302003-11-26 17:52:45 +0000460fill character other than a space.
461
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000462\item Strings also gained an \method{rsplit()} method that
Raymond Hettingered54d912003-12-31 01:59:18 +0000463works like the \method{split()} method but splits from the end of
Andrew M. Kuchling44a31e12004-01-01 18:33:34 +0000464the string.
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000465
466\begin{verbatim}
Raymond Hettinger7a6d2972004-02-13 19:00:07 +0000467>>> 'www.python.org'.split('.', 1)
468['www', 'python.org']
469'www.python.org'.rsplit('.', 1)
470['www.python', 'org']
471\end{verbatim}
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000472
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000473\item The \method{sort()} method of lists gained three keyword
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000474arguments: \var{cmp}, \var{key}, and \var{reverse}. These arguments
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000475make some common usages of \method{sort()} simpler. All are optional.
476
477\var{cmp} is the same as the previous single argument to
478\method{sort()}; if provided, the value should be a comparison
479function that takes two arguments and returns -1, 0, or +1 depending
480on how the arguments compare.
481
482\var{key} should be a single-argument function that takes a list
483element and returns a comparison key for the element. The list is
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000484then sorted using the comparison keys. The following example sorts a
485list case-insensitively:
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000486
487\begin{verbatim}
488>>> L = ['A', 'b', 'c', 'D']
489>>> L.sort() # Case-sensitive sort
490>>> L
491['A', 'D', 'b', 'c']
492>>> L.sort(key=lambda x: x.lower())
493>>> L
494['A', 'b', 'c', 'D']
495>>> L.sort(cmp=lambda x,y: cmp(x.lower(), y.lower()))
496>>> L
497['A', 'b', 'c', 'D']
498\end{verbatim}
499
500The last example, which uses the \var{cmp} parameter, is the old way
Raymond Hettingered54d912003-12-31 01:59:18 +0000501to perform a case-insensitive sort. It works but is slower than
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000502using a \var{key} parameter. Using \var{key} results in calling the
503\method{lower()} method once for each element in the list while using
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000504\var{cmp} will call it twice for each comparison.
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000505
Andrew M. Kuchling981a9182003-11-13 21:33:26 +0000506For simple key functions and comparison functions, it is often
507possible to avoid a \keyword{lambda} expression by using an unbound
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000508method instead. For example, the above case-insensitive sort is best
509coded as:
510
511\begin{verbatim}
512>>> L.sort(key=str.lower)
513>>> L
514['A', 'b', 'c', 'D']
515\end{verbatim}
516
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000517The \var{reverse} parameter should have a Boolean value. If the value
518is \constant{True}, the list will be sorted into reverse order.
519Instead of \code{L.sort(lambda x,y: cmp(x.score, y.score)) ;
520L.reverse()}, you can now write: \code{L.sort(key = lambda x: x.score,
521reverse=True)}.
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000522
Andrew M. Kuchling981a9182003-11-13 21:33:26 +0000523The results of sorting are now guaranteed to be stable. This means
524that two entries with equal keys will be returned in the same order as
525they were input. For example, you can sort a list of people by name,
526and then sort the list by age, resulting in a list sorted by age where
527people with the same age are in name-sorted order.
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000528
Fred Drake56fcc232004-05-06 02:55:35 +0000529\item There is a new built-in function
530\function{sorted(\var{iterable})} that works like the in-place
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000531\method{list.sort()} method but can be used in
Fred Drake56fcc232004-05-06 02:55:35 +0000532expressions. The differences are:
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000533 \begin{itemize}
Raymond Hettinger7d1dd042003-11-12 16:42:10 +0000534 \item the input may be any iterable;
535 \item a newly formed copy is sorted, leaving the original intact; and
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000536 \item the expression returns the new sorted copy
537 \end{itemize}
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000538
539\begin{verbatim}
540>>> L = [9,7,8,3,2,4,1,6,5]
Raymond Hettinger64958a12003-12-17 20:43:33 +0000541>>> [10+i for i in sorted(L)] # usable in a list comprehension
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000542[11, 12, 13, 14, 15, 16, 17, 18, 19]
543>>> L = [9,7,8,3,2,4,1,6,5] # original is left unchanged
544[9,7,8,3,2,4,1,6,5]
Raymond Hettingerd4462302003-11-26 17:52:45 +0000545
Raymond Hettinger64958a12003-12-17 20:43:33 +0000546>>> sorted('Monte Python') # any iterable may be an input
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000547[' ', 'M', 'P', 'e', 'h', 'n', 'n', 'o', 'o', 't', 't', 'y']
Raymond Hettingerd4462302003-11-26 17:52:45 +0000548
549>>> # List the contents of a dict sorted by key values
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000550>>> colormap = dict(red=1, blue=2, green=3, black=4, yellow=5)
Raymond Hettinger64958a12003-12-17 20:43:33 +0000551>>> for k, v in sorted(colormap.iteritems()):
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000552... print k, v
553...
554black 4
555blue 2
556green 3
557red 1
558yellow 5
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000559\end{verbatim}
560
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +0000561\item The \function{eval(\var{expr}, \var{globals}, \var{locals})}
562function now accepts any mapping type for the \var{locals} argument.
563Previously this had to be a regular Python dictionary.
564
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000565\item The \function{zip()} built-in function and \function{itertools.izip()}
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000566 now return an empty list if called with no arguments.
567 Previously they raised a \exception{TypeError}
568 exception. This makes them more
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000569 suitable for use with variable length argument lists:
570
571\begin{verbatim}
572>>> def transpose(array):
573... return zip(*array)
574...
575>>> transpose([(1,2,3), (4,5,6)])
576[(1, 4), (2, 5), (3, 6)]
577>>> transpose([])
578[]
579\end{verbatim}
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +0000580
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000581\end{itemize}
582
583
584%======================================================================
585\subsection{Optimizations}
586
587\begin{itemize}
588
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000589\item The inner loops for list and tuple slicing
Raymond Hettingerade08ea2004-03-18 09:48:12 +0000590 were optimized and now run about one-third faster. The inner
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000591 loops were also optimized for dictionaries with performance
Raymond Hettingerade08ea2004-03-18 09:48:12 +0000592 boosts to \method{keys()}, \method{values()}, \method{items()},
Fred Drake9de0a2b2004-03-20 08:13:32 +0000593\method{iterkeys()}, \method{itervalues()}, and \method{iteritems()}.
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000594
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000595\item The machinery for growing and shrinking lists was optimized for
596 speed and for space efficiency. Appending and popping from lists now
597 runs faster due to more efficient code paths and less frequent use of
598 the underlying system \cfunction{realloc()}. List comprehensions
599 also benefit. \method{list.extend()} was also optimized and no
600 longer converts its argument into a temporary list before extending
601 the base list.
Raymond Hettinger7a6d2972004-02-13 19:00:07 +0000602
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000603\item \function{list()}, \function{tuple()}, \function{map()},
604 \function{filter()}, and \function{zip()} now run several times
605 faster with non-sequence arguments that supply a \method{__len__()}
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000606 method.
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000607
Raymond Hettinger23a0f4e2004-01-05 08:15:20 +0000608\item The methods \method{list.__getitem__()},
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000609 \method{dict.__getitem__()}, and \method{dict.__contains__()} are
610 are now implemented as \class{method_descriptor} objects rather
611 than \class{wrapper_descriptor} objects. This form of optimized
612 access doubles their performance and makes them more suitable for
Raymond Hettinger23a0f4e2004-01-05 08:15:20 +0000613 use as arguments to functionals:
614 \samp{map(mydict.__getitem__, keylist)}.
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000615
Fred Draked6d35d92004-06-03 13:31:22 +0000616\item Added a new opcode, \code{LIST_APPEND}, that simplifies
Raymond Hettingerdd80f762004-03-07 07:31:06 +0000617 the generated bytecode for list comprehensions and speeds them up
618 by about a third.
619
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000620\end{itemize}
621
622The net result of the 2.4 optimizations is that Python 2.4 runs the
623pystone benchmark around XX\% faster than Python 2.3 and YY\% faster
624than Python 2.2.
625
626
627%======================================================================
628\section{New, Improved, and Deprecated Modules}
629
630As usual, Python's standard library received a number of enhancements and
631bug fixes. Here's a partial list of the most notable changes, sorted
632alphabetically by module name. Consult the
633\file{Misc/NEWS} file in the source tree for a more
634complete list of changes, or look through the CVS logs for all the
635details.
636
637\begin{itemize}
638
Anthony Baxter5da4c832004-07-09 16:16:46 +0000639% XXX new email parser
640
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +0000641\item The \module{asyncore} module's \function{loop()} now has a
642 \var{count} parameter that lets you perform a limited number
643 of passes through the polling loop. The default is still to loop
644 forever.
645
Andrew M. Kuchling69f31eb2003-08-13 23:11:04 +0000646\item The \module{curses} modules now supports the ncurses extension
Fred Draked6d35d92004-06-03 13:31:22 +0000647 \function{use_default_colors()}. On platforms where the terminal
648 supports transparency, this makes it possible to use a transparent
649 background. (Contributed by J\"org Lehmann.)
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +0000650
Raymond Hettinger0c410272004-01-05 10:13:35 +0000651\item The \module{bisect} module now has an underlying C implementation
652 for improved performance.
653 (Contributed by Dmitry Vasiliev.)
654
Andrew M. Kuchling5303a962004-01-18 15:55:51 +0000655\item The CJKCodecs collections of East Asian codecs, maintained
656by Hye-Shik Chang, was integrated into 2.4.
657The new encodings are:
658
659\begin{itemize}
660 \item Chinese (PRC): gb2312, gbk, gb18030, hz
661 \item Chinese (ROC): big5, cp950
662 \item Japanese: cp932, shift-jis, shift-jisx0213, euc-jp,
663euc-jisx0213, iso-2022-jp, iso-2022-jp-1, iso-2022-jp-2,
664 iso-2022-jp-3, iso-2022-jp-ext
665 \item Korean: cp949, euc-kr, johab, iso-2022-kr
666\end{itemize}
667
Andrew M. Kuchlingfd0e4942004-02-09 13:23:34 +0000668\item There is a new \module{collections} module for
669 various specialized collection datatypes.
670 Currently it contains just one type, \class{deque},
671 a double-ended queue that supports efficiently adding and removing
672 elements from either end.
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000673
674\begin{verbatim}
675>>> from collections import deque
676>>> d = deque('ghi') # make a new deque with three items
677>>> d.append('j') # add a new entry to the right side
678>>> d.appendleft('f') # add a new entry to the left side
679>>> d # show the representation of the deque
680deque(['f', 'g', 'h', 'i', 'j'])
681>>> d.pop() # return and remove the rightmost item
682'j'
683>>> d.popleft() # return and remove the leftmost item
684'f'
685>>> list(d) # list the contents of the deque
686['g', 'h', 'i']
687>>> 'h' in d # search the deque
688True
689\end{verbatim}
690
Andrew M. Kuchlingfd0e4942004-02-09 13:23:34 +0000691Several modules now take advantage of \class{collections.deque} for
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000692improved performance, such as the \module{Queue} and
693\module{threading} modules.
Andrew M. Kuchling5303a962004-01-18 15:55:51 +0000694
Fred Drake9f15b5c2004-05-18 04:30:00 +0000695\item The \module{ConfigParser} classes have been enhanced slightly.
696 The \method{read()} method now returns a list of the files that
697 were successfully parsed, and the \method{set()} method raises
698 \exception{TypeError} if passed a \var{value} argument that isn't a
699 string.
700
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000701\item The \module{heapq} module has been converted to C. The resulting
Andrew M. Kuchlingfd0e4942004-02-09 13:23:34 +0000702 tenfold improvement in speed makes the module suitable for handling
Raymond Hettinger33ecffb2004-06-10 05:03:17 +0000703 high volumes of data. In addition, the module has two new functions
704 \function{nlargest()} and \function{nsmallest()} that use heaps to
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +0000705 find the N largest or smallest values in a dataset without the
Raymond Hettinger33ecffb2004-06-10 05:03:17 +0000706 expense of a full sort.
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000707
Andrew M. Kuchlingdff9dbd2003-11-20 22:22:19 +0000708\item The \module{imaplib} module now supports IMAP's THREAD command.
709(Contributed by Yves Dionne.)
710
Andrew M. Kuchlingad809552003-12-06 23:19:23 +0000711\item The \module{itertools} module gained a
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000712 \function{groupby(\var{iterable}\optional{, \var{func}})} function.
Andrew M. Kuchlingad809552003-12-06 23:19:23 +0000713 \var{iterable} returns a succession of elements, and the optional
714 \var{func} is a function that takes an element and returns a key
715 value; if omitted, the key is simply the element itself.
716 \function{groupby()} then groups the elements into subsequences
717 which have matching values of the key, and returns a series of 2-tuples
718 containing the key value and an iterator over the subsequence.
719
720Here's an example. The \var{key} function simply returns whether a
721number is even or odd, so the result of \function{groupby()} is to
722return consecutive runs of odd or even numbers.
723
724\begin{verbatim}
725>>> import itertools
726>>> L = [2,4,6, 7,8,9,11, 12, 14]
727>>> for key_val, it in itertools.groupby(L, lambda x: x % 2):
728... print key_val, list(it)
729...
7300 [2, 4, 6]
7311 [7]
7320 [8]
7331 [9, 11]
7340 [12, 14]
735>>>
736\end{verbatim}
737
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000738\function{groupby()} is typically used with sorted input. The logic
739for \function{groupby()} is similar to the \UNIX{} \code{uniq} filter
740which makes it handy for eliminating, counting, or identifying
741duplicate elements:
Raymond Hettingerfeb78c92003-12-12 13:13:47 +0000742
743\begin{verbatim}
744>>> word = 'abracadabra'
Raymond Hettingered54d912003-12-31 01:59:18 +0000745>>> letters = sorted(word) # Turn string into a sorted list of letters
Raymond Hettinger64958a12003-12-17 20:43:33 +0000746>>> letters
Andrew M. Kuchling4612bc52003-12-16 20:59:37 +0000747['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r']
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000748>>> for k, g in itertools.groupby(letters):
749... print k, list(g)
750...
751a ['a', 'a', 'a', 'a', 'a']
752b ['b', 'b']
753c ['c']
754d ['d']
755r ['r', 'r']
756>>> # List unique letters
757>>> [k for k, g in groupby(letters)]
Raymond Hettingerfeb78c92003-12-12 13:13:47 +0000758['a', 'b', 'c', 'd', 'r']
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000759>>> # Count letter occurences
760>>> [(k, len(list(g))) for k, g in groupby(letters)]
Raymond Hettingerfeb78c92003-12-12 13:13:47 +0000761[('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)]
Raymond Hettingerfeb78c92003-12-12 13:13:47 +0000762\end{verbatim}
763
Raymond Hettingered54d912003-12-31 01:59:18 +0000764\item \module{itertools} also gained a function named
765\function{tee(\var{iterator}, \var{N})} that returns \var{N} independent
766iterators that replicate \var{iterator}. If \var{N} is omitted, the
767default is 2.
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000768
769\begin{verbatim}
770>>> L = [1,2,3]
771>>> i1, i2 = itertools.tee(L)
772>>> i1,i2
773(<itertools.tee object at 0x402c2080>, <itertools.tee object at 0x402c2090>)
Raymond Hettingered54d912003-12-31 01:59:18 +0000774>>> list(i1) # Run the first iterator to exhaustion
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000775[1, 2, 3]
Raymond Hettingered54d912003-12-31 01:59:18 +0000776>>> list(i2) # Run the second iterator to exhaustion
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000777[1, 2, 3]
778>\end{verbatim}
779
780Note that \function{tee()} has to keep copies of the values returned
Raymond Hettingered54d912003-12-31 01:59:18 +0000781by the iterator; in the worst case, it may need to keep all of them.
Andrew M. Kuchling44a31e12004-01-01 18:33:34 +0000782This should therefore be used carefully if the leading iterator
Raymond Hettingered54d912003-12-31 01:59:18 +0000783can run far ahead of the trailing iterator in a long stream of inputs.
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000784If the separation is large, then you might as well use
Raymond Hettingered54d912003-12-31 01:59:18 +0000785\function{list()} instead. When the iterators track closely with one
786another, \function{tee()} is ideal. Possible applications include
787bookmarking, windowing, or lookahead iterators.
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000788
Andrew M. Kuchling23406892004-07-15 11:44:42 +0000789\item The \module{logging} package's \function{basicConfig} function
790gained some keyword arguments to simplify log configuration. The
791default behavior is to log messages to standard error, but
792various keyword arguments can be specified to log to a particular file,
793change the logging format, or set the logging level. For example:
Andrew M. Kuchlingbcefe692004-07-07 13:01:53 +0000794
795\begin{verbatim}
796import logging
797logging.basicConfig(filename = '/var/log/application.log',
798 level=0, # Log all messages, including debugging,
799 format='%(levelname):%(process):%(thread):%(message)')
800\end{verbatim}
801
802Another addition to \module{logging} is a
803\class{TimedRotatingFileHandler} class which rotates its log files at
804a timed interval. The module already had \class{RotatingFileHandler},
805which rotated logs once the file exceeded a certain size. Both
806classes derive from a new \class{BaseRotatingHandler} class that can
807be used to implement other rotating handlers.
808
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000809\item The \module{operator} module gained two new functions,
810\function{attrgetter(\var{attr})} and \function{itemgetter(\var{index})}.
811Both functions return callables that take a single argument and return
Raymond Hettingered54d912003-12-31 01:59:18 +0000812the corresponding attribute or item; these callables make excellent
Andrew M. Kuchlingbcefe692004-07-07 13:01:53 +0000813data extractors when used with \function{map()} or
814\function{sorted()}. For example:
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000815
816\begin{verbatim}
Raymond Hettingered54d912003-12-31 01:59:18 +0000817>>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000818>>> map(operator.itemgetter(0), L)
819['c', 'd', 'a', 'b']
820>>> map(operator.itemgetter(1), L)
Raymond Hettingered54d912003-12-31 01:59:18 +0000821[2, 1, 4, 3]
822>>> sorted(L, key=operator.itemgetter(1)) # Sort list by second tuple item
823[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000824\end{verbatim}
825
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +0000826\item A new \function{getsid()} function was added to the
827\module{posix} module that underlies the \module{os} module.
828(Contributed by J. Raynor.)
829
830\item The \module{poplib} module now supports POP over SSL.
831
832\item The \module{profile} module can now profile C extension functions.
833% XXX more to say about this?
834
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +0000835\item The \module{random} module has a new method called \method{getrandbits(N)}
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000836 which returns an N-bit long integer. This method supports the existing
837 \method{randrange()} method, making it possible to efficiently generate
Andrew M. Kuchling44a31e12004-01-01 18:33:34 +0000838 arbitrarily large random numbers.
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +0000839
840\item The regular expression language accepted by the \module{re} module
841 was extended with simple conditional expressions, written as
842 \code{(?(\var{group})\var{A}|\var{B})}. \var{group} is either a
843 numeric group ID or a group name defined with \code{(?P<group>...)}
844 earlier in the expression. If the specified group matched, the
845 regular expression pattern \var{A} will be tested against the string; if
846 the group didn't match, the pattern \var{B} will be used instead.
Raymond Hettinger874ebd52004-05-31 03:15:02 +0000847
Anthony Baxter1869df12004-07-12 08:15:37 +0000848% XXX sre is now non-recursive.
849
Raymond Hettinger874ebd52004-05-31 03:15:02 +0000850\item The \module{weakref} module now supports a wider variety of objects
851 including Python functions, class instances, sets, frozensets, deques,
852 arrays, files, sockets, and regular expression pattern objects.
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +0000853
854\item The \module{xmlrpclib} module now supports a multi-call extension for
855tranmitting multiple XML-RPC calls in a single HTTP operation.
Andrew M. Kuchling69f31eb2003-08-13 23:11:04 +0000856
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000857\end{itemize}
858
859
860%======================================================================
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000861% whole new modules get described in subsections here
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000862
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000863\subsection{cookielib}
864
865The \module{cookielib} library supports client-side handling for HTTP
866cookies, just as the \module{Cookie} provides server-side cookie
Andrew M. Kuchling71432f12004-07-05 01:40:07 +0000867support in CGI scripts. Cookies are stored in cookie jars; the library
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000868transparently stores cookies offered by the web server in the cookie
869jar, and fetches the cookie from the jar when connecting to the
870server. Similar to web browsers, policy objects control whether
871cookies are accepted or not.
872
873In order to store cookies across sessions, two implementations of
874cookie jars are provided: one that stores cookies in the Netscape
875format, so applications can use the Mozilla or Lynx cookie jars, and
876one that stores cookies in the same format as the Perl libwww libary.
877
878\module{urllib2} has been changed to interact with \module{cookielib}:
879\class{HTTPCookieProcessor} manages a cookie jar that is used when
880accessing URLs.
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000881
882% ======================================================================
883\section{Build and C API Changes}
884
885Changes to Python's build process and to the C API include:
886
887\begin{itemize}
888
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +0000889 \item Three new convenience macros were added for common return
890 values from extension functions: \csimplemacro{Py_RETURN_NONE},
891 \csimplemacro{Py_RETURN_TRUE}, and \csimplemacro{Py_RETURN_FALSE}.
892
Fred Drakece3caf22004-02-12 18:13:12 +0000893 \item A new function, \cfunction{PyTuple_Pack(\var{N}, \var{obj1},
894 \var{obj2}, ..., \var{objN})}, constructs tuples from a variable
895 length argument list of Python objects.
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000896
Fred Drakece3caf22004-02-12 18:13:12 +0000897 \item A new function, \cfunction{PyDict_Contains(\var{d}, \var{k})},
898 implements fast dictionary lookups without masking exceptions raised
899 during the look-up process.
Raymond Hettingerd4462302003-11-26 17:52:45 +0000900
Fred Drakece3caf22004-02-12 18:13:12 +0000901 \item A new method flag, \constant{METH_COEXISTS}, allows a function
Andrew M. Kuchling71432f12004-07-05 01:40:07 +0000902 defined in slots to co-exist with a \ctype{PyCFunction} having the
903 same name. This can halve the access time for a method such as
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +0000904 \method{set.__contains__()}.
905
906 \item Python can now be built with additional profiling for the interpreter
Andrew M. Kuchling71432f12004-07-05 01:40:07 +0000907 itself. This is intended for people developing on the Python core.
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +0000908 Providing \longprogramopt{--enable-profiling} to the
909 \program{configure} script will let you profile the interpreter with
910 \program{gprof}, and providing the \longprogramopt{--with-tsc} switch
Andrew M. Kuchling71432f12004-07-05 01:40:07 +0000911 enables profiling using the Pentium's Time-Stamp-Counter register.
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +0000912
913 \item The \ctype{tracebackobject} type has been renamed to \ctype{PyTracebackObject}.
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000914
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000915\end{itemize}
916
917
918%======================================================================
919\subsection{Port-Specific Changes}
920
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000921\begin{itemize}
922
923\item The Windows port now builds under MSVC++ 7.1 as well as version 6.
924
925\end{itemize}
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000926
927
928%======================================================================
929\section{Other Changes and Fixes \label{section-other}}
930
931As usual, there were a bunch of other improvements and bugfixes
932scattered throughout the source tree. A search through the CVS change
933logs finds there were XXX patches applied and YYY bugs fixed between
934Python 2.3 and 2.4. Both figures are likely to be underestimates.
935
936Some of the more notable changes are:
937
938\begin{itemize}
939
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000940\item The \module{timeit} module now automatically disables periodic
941 garbarge collection during the timing loop. This change makes
942 consecutive timings more comparable.
943
944\item The \module{base64} module now has more complete RFC 3548 support
945 for Base64, Base32, and Base16 encoding and decoding, including
946 optional case folding and optional alternative alphabets.
947 (Contributed by Barry Warsaw.)
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000948
949\end{itemize}
950
951
952%======================================================================
953\section{Porting to Python 2.4}
954
955This section lists previously described changes that may require
956changes to your code:
957
958\begin{itemize}
959
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000960\item The \function{zip()} built-in function and \function{itertools.izip()}
961 now return an empty list instead of raising a \exception{TypeError}
962 exception if called with no arguments.
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +0000963
964\item \function{dircache.listdir()} now passes exceptions to the caller
965 instead of returning empty lists.
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000966
Andrew M. Kuchling71432f12004-07-05 01:40:07 +0000967\item \function{LexicalHandler.startDTD()} used to receive the public and
968 system IDs in the wrong order. This has been corrected; applications
Fred Drake56fcc232004-05-06 02:55:35 +0000969 relying on the wrong order need to be fixed.
Martin v. Löwis456ab1d2004-05-06 01:54:36 +0000970
Andrew M. Kuchling71432f12004-07-05 01:40:07 +0000971\item \function{fcntl.ioctl} now warns if the \var{mutate}
972 argument is omitted and relevant.
Martin v. Löwis77ca6c42004-06-03 12:47:26 +0000973
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000974\end{itemize}
975
976
977%======================================================================
978\section{Acknowledgements \label{acks}}
979
980The author would like to thank the following people for offering
981suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchling981a9182003-11-13 21:33:26 +0000982article: Raymond Hettinger.
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000983
984\end{document}