blob: d1d316e9e53d2ce1db03ad99be4043c5389c3d2f [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. Kuchlingba59be02004-08-06 18:55:48 +000013\release{0.3}
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. Kuchling3294e9d2004-08-31 11:26:23 +000024This article explains the new features in Python 2.4 alpha3, scheduled
25for release in early September. The final version of Python 2.4 is
26expected to be released around December 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
Andrew M. Kuchling3294e9d2004-08-31 11:26:23 +000031features (as of this writing) are function decorators and generator
32expressions; most 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
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000108hexadecimal and octal constants. For example,
109\code{2 \textless{}\textless{} 32} results
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000110in a warning in 2.3, evaluating to 0 on 32-bit platforms. In Python
1112.4, this expression now returns the correct answer, 8589934592.
Andrew M. Kuchlingd4be86c2004-07-04 01:44:04 +0000112
113\begin{seealso}
114\seepep{237}{Unifying Long Integers and Integers}{Original PEP
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000115written by Moshe Zadka and GvR. The changes for 2.4 were implemented by
Andrew M. Kuchlingd4be86c2004-07-04 01:44:04 +0000116Kalle Svensson.}
117\end{seealso}
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000118
119%======================================================================
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000120\section{PEP 289: Generator Expressions}
Raymond Hettinger354433a2004-05-19 08:20:33 +0000121
Andrew M. Kuchling38dc2a62004-08-07 13:24:12 +0000122The iterator feature introduced in Python 2.2 and the
123\module{itertools} module make it easier to write programs that loop
124through large data sets without having the entire data set in memory
125at one time. List comprehensions don't fit into this picture very
126well because they produce a Python list object containing all of the
127items, unavoidably pulling them all into memory. When trying to write
128a functionally-styled program, it would be natural to write something
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000129like:
Raymond Hettinger354433a2004-05-19 08:20:33 +0000130
131\begin{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000132links = [link for link in get_all_links() if not link.followed]
133for link in links:
134 ...
Raymond Hettinger354433a2004-05-19 08:20:33 +0000135\end{verbatim}
136
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000137instead of
Raymond Hettinger354433a2004-05-19 08:20:33 +0000138
139\begin{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000140for link in get_all_links():
141 if link.followed:
142 continue
143 ...
144\end{verbatim}
Raymond Hettinger354433a2004-05-19 08:20:33 +0000145
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000146The first form is more concise and perhaps more readable, but if
147you're dealing with a large number of link objects the second form
Andrew M. Kuchling38dc2a62004-08-07 13:24:12 +0000148would have to be used to avoid having all link objects in memory at
149the same time.
Raymond Hettinger354433a2004-05-19 08:20:33 +0000150
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000151Generator expressions work similarly to list comprehensions but don't
152materialize the entire list; instead they create a generator that will
153return elements one by one. The above example could be written as:
Raymond Hettinger354433a2004-05-19 08:20:33 +0000154
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000155\begin{verbatim}
156links = (link for link in get_all_links() if not link.followed)
157for link in links:
158 ...
159\end{verbatim}
Raymond Hettinger170a6222004-05-19 19:45:19 +0000160
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000161Generator expressions always have to be written inside parentheses, as
162in the above example. The parentheses signalling a function call also
163count, so if you want to create a iterator that will be immediately
164passed to a function you could write:
Raymond Hettinger170a6222004-05-19 19:45:19 +0000165
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000166\begin{verbatim}
167print sum(obj.count for obj in list_all_objects())
168\end{verbatim}
Raymond Hettinger170a6222004-05-19 19:45:19 +0000169
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000170Generator expressions differ from list comprehensions in various small
171ways. Most notably, the loop variable (\var{obj} in the above
172example) is not accessible outside of the generator expression. List
173comprehensions leave the variable assigned to its last value; future
174versions of Python will change this, making list comprehensions match
175generator expressions in this respect.
Raymond Hettinger354433a2004-05-19 08:20:33 +0000176
177\begin{seealso}
178\seepep{289}{Generator Expressions}{Proposed by Raymond Hettinger and
179implemented by Jiwon Seo with early efforts steered by Hye-Shik Chang.}
180\end{seealso}
181
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +0000182
183%======================================================================
184\section{PEP 292: Simpler String Substitutions}
185
186Some new classes in the standard library provide a
187alternative mechanism for substituting variables into strings that's
188better-suited for applications where untrained users need to edit templates.
189
190The usual way of substituting variables by name is the \code{\%}
191operator:
192
193\begin{verbatim}
194>>> '%(page)i: %(title)s' % {'page':2, 'title': 'The Best of Times'}
195'2: The Best of Times'
196\end{verbatim}
197
198When writing the template string, it can be easy to forget the
199\samp{i} or \samp{s} after the closing parenthesis. This isn't a big
200problem if the template is in a Python module, because you run the
201code, get an ``Unsupported format character'' \exception{ValueError},
202and fix the problem. However, consider an application such as Mailman
203where template strings or translations are being edited by users who
204aren't aware of the Python language; the syntax is complicated to
205explain to such users, and if they make a mistake, it's difficult to
206provide helpful feedback to them.
207
208PEP 292 adds a \class{Template} class to the \module{string} module
209that uses \samp{\$} to indicate a substitution. \class{Template} is a
210subclass of the built-in Unicode type, so the result is always a
211Unicode string:
212
213\begin{verbatim}
214>>> import string
215>>> t = string.Template('$page: $title')
216>>> t % {'page':2, 'title': 'The Best of Times'}
217u'2: The Best of Times'
218>>> t2 % {'cost':42.50, 'action':'polish'}
219u'$ 42.5: polishing'
220\end{verbatim}
221
222% $ Terminate $-mode for Emacs
223
224If a key is missing from the dictionary, the \class{Template} class
225will raise a \exception{KeyError}. There's also a \class{SafeTemplate}
226class that ignores missing keys:
227
228\begin{verbatim}
229>>> t = string.SafeTemplate('$page: $title')
230>>> t % {'page':3}
231u'3: $title'
232\end{verbatim}
233
234Because templates are Unicode strings, you can use a template with the
235\module{gettext} module to look up translated versions of a message.
236
237\begin{seealso}
238\seepep{292}{Simpler String Substitutions}{Written and implemented
239by Barry Warsaw.}
240\end{seealso}
241
242
Raymond Hettinger354433a2004-05-19 08:20:33 +0000243%======================================================================
Andrew M. Kuchlingd91fcbe2004-08-02 12:44:28 +0000244\section{PEP 318: Decorators for Functions, Methods and Classes}
245
Andrew M. Kuchling77a602f2004-08-02 13:48:18 +0000246Python 2.2 extended Python's object model by adding static methods and
247class methods, but it didn't extend Python's syntax to provide any new
248way of defining static or class methods. Instead, you had to write a
249\keyword{def} statement in the usual way, and pass the resulting
250method to a \function{staticmethod()} or \function{classmethod()}
251function that would wrap up the function as a method of the new type.
252Your code would look like this:
253
254\begin{verbatim}
255class C:
256 def meth (cls):
257 ...
258
259 meth = classmethod(meth) # Rebind name to wrapped-up class method
260\end{verbatim}
261
262If the method was very long, it would be easy to miss or forget the
263\function{classmethod()} invocation after the function body.
264
265The intention was always to add some syntax to make such definitions
266more readable, but at the time of 2.2's release a good syntax was not
267obvious. Years later, when Python 2.4 is coming out, a good syntax
268\emph{still} isn't obvious but users are asking for easier access to
269the feature, so a new syntactic feature has been added.
270
271The feature is called ``function decorators''. The name comes from
272the idea that \function{classmethod}, \function{staticmethod}, and
273friends are storing additional information on a function object; they're
274\emph{decorating} functions with more details.
275
Fred Drake3f5c6542004-08-06 03:34:20 +0000276The notation borrows from Java and uses the \character{@} character as an
Andrew M. Kuchling77a602f2004-08-02 13:48:18 +0000277indicator. Using the new syntax, the example above would be written:
278
279\begin{verbatim}
280class C:
281
282 @classmethod
283 def meth (cls):
284 ...
285
286\end{verbatim}
287
288The \code{@classmethod} is shorthand for the
Fred Drake3f5c6542004-08-06 03:34:20 +0000289\code{meth=classmethod(meth)} assignment. More generally, if you have
Andrew M. Kuchling77a602f2004-08-02 13:48:18 +0000290the following:
291
292\begin{verbatim}
293@A @B @C
294def f ():
295 ...
296\end{verbatim}
297
298It's equivalent to:
299
300\begin{verbatim}
301def f(): ...
302f = C(B(A(f)))
303\end{verbatim}
304
305Decorators must come on the line before a function definition, and
306can't be on the same line, meaning that \code{@A def f(): ...} is
307illegal. You can only decorate function definitions, either at the
308module-level or inside a class; you can't decorate class definitions.
309
310A decorator is just a function that takes the function to be decorated
311as an argument and returns either the same function or some new
312callable thing. It's easy to write your own decorators. The
313following simple example just sets an attribute on the function
314object:
315
316\begin{verbatim}
317>>> def deco(func):
318... func.attr = 'decorated'
319... return func
320...
321>>> @deco
322... def f(): pass
323...
324>>> f
325<function f at 0x402ef0d4>
326>>> f.attr
327'decorated'
328>>>
329\end{verbatim}
330
331As a slightly more realistic example, the following decorator checks
332that the supplied argument is an integer:
333
334\begin{verbatim}
335def require_int (func):
336 def wrapper (arg):
337 assert isinstance(arg, int)
338 return func(arg)
339
340 return wrapper
341
342@require_int
343def p1 (arg):
344 print arg
345
346@require_int
347def p2(arg):
348 print arg*2
349\end{verbatim}
350
351An example in \pep{318} contains a fancier version of this idea that
352lets you specify the required type and check the returned type as
353well.
354
355Decorator functions can take arguments. If arguments are supplied,
356the decorator function is called with only those arguments and must
357return a new decorator function; this new function must take a single
358function and return a function, as previously described. In other
359words, \code{@A @B @C(args)} becomes:
360
361\begin{verbatim}
362def f(): ...
363_deco = C(args)
364f = _deco(B(A(f)))
365\end{verbatim}
366
367Getting this right can be slightly brain-bending, but it's not too
368difficult.
369
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +0000370A small related change makes the \member{func_name} attribute of
371functions writable. This attribute is used to display function names
372in tracebacks, so decorators should change the name of any new
373function that's constructed and returned.
374
Andrew M. Kuchling77a602f2004-08-02 13:48:18 +0000375The new syntax was provisionally added in 2.4alpha2, and is subject to
376change during the 2.4alpha release cycle depending on the Python
377community's reaction. Post-2.4 versions of Python will preserve
378compatibility with whatever syntax is used in 2.4final.
Andrew M. Kuchlingd91fcbe2004-08-02 12:44:28 +0000379
380\begin{seealso}
381\seepep{318}{Decorators for Functions, Methods and Classes}{Written
Andrew M. Kuchling77a602f2004-08-02 13:48:18 +0000382by Kevin D. Smith, Jim Jewett, and Skip Montanaro. Several people
383wrote patches implementing function decorators, but the one that was
Fred Drakee72bd4d2004-08-02 21:50:26 +0000384actually checked in was patch \#979728, written by Mark Russell.}
Andrew M. Kuchlingd91fcbe2004-08-02 12:44:28 +0000385\end{seealso}
386
387%======================================================================
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000388\section{PEP 322: Reverse Iteration}
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000389
Fred Drake56fcc232004-05-06 02:55:35 +0000390A new built-in function, \function{reversed(\var{seq})}, takes a sequence
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000391and returns an iterator that loops over the elements of the sequence
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000392in reverse order.
393
394\begin{verbatim}
Raymond Hettingerbc3cba22003-11-12 16:39:30 +0000395>>> for i in reversed(xrange(1,4)):
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000396... print i
397...
3983
3992
4001
401\end{verbatim}
402
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000403Compared to extended slicing, such as \code{range(1,4)[::-1]},
404\function{reversed()} is easier to read, runs faster, and uses
405substantially less memory.
Raymond Hettingerbc3cba22003-11-12 16:39:30 +0000406
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000407Note that \function{reversed()} only accepts sequences, not arbitrary
Raymond Hettingerbc3cba22003-11-12 16:39:30 +0000408iterators. If you want to reverse an iterator, first convert it to
409a list with \function{list()}.
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000410
411\begin{verbatim}
Andrew M. Kuchling44a31e12004-01-01 18:33:34 +0000412>>> input= open('/etc/passwd', 'r')
413>>> for line in reversed(list(input)):
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000414... print line
415...
416root:*:0:0:System Administrator:/var/root:/bin/tcsh
417 ...
418\end{verbatim}
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000419
Andrew M. Kuchlingf7a6b672003-11-08 16:05:37 +0000420\begin{seealso}
421\seepep{322}{Reverse Iteration}{Written and implemented by Raymond Hettinger.}
422
423\end{seealso}
424
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000425
426%======================================================================
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000427\section{PEP 327: Decimal Data Type}
428
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000429Python has always supported floating-point (FP) numbers as a data
430type, based on the underlying C \ctype{double} type. However, while
431most programming languages provide a floating-point type, most people
432(even programmers) are unaware that computing with floating-point
433numbers entails certain unavoidable inaccuracies. The new decimal
434type provides a way to avoid these inaccuracies.
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000435
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000436\subsection{Why is Decimal needed?}
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000437
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000438The limitations arise from the representation used for floating-point numbers.
439FP numbers are made up of three components:
440
441\begin{itemize}
Andrew M. Kuchlinge34c3bd2004-08-31 12:21:44 +0000442\item The sign, which is positive or negative.
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000443\item The mantissa, which is a single-digit binary number
444followed by a fractional part. For example, \code{1.01} in base-2 notation
445is \code{1 + 0/2 + 1/4}, or 1.25 in decimal notation.
446\item The exponent, which tells where the decimal point is located in the number represented.
447\end{itemize}
448
Andrew M. Kuchlinge34c3bd2004-08-31 12:21:44 +0000449For example, the number 1.25 has positive sign, a mantissa value of
4501.01 (in binary), and an exponent of 0 (the decimal point doesn't need
451to be shifted). The number 5 has the same sign and mantissa, but the
452exponent is 2 because the mantissa is multiplied by 4 (2 to the power
453of the exponent 2).
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000454
455Modern systems usually provide floating-point support that conforms to
456a relevant standard called IEEE 754. C's \ctype{double} type is
457usually implemented as a 64-bit IEEE 754 number, which uses 52 bits of
458space for the mantissa. This means that numbers can only be specified
459to 52 bits of precision. If you're trying to represent numbers whose
460expansion repeats endlessly, the expansion is cut off after 52 bits.
461Unfortunately, most software needs to produce output in base 10, and
Andrew M. Kuchlinge34c3bd2004-08-31 12:21:44 +0000462base 10 often gives rise to such repeating decimals in the binary
463expansion. For example, 1.1 decimal is binary \code{1.0001100110011
464...}; .1 = 1/16 + 1/32 + 1/256 plus an infinite number of additional
465terms. IEEE 754 has to chop off that infinitely repeated decimal
466after 52 digits, so the representation is slightly inaccurate.
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000467
468Sometimes you can see this inaccuracy when the number is printed:
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000469\begin{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000470>>> 1.1
4711.1000000000000001
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000472\end{verbatim}
473
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000474The inaccuracy isn't always visible when you print the number because
Andrew M. Kuchlinge34c3bd2004-08-31 12:21:44 +0000475the FP-to-decimal-string conversion is provided by the C library, and
476most C libraries try to produce sensible output. Even if it's not
477displayed, however, the inaccuracy is still there and subsequent
478operations can magnify the error.
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000479
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000480For many applications this doesn't matter. If I'm plotting points and
481displaying them on my monitor, the difference between 1.1 and
4821.1000000000000001 is too small to be visible. Reports often limit
483output to a certain number of decimal places, and if you round the
484number to two or three or even eight decimal places, the error is
485never apparent. However, for applications where it does matter,
486it's a lot of work to implement your own custom arithmetic routines.
487
Andrew M. Kuchlinge34c3bd2004-08-31 12:21:44 +0000488Hence, the \class{Decimal} type was created.
489
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000490\subsection{The \class{Decimal} type}
491
492A new module, \module{decimal}, was added to Python's standard library.
493It contains two classes, \class{Decimal} and \class{Context}.
494\class{Decimal} instances represent numbers, and
495\class{Context} instances are used to wrap up various settings such as the precision and default rounding mode.
496
Andrew M. Kuchlinge34c3bd2004-08-31 12:21:44 +0000497\class{Decimal} instances, like regular Python integers and FP
498numbers, are immutable; once they've been created, you can't change
499the value it represents. \class{Decimal} instances can be created
500from integers or strings:
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000501
502\begin{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000503>>> import decimal
504>>> decimal.Decimal(1972)
505Decimal("1972")
506>>> decimal.Decimal("1.1")
507Decimal("1.1")
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000508\end{verbatim}
509
Andrew M. Kuchlinge34c3bd2004-08-31 12:21:44 +0000510You can also provide tuples containing the sign, the mantissa represented
511as a tuple of decimal digits, and the exponent:
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000512
513\begin{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000514>>> decimal.Decimal((1, (1, 4, 7, 5), -2))
515Decimal("-14.75")
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000516\end{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000517
Andrew M. Kuchlinge34c3bd2004-08-31 12:21:44 +0000518Cautionary note: the sign bit is a Boolean value, so 0 is positive and
5191 is negative.
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000520
Andrew M. Kuchlinge34c3bd2004-08-31 12:21:44 +0000521Converting from floating-point numbers poses a bit of a problem:
522should the FP number representing 1.1 turn into the decimal number for
523exactly 1.1, or for 1.1 plus whatever inaccuracies are introduced?
524The decision was to leave such a conversion out of the API. Instead,
525you should convert the floating-point number into a string using the
526desired precision and pass the string to the \class{Decimal}
527constructor:
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000528
529\begin{verbatim}
530>>> f = 1.1
531>>> decimal.Decimal(str(f))
532Decimal("1.1")
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000533>>> decimal.Decimal('%.12f' % f)
534Decimal("1.100000000000")
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000535\end{verbatim}
536
537Once you have \class{Decimal} instances, you can perform the usual
538mathematical operations on them. One limitation: exponentiation
539requires an integer exponent:
540
541\begin{verbatim}
542>>> a = decimal.Decimal('35.72')
543>>> b = decimal.Decimal('1.73')
544>>> a+b
545Decimal("37.45")
546>>> a-b
547Decimal("33.99")
548>>> a*b
549Decimal("61.7956")
550>>> a/b
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000551Decimal("20.64739884393063583815028902")
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000552>>> a ** 2
553Decimal("1275.9184")
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000554>>> a**b
555Traceback (most recent call last):
556 ...
557decimal.InvalidOperation: x ** (non-integer)
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000558\end{verbatim}
559
560You can combine \class{Decimal} instances with integers, but not with
561floating-point numbers:
562
563\begin{verbatim}
564>>> a + 4
565Decimal("39.72")
566>>> a + 4.5
567Traceback (most recent call last):
568 ...
569TypeError: You can interact Decimal only with int, long or Decimal data types.
570>>>
571\end{verbatim}
572
573\class{Decimal} numbers can be used with the \module{math} and
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000574\module{cmath} modules, but note that they'll be immediately converted to
575floating-point numbers before the operation is performed, resulting in
576a possible loss of precision and accuracy. You'll also get back a
577regular floating-point number and not a \class{Decimal}.
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000578
579\begin{verbatim}
580>>> import math, cmath
581>>> d = decimal.Decimal('123456789012.345')
582>>> math.sqrt(d)
583351364.18288201344
584>>> cmath.sqrt(-d)
585351364.18288201344j
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000586\end{verbatim}
587
588Instances also have a \method{sqrt()} method that returns a
589\class{Decimal}, but if you need other things such as trigonometric
590functions you'll have to implement them.
591
592\begin{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000593>>> d.sqrt()
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000594Decimal("351364.1828820134592177245001")
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000595\end{verbatim}
596
597
598\subsection{The \class{Context} type}
599
600Instances of the \class{Context} class encapsulate several settings for
601decimal operations:
602
603\begin{itemize}
604 \item \member{prec} is the precision, the number of decimal places.
605 \item \member{rounding} specifies the rounding mode. The \module{decimal}
606 module has constants for the various possibilities:
607 \constant{ROUND_DOWN}, \constant{ROUND_CEILING}, \constant{ROUND_HALF_EVEN}, and various others.
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000608 \item \member{traps} is a dictionary specifying what happens on
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000609encountering certain error conditions: either an exception is raised or
610a value is returned. Some examples of error conditions are
611division by zero, loss of precision, and overflow.
612\end{itemize}
613
614There's a thread-local default context available by calling
615\function{getcontext()}; you can change the properties of this context
616to alter the default precision, rounding, or trap handling.
617
618\begin{verbatim}
619>>> decimal.getcontext().prec
62028
621>>> decimal.Decimal(1) / decimal.Decimal(7)
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000622Decimal("0.1428571428571428571428571429")
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000623>>> decimal.getcontext().prec = 9
624>>> decimal.Decimal(1) / decimal.Decimal(7)
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000625Decimal("0.142857143")
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000626\end{verbatim}
627
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000628The default action for error conditions is selectable; the module can
629either return a special value such as infinity or not-a-number, or
630exceptions can be raised:
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000631
632\begin{verbatim}
633>>> decimal.Decimal(1) / decimal.Decimal(0)
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000634Traceback (most recent call last):
635 ...
636decimal.DivisionByZero: x / 0
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000637>>> decimal.getcontext().traps[decimal.DivisionByZero] = False
638>>> decimal.Decimal(1) / decimal.Decimal(0)
639Decimal("Infinity")
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000640>>>
641\end{verbatim}
642
643The \class{Context} instance also has various methods for formatting
644numbers such as \method{to_eng_string()} and \method{to_sci_string()}.
645
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000646For more information, see the documentation for the \module{decimal}
647module, which includes a quick-start tutorial and a reference.
648
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000649\begin{seealso}
650\seepep{327}{Decimal Data Type}{Written by Facundo Batista and implemented
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000651 by Facundo Batista, Eric Price, Raymond Hettinger, Aahz, and Tim Peters.}
652
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000653\seeurl{http://research.microsoft.com/\textasciitilde hollasch/cgindex/coding/ieeefloat.html}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000654{A more detailed overview of the IEEE-754 representation.}
655
656\seeurl{http://www.lahey.com/float.htm}
657{The article uses Fortran code to illustrate many of the problems
658that floating-point inaccuracy can cause.}
659
660\seeurl{http://www2.hursley.ibm.com/decimal/}
661{A description of a decimal-based representation. This representation
662is being proposed as a standard, and underlies the new Python decimal
663type. Much of this material was written by Mike Cowlishaw, designer of the
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000664Rexx language.}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000665
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000666\end{seealso}
667
668
669%======================================================================
Andrew M. Kuchling3294e9d2004-08-31 11:26:23 +0000670\section{PEP 328: Multi-line Imports}
671
672One language change is a small syntactic tweak aimed at making it
673easier to import many names from a module. In a
674\code{from \var{module} import \var{names}} statement,
675\var{names} is a sequence of names separated by commas. If the sequence is
676very long, you can either write multiple imports from the same module,
677or you can use backslashes to escape the line endings:
678
679\begin{verbatim}
680from SimpleXMLRPCServer import SimpleXMLRPCServer,\
681 SimpleXMLRPCRequestHandler,\
682 CGIXMLRPCRequestHandler,\
683 resolve_dotted_attribute
684\end{verbatim}
685
686The syntactic change simply allows putting the names within
687parentheses. Python ignores newlines within a parenthesized
688expression, so the backslashes are no longer needed:
689
690\begin{verbatim}
691from SimpleXMLRPCServer import (SimpleXMLRPCServer,
692 SimpleXMLRPCRequestHandler,
693 CGIXMLRPCRequestHandler,
694 resolve_dotted_attribute)
695\end{verbatim}
696
697The PEP also proposes that all \keyword{import} statements be
698absolute imports, with a leading \samp{.} character to indicate a
699relative import. This part of the PEP is not yet implemented.
700
701\begin{seealso}
Fred Drake410eb842004-09-01 04:05:08 +0000702\seepep{328}{Imports: Multi-Line and Absolute/Relative}
703 {Written by Aahz. Multi-line imports were implemented by
704 Dima Dorfman.}
705\end{seealso}
Andrew M. Kuchling3294e9d2004-08-31 11:26:23 +0000706
707
708%======================================================================
Andrew M. Kuchling65a33322004-07-21 12:41:38 +0000709\section{PEP 331: Locale-Independent Float/String Conversions}
710
711The \module{locale} modules lets Python software select various
712conversions and display conventions that are localized to a particular
713country or language. However, the module was careful to not change
714the numeric locale because various functions in Python's
715implementation required that the numeric locale remain set to the
716\code{'C'} locale. Often this was because the code was using the C library's
717\cfunction{atof()} function.
718
719Not setting the numeric locale caused trouble for extensions that used
720third-party C libraries, however, because they wouldn't have the
721correct locale set. The motivating example was GTK+, whose user
722interface widgets weren't displaying numbers in the current locale.
723
724The solution described in the PEP is to add three new functions to the
725Python API that perform ASCII-only conversions, ignoring the locale
726setting:
727
728\begin{itemize}
729 \item \cfunction{PyOS_ascii_strtod(\var{str}, \var{ptr})}
730and \cfunction{PyOS_ascii_atof(\var{str}, \var{ptr})}
731both convert a string to a C \ctype{double}.
732 \item \cfunction{PyOS_ascii_formatd(\var{buffer}, \var{buf_len}, \var{format}, \var{d})} converts a \ctype{double} to an ASCII string.
733\end{itemize}
734
735The code for these functions came from the GLib library
736(\url{http://developer.gnome.org/arch/gtk/glib.html}), whose
737developers kindly relicensed the relevant functions and donated them
738to the Python Software Foundation. The \module{locale} module
739can now change the numeric locale, letting extensions such as GTK+
740produce the correct results.
741
742\begin{seealso}
743\seepep{331}{Locale-Independent Float/String Conversions}{Written by Christian R. Reis, and implemented by Gustavo Carneiro.}
744\end{seealso}
745
746%======================================================================
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000747\section{Other Language Changes}
748
749Here are all of the changes that Python 2.4 makes to the core Python
750language.
751
752\begin{itemize}
Raymond Hettingerd4462302003-11-26 17:52:45 +0000753
Raymond Hettinger31017ae2004-03-04 08:25:44 +0000754\item The \method{dict.update()} method now accepts the same
755argument forms as the \class{dict} constructor. This includes any
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +0000756mapping, any iterable of key/value pairs, and keyword arguments.
Raymond Hettinger31017ae2004-03-04 08:25:44 +0000757
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000758\item The string methods \method{ljust()}, \method{rjust()}, and
Andrew M. Kuchling67087562003-11-26 18:03:48 +0000759\method{center()} now take an optional argument for specifying a
Raymond Hettingerd4462302003-11-26 17:52:45 +0000760fill character other than a space.
761
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000762\item Strings also gained an \method{rsplit()} method that
Raymond Hettingered54d912003-12-31 01:59:18 +0000763works like the \method{split()} method but splits from the end of
Andrew M. Kuchling44a31e12004-01-01 18:33:34 +0000764the string.
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000765
766\begin{verbatim}
Raymond Hettinger7a6d2972004-02-13 19:00:07 +0000767>>> 'www.python.org'.split('.', 1)
768['www', 'python.org']
769'www.python.org'.rsplit('.', 1)
770['www.python', 'org']
771\end{verbatim}
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000772
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000773\item The \method{sort()} method of lists gained three keyword
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000774arguments: \var{cmp}, \var{key}, and \var{reverse}. These arguments
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000775make some common usages of \method{sort()} simpler. All are optional.
776
777\var{cmp} is the same as the previous single argument to
778\method{sort()}; if provided, the value should be a comparison
779function that takes two arguments and returns -1, 0, or +1 depending
780on how the arguments compare.
781
782\var{key} should be a single-argument function that takes a list
783element and returns a comparison key for the element. The list is
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000784then sorted using the comparison keys. The following example sorts a
785list case-insensitively:
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000786
787\begin{verbatim}
788>>> L = ['A', 'b', 'c', 'D']
789>>> L.sort() # Case-sensitive sort
790>>> L
791['A', 'D', 'b', 'c']
792>>> L.sort(key=lambda x: x.lower())
793>>> L
794['A', 'b', 'c', 'D']
795>>> L.sort(cmp=lambda x,y: cmp(x.lower(), y.lower()))
796>>> L
797['A', 'b', 'c', 'D']
798\end{verbatim}
799
800The last example, which uses the \var{cmp} parameter, is the old way
Raymond Hettingered54d912003-12-31 01:59:18 +0000801to perform a case-insensitive sort. It works but is slower than
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000802using a \var{key} parameter. Using \var{key} results in calling the
803\method{lower()} method once for each element in the list while using
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000804\var{cmp} will call it twice for each comparison.
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000805
Andrew M. Kuchling981a9182003-11-13 21:33:26 +0000806For simple key functions and comparison functions, it is often
807possible to avoid a \keyword{lambda} expression by using an unbound
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000808method instead. For example, the above case-insensitive sort is best
809coded as:
810
811\begin{verbatim}
812>>> L.sort(key=str.lower)
813>>> L
814['A', 'b', 'c', 'D']
815\end{verbatim}
816
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000817The \var{reverse} parameter should have a Boolean value. If the value
818is \constant{True}, the list will be sorted into reverse order.
819Instead of \code{L.sort(lambda x,y: cmp(x.score, y.score)) ;
820L.reverse()}, you can now write: \code{L.sort(key = lambda x: x.score,
821reverse=True)}.
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000822
Andrew M. Kuchling981a9182003-11-13 21:33:26 +0000823The results of sorting are now guaranteed to be stable. This means
824that two entries with equal keys will be returned in the same order as
825they were input. For example, you can sort a list of people by name,
826and then sort the list by age, resulting in a list sorted by age where
827people with the same age are in name-sorted order.
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000828
Fred Drake56fcc232004-05-06 02:55:35 +0000829\item There is a new built-in function
830\function{sorted(\var{iterable})} that works like the in-place
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000831\method{list.sort()} method but can be used in
Fred Drake56fcc232004-05-06 02:55:35 +0000832expressions. The differences are:
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000833 \begin{itemize}
Raymond Hettinger7d1dd042003-11-12 16:42:10 +0000834 \item the input may be any iterable;
835 \item a newly formed copy is sorted, leaving the original intact; and
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000836 \item the expression returns the new sorted copy
837 \end{itemize}
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000838
839\begin{verbatim}
840>>> L = [9,7,8,3,2,4,1,6,5]
Raymond Hettinger64958a12003-12-17 20:43:33 +0000841>>> [10+i for i in sorted(L)] # usable in a list comprehension
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000842[11, 12, 13, 14, 15, 16, 17, 18, 19]
Hye-Shik Chang2b052482004-07-17 13:53:48 +0000843>>> L # original is left unchanged
Andrew M. Kuchlinge3e1eca2004-07-26 18:52:48 +0000844[9,7,8,3,2,4,1,6,5]
845>>> sorted('Monty Python') # any iterable may be an input
846[' ', 'M', 'P', 'h', 'n', 'n', 'o', 'o', 't', 't', 'y', 'y']
Raymond Hettingerd4462302003-11-26 17:52:45 +0000847
848>>> # List the contents of a dict sorted by key values
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000849>>> colormap = dict(red=1, blue=2, green=3, black=4, yellow=5)
Raymond Hettinger64958a12003-12-17 20:43:33 +0000850>>> for k, v in sorted(colormap.iteritems()):
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000851... print k, v
852...
853black 4
854blue 2
855green 3
856red 1
857yellow 5
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000858\end{verbatim}
859
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +0000860\item Integer operations will no longer trigger an \exception{OverflowWarning}.
861The \exception{OverflowWarning} warning will disappear in Python 2.5.
862
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +0000863\item The \function{eval(\var{expr}, \var{globals}, \var{locals})}
Andrew M. Kuchling1455f792004-08-02 12:09:58 +0000864and \function{execfile(\var{filename}, \var{globals}, \var{locals})}
865functions and the \keyword{exec} statement now accept any mapping type
866for the \var{locals} argument. Previously this had to be a regular
867Python dictionary. (Contributed by Raymond Hettinger.)
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +0000868
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000869\item The \function{zip()} built-in function and \function{itertools.izip()}
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000870 now return an empty list if called with no arguments.
871 Previously they raised a \exception{TypeError}
872 exception. This makes them more
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000873 suitable for use with variable length argument lists:
874
875\begin{verbatim}
876>>> def transpose(array):
877... return zip(*array)
878...
879>>> transpose([(1,2,3), (4,5,6)])
880[(1, 4), (2, 5), (3, 6)]
881>>> transpose([])
882[]
883\end{verbatim}
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +0000884
Andrew M. Kuchlingd91fcbe2004-08-02 12:44:28 +0000885\item Encountering a failure while importing a module no longer leaves
886a partially-initialized module object in \code{sys.modules}. The
887incomplete module object left behind would fool further imports of the
888same module into succeeding, leading to confusing errors.
889
Andrew M. Kuchling65a33322004-07-21 12:41:38 +0000890\item \constant{None} is now a constant; code that binds a new value to
891the name \samp{None} is now a syntax error.
892
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000893\end{itemize}
894
895
896%======================================================================
897\subsection{Optimizations}
898
899\begin{itemize}
900
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000901\item The inner loops for list and tuple slicing
Andrew M. Kuchling65a33322004-07-21 12:41:38 +0000902 were optimized and now run about one-third faster. The inner loops
903 were also optimized for dictionaries, resulting in performance boosts for
904 \method{keys()}, \method{values()}, \method{items()},
905 \method{iterkeys()}, \method{itervalues()}, and \method{iteritems()}.
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000906
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000907\item The machinery for growing and shrinking lists was optimized for
908 speed and for space efficiency. Appending and popping from lists now
909 runs faster due to more efficient code paths and less frequent use of
910 the underlying system \cfunction{realloc()}. List comprehensions
911 also benefit. \method{list.extend()} was also optimized and no
912 longer converts its argument into a temporary list before extending
913 the base list.
Raymond Hettinger7a6d2972004-02-13 19:00:07 +0000914
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000915\item \function{list()}, \function{tuple()}, \function{map()},
916 \function{filter()}, and \function{zip()} now run several times
917 faster with non-sequence arguments that supply a \method{__len__()}
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000918 method.
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000919
Raymond Hettinger23a0f4e2004-01-05 08:15:20 +0000920\item The methods \method{list.__getitem__()},
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000921 \method{dict.__getitem__()}, and \method{dict.__contains__()} are
922 are now implemented as \class{method_descriptor} objects rather
923 than \class{wrapper_descriptor} objects. This form of optimized
924 access doubles their performance and makes them more suitable for
Raymond Hettinger23a0f4e2004-01-05 08:15:20 +0000925 use as arguments to functionals:
926 \samp{map(mydict.__getitem__, keylist)}.
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000927
Fred Draked6d35d92004-06-03 13:31:22 +0000928\item Added a new opcode, \code{LIST_APPEND}, that simplifies
Raymond Hettingerdd80f762004-03-07 07:31:06 +0000929 the generated bytecode for list comprehensions and speeds them up
930 by about a third.
931
Andrew M. Kuchlingac642872004-08-07 13:13:31 +0000932\item String concatenations in statements of the form \code{s = s +
933"abc"} and \code{s += "abc"} are now performed more efficiently in
934certain circumstances. This optimization won't be present in other
935Python implementations such as Jython, so you shouldn't rely on it;
936using the \method{join()} method of strings is still recommended when
937you want to efficiently glue a large number of strings together.
938
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000939\end{itemize}
940
941The net result of the 2.4 optimizations is that Python 2.4 runs the
942pystone benchmark around XX\% faster than Python 2.3 and YY\% faster
943than Python 2.2.
944
945
946%======================================================================
947\section{New, Improved, and Deprecated Modules}
948
949As usual, Python's standard library received a number of enhancements and
950bug fixes. Here's a partial list of the most notable changes, sorted
951alphabetically by module name. Consult the
952\file{Misc/NEWS} file in the source tree for a more
953complete list of changes, or look through the CVS logs for all the
954details.
955
956\begin{itemize}
957
Anthony Baxter5da4c832004-07-09 16:16:46 +0000958% XXX new email parser
959
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +0000960\item The \module{asyncore} module's \function{loop()} now has a
961 \var{count} parameter that lets you perform a limited number
962 of passes through the polling loop. The default is still to loop
963 forever.
964
Andrew M. Kuchling69f31eb2003-08-13 23:11:04 +0000965\item The \module{curses} modules now supports the ncurses extension
Fred Draked6d35d92004-06-03 13:31:22 +0000966 \function{use_default_colors()}. On platforms where the terminal
967 supports transparency, this makes it possible to use a transparent
968 background. (Contributed by J\"org Lehmann.)
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +0000969
Raymond Hettinger0c410272004-01-05 10:13:35 +0000970\item The \module{bisect} module now has an underlying C implementation
971 for improved performance.
972 (Contributed by Dmitry Vasiliev.)
973
Andrew M. Kuchling5303a962004-01-18 15:55:51 +0000974\item The CJKCodecs collections of East Asian codecs, maintained
975by Hye-Shik Chang, was integrated into 2.4.
976The new encodings are:
977
978\begin{itemize}
Andrew M. Kuchling671c5062004-07-28 15:29:39 +0000979 \item Chinese (PRC): gb2312, gbk, gb18030, big5hkscs, hz
Andrew M. Kuchling5303a962004-01-18 15:55:51 +0000980 \item Chinese (ROC): big5, cp950
Andrew M. Kuchling671c5062004-07-28 15:29:39 +0000981 \item Japanese: cp932, euc-jis-2004, euc-jp,
Andrew M. Kuchling5303a962004-01-18 15:55:51 +0000982euc-jisx0213, iso-2022-jp, iso-2022-jp-1, iso-2022-jp-2,
Andrew M. Kuchling671c5062004-07-28 15:29:39 +0000983 iso-2022-jp-3, iso-2022-jp-ext, iso-2022-jp-2004,
984 shift-jis, shift-jisx0213, shift-jis-2004
Andrew M. Kuchling5303a962004-01-18 15:55:51 +0000985 \item Korean: cp949, euc-kr, johab, iso-2022-kr
986\end{itemize}
987
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +0000988\item Some other new encodings were added: HP Roman8,
989ISO_8859-11, ISO_8859-16, PCTP-154,
Andrew M. Kuchlinge30c4d42004-08-07 13:58:02 +0000990and TIS-620.
991
Andrew M. Kuchlingfd0e4942004-02-09 13:23:34 +0000992\item There is a new \module{collections} module for
993 various specialized collection datatypes.
994 Currently it contains just one type, \class{deque},
995 a double-ended queue that supports efficiently adding and removing
996 elements from either end.
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000997
998\begin{verbatim}
999>>> from collections import deque
1000>>> d = deque('ghi') # make a new deque with three items
1001>>> d.append('j') # add a new entry to the right side
1002>>> d.appendleft('f') # add a new entry to the left side
1003>>> d # show the representation of the deque
1004deque(['f', 'g', 'h', 'i', 'j'])
1005>>> d.pop() # return and remove the rightmost item
1006'j'
1007>>> d.popleft() # return and remove the leftmost item
1008'f'
1009>>> list(d) # list the contents of the deque
1010['g', 'h', 'i']
1011>>> 'h' in d # search the deque
1012True
1013\end{verbatim}
1014
Andrew M. Kuchlingfd0e4942004-02-09 13:23:34 +00001015Several modules now take advantage of \class{collections.deque} for
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +00001016improved performance, such as the \module{Queue} and
1017\module{threading} modules.
Andrew M. Kuchling5303a962004-01-18 15:55:51 +00001018
Fred Drake9f15b5c2004-05-18 04:30:00 +00001019\item The \module{ConfigParser} classes have been enhanced slightly.
1020 The \method{read()} method now returns a list of the files that
1021 were successfully parsed, and the \method{set()} method raises
1022 \exception{TypeError} if passed a \var{value} argument that isn't a
1023 string.
1024
Raymond Hettinger607c00f2003-11-12 16:27:50 +00001025\item The \module{heapq} module has been converted to C. The resulting
Andrew M. Kuchlingfd0e4942004-02-09 13:23:34 +00001026 tenfold improvement in speed makes the module suitable for handling
Raymond Hettinger33ecffb2004-06-10 05:03:17 +00001027 high volumes of data. In addition, the module has two new functions
1028 \function{nlargest()} and \function{nsmallest()} that use heaps to
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +00001029 find the N largest or smallest values in a dataset without the
Raymond Hettinger33ecffb2004-06-10 05:03:17 +00001030 expense of a full sort.
Andrew M. Kuchling1a420252003-11-08 15:58:49 +00001031
Andrew M. Kuchlingce4bae62004-07-27 12:13:25 +00001032\item The \module{imaplib} module now supports IMAP's THREAD command
1033(contributed by Yves Dionne) and new \method{deleteacl()} and
1034\method{myrights()} methods (contributed by Arnaud Mazin).
Andrew M. Kuchlingdff9dbd2003-11-20 22:22:19 +00001035
Andrew M. Kuchlingad809552003-12-06 23:19:23 +00001036\item The \module{itertools} module gained a
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +00001037 \function{groupby(\var{iterable}\optional{, \var{func}})} function.
Andrew M. Kuchlingad809552003-12-06 23:19:23 +00001038 \var{iterable} returns a succession of elements, and the optional
1039 \var{func} is a function that takes an element and returns a key
1040 value; if omitted, the key is simply the element itself.
1041 \function{groupby()} then groups the elements into subsequences
1042 which have matching values of the key, and returns a series of 2-tuples
1043 containing the key value and an iterator over the subsequence.
1044
1045Here's an example. The \var{key} function simply returns whether a
1046number is even or odd, so the result of \function{groupby()} is to
1047return consecutive runs of odd or even numbers.
1048
1049\begin{verbatim}
1050>>> import itertools
1051>>> L = [2,4,6, 7,8,9,11, 12, 14]
1052>>> for key_val, it in itertools.groupby(L, lambda x: x % 2):
1053... print key_val, list(it)
1054...
10550 [2, 4, 6]
10561 [7]
10570 [8]
10581 [9, 11]
10590 [12, 14]
1060>>>
1061\end{verbatim}
1062
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +00001063\function{groupby()} is typically used with sorted input. The logic
1064for \function{groupby()} is similar to the \UNIX{} \code{uniq} filter
1065which makes it handy for eliminating, counting, or identifying
1066duplicate elements:
Raymond Hettingerfeb78c92003-12-12 13:13:47 +00001067
1068\begin{verbatim}
1069>>> word = 'abracadabra'
Raymond Hettingered54d912003-12-31 01:59:18 +00001070>>> letters = sorted(word) # Turn string into a sorted list of letters
Raymond Hettinger64958a12003-12-17 20:43:33 +00001071>>> letters
Andrew M. Kuchling4612bc52003-12-16 20:59:37 +00001072['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r']
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +00001073>>> for k, g in itertools.groupby(letters):
1074... print k, list(g)
1075...
1076a ['a', 'a', 'a', 'a', 'a']
1077b ['b', 'b']
1078c ['c']
1079d ['d']
1080r ['r', 'r']
1081>>> # List unique letters
1082>>> [k for k, g in groupby(letters)]
Raymond Hettingerfeb78c92003-12-12 13:13:47 +00001083['a', 'b', 'c', 'd', 'r']
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +00001084>>> # Count letter occurences
1085>>> [(k, len(list(g))) for k, g in groupby(letters)]
Raymond Hettingerfeb78c92003-12-12 13:13:47 +00001086[('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)]
Raymond Hettingerfeb78c92003-12-12 13:13:47 +00001087\end{verbatim}
1088
Raymond Hettingered54d912003-12-31 01:59:18 +00001089\item \module{itertools} also gained a function named
1090\function{tee(\var{iterator}, \var{N})} that returns \var{N} independent
1091iterators that replicate \var{iterator}. If \var{N} is omitted, the
1092default is 2.
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +00001093
1094\begin{verbatim}
1095>>> L = [1,2,3]
1096>>> i1, i2 = itertools.tee(L)
1097>>> i1,i2
1098(<itertools.tee object at 0x402c2080>, <itertools.tee object at 0x402c2090>)
Raymond Hettingered54d912003-12-31 01:59:18 +00001099>>> list(i1) # Run the first iterator to exhaustion
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +00001100[1, 2, 3]
Raymond Hettingered54d912003-12-31 01:59:18 +00001101>>> list(i2) # Run the second iterator to exhaustion
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +00001102[1, 2, 3]
1103>\end{verbatim}
1104
1105Note that \function{tee()} has to keep copies of the values returned
Raymond Hettingered54d912003-12-31 01:59:18 +00001106by the iterator; in the worst case, it may need to keep all of them.
Andrew M. Kuchling44a31e12004-01-01 18:33:34 +00001107This should therefore be used carefully if the leading iterator
Raymond Hettingered54d912003-12-31 01:59:18 +00001108can run far ahead of the trailing iterator in a long stream of inputs.
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +00001109If the separation is large, then you might as well use
Raymond Hettingered54d912003-12-31 01:59:18 +00001110\function{list()} instead. When the iterators track closely with one
1111another, \function{tee()} is ideal. Possible applications include
1112bookmarking, windowing, or lookahead iterators.
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +00001113
Andrew M. Kuchling5785a132004-07-26 19:28:46 +00001114\item A number of functions were added to the \module{locale}
1115module, such as \function{bind_textdomain_codeset()} to specify a
1116particular encoding, and a family of \function{l*gettext()} functions
1117that return messages in the chosen encoding.
1118(Contributed by Gustavo Niemeyer.)
1119
Andrew M. Kuchling23406892004-07-15 11:44:42 +00001120\item The \module{logging} package's \function{basicConfig} function
1121gained some keyword arguments to simplify log configuration. The
1122default behavior is to log messages to standard error, but
1123various keyword arguments can be specified to log to a particular file,
1124change the logging format, or set the logging level. For example:
Andrew M. Kuchlingbcefe692004-07-07 13:01:53 +00001125
1126\begin{verbatim}
1127import logging
1128logging.basicConfig(filename = '/var/log/application.log',
1129 level=0, # Log all messages, including debugging,
1130 format='%(levelname):%(process):%(thread):%(message)')
1131\end{verbatim}
1132
1133Another addition to \module{logging} is a
1134\class{TimedRotatingFileHandler} class which rotates its log files at
1135a timed interval. The module already had \class{RotatingFileHandler},
1136which rotated logs once the file exceeded a certain size. Both
1137classes derive from a new \class{BaseRotatingHandler} class that can
1138be used to implement other rotating handlers.
1139
Andrew M. Kuchling5785a132004-07-26 19:28:46 +00001140\item The \module{nntplib} module's \class{NNTP} class gained
1141\method{description()} and \method{descriptions()} methods to retrieve
1142newsgroup descriptions for a single group or for a range of groups.
1143(Contributed by J\"urgen A. Erhard.)
1144
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +00001145\item The \module{operator} module gained two new functions,
1146\function{attrgetter(\var{attr})} and \function{itemgetter(\var{index})}.
1147Both functions return callables that take a single argument and return
Raymond Hettingered54d912003-12-31 01:59:18 +00001148the corresponding attribute or item; these callables make excellent
Andrew M. Kuchlingbcefe692004-07-07 13:01:53 +00001149data extractors when used with \function{map()} or
1150\function{sorted()}. For example:
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +00001151
1152\begin{verbatim}
Raymond Hettingered54d912003-12-31 01:59:18 +00001153>>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +00001154>>> map(operator.itemgetter(0), L)
1155['c', 'd', 'a', 'b']
1156>>> map(operator.itemgetter(1), L)
Raymond Hettingered54d912003-12-31 01:59:18 +00001157[2, 1, 4, 3]
1158>>> sorted(L, key=operator.itemgetter(1)) # Sort list by second tuple item
1159[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +00001160\end{verbatim}
1161
Andrew M. Kuchlinge30c4d42004-08-07 13:58:02 +00001162\item The \module{optparse} module was updated. The module now passes
1163its messages through \function{gettext.gettext()}, making it possible
1164to internationalize Optik's help and error messages. Help messages
Fred Drake9bae19e2004-08-07 14:28:37 +00001165for options can now include the string \code{'\%default'}, which will
Andrew M. Kuchlinge30c4d42004-08-07 13:58:02 +00001166be replaced by the option's default value.
1167
Andrew M. Kuchlingcb7b3f32004-08-30 11:58:04 +00001168\item A new \function{urandom(\var{n})} function
1169was added to the \module{os} module, providing access to
1170platform-specific sources of randomness such as
Johannes Gijsbersed047482004-08-30 15:03:23 +00001171\file{/dev/urandom} on Linux or the Windows CryptoAPI. The
Andrew M. Kuchlingcb7b3f32004-08-30 11:58:04 +00001172function returns a string containing \var{n} bytes of random data.
1173(Contributed by Trevor Perrin.)
1174
1175\item Another new function: \function{os.path.lexists(\var{path})}
1176returns true if the file specified by \var{path} exists, whether or
1177not it's a symbolic link. This differs from the existing
1178\function{os.path.exists(\var{path})} function, which returns false if
1179\var{path} is a symlink that points to a destination that doesn't exist.
1180(Contributed by Beni Cherniavsky.)
1181
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +00001182\item A new \function{getsid()} function was added to the
1183\module{posix} module that underlies the \module{os} module.
1184(Contributed by J. Raynor.)
1185
1186\item The \module{poplib} module now supports POP over SSL.
1187
1188\item The \module{profile} module can now profile C extension functions.
1189% XXX more to say about this?
1190
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +00001191\item The \module{random} module has a new method called \method{getrandbits(N)}
Raymond Hettinger607c00f2003-11-12 16:27:50 +00001192 which returns an N-bit long integer. This method supports the existing
1193 \method{randrange()} method, making it possible to efficiently generate
Andrew M. Kuchling44a31e12004-01-01 18:33:34 +00001194 arbitrarily large random numbers.
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +00001195
1196\item The regular expression language accepted by the \module{re} module
1197 was extended with simple conditional expressions, written as
Andrew M. Kuchlingab778222004-08-31 12:07:43 +00001198 \regexp{(?(\var{group})\var{A}|\var{B})}. \var{group} is either a
1199 numeric group ID or a group name defined with \regexp{(?P<group>...)}
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +00001200 earlier in the expression. If the specified group matched, the
1201 regular expression pattern \var{A} will be tested against the string; if
1202 the group didn't match, the pattern \var{B} will be used instead.
Raymond Hettinger874ebd52004-05-31 03:15:02 +00001203
Andrew M. Kuchlingab778222004-08-31 12:07:43 +00001204\item The \module{re} module is also no longer recursive, thanks
1205to a massive amount of work by Gustavo Niemeyer. In a recursive
1206regular expression engine, certain patterns result in a large amount
1207of C stack space being consumed, and it was possible to overflow the
1208stack. For example, if you matched a 30000-byte string of \samp{a}
1209characters against the expression \regexp{(a|b)+}, one stack frame was
1210consumed per character. Python 2.3 tried to check for stack overflow
1211and raise a \exception{RuntimeError} exception, but if you were
1212unlucky Python could dump core. Python 2.4's regular expression
1213engine can match this pattern without problems.
1214
Andrew M. Kuchling7f203b82004-08-09 14:48:28 +00001215\item A new \function{socketpair()} function was added to the
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +00001216\module{socket} module, returning a pair of connected sockets.
1217(Contributed by Dave Cole.)
Andrew M. Kuchling7f203b82004-08-09 14:48:28 +00001218
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +00001219\item The \function{sys.exitfunc()} function has been deprecated. Code
1220should be using the existing \module{atexit} module, which correctly
1221handles calling multiple exit functions. Eventually
1222\function{sys.exitfunc()} will become a purely internal interface,
1223accessed only by \module{atexit}.
1224
1225\item The \module{tarfile} module now generates GNU-format tar files
1226by default.
1227
Andrew M. Kuchling00457172004-07-15 11:52:40 +00001228\item The \module{threading} module now has an elegantly simple way to support
1229thread-local data. The module contains a \class{local} class whose
1230attribute values are local to different threads.
1231
1232\begin{verbatim}
1233import threading
1234
1235data = threading.local()
1236data.number = 42
1237data.url = ('www.python.org', 80)
1238\end{verbatim}
1239
1240Other threads can assign and retrieve their own values for the
1241\member{number} and \member{url} attributes. You can subclass
1242\class{local} to initialize attributes or to add methods.
1243(Contributed by Jim Fulton.)
1244
Raymond Hettinger874ebd52004-05-31 03:15:02 +00001245\item The \module{weakref} module now supports a wider variety of objects
1246 including Python functions, class instances, sets, frozensets, deques,
1247 arrays, files, sockets, and regular expression pattern objects.
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +00001248
1249\item The \module{xmlrpclib} module now supports a multi-call extension for
Andrew M. Kuchling00457172004-07-15 11:52:40 +00001250transmitting multiple XML-RPC calls in a single HTTP operation.
Andrew M. Kuchling3d3db962004-08-31 13:57:02 +00001251
1252\item The \module{mpz}, \module{rotor}, and \module{xreadlines} modules have
1253been removed.
Andrew M. Kuchling69f31eb2003-08-13 23:11:04 +00001254
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001255\end{itemize}
1256
1257
1258%======================================================================
Raymond Hettingerca1a7752004-07-12 13:00:45 +00001259% whole new modules get described in subsections here
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001260
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001261\subsection{cookielib}
1262
1263The \module{cookielib} library supports client-side handling for HTTP
1264cookies, just as the \module{Cookie} provides server-side cookie
Andrew M. Kuchling71432f12004-07-05 01:40:07 +00001265support in CGI scripts. Cookies are stored in cookie jars; the library
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001266transparently stores cookies offered by the web server in the cookie
1267jar, and fetches the cookie from the jar when connecting to the
1268server. Similar to web browsers, policy objects control whether
1269cookies are accepted or not.
1270
1271In order to store cookies across sessions, two implementations of
1272cookie jars are provided: one that stores cookies in the Netscape
1273format, so applications can use the Mozilla or Lynx cookie jars, and
1274one that stores cookies in the same format as the Perl libwww libary.
1275
1276\module{urllib2} has been changed to interact with \module{cookielib}:
1277\class{HTTPCookieProcessor} manages a cookie jar that is used when
1278accessing URLs.
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001279
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +00001280\subsection{doctest}
1281
1282The \module{doctest} module underwent considerable refactoring thanks
1283to Edward Loper and Tim Peters.
1284
1285% XXX describe this
1286
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001287% ======================================================================
1288\section{Build and C API Changes}
1289
1290Changes to Python's build process and to the C API include:
1291
1292\begin{itemize}
1293
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +00001294 \item Three new convenience macros were added for common return
1295 values from extension functions: \csimplemacro{Py_RETURN_NONE},
1296 \csimplemacro{Py_RETURN_TRUE}, and \csimplemacro{Py_RETURN_FALSE}.
1297
Andrew M. Kuchling5785a132004-07-26 19:28:46 +00001298 \item Another new macro, \csimplemacro{Py_CLEAR(\var{obj})},
1299 decreases the reference count of \var{obj} and sets \var{obj} to the
1300 null pointer.
1301
Fred Drakece3caf22004-02-12 18:13:12 +00001302 \item A new function, \cfunction{PyTuple_Pack(\var{N}, \var{obj1},
1303 \var{obj2}, ..., \var{objN})}, constructs tuples from a variable
1304 length argument list of Python objects.
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001305
Fred Drakece3caf22004-02-12 18:13:12 +00001306 \item A new function, \cfunction{PyDict_Contains(\var{d}, \var{k})},
1307 implements fast dictionary lookups without masking exceptions raised
1308 during the look-up process.
Raymond Hettingerd4462302003-11-26 17:52:45 +00001309
Andrew M. Kuchlinge30c4d42004-08-07 13:58:02 +00001310 \item A new function, \cfunction{PyArg_VaParseTupleAndKeywords()},
1311 is the same as \cfunction{PyArg_ParseTupleAndKeywords()} but takes a
1312 \ctype{va_list} instead of a number of arguments.
1313 (Contributed by Greg Chapman.)
1314
Fred Drakece3caf22004-02-12 18:13:12 +00001315 \item A new method flag, \constant{METH_COEXISTS}, allows a function
Andrew M. Kuchling71432f12004-07-05 01:40:07 +00001316 defined in slots to co-exist with a \ctype{PyCFunction} having the
1317 same name. This can halve the access time for a method such as
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +00001318 \method{set.__contains__()}.
1319
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +00001320 \item Python can now be built with additional profiling for the
1321 interpreter itself. This is intended for people developing on the
1322 Python core. Providing \longprogramopt{--enable-profiling} to the
1323 \program{configure} script will let you profile the interpreter with
1324 \program{gprof}, and providing the \longprogramopt{--with-tsc}
1325 switch enables profiling using the Pentium's Time-Stamp-Counter
1326 register. The switch is slightly misnamed, because the profiling
1327 feature also works on the PowerPC platform, though that processor
1328 architecture doesn't called that register the TSC.
1329
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +00001330 \item The \ctype{tracebackobject} type has been renamed to \ctype{PyTracebackObject}.
Raymond Hettinger97ef8de2004-01-05 00:29:57 +00001331
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001332\end{itemize}
1333
1334
1335%======================================================================
1336\subsection{Port-Specific Changes}
1337
Raymond Hettinger97ef8de2004-01-05 00:29:57 +00001338\begin{itemize}
1339
1340\item The Windows port now builds under MSVC++ 7.1 as well as version 6.
1341
1342\end{itemize}
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001343
1344
1345%======================================================================
1346\section{Other Changes and Fixes \label{section-other}}
1347
Andrew M. Kuchlingb07aae22004-08-31 11:54:22 +00001348% XXX update these figures as we go
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001349As usual, there were a bunch of other improvements and bugfixes
1350scattered throughout the source tree. A search through the CVS change
Andrew M. Kuchlingb07aae22004-08-31 11:54:22 +00001351logs finds there were 421 patches applied and 413 bugs fixed between
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001352Python 2.3 and 2.4. Both figures are likely to be underestimates.
1353
1354Some of the more notable changes are:
1355
1356\begin{itemize}
1357
Raymond Hettinger97ef8de2004-01-05 00:29:57 +00001358\item The \module{timeit} module now automatically disables periodic
1359 garbarge collection during the timing loop. This change makes
1360 consecutive timings more comparable.
1361
1362\item The \module{base64} module now has more complete RFC 3548 support
1363 for Base64, Base32, and Base16 encoding and decoding, including
1364 optional case folding and optional alternative alphabets.
1365 (Contributed by Barry Warsaw.)
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001366
1367\end{itemize}
1368
1369
1370%======================================================================
1371\section{Porting to Python 2.4}
1372
1373This section lists previously described changes that may require
1374changes to your code:
1375
1376\begin{itemize}
1377
Raymond Hettinger607c00f2003-11-12 16:27:50 +00001378\item The \function{zip()} built-in function and \function{itertools.izip()}
1379 now return an empty list instead of raising a \exception{TypeError}
1380 exception if called with no arguments.
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +00001381
1382\item \function{dircache.listdir()} now passes exceptions to the caller
1383 instead of returning empty lists.
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001384
Andrew M. Kuchling71432f12004-07-05 01:40:07 +00001385\item \function{LexicalHandler.startDTD()} used to receive the public and
1386 system IDs in the wrong order. This has been corrected; applications
Fred Drake56fcc232004-05-06 02:55:35 +00001387 relying on the wrong order need to be fixed.
Martin v. Löwis456ab1d2004-05-06 01:54:36 +00001388
Andrew M. Kuchling71432f12004-07-05 01:40:07 +00001389\item \function{fcntl.ioctl} now warns if the \var{mutate}
1390 argument is omitted and relevant.
Martin v. Löwis77ca6c42004-06-03 12:47:26 +00001391
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +00001392\item The \module{tarfile} module now generates GNU-format tar files
1393by default.
1394
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001395\end{itemize}
1396
1397
1398%======================================================================
1399\section{Acknowledgements \label{acks}}
1400
1401The author would like to thank the following people for offering
1402suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchling671c5062004-07-28 15:29:39 +00001403article: Hye-Shik Chang, Michael Dyck, Raymond Hettinger.
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001404
1405\end{document}