blob: 642ced1f799df513d006493a8fda2376f784d726 [file] [log] [blame]
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001\documentclass{howto}
2\usepackage{distutils}
3% $Id$
4
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +00005% Don't write extensive text for new sections; I'll do that.
6% Feel free to add commented-out reminders of things that need
7% to be covered. --amk
8
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +00009% XXX pydoc can display links to module docs -- but when?
10%
11
Fred Drakeed0fa3d2003-07-30 19:14:09 +000012\title{What's New in Python 2.4}
Andrew M. Kuchling3b790912004-07-04 16:39:40 +000013\release{0.1}
Fred Drakeed0fa3d2003-07-30 19:14:09 +000014\author{A.M.\ Kuchling}
Fred Drakeb914ef02004-01-02 06:57:50 +000015\authoraddress{
16 \strong{Python Software Foundation}\\
17 Email: \email{amk@amk.ca}
18}
Fred Drakeed0fa3d2003-07-30 19:14:09 +000019
20\begin{document}
21\maketitle
22\tableofcontents
23
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +000024This article explains the new features in Python 2.4 alpha1, scheduled
25for release in early July 2004. The final version of Python 2.4 is
26expected to be released around September 2004.
Fred Drakeed0fa3d2003-07-30 19:14:09 +000027
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +000028Python 2.4 is a medium-sized release. It doesn't introduce as many
Andrew M. Kuchling3b790912004-07-04 16:39:40 +000029changes as the radical Python 2.2, but introduces more features than
30the conservative 2.3 release did. The most significant new language
31feature (as of this writing) is the addition of generator expressions;
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +000032most other changes are to the standard library.
Fred Drakeed0fa3d2003-07-30 19:14:09 +000033
34This article doesn't attempt to provide a complete specification of
Andrew M. Kuchling3b790912004-07-04 16:39:40 +000035every single new feature, but instead provides a convenient overview.
36For full details, you should refer to the documentation for Python
372.4, such as the \citetitle[../lib/lib.html]{Python Library Reference}
38and the \citetitle[../ref/ref.html]{Python Reference Manual}. If you
39want to understand the complete implementation and design rationale,
40refer to the PEP for a particular new feature or to the module
41documentation.
Fred Drakeed0fa3d2003-07-30 19:14:09 +000042
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +000043
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000044%======================================================================
45\section{PEP 218: Built-In Set Objects}
46
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +000047Python 2.3 introduced the \module{sets} module. C implementations of
48set data types have now been added to the Python core as two new
49built-in types, \function{set(\var{iterable})} and
50\function{frozenset(\var{iterable})}. They provide high speed
51operations for membership testing, for eliminating duplicates from
52sequences, and for mathematical operations like unions, intersections,
53differences, and symmetric differences.
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000054
55\begin{verbatim}
56>>> a = set('abracadabra') # form a set from a string
57>>> 'z' in a # fast membership testing
58False
59>>> a # unique letters in a
60set(['a', 'r', 'b', 'c', 'd'])
61>>> ''.join(a) # convert back into a string
62'arbcd'
Raymond Hettingerd4462302003-11-26 17:52:45 +000063
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000064>>> b = set('alacazam') # form a second set
65>>> a - b # letters in a but not in b
66set(['r', 'd', 'b'])
67>>> a | b # letters in either a or b
68set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
69>>> a & b # letters in both a and b
70set(['a', 'c'])
71>>> a ^ b # letters in a or b but not both
72set(['r', 'd', 'b', 'm', 'z', 'l'])
Raymond Hettingerd4462302003-11-26 17:52:45 +000073
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000074>>> a.add('z') # add a new element
75>>> a.update('wxy') # add multiple new elements
76>>> a
77set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'x', 'z'])
78>>> a.remove('x') # take one element out
79>>> a
80set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'z'])
81\end{verbatim}
82
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +000083The \function{frozenset} type is an immutable version of \function{set}.
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000084Since it is immutable and hashable, it may be used as a dictionary key or
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +000085as a member of another set.
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000086
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +000087The \module{sets} module remains in the standard library, and may be
88useful if you wish to subclass the \class{Set} or \class{ImmutableSet}
89classes. There are currently no plans to deprecate the module.
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +000090
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000091\begin{seealso}
92\seepep{218}{Adding a Built-In Set Object Type}{Originally proposed by
93Greg Wilson and ultimately implemented by Raymond Hettinger.}
94\end{seealso}
Fred Drakeed0fa3d2003-07-30 19:14:09 +000095
96%======================================================================
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +000097\section{PEP 237: Unifying Long Integers and Integers}
98
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +000099The lengthy transition process for this PEP, begun in Python 2.2,
Andrew M. Kuchlingd4be86c2004-07-04 01:44:04 +0000100takes another step forward in Python 2.4. In 2.3, certain integer
101operations that would behave differently after int/long unification
102triggered \exception{FutureWarning} warnings and returned values
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000103limited to 32 or 64 bits (depending on your platform). In 2.4, these
104expressions no longer produce a warning and instead produce a
105different result that's usually a long integer.
Andrew M. Kuchlingd4be86c2004-07-04 01:44:04 +0000106
107The problematic expressions are primarily left shifts and lengthy
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000108hexadecimal and octal constants. For example, \code{2 << 32} results
109in a warning in 2.3, evaluating to 0 on 32-bit platforms. In Python
1102.4, this expression now returns the correct answer, 8589934592.
Andrew M. Kuchlingd4be86c2004-07-04 01:44:04 +0000111
112\begin{seealso}
113\seepep{237}{Unifying Long Integers and Integers}{Original PEP
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000114written by Moshe Zadka and GvR. The changes for 2.4 were implemented by
Andrew M. Kuchlingd4be86c2004-07-04 01:44:04 +0000115Kalle Svensson.}
116\end{seealso}
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000117
118%======================================================================
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000119\section{PEP 289: Generator Expressions}
Raymond Hettinger354433a2004-05-19 08:20:33 +0000120
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000121The iterator feature introduced in Python 2.2 makes it easier to write
122programs that loop through large data sets without having the entire
123data set in memory at one time. Programmers can use iterators and the
124\module{itertools} module to write code in a fairly functional style.
125
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000126% XXX avoid metaphor
127List comprehensions have been the fly in the ointment because they
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000128produce a Python list object containing all of the items, unavoidably
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000129pulling them all into memory. When trying to write a
130functionally-styled program, it would be natural to write something
131like:
Raymond Hettinger354433a2004-05-19 08:20:33 +0000132
133\begin{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000134links = [link for link in get_all_links() if not link.followed]
135for link in links:
136 ...
Raymond Hettinger354433a2004-05-19 08:20:33 +0000137\end{verbatim}
138
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000139instead of
Raymond Hettinger354433a2004-05-19 08:20:33 +0000140
141\begin{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000142for link in get_all_links():
143 if link.followed:
144 continue
145 ...
146\end{verbatim}
Raymond Hettinger354433a2004-05-19 08:20:33 +0000147
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000148The first form is more concise and perhaps more readable, but if
149you're dealing with a large number of link objects the second form
150would have to be used.
Raymond Hettinger354433a2004-05-19 08:20:33 +0000151
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000152Generator expressions work similarly to list comprehensions but don't
153materialize the entire list; instead they create a generator that will
154return elements one by one. The above example could be written as:
Raymond Hettinger354433a2004-05-19 08:20:33 +0000155
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000156\begin{verbatim}
157links = (link for link in get_all_links() if not link.followed)
158for link in links:
159 ...
160\end{verbatim}
Raymond Hettinger170a6222004-05-19 19:45:19 +0000161
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000162Generator expressions always have to be written inside parentheses, as
163in the above example. The parentheses signalling a function call also
164count, so if you want to create a iterator that will be immediately
165passed to a function you could write:
Raymond Hettinger170a6222004-05-19 19:45:19 +0000166
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000167\begin{verbatim}
168print sum(obj.count for obj in list_all_objects())
169\end{verbatim}
Raymond Hettinger170a6222004-05-19 19:45:19 +0000170
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000171Generator expressions differ from list comprehensions in various small
172ways. Most notably, the loop variable (\var{obj} in the above
173example) is not accessible outside of the generator expression. List
174comprehensions leave the variable assigned to its last value; future
175versions of Python will change this, making list comprehensions match
176generator expressions in this respect.
Raymond Hettinger354433a2004-05-19 08:20:33 +0000177
178\begin{seealso}
179\seepep{289}{Generator Expressions}{Proposed by Raymond Hettinger and
180implemented by Jiwon Seo with early efforts steered by Hye-Shik Chang.}
181\end{seealso}
182
183%======================================================================
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000184\section{PEP 322: Reverse Iteration}
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000185
Fred Drake56fcc232004-05-06 02:55:35 +0000186A new built-in function, \function{reversed(\var{seq})}, takes a sequence
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000187and returns an iterator that loops over the elements of the sequence
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000188in reverse order.
189
190\begin{verbatim}
Raymond Hettingerbc3cba22003-11-12 16:39:30 +0000191>>> for i in reversed(xrange(1,4)):
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000192... print i
193...
1943
1952
1961
197\end{verbatim}
198
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000199Compared to extended slicing, such as \code{range(1,4)[::-1]},
200\function{reversed()} is easier to read, runs faster, and uses
201substantially less memory.
Raymond Hettingerbc3cba22003-11-12 16:39:30 +0000202
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000203Note that \function{reversed()} only accepts sequences, not arbitrary
Raymond Hettingerbc3cba22003-11-12 16:39:30 +0000204iterators. If you want to reverse an iterator, first convert it to
205a list with \function{list()}.
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000206
207\begin{verbatim}
Andrew M. Kuchling44a31e12004-01-01 18:33:34 +0000208>>> input= open('/etc/passwd', 'r')
209>>> for line in reversed(list(input)):
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000210... print line
211...
212root:*:0:0:System Administrator:/var/root:/bin/tcsh
213 ...
214\end{verbatim}
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000215
Andrew M. Kuchlingf7a6b672003-11-08 16:05:37 +0000216\begin{seealso}
217\seepep{322}{Reverse Iteration}{Written and implemented by Raymond Hettinger.}
218
219\end{seealso}
220
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000221
222%======================================================================
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000223\section{PEP 327: Decimal Data Type}
224
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000225Python has always supported floating-point (FP) numbers as a data
226type, based on the underlying C \ctype{double} type. However, while
227most programming languages provide a floating-point type, most people
228(even programmers) are unaware that computing with floating-point
229numbers entails certain unavoidable inaccuracies. The new decimal
230type provides a way to avoid these inaccuracies.
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000231
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000232\subsection{Why is Decimal needed?}
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000233
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000234The limitations arise from the representation used for floating-point numbers.
235FP numbers are made up of three components:
236
237\begin{itemize}
238\item The sign, which is -1 or +1.
239\item The mantissa, which is a single-digit binary number
240followed by a fractional part. For example, \code{1.01} in base-2 notation
241is \code{1 + 0/2 + 1/4}, or 1.25 in decimal notation.
242\item The exponent, which tells where the decimal point is located in the number represented.
243\end{itemize}
244
245For example, the number 1.25 has sign +1, mantissa 1.01 (in binary),
246and exponent of 0 (the decimal point doesn't need to be shifted). The
247number 5 has the same sign and mantissa, but the exponent is 2
248because the mantissa is multiplied by 4 (2 to the power of the exponent 2).
249
250Modern systems usually provide floating-point support that conforms to
251a relevant standard called IEEE 754. C's \ctype{double} type is
252usually implemented as a 64-bit IEEE 754 number, which uses 52 bits of
253space for the mantissa. This means that numbers can only be specified
254to 52 bits of precision. If you're trying to represent numbers whose
255expansion repeats endlessly, the expansion is cut off after 52 bits.
256Unfortunately, most software needs to produce output in base 10, and
257base 10 often gives rise to such repeating decimals. For example, 1.1
258decimal is binary \code{1.0001100110011 ...}; .1 = 1/16 + 1/32 + 1/256
259plus an infinite number of additional terms. IEEE 754 has to chop off
260that infinitely repeated decimal after 52 digits, so the
261representation is slightly inaccurate.
262
263Sometimes you can see this inaccuracy when the number is printed:
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000264\begin{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000265>>> 1.1
2661.1000000000000001
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000267\end{verbatim}
268
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000269The inaccuracy isn't always visible when you print the number because
270the FP-to-decimal-string conversion is provided by the C library, and
271most C libraries try to produce sensible output, but the inaccuracy is
272still there and subsequent operations can magnify the error.
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000273
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000274For many applications this doesn't matter. If I'm plotting points and
275displaying them on my monitor, the difference between 1.1 and
2761.1000000000000001 is too small to be visible. Reports often limit
277output to a certain number of decimal places, and if you round the
278number to two or three or even eight decimal places, the error is
279never apparent. However, for applications where it does matter,
280it's a lot of work to implement your own custom arithmetic routines.
281
282\subsection{The \class{Decimal} type}
283
284A new module, \module{decimal}, was added to Python's standard library.
285It contains two classes, \class{Decimal} and \class{Context}.
286\class{Decimal} instances represent numbers, and
287\class{Context} instances are used to wrap up various settings such as the precision and default rounding mode.
288
289\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.
290\class{Decimal} instances can be created from integers or strings:
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000291
292\begin{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000293>>> import decimal
294>>> decimal.Decimal(1972)
295Decimal("1972")
296>>> decimal.Decimal("1.1")
297Decimal("1.1")
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000298\end{verbatim}
299
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000300You can also provide tuples containing the sign, mantissa represented
301as a tuple of decimal digits, and exponent:
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000302
303\begin{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000304>>> decimal.Decimal((1, (1, 4, 7, 5), -2))
305Decimal("-14.75")
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000306\end{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000307
308Cautionary note: the sign bit is a Boolean value, so 0 is positive and 1 is negative.
309
310Floating-point numbers posed a bit of a problem: should the FP number
311representing 1.1 turn into the decimal number for exactly 1.1, or for
3121.1 plus whatever inaccuracies are introduced? The decision was to
313leave such a conversion out of the API. Instead, you should convert
314the floating-point number into a string using the desired precision and
315pass the string to the \class{Decimal} constructor:
316
317\begin{verbatim}
318>>> f = 1.1
319>>> decimal.Decimal(str(f))
320Decimal("1.1")
321>>> decimal.Decimal(repr(f))
322Decimal("1.1000000000000001")
323\end{verbatim}
324
325Once you have \class{Decimal} instances, you can perform the usual
326mathematical operations on them. One limitation: exponentiation
327requires an integer exponent:
328
329\begin{verbatim}
330>>> a = decimal.Decimal('35.72')
331>>> b = decimal.Decimal('1.73')
332>>> a+b
333Decimal("37.45")
334>>> a-b
335Decimal("33.99")
336>>> a*b
337Decimal("61.7956")
338>>> a/b
339Decimal("20.6473988")
340>>> a ** 2
341Decimal("1275.9184")
342>>> a ** b
343Decimal("NaN")
344\end{verbatim}
345
346You can combine \class{Decimal} instances with integers, but not with
347floating-point numbers:
348
349\begin{verbatim}
350>>> a + 4
351Decimal("39.72")
352>>> a + 4.5
353Traceback (most recent call last):
354 ...
355TypeError: You can interact Decimal only with int, long or Decimal data types.
356>>>
357\end{verbatim}
358
359\class{Decimal} numbers can be used with the \module{math} and
360\module{cmath} modules, though you'll get back a regular
361floating-point number and not a \class{Decimal}. Instances also have a \method{sqrt()} method:
362
363\begin{verbatim}
364>>> import math, cmath
365>>> d = decimal.Decimal('123456789012.345')
366>>> math.sqrt(d)
367351364.18288201344
368>>> cmath.sqrt(-d)
369351364.18288201344j
370>>> d.sqrt()
371Decimal(``351364.1828820134592177245001'')
372\end{verbatim}
373
374
375\subsection{The \class{Context} type}
376
377Instances of the \class{Context} class encapsulate several settings for
378decimal operations:
379
380\begin{itemize}
381 \item \member{prec} is the precision, the number of decimal places.
382 \item \member{rounding} specifies the rounding mode. The \module{decimal}
383 module has constants for the various possibilities:
384 \constant{ROUND_DOWN}, \constant{ROUND_CEILING}, \constant{ROUND_HALF_EVEN}, and various others.
385 \item \member{trap_enablers} is a dictionary specifying what happens on
386encountering certain error conditions: either an exception is raised or
387a value is returned. Some examples of error conditions are
388division by zero, loss of precision, and overflow.
389\end{itemize}
390
391There's a thread-local default context available by calling
392\function{getcontext()}; you can change the properties of this context
393to alter the default precision, rounding, or trap handling.
394
395\begin{verbatim}
396>>> decimal.getcontext().prec
39728
398>>> decimal.Decimal(1) / decimal.Decimal(7)
399Decimal(``0.1428571428571428571428571429'')
400>>> decimal.getcontext().prec = 9
401>>> decimal.Decimal(1) / decimal.Decimal(7)
402Decimal(``0.142857143'')
403\end{verbatim}
404
405The default action for error conditions is to return a special value
406such as infinity or not-a-number, but you can request that exceptions
407be raised:
408
409\begin{verbatim}
410>>> decimal.Decimal(1) / decimal.Decimal(0)
411Decimal(``Infinity'')
412>>> decimal.getcontext().trap_enablers[decimal.DivisionByZero] = True
413>>> decimal.Decimal(1) / decimal.Decimal(0)
414Traceback (most recent call last):
415 ...
416decimal.DivisionByZero: x / 0
417>>>
418\end{verbatim}
419
420The \class{Context} instance also has various methods for formatting
421numbers such as \method{to_eng_string()} and \method{to_sci_string()}.
422
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000423
424\begin{seealso}
425\seepep{327}{Decimal Data Type}{Written by Facundo Batista and implemented
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000426 by Facundo Batista, Eric Price, Raymond Hettinger, Aahz, and Tim Peters.}
427
428\seeurl{http://research.microsoft.com/~hollasch/cgindex/coding/ieeefloat.html}
429{A more detailed overview of the IEEE-754 representation.}
430
431\seeurl{http://www.lahey.com/float.htm}
432{The article uses Fortran code to illustrate many of the problems
433that floating-point inaccuracy can cause.}
434
435\seeurl{http://www2.hursley.ibm.com/decimal/}
436{A description of a decimal-based representation. This representation
437is being proposed as a standard, and underlies the new Python decimal
438type. Much of this material was written by Mike Cowlishaw, designer of the
439REXX language.}
440
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000441\end{seealso}
442
443
444%======================================================================
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000445\section{Other Language Changes}
446
447Here are all of the changes that Python 2.4 makes to the core Python
448language.
449
450\begin{itemize}
Raymond Hettingerd4462302003-11-26 17:52:45 +0000451
Raymond Hettinger31017ae2004-03-04 08:25:44 +0000452\item The \method{dict.update()} method now accepts the same
453argument forms as the \class{dict} constructor. This includes any
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +0000454mapping, any iterable of key/value pairs, and keyword arguments.
Raymond Hettinger31017ae2004-03-04 08:25:44 +0000455
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000456\item The string methods \method{ljust()}, \method{rjust()}, and
Andrew M. Kuchling67087562003-11-26 18:03:48 +0000457\method{center()} now take an optional argument for specifying a
Raymond Hettingerd4462302003-11-26 17:52:45 +0000458fill character other than a space.
459
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000460\item Strings also gained an \method{rsplit()} method that
Raymond Hettingered54d912003-12-31 01:59:18 +0000461works like the \method{split()} method but splits from the end of
Andrew M. Kuchling44a31e12004-01-01 18:33:34 +0000462the string.
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000463
464\begin{verbatim}
Raymond Hettinger7a6d2972004-02-13 19:00:07 +0000465>>> 'www.python.org'.split('.', 1)
466['www', 'python.org']
467'www.python.org'.rsplit('.', 1)
468['www.python', 'org']
469\end{verbatim}
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000470
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000471\item The \method{sort()} method of lists gained three keyword
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000472arguments: \var{cmp}, \var{key}, and \var{reverse}. These arguments
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000473make some common usages of \method{sort()} simpler. All are optional.
474
475\var{cmp} is the same as the previous single argument to
476\method{sort()}; if provided, the value should be a comparison
477function that takes two arguments and returns -1, 0, or +1 depending
478on how the arguments compare.
479
480\var{key} should be a single-argument function that takes a list
481element and returns a comparison key for the element. The list is
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000482then sorted using the comparison keys. The following example sorts a
483list case-insensitively:
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000484
485\begin{verbatim}
486>>> L = ['A', 'b', 'c', 'D']
487>>> L.sort() # Case-sensitive sort
488>>> L
489['A', 'D', 'b', 'c']
490>>> L.sort(key=lambda x: x.lower())
491>>> L
492['A', 'b', 'c', 'D']
493>>> L.sort(cmp=lambda x,y: cmp(x.lower(), y.lower()))
494>>> L
495['A', 'b', 'c', 'D']
496\end{verbatim}
497
498The last example, which uses the \var{cmp} parameter, is the old way
Raymond Hettingered54d912003-12-31 01:59:18 +0000499to perform a case-insensitive sort. It works but is slower than
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000500using a \var{key} parameter. Using \var{key} results in calling the
501\method{lower()} method once for each element in the list while using
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000502\var{cmp} will call it twice for each comparison.
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000503
Andrew M. Kuchling981a9182003-11-13 21:33:26 +0000504For simple key functions and comparison functions, it is often
505possible to avoid a \keyword{lambda} expression by using an unbound
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000506method instead. For example, the above case-insensitive sort is best
507coded as:
508
509\begin{verbatim}
510>>> L.sort(key=str.lower)
511>>> L
512['A', 'b', 'c', 'D']
513\end{verbatim}
514
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000515The \var{reverse} parameter should have a Boolean value. If the value
516is \constant{True}, the list will be sorted into reverse order.
517Instead of \code{L.sort(lambda x,y: cmp(x.score, y.score)) ;
518L.reverse()}, you can now write: \code{L.sort(key = lambda x: x.score,
519reverse=True)}.
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000520
Andrew M. Kuchling981a9182003-11-13 21:33:26 +0000521The results of sorting are now guaranteed to be stable. This means
522that two entries with equal keys will be returned in the same order as
523they were input. For example, you can sort a list of people by name,
524and then sort the list by age, resulting in a list sorted by age where
525people with the same age are in name-sorted order.
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000526
Fred Drake56fcc232004-05-06 02:55:35 +0000527\item There is a new built-in function
528\function{sorted(\var{iterable})} that works like the in-place
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000529\method{list.sort()} method but can be used in
Fred Drake56fcc232004-05-06 02:55:35 +0000530expressions. The differences are:
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000531 \begin{itemize}
Raymond Hettinger7d1dd042003-11-12 16:42:10 +0000532 \item the input may be any iterable;
533 \item a newly formed copy is sorted, leaving the original intact; and
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000534 \item the expression returns the new sorted copy
535 \end{itemize}
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000536
537\begin{verbatim}
538>>> L = [9,7,8,3,2,4,1,6,5]
Raymond Hettinger64958a12003-12-17 20:43:33 +0000539>>> [10+i for i in sorted(L)] # usable in a list comprehension
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000540[11, 12, 13, 14, 15, 16, 17, 18, 19]
541>>> L = [9,7,8,3,2,4,1,6,5] # original is left unchanged
542[9,7,8,3,2,4,1,6,5]
Raymond Hettingerd4462302003-11-26 17:52:45 +0000543
Raymond Hettinger64958a12003-12-17 20:43:33 +0000544>>> sorted('Monte Python') # any iterable may be an input
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000545[' ', 'M', 'P', 'e', 'h', 'n', 'n', 'o', 'o', 't', 't', 'y']
Raymond Hettingerd4462302003-11-26 17:52:45 +0000546
547>>> # List the contents of a dict sorted by key values
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000548>>> colormap = dict(red=1, blue=2, green=3, black=4, yellow=5)
Raymond Hettinger64958a12003-12-17 20:43:33 +0000549>>> for k, v in sorted(colormap.iteritems()):
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000550... print k, v
551...
552black 4
553blue 2
554green 3
555red 1
556yellow 5
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000557\end{verbatim}
558
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +0000559\item The \function{eval(\var{expr}, \var{globals}, \var{locals})}
560function now accepts any mapping type for the \var{locals} argument.
561Previously this had to be a regular Python dictionary.
562
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000563\item The \function{zip()} built-in function and \function{itertools.izip()}
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000564 now return an empty list if called with no arguments.
565 Previously they raised a \exception{TypeError}
566 exception. This makes them more
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000567 suitable for use with variable length argument lists:
568
569\begin{verbatim}
570>>> def transpose(array):
571... return zip(*array)
572...
573>>> transpose([(1,2,3), (4,5,6)])
574[(1, 4), (2, 5), (3, 6)]
575>>> transpose([])
576[]
577\end{verbatim}
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +0000578
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000579\end{itemize}
580
581
582%======================================================================
583\subsection{Optimizations}
584
585\begin{itemize}
586
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000587\item The inner loops for list and tupleslicing
Raymond Hettingerade08ea2004-03-18 09:48:12 +0000588 were optimized and now run about one-third faster. The inner
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000589 loops were also optimized for dictionaries with performance
Raymond Hettingerade08ea2004-03-18 09:48:12 +0000590 boosts to \method{keys()}, \method{values()}, \method{items()},
Fred Drake9de0a2b2004-03-20 08:13:32 +0000591\method{iterkeys()}, \method{itervalues()}, and \method{iteritems()}.
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000592
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000593\item The machinery for growing and shrinking lists was optimized for
594 speed and for space efficiency. Appending and popping from lists now
595 runs faster due to more efficient code paths and less frequent use of
596 the underlying system \cfunction{realloc()}. List comprehensions
597 also benefit. \method{list.extend()} was also optimized and no
598 longer converts its argument into a temporary list before extending
599 the base list.
Raymond Hettinger7a6d2972004-02-13 19:00:07 +0000600
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000601\item \function{list()}, \function{tuple()}, \function{map()},
602 \function{filter()}, and \function{zip()} now run several times
603 faster with non-sequence arguments that supply a \method{__len__()}
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000604 method.
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000605
Raymond Hettinger23a0f4e2004-01-05 08:15:20 +0000606\item The methods \method{list.__getitem__()},
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000607 \method{dict.__getitem__()}, and \method{dict.__contains__()} are
608 are now implemented as \class{method_descriptor} objects rather
609 than \class{wrapper_descriptor} objects. This form of optimized
610 access doubles their performance and makes them more suitable for
Raymond Hettinger23a0f4e2004-01-05 08:15:20 +0000611 use as arguments to functionals:
612 \samp{map(mydict.__getitem__, keylist)}.
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000613
Fred Draked6d35d92004-06-03 13:31:22 +0000614\item Added a new opcode, \code{LIST_APPEND}, that simplifies
Raymond Hettingerdd80f762004-03-07 07:31:06 +0000615 the generated bytecode for list comprehensions and speeds them up
616 by about a third.
617
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000618\end{itemize}
619
620The net result of the 2.4 optimizations is that Python 2.4 runs the
621pystone benchmark around XX\% faster than Python 2.3 and YY\% faster
622than Python 2.2.
623
624
625%======================================================================
626\section{New, Improved, and Deprecated Modules}
627
628As usual, Python's standard library received a number of enhancements and
629bug fixes. Here's a partial list of the most notable changes, sorted
630alphabetically by module name. Consult the
631\file{Misc/NEWS} file in the source tree for a more
632complete list of changes, or look through the CVS logs for all the
633details.
634
635\begin{itemize}
636
Anthony Baxter5da4c832004-07-09 16:16:46 +0000637% XXX new email parser
638
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +0000639\item The \module{asyncore} module's \function{loop()} now has a
640 \var{count} parameter that lets you perform a limited number
641 of passes through the polling loop. The default is still to loop
642 forever.
643
Andrew M. Kuchling69f31eb2003-08-13 23:11:04 +0000644\item The \module{curses} modules now supports the ncurses extension
Fred Draked6d35d92004-06-03 13:31:22 +0000645 \function{use_default_colors()}. On platforms where the terminal
646 supports transparency, this makes it possible to use a transparent
647 background. (Contributed by J\"org Lehmann.)
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +0000648
Raymond Hettinger0c410272004-01-05 10:13:35 +0000649\item The \module{bisect} module now has an underlying C implementation
650 for improved performance.
651 (Contributed by Dmitry Vasiliev.)
652
Andrew M. Kuchling5303a962004-01-18 15:55:51 +0000653\item The CJKCodecs collections of East Asian codecs, maintained
654by Hye-Shik Chang, was integrated into 2.4.
655The new encodings are:
656
657\begin{itemize}
658 \item Chinese (PRC): gb2312, gbk, gb18030, hz
659 \item Chinese (ROC): big5, cp950
660 \item Japanese: cp932, shift-jis, shift-jisx0213, euc-jp,
661euc-jisx0213, iso-2022-jp, iso-2022-jp-1, iso-2022-jp-2,
662 iso-2022-jp-3, iso-2022-jp-ext
663 \item Korean: cp949, euc-kr, johab, iso-2022-kr
664\end{itemize}
665
Andrew M. Kuchlingfd0e4942004-02-09 13:23:34 +0000666\item There is a new \module{collections} module for
667 various specialized collection datatypes.
668 Currently it contains just one type, \class{deque},
669 a double-ended queue that supports efficiently adding and removing
670 elements from either end.
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000671
672\begin{verbatim}
673>>> from collections import deque
674>>> d = deque('ghi') # make a new deque with three items
675>>> d.append('j') # add a new entry to the right side
676>>> d.appendleft('f') # add a new entry to the left side
677>>> d # show the representation of the deque
678deque(['f', 'g', 'h', 'i', 'j'])
679>>> d.pop() # return and remove the rightmost item
680'j'
681>>> d.popleft() # return and remove the leftmost item
682'f'
683>>> list(d) # list the contents of the deque
684['g', 'h', 'i']
685>>> 'h' in d # search the deque
686True
687\end{verbatim}
688
Andrew M. Kuchlingfd0e4942004-02-09 13:23:34 +0000689Several modules now take advantage of \class{collections.deque} for
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000690improved performance, such as the \module{Queue} and
691\module{threading} modules.
Andrew M. Kuchling5303a962004-01-18 15:55:51 +0000692
Fred Drake9f15b5c2004-05-18 04:30:00 +0000693\item The \module{ConfigParser} classes have been enhanced slightly.
694 The \method{read()} method now returns a list of the files that
695 were successfully parsed, and the \method{set()} method raises
696 \exception{TypeError} if passed a \var{value} argument that isn't a
697 string.
698
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000699\item The \module{heapq} module has been converted to C. The resulting
Andrew M. Kuchlingfd0e4942004-02-09 13:23:34 +0000700 tenfold improvement in speed makes the module suitable for handling
Raymond Hettinger33ecffb2004-06-10 05:03:17 +0000701 high volumes of data. In addition, the module has two new functions
702 \function{nlargest()} and \function{nsmallest()} that use heaps to
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +0000703 find the N largest or smallest values in a dataset without the
Raymond Hettinger33ecffb2004-06-10 05:03:17 +0000704 expense of a full sort.
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000705
Andrew M. Kuchlingdff9dbd2003-11-20 22:22:19 +0000706\item The \module{imaplib} module now supports IMAP's THREAD command.
707(Contributed by Yves Dionne.)
708
Andrew M. Kuchlingad809552003-12-06 23:19:23 +0000709\item The \module{itertools} module gained a
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000710 \function{groupby(\var{iterable}\optional{, \var{func}})} function.
Andrew M. Kuchlingad809552003-12-06 23:19:23 +0000711 \var{iterable} returns a succession of elements, and the optional
712 \var{func} is a function that takes an element and returns a key
713 value; if omitted, the key is simply the element itself.
714 \function{groupby()} then groups the elements into subsequences
715 which have matching values of the key, and returns a series of 2-tuples
716 containing the key value and an iterator over the subsequence.
717
718Here's an example. The \var{key} function simply returns whether a
719number is even or odd, so the result of \function{groupby()} is to
720return consecutive runs of odd or even numbers.
721
722\begin{verbatim}
723>>> import itertools
724>>> L = [2,4,6, 7,8,9,11, 12, 14]
725>>> for key_val, it in itertools.groupby(L, lambda x: x % 2):
726... print key_val, list(it)
727...
7280 [2, 4, 6]
7291 [7]
7300 [8]
7311 [9, 11]
7320 [12, 14]
733>>>
734\end{verbatim}
735
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000736\function{groupby()} is typically used with sorted input. The logic
737for \function{groupby()} is similar to the \UNIX{} \code{uniq} filter
738which makes it handy for eliminating, counting, or identifying
739duplicate elements:
Raymond Hettingerfeb78c92003-12-12 13:13:47 +0000740
741\begin{verbatim}
742>>> word = 'abracadabra'
Raymond Hettingered54d912003-12-31 01:59:18 +0000743>>> letters = sorted(word) # Turn string into a sorted list of letters
Raymond Hettinger64958a12003-12-17 20:43:33 +0000744>>> letters
Andrew M. Kuchling4612bc52003-12-16 20:59:37 +0000745['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r']
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000746>>> for k, g in itertools.groupby(letters):
747... print k, list(g)
748...
749a ['a', 'a', 'a', 'a', 'a']
750b ['b', 'b']
751c ['c']
752d ['d']
753r ['r', 'r']
754>>> # List unique letters
755>>> [k for k, g in groupby(letters)]
Raymond Hettingerfeb78c92003-12-12 13:13:47 +0000756['a', 'b', 'c', 'd', 'r']
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000757>>> # Count letter occurences
758>>> [(k, len(list(g))) for k, g in groupby(letters)]
Raymond Hettingerfeb78c92003-12-12 13:13:47 +0000759[('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)]
Raymond Hettingerfeb78c92003-12-12 13:13:47 +0000760\end{verbatim}
761
Raymond Hettingered54d912003-12-31 01:59:18 +0000762\item \module{itertools} also gained a function named
763\function{tee(\var{iterator}, \var{N})} that returns \var{N} independent
764iterators that replicate \var{iterator}. If \var{N} is omitted, the
765default is 2.
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000766
767\begin{verbatim}
768>>> L = [1,2,3]
769>>> i1, i2 = itertools.tee(L)
770>>> i1,i2
771(<itertools.tee object at 0x402c2080>, <itertools.tee object at 0x402c2090>)
Raymond Hettingered54d912003-12-31 01:59:18 +0000772>>> list(i1) # Run the first iterator to exhaustion
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000773[1, 2, 3]
Raymond Hettingered54d912003-12-31 01:59:18 +0000774>>> list(i2) # Run the second iterator to exhaustion
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000775[1, 2, 3]
776>\end{verbatim}
777
778Note that \function{tee()} has to keep copies of the values returned
Raymond Hettingered54d912003-12-31 01:59:18 +0000779by the iterator; in the worst case, it may need to keep all of them.
Andrew M. Kuchling44a31e12004-01-01 18:33:34 +0000780This should therefore be used carefully if the leading iterator
Raymond Hettingered54d912003-12-31 01:59:18 +0000781can run far ahead of the trailing iterator in a long stream of inputs.
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000782If the separation is large, then you might as well use
Raymond Hettingered54d912003-12-31 01:59:18 +0000783\function{list()} instead. When the iterators track closely with one
784another, \function{tee()} is ideal. Possible applications include
785bookmarking, windowing, or lookahead iterators.
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000786
Andrew M. Kuchlingbcefe692004-07-07 13:01:53 +0000787\item A \function{basicConfig} function was added to the
788\module{logging} package to simplify log configuration. It defaults
789to logging to standard error, but a
790number of optional keyword arguments can be specified to
791log to a particular file, change the logging format, or set the
792logging level. For example:
793
794\begin{verbatim}
795import logging
796logging.basicConfig(filename = '/var/log/application.log',
797 level=0, # Log all messages, including debugging,
798 format='%(levelname):%(process):%(thread):%(message)')
799\end{verbatim}
800
801Another addition to \module{logging} is a
802\class{TimedRotatingFileHandler} class which rotates its log files at
803a timed interval. The module already had \class{RotatingFileHandler},
804which rotated logs once the file exceeded a certain size. Both
805classes derive from a new \class{BaseRotatingHandler} class that can
806be used to implement other rotating handlers.
807
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000808\item The \module{operator} module gained two new functions,
809\function{attrgetter(\var{attr})} and \function{itemgetter(\var{index})}.
810Both functions return callables that take a single argument and return
Raymond Hettingered54d912003-12-31 01:59:18 +0000811the corresponding attribute or item; these callables make excellent
Andrew M. Kuchlingbcefe692004-07-07 13:01:53 +0000812data extractors when used with \function{map()} or
813\function{sorted()}. For example:
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000814
815\begin{verbatim}
Raymond Hettingered54d912003-12-31 01:59:18 +0000816>>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000817>>> map(operator.itemgetter(0), L)
818['c', 'd', 'a', 'b']
819>>> map(operator.itemgetter(1), L)
Raymond Hettingered54d912003-12-31 01:59:18 +0000820[2, 1, 4, 3]
821>>> sorted(L, key=operator.itemgetter(1)) # Sort list by second tuple item
822[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000823\end{verbatim}
824
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +0000825\item A new \function{getsid()} function was added to the
826\module{posix} module that underlies the \module{os} module.
827(Contributed by J. Raynor.)
828
829\item The \module{poplib} module now supports POP over SSL.
830
831\item The \module{profile} module can now profile C extension functions.
832% XXX more to say about this?
833
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +0000834\item The \module{random} module has a new method called \method{getrandbits(N)}
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000835 which returns an N-bit long integer. This method supports the existing
836 \method{randrange()} method, making it possible to efficiently generate
Andrew M. Kuchling44a31e12004-01-01 18:33:34 +0000837 arbitrarily large random numbers.
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +0000838
839\item The regular expression language accepted by the \module{re} module
840 was extended with simple conditional expressions, written as
841 \code{(?(\var{group})\var{A}|\var{B})}. \var{group} is either a
842 numeric group ID or a group name defined with \code{(?P<group>...)}
843 earlier in the expression. If the specified group matched, the
844 regular expression pattern \var{A} will be tested against the string; if
845 the group didn't match, the pattern \var{B} will be used instead.
Raymond Hettinger874ebd52004-05-31 03:15:02 +0000846
847\item The \module{weakref} module now supports a wider variety of objects
848 including Python functions, class instances, sets, frozensets, deques,
849 arrays, files, sockets, and regular expression pattern objects.
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +0000850
851\item The \module{xmlrpclib} module now supports a multi-call extension for
852tranmitting multiple XML-RPC calls in a single HTTP operation.
Andrew M. Kuchling69f31eb2003-08-13 23:11:04 +0000853
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000854\end{itemize}
855
856
857%======================================================================
858% whole new modules get described in \subsections here
859
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000860\subsection{cookielib}
861
862The \module{cookielib} library supports client-side handling for HTTP
863cookies, just as the \module{Cookie} provides server-side cookie
Andrew M. Kuchling71432f12004-07-05 01:40:07 +0000864support in CGI scripts. Cookies are stored in cookie jars; the library
Martin v. Löwis2a6ba902004-05-31 18:22:40 +0000865transparently stores cookies offered by the web server in the cookie
866jar, and fetches the cookie from the jar when connecting to the
867server. Similar to web browsers, policy objects control whether
868cookies are accepted or not.
869
870In order to store cookies across sessions, two implementations of
871cookie jars are provided: one that stores cookies in the Netscape
872format, so applications can use the Mozilla or Lynx cookie jars, and
873one that stores cookies in the same format as the Perl libwww libary.
874
875\module{urllib2} has been changed to interact with \module{cookielib}:
876\class{HTTPCookieProcessor} manages a cookie jar that is used when
877accessing URLs.
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000878
879% ======================================================================
880\section{Build and C API Changes}
881
882Changes to Python's build process and to the C API include:
883
884\begin{itemize}
885
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +0000886 \item Three new convenience macros were added for common return
887 values from extension functions: \csimplemacro{Py_RETURN_NONE},
888 \csimplemacro{Py_RETURN_TRUE}, and \csimplemacro{Py_RETURN_FALSE}.
889
Fred Drakece3caf22004-02-12 18:13:12 +0000890 \item A new function, \cfunction{PyTuple_Pack(\var{N}, \var{obj1},
891 \var{obj2}, ..., \var{objN})}, constructs tuples from a variable
892 length argument list of Python objects.
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000893
Fred Drakece3caf22004-02-12 18:13:12 +0000894 \item A new function, \cfunction{PyDict_Contains(\var{d}, \var{k})},
895 implements fast dictionary lookups without masking exceptions raised
896 during the look-up process.
Raymond Hettingerd4462302003-11-26 17:52:45 +0000897
Fred Drakece3caf22004-02-12 18:13:12 +0000898 \item A new method flag, \constant{METH_COEXISTS}, allows a function
Andrew M. Kuchling71432f12004-07-05 01:40:07 +0000899 defined in slots to co-exist with a \ctype{PyCFunction} having the
900 same name. This can halve the access time for a method such as
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +0000901 \method{set.__contains__()}.
902
903 \item Python can now be built with additional profiling for the interpreter
Andrew M. Kuchling71432f12004-07-05 01:40:07 +0000904 itself. This is intended for people developing on the Python core.
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +0000905 Providing \longprogramopt{--enable-profiling} to the
906 \program{configure} script will let you profile the interpreter with
907 \program{gprof}, and providing the \longprogramopt{--with-tsc} switch
Andrew M. Kuchling71432f12004-07-05 01:40:07 +0000908 enables profiling using the Pentium's Time-Stamp-Counter register.
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +0000909
910 \item The \ctype{tracebackobject} type has been renamed to \ctype{PyTracebackObject}.
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000911
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000912\end{itemize}
913
914
915%======================================================================
916\subsection{Port-Specific Changes}
917
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000918\begin{itemize}
919
920\item The Windows port now builds under MSVC++ 7.1 as well as version 6.
921
922\end{itemize}
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000923
924
925%======================================================================
926\section{Other Changes and Fixes \label{section-other}}
927
928As usual, there were a bunch of other improvements and bugfixes
929scattered throughout the source tree. A search through the CVS change
930logs finds there were XXX patches applied and YYY bugs fixed between
931Python 2.3 and 2.4. Both figures are likely to be underestimates.
932
933Some of the more notable changes are:
934
935\begin{itemize}
936
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000937\item The \module{timeit} module now automatically disables periodic
938 garbarge collection during the timing loop. This change makes
939 consecutive timings more comparable.
940
941\item The \module{base64} module now has more complete RFC 3548 support
942 for Base64, Base32, and Base16 encoding and decoding, including
943 optional case folding and optional alternative alphabets.
944 (Contributed by Barry Warsaw.)
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000945
946\end{itemize}
947
948
949%======================================================================
950\section{Porting to Python 2.4}
951
952This section lists previously described changes that may require
953changes to your code:
954
955\begin{itemize}
956
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000957\item The \function{zip()} built-in function and \function{itertools.izip()}
958 now return an empty list instead of raising a \exception{TypeError}
959 exception if called with no arguments.
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +0000960
961\item \function{dircache.listdir()} now passes exceptions to the caller
962 instead of returning empty lists.
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000963
Andrew M. Kuchling71432f12004-07-05 01:40:07 +0000964\item \function{LexicalHandler.startDTD()} used to receive the public and
965 system IDs in the wrong order. This has been corrected; applications
Fred Drake56fcc232004-05-06 02:55:35 +0000966 relying on the wrong order need to be fixed.
Martin v. Löwis456ab1d2004-05-06 01:54:36 +0000967
Andrew M. Kuchling71432f12004-07-05 01:40:07 +0000968\item \function{fcntl.ioctl} now warns if the \var{mutate}
969 argument is omitted and relevant.
Martin v. Löwis77ca6c42004-06-03 12:47:26 +0000970
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000971\end{itemize}
972
973
974%======================================================================
975\section{Acknowledgements \label{acks}}
976
977The author would like to thank the following people for offering
978suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchling981a9182003-11-13 21:33:26 +0000979article: Raymond Hettinger.
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000980
981\end{document}