blob: 2936bd50ee81541812ec4a2a151f12015a2ee937 [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. Kuchling74666592004-11-19 14:26:23 +000013\release{1.0}
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. Kuchling74666592004-11-19 14:26:23 +000024This article explains the new features in Python 2.4, released in December
252004.
Fred Drakeed0fa3d2003-07-30 19:14:09 +000026
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +000027Python 2.4 is a medium-sized release. It doesn't introduce as many
Andrew M. Kuchling3b790912004-07-04 16:39:40 +000028changes as the radical Python 2.2, but introduces more features than
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +000029the conservative 2.3 release. The most significant new language
30features are function decorators and generator expressions; most other
31changes are to the standard library.
32
Andrew M. Kuchling74666592004-11-19 14:26:23 +000033According to the CVS change logs, there were 481 patches applied and
34502 bugs fixed between Python 2.3 and 2.4. Both figures are likely to
Andrew M. Kuchlinga331e862004-09-10 13:05:22 +000035be underestimates.
36
Fred Drakeed0fa3d2003-07-30 19:14:09 +000037This article doesn't attempt to provide a complete specification of
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +000038every single new feature, but instead provides a brief introduction to
39each feature. For full details, you should refer to the documentation
40for Python 2.4, such as the \citetitle[../lib/lib.html]{Python Library
41Reference} and the \citetitle[../ref/ref.html]{Python Reference
42Manual}. Often you will be referred to the PEP for a particular new
43feature for explanations of the implementation and design rationale.
Fred Drakeed0fa3d2003-07-30 19:14:09 +000044
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +000045
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000046%======================================================================
47\section{PEP 218: Built-In Set Objects}
48
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +000049Python 2.3 introduced the \module{sets} module. C implementations of
50set data types have now been added to the Python core as two new
51built-in types, \function{set(\var{iterable})} and
52\function{frozenset(\var{iterable})}. They provide high speed
53operations for membership testing, for eliminating duplicates from
54sequences, and for mathematical operations like unions, intersections,
55differences, and symmetric differences.
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000056
57\begin{verbatim}
58>>> a = set('abracadabra') # form a set from a string
59>>> 'z' in a # fast membership testing
60False
61>>> a # unique letters in a
62set(['a', 'r', 'b', 'c', 'd'])
63>>> ''.join(a) # convert back into a string
64'arbcd'
Raymond Hettingerd4462302003-11-26 17:52:45 +000065
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000066>>> b = set('alacazam') # form a second set
67>>> a - b # letters in a but not in b
68set(['r', 'd', 'b'])
69>>> a | b # letters in either a or b
70set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
71>>> a & b # letters in both a and b
72set(['a', 'c'])
73>>> a ^ b # letters in a or b but not both
74set(['r', 'd', 'b', 'm', 'z', 'l'])
Raymond Hettingerd4462302003-11-26 17:52:45 +000075
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000076>>> a.add('z') # add a new element
77>>> a.update('wxy') # add multiple new elements
78>>> a
79set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'x', 'z'])
80>>> a.remove('x') # take one element out
81>>> a
82set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'z'])
83\end{verbatim}
84
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +000085The \function{frozenset} type is an immutable version of \function{set}.
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000086Since it is immutable and hashable, it may be used as a dictionary key or
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +000087as a member of another set.
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000088
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +000089The \module{sets} module remains in the standard library, and may be
90useful if you wish to subclass the \class{Set} or \class{ImmutableSet}
91classes. There are currently no plans to deprecate the module.
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +000092
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000093\begin{seealso}
94\seepep{218}{Adding a Built-In Set Object Type}{Originally proposed by
95Greg Wilson and ultimately implemented by Raymond Hettinger.}
96\end{seealso}
Fred Drakeed0fa3d2003-07-30 19:14:09 +000097
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +000098
Fred Drakeed0fa3d2003-07-30 19:14:09 +000099%======================================================================
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000100\section{PEP 237: Unifying Long Integers and Integers}
101
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000102The lengthy transition process for this PEP, begun in Python 2.2,
Andrew M. Kuchlingd4be86c2004-07-04 01:44:04 +0000103takes another step forward in Python 2.4. In 2.3, certain integer
104operations that would behave differently after int/long unification
105triggered \exception{FutureWarning} warnings and returned values
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000106limited to 32 or 64 bits (depending on your platform). In 2.4, these
107expressions no longer produce a warning and instead produce a
108different result that's usually a long integer.
Andrew M. Kuchlingd4be86c2004-07-04 01:44:04 +0000109
110The problematic expressions are primarily left shifts and lengthy
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000111hexadecimal and octal constants. For example,
112\code{2 \textless{}\textless{} 32} results
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000113in a warning in 2.3, evaluating to 0 on 32-bit platforms. In Python
1142.4, this expression now returns the correct answer, 8589934592.
Andrew M. Kuchlingd4be86c2004-07-04 01:44:04 +0000115
116\begin{seealso}
117\seepep{237}{Unifying Long Integers and Integers}{Original PEP
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000118written by Moshe Zadka and GvR. The changes for 2.4 were implemented by
Andrew M. Kuchlingd4be86c2004-07-04 01:44:04 +0000119Kalle Svensson.}
120\end{seealso}
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000121
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000122
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000123%======================================================================
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000124\section{PEP 289: Generator Expressions}
Raymond Hettinger354433a2004-05-19 08:20:33 +0000125
Andrew M. Kuchling38dc2a62004-08-07 13:24:12 +0000126The iterator feature introduced in Python 2.2 and the
127\module{itertools} module make it easier to write programs that loop
128through large data sets without having the entire data set in memory
129at one time. List comprehensions don't fit into this picture very
130well because they produce a Python list object containing all of the
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000131items. This unavoidably pulls all of the objects into memory, which
132can be a problem if your data set is very large. When trying to write
Andrew M. Kuchling38dc2a62004-08-07 13:24:12 +0000133a functionally-styled program, it would be natural to write something
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000134like:
Raymond Hettinger354433a2004-05-19 08:20:33 +0000135
136\begin{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000137links = [link for link in get_all_links() if not link.followed]
138for link in links:
139 ...
Raymond Hettinger354433a2004-05-19 08:20:33 +0000140\end{verbatim}
141
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000142instead of
Raymond Hettinger354433a2004-05-19 08:20:33 +0000143
144\begin{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000145for link in get_all_links():
146 if link.followed:
147 continue
148 ...
149\end{verbatim}
Raymond Hettinger354433a2004-05-19 08:20:33 +0000150
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000151The first form is more concise and perhaps more readable, but if
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000152you're dealing with a large number of link objects you'd have to write
153the second form to avoid having all link objects in memory at the same
154time.
Raymond Hettinger354433a2004-05-19 08:20:33 +0000155
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000156Generator expressions work similarly to list comprehensions but don't
157materialize the entire list; instead they create a generator that will
158return elements one by one. The above example could be written as:
Raymond Hettinger354433a2004-05-19 08:20:33 +0000159
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000160\begin{verbatim}
161links = (link for link in get_all_links() if not link.followed)
162for link in links:
163 ...
164\end{verbatim}
Raymond Hettinger170a6222004-05-19 19:45:19 +0000165
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000166Generator expressions always have to be written inside parentheses, as
167in the above example. The parentheses signalling a function call also
168count, so if you want to create a iterator that will be immediately
169passed to a function you could write:
Raymond Hettinger170a6222004-05-19 19:45:19 +0000170
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000171\begin{verbatim}
172print sum(obj.count for obj in list_all_objects())
173\end{verbatim}
Raymond Hettinger170a6222004-05-19 19:45:19 +0000174
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000175Generator expressions differ from list comprehensions in various small
176ways. Most notably, the loop variable (\var{obj} in the above
177example) is not accessible outside of the generator expression. List
178comprehensions leave the variable assigned to its last value; future
179versions of Python will change this, making list comprehensions match
180generator expressions in this respect.
Raymond Hettinger354433a2004-05-19 08:20:33 +0000181
182\begin{seealso}
183\seepep{289}{Generator Expressions}{Proposed by Raymond Hettinger and
184implemented by Jiwon Seo with early efforts steered by Hye-Shik Chang.}
185\end{seealso}
186
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +0000187
188%======================================================================
189\section{PEP 292: Simpler String Substitutions}
190
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000191Some new classes in the standard library provide an alternative
192mechanism for substituting variables into strings; this style of
193substitution may be better for applications where untrained
194users need to edit templates.
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +0000195
196The usual way of substituting variables by name is the \code{\%}
197operator:
198
199\begin{verbatim}
200>>> '%(page)i: %(title)s' % {'page':2, 'title': 'The Best of Times'}
201'2: The Best of Times'
202\end{verbatim}
203
204When writing the template string, it can be easy to forget the
205\samp{i} or \samp{s} after the closing parenthesis. This isn't a big
206problem if the template is in a Python module, because you run the
207code, get an ``Unsupported format character'' \exception{ValueError},
208and fix the problem. However, consider an application such as Mailman
209where template strings or translations are being edited by users who
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000210aren't aware of the Python language. The format string's syntax is
211complicated to explain to such users, and if they make a mistake, it's
212difficult to provide helpful feedback to them.
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +0000213
214PEP 292 adds a \class{Template} class to the \module{string} module
215that uses \samp{\$} to indicate a substitution. \class{Template} is a
216subclass of the built-in Unicode type, so the result is always a
217Unicode string:
218
219\begin{verbatim}
220>>> import string
221>>> t = string.Template('$page: $title')
Andrew M. Kuchlinga79ec222004-09-10 11:34:39 +0000222>>> t.substitute({'page':2, 'title': 'The Best of Times'})
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +0000223u'2: The Best of Times'
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +0000224\end{verbatim}
225
226% $ Terminate $-mode for Emacs
227
Andrew M. Kuchlinga79ec222004-09-10 11:34:39 +0000228If a key is missing from the dictionary, the \method{substitute} method
229will raise a \exception{KeyError}. There's also a \method{safe_substitute}
230method that ignores missing keys:
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +0000231
232\begin{verbatim}
233>>> t = string.SafeTemplate('$page: $title')
Andrew M. Kuchlinga79ec222004-09-10 11:34:39 +0000234>>> t.safe_substitute({'page':3})
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +0000235u'3: $title'
236\end{verbatim}
237
Andrew M. Kuchlinga331e862004-09-10 13:05:22 +0000238% $ Terminate math-mode for Emacs
239
240
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +0000241\begin{seealso}
242\seepep{292}{Simpler String Substitutions}{Written and implemented
243by Barry Warsaw.}
244\end{seealso}
245
246
Raymond Hettinger354433a2004-05-19 08:20:33 +0000247%======================================================================
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000248\section{PEP 318: Decorators for Functions and Methods}
Andrew M. Kuchlingd91fcbe2004-08-02 12:44:28 +0000249
Andrew M. Kuchling77a602f2004-08-02 13:48:18 +0000250Python 2.2 extended Python's object model by adding static methods and
251class methods, but it didn't extend Python's syntax to provide any new
252way of defining static or class methods. Instead, you had to write a
253\keyword{def} statement in the usual way, and pass the resulting
254method to a \function{staticmethod()} or \function{classmethod()}
255function that would wrap up the function as a method of the new type.
256Your code would look like this:
257
258\begin{verbatim}
259class C:
260 def meth (cls):
261 ...
262
263 meth = classmethod(meth) # Rebind name to wrapped-up class method
264\end{verbatim}
265
266If the method was very long, it would be easy to miss or forget the
267\function{classmethod()} invocation after the function body.
268
269The intention was always to add some syntax to make such definitions
270more readable, but at the time of 2.2's release a good syntax was not
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000271obvious. Today a good syntax \emph{still} isn't obvious but users are
272asking for easier access to the feature; a new syntactic feature has
273been added to meet this need.
Andrew M. Kuchling77a602f2004-08-02 13:48:18 +0000274
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000275The new feature is called ``function decorators''. The name comes
276from the idea that \function{classmethod}, \function{staticmethod},
277and friends are storing additional information on a function object;
278they're \emph{decorating} functions with more details.
Andrew M. Kuchling77a602f2004-08-02 13:48:18 +0000279
Fred Drake3f5c6542004-08-06 03:34:20 +0000280The notation borrows from Java and uses the \character{@} character as an
Andrew M. Kuchling77a602f2004-08-02 13:48:18 +0000281indicator. Using the new syntax, the example above would be written:
282
283\begin{verbatim}
284class C:
285
286 @classmethod
287 def meth (cls):
288 ...
289
290\end{verbatim}
291
292The \code{@classmethod} is shorthand for the
Fred Drake3f5c6542004-08-06 03:34:20 +0000293\code{meth=classmethod(meth)} assignment. More generally, if you have
Andrew M. Kuchling77a602f2004-08-02 13:48:18 +0000294the following:
295
296\begin{verbatim}
297@A @B @C
298def f ():
299 ...
300\end{verbatim}
301
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000302It's equivalent to the following pre-decorator code:
Andrew M. Kuchling77a602f2004-08-02 13:48:18 +0000303
304\begin{verbatim}
305def f(): ...
Andrew M. Kuchlingcebdd3c2004-10-08 18:29:29 +0000306f = A(B(C(f)))
Andrew M. Kuchling77a602f2004-08-02 13:48:18 +0000307\end{verbatim}
308
309Decorators must come on the line before a function definition, and
310can't be on the same line, meaning that \code{@A def f(): ...} is
311illegal. You can only decorate function definitions, either at the
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000312module level or inside a class; you can't decorate class definitions.
Andrew M. Kuchling77a602f2004-08-02 13:48:18 +0000313
314A decorator is just a function that takes the function to be decorated
315as an argument and returns either the same function or some new
316callable thing. It's easy to write your own decorators. The
317following simple example just sets an attribute on the function
318object:
319
320\begin{verbatim}
321>>> def deco(func):
322... func.attr = 'decorated'
323... return func
324...
325>>> @deco
326... def f(): pass
327...
328>>> f
329<function f at 0x402ef0d4>
330>>> f.attr
331'decorated'
332>>>
333\end{verbatim}
334
335As a slightly more realistic example, the following decorator checks
336that the supplied argument is an integer:
337
338\begin{verbatim}
339def require_int (func):
340 def wrapper (arg):
341 assert isinstance(arg, int)
342 return func(arg)
343
344 return wrapper
345
346@require_int
347def p1 (arg):
348 print arg
349
350@require_int
351def p2(arg):
352 print arg*2
353\end{verbatim}
354
355An example in \pep{318} contains a fancier version of this idea that
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000356lets you both specify the required type and check the returned type.
Andrew M. Kuchling77a602f2004-08-02 13:48:18 +0000357
358Decorator functions can take arguments. If arguments are supplied,
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000359your decorator function is called with only those arguments and must
360return a new decorator function; this function must take a single
Andrew M. Kuchling77a602f2004-08-02 13:48:18 +0000361function and return a function, as previously described. In other
362words, \code{@A @B @C(args)} becomes:
363
364\begin{verbatim}
365def f(): ...
366_deco = C(args)
Andrew M. Kuchlingcebdd3c2004-10-08 18:29:29 +0000367f = A(B(_deco(f)))
Andrew M. Kuchling77a602f2004-08-02 13:48:18 +0000368\end{verbatim}
369
370Getting this right can be slightly brain-bending, but it's not too
371difficult.
372
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +0000373A small related change makes the \member{func_name} attribute of
374functions writable. This attribute is used to display function names
375in tracebacks, so decorators should change the name of any new
376function that's constructed and returned.
377
Andrew M. Kuchlingd91fcbe2004-08-02 12:44:28 +0000378\begin{seealso}
379\seepep{318}{Decorators for Functions, Methods and Classes}{Written
Andrew M. Kuchling77a602f2004-08-02 13:48:18 +0000380by Kevin D. Smith, Jim Jewett, and Skip Montanaro. Several people
381wrote patches implementing function decorators, but the one that was
Fred Drakee72bd4d2004-08-02 21:50:26 +0000382actually checked in was patch \#979728, written by Mark Russell.}
Andrew M. Kuchlingd91fcbe2004-08-02 12:44:28 +0000383\end{seealso}
384
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000385% XXX add link to decorators module in Wiki
386
387
Andrew M. Kuchlingd91fcbe2004-08-02 12:44:28 +0000388%======================================================================
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000389\section{PEP 322: Reverse Iteration}
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000390
Fred Drake56fcc232004-05-06 02:55:35 +0000391A new built-in function, \function{reversed(\var{seq})}, takes a sequence
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000392and returns an iterator that loops over the elements of the sequence
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000393in reverse order.
394
395\begin{verbatim}
Raymond Hettingerbc3cba22003-11-12 16:39:30 +0000396>>> for i in reversed(xrange(1,4)):
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000397... print i
398...
3993
4002
4011
402\end{verbatim}
403
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000404Compared to extended slicing, such as \code{range(1,4)[::-1]},
405\function{reversed()} is easier to read, runs faster, and uses
406substantially less memory.
Raymond Hettingerbc3cba22003-11-12 16:39:30 +0000407
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000408Note that \function{reversed()} only accepts sequences, not arbitrary
Raymond Hettingerbc3cba22003-11-12 16:39:30 +0000409iterators. If you want to reverse an iterator, first convert it to
410a list with \function{list()}.
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000411
412\begin{verbatim}
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000413>>> input = open('/etc/passwd', 'r')
Andrew M. Kuchling44a31e12004-01-01 18:33:34 +0000414>>> for line in reversed(list(input)):
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000415... print line
416...
417root:*:0:0:System Administrator:/var/root:/bin/tcsh
418 ...
419\end{verbatim}
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000420
Andrew M. Kuchlingf7a6b672003-11-08 16:05:37 +0000421\begin{seealso}
422\seepep{322}{Reverse Iteration}{Written and implemented by Raymond Hettinger.}
423
424\end{seealso}
425
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000426
427%======================================================================
Andrew M. Kuchlingc9e7d772004-10-12 15:58:02 +0000428\section{PEP 324: New subprocess Module}
429
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000430The standard library provides a number of ways to execute a
431subprocess, offering different features and different levels of
432complexity. \function{os.system(\var{command})} is easy to use, but
433slow (it runs a shell process which executes the command) and
434dangerous (you have to be careful about escaping the shell's
435metacharacters). The \module{popen2} module offers classes that can
436capture standard output and standard error from the subprocess, but
437the naming is confusing. The \module{subprocess} module cleans
438this up, providing a unified interface that offers all the features
439you might need.
Andrew M. Kuchlingc9e7d772004-10-12 15:58:02 +0000440
Andrew M. Kuchlingb6ffc272004-10-12 16:36:57 +0000441Instead of \module{popen2}'s collection of classes,
442\module{subprocess} contains a single class called \class{Popen}
443whose constructor supports a number of different keyword arguments.
Andrew M. Kuchlingc9e7d772004-10-12 15:58:02 +0000444
Andrew M. Kuchlingb6ffc272004-10-12 16:36:57 +0000445\begin{verbatim}
446class Popen(args, bufsize=0, executable=None,
447 stdin=None, stdout=None, stderr=None,
448 preexec_fn=None, close_fds=False, shell=False,
449 cwd=None, env=None, universal_newlines=False,
450 startupinfo=None, creationflags=0):
451\end{verbatim}
Andrew M. Kuchlingc9e7d772004-10-12 15:58:02 +0000452
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000453\var{args} is commonly a sequence of strings that will be the
454arguments to the program executed as the subprocess. (If the
455\var{shell} argument is true, \var{args} can be a string which will
456then be passed on to the shell for interpretation, just as
457\function{os.system()} does.)
Andrew M. Kuchlingb6ffc272004-10-12 16:36:57 +0000458
459\var{stdin}, \var{stdout}, and \var{stderr} specify what the
460subprocess's input, output, and error streams will be. You can
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000461provide a file object or a file descriptor, or you can use the
462constant \code{subprocess.PIPE} to create a pipe between the
463subprocess and the parent.
Andrew M. Kuchlingb6ffc272004-10-12 16:36:57 +0000464
465The constructor has a number of handy options:
466
467\begin{itemize}
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000468 \item \var{close_fds} requests that all file descriptors be closed
469 before running the subprocess.
470
471 \item \var{cwd} specifies the working directory in which the
472 subprocess will be executed (defaulting to whatever the parent's
473 working directory is).
474
Andrew M. Kuchlingb6ffc272004-10-12 16:36:57 +0000475 \item \var{env} is a dictionary specifying environment variables.
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000476
477 \item \var{preexec_fn} is a function that gets called before the
478 child is started.
479
480 \item \var{universal_newlines} opens the child's input and output
481 using Python's universal newline feature.
482
Andrew M. Kuchlingb6ffc272004-10-12 16:36:57 +0000483\end{itemize}
484
485Once you've created the \class{Popen} instance,
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000486you can call its \method{wait()} method to pause until the subprocess
487has exited, \method{poll()} to check if it's exited without pausing,
488or \method{communicate(\var{data})} to send the string \var{data} to
Andrew M. Kuchlingb6ffc272004-10-12 16:36:57 +0000489the subprocess's standard input. \method{communicate(\var{data})}
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000490then reads any data that the subprocess has sent to its standard output
491or standard error, returning a tuple \code{(\var{stdout_data},
492\var{stderr_data})}.
Andrew M. Kuchlingb6ffc272004-10-12 16:36:57 +0000493
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000494\function{call()} is a shortcut that passes its arguments along to the
495\class{Popen} constructor, waits for the command to complete, and
496returns the status code of the subprocess. It can serve as a safer
497analog to \function{os.system()}:
Andrew M. Kuchlingb6ffc272004-10-12 16:36:57 +0000498
499\begin{verbatim}
500sts = subprocess.call(['dpkg', '-i', '/tmp/new-package.deb'])
501if sts == 0:
502 # Success
503 ...
504else:
505 # dpkg returned an error
506 ...
507\end{verbatim}
508
509The command is invoked without use of the shell. If you really do want to
510use the shell, you can add \code{shell=True} as a keyword argument and provide
511a string instead of a sequence:
512
513\begin{verbatim}
514sts = subprocess.call('dpkg -i /tmp/new-package.deb', shell=True)
515\end{verbatim}
516
517The PEP takes various examples of shell and Python code and shows how
518they'd be translated into Python code that uses \module{subprocess}.
519Reading this section of the PEP is highly recommended.
Andrew M. Kuchlingc9e7d772004-10-12 15:58:02 +0000520
521\begin{seealso}
Andrew M. Kuchlingb6ffc272004-10-12 16:36:57 +0000522\seepep{324}{subprocess - New process module}{Written and implemented by Peter {\AA}strand, with assistance from Fredrik Lundh and others.}
Andrew M. Kuchlingc9e7d772004-10-12 15:58:02 +0000523\end{seealso}
524
Andrew M. Kuchlingb6ffc272004-10-12 16:36:57 +0000525
Andrew M. Kuchlingc9e7d772004-10-12 15:58:02 +0000526%======================================================================
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000527\section{PEP 327: Decimal Data Type}
528
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000529Python has always supported floating-point (FP) numbers, based on the
530underlying C \ctype{double} type, as a data type. However, while most
531programming languages provide a floating-point type, most people (even
532programmers) are unaware that computing with floating-point numbers
533entails certain unavoidable inaccuracies. The new decimal type
534provides a way to avoid these inaccuracies.
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000535
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000536\subsection{Why is Decimal needed?}
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000537
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000538The limitations arise from the representation used for floating-point numbers.
539FP numbers are made up of three components:
540
541\begin{itemize}
Andrew M. Kuchlinge34c3bd2004-08-31 12:21:44 +0000542\item The sign, which is positive or negative.
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000543\item The mantissa, which is a single-digit binary number
544followed by a fractional part. For example, \code{1.01} in base-2 notation
545is \code{1 + 0/2 + 1/4}, or 1.25 in decimal notation.
546\item The exponent, which tells where the decimal point is located in the number represented.
547\end{itemize}
548
Andrew M. Kuchlinge34c3bd2004-08-31 12:21:44 +0000549For example, the number 1.25 has positive sign, a mantissa value of
5501.01 (in binary), and an exponent of 0 (the decimal point doesn't need
551to be shifted). The number 5 has the same sign and mantissa, but the
552exponent is 2 because the mantissa is multiplied by 4 (2 to the power
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000553of the exponent 2); 1.25 * 4 equals 5.
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000554
555Modern systems usually provide floating-point support that conforms to
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000556a standard called IEEE 754. C's \ctype{double} type is usually
557implemented as a 64-bit IEEE 754 number, which uses 52 bits of space
558for the mantissa. This means that numbers can only be specified to 52
559bits of precision. If you're trying to represent numbers whose
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000560expansion repeats endlessly, the expansion is cut off after 52 bits.
561Unfortunately, most software needs to produce output in base 10, and
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000562common fractions in base 10 are often repeating decimals in binary.
563For example, 1.1 decimal is binary \code{1.0001100110011 ...}; .1 =
5641/16 + 1/32 + 1/256 plus an infinite number of additional terms. IEEE
565754 has to chop off that infinitely repeated decimal after 52 digits,
566so the representation is slightly inaccurate.
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000567
568Sometimes you can see this inaccuracy when the number is printed:
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000569\begin{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000570>>> 1.1
5711.1000000000000001
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000572\end{verbatim}
573
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000574The inaccuracy isn't always visible when you print the number because
Andrew M. Kuchlinge34c3bd2004-08-31 12:21:44 +0000575the FP-to-decimal-string conversion is provided by the C library, and
576most C libraries try to produce sensible output. Even if it's not
577displayed, however, the inaccuracy is still there and subsequent
578operations can magnify the error.
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000579
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000580For many applications this doesn't matter. If I'm plotting points and
581displaying them on my monitor, the difference between 1.1 and
5821.1000000000000001 is too small to be visible. Reports often limit
583output to a certain number of decimal places, and if you round the
584number to two or three or even eight decimal places, the error is
585never apparent. However, for applications where it does matter,
586it's a lot of work to implement your own custom arithmetic routines.
587
Andrew M. Kuchlinge34c3bd2004-08-31 12:21:44 +0000588Hence, the \class{Decimal} type was created.
589
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000590\subsection{The \class{Decimal} type}
591
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000592A new module, \module{decimal}, was added to Python's standard
593library. It contains two classes, \class{Decimal} and
594\class{Context}. \class{Decimal} instances represent numbers, and
595\class{Context} instances are used to wrap up various settings such as
596the precision and default rounding mode.
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000597
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000598\class{Decimal} instances are immutable, like regular Python integers
599and FP numbers; once it's been created, you can't change the value an
600instance represents. \class{Decimal} instances can be created from
601integers or strings:
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000602
603\begin{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000604>>> import decimal
605>>> decimal.Decimal(1972)
606Decimal("1972")
607>>> decimal.Decimal("1.1")
608Decimal("1.1")
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000609\end{verbatim}
610
Andrew M. Kuchlinge34c3bd2004-08-31 12:21:44 +0000611You can also provide tuples containing the sign, the mantissa represented
612as a tuple of decimal digits, and the exponent:
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000613
614\begin{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000615>>> decimal.Decimal((1, (1, 4, 7, 5), -2))
616Decimal("-14.75")
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000617\end{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000618
Andrew M. Kuchlinge34c3bd2004-08-31 12:21:44 +0000619Cautionary note: the sign bit is a Boolean value, so 0 is positive and
6201 is negative.
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000621
Andrew M. Kuchlinge34c3bd2004-08-31 12:21:44 +0000622Converting from floating-point numbers poses a bit of a problem:
623should the FP number representing 1.1 turn into the decimal number for
624exactly 1.1, or for 1.1 plus whatever inaccuracies are introduced?
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000625The decision was to dodge the issue and leave such a conversion out of
626the API. Instead, you should convert the floating-point number into a
627string using the desired precision and pass the string to the
628\class{Decimal} constructor:
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000629
630\begin{verbatim}
631>>> f = 1.1
632>>> decimal.Decimal(str(f))
633Decimal("1.1")
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000634>>> decimal.Decimal('%.12f' % f)
635Decimal("1.100000000000")
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000636\end{verbatim}
637
638Once you have \class{Decimal} instances, you can perform the usual
639mathematical operations on them. One limitation: exponentiation
640requires an integer exponent:
641
642\begin{verbatim}
643>>> a = decimal.Decimal('35.72')
644>>> b = decimal.Decimal('1.73')
645>>> a+b
646Decimal("37.45")
647>>> a-b
648Decimal("33.99")
649>>> a*b
650Decimal("61.7956")
651>>> a/b
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000652Decimal("20.64739884393063583815028902")
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000653>>> a ** 2
654Decimal("1275.9184")
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000655>>> a**b
656Traceback (most recent call last):
657 ...
658decimal.InvalidOperation: x ** (non-integer)
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000659\end{verbatim}
660
661You can combine \class{Decimal} instances with integers, but not with
662floating-point numbers:
663
664\begin{verbatim}
665>>> a + 4
666Decimal("39.72")
667>>> a + 4.5
668Traceback (most recent call last):
669 ...
670TypeError: You can interact Decimal only with int, long or Decimal data types.
671>>>
672\end{verbatim}
673
674\class{Decimal} numbers can be used with the \module{math} and
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000675\module{cmath} modules, but note that they'll be immediately converted to
676floating-point numbers before the operation is performed, resulting in
677a possible loss of precision and accuracy. You'll also get back a
678regular floating-point number and not a \class{Decimal}.
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000679
680\begin{verbatim}
681>>> import math, cmath
682>>> d = decimal.Decimal('123456789012.345')
683>>> math.sqrt(d)
684351364.18288201344
685>>> cmath.sqrt(-d)
686351364.18288201344j
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000687\end{verbatim}
688
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000689\class{Decimal} instances have a \method{sqrt()} method that
690returns a \class{Decimal}, but if you need other things such as
691trigonometric functions you'll have to implement them.
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000692
693\begin{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000694>>> d.sqrt()
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000695Decimal("351364.1828820134592177245001")
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000696\end{verbatim}
697
698
699\subsection{The \class{Context} type}
700
701Instances of the \class{Context} class encapsulate several settings for
702decimal operations:
703
704\begin{itemize}
705 \item \member{prec} is the precision, the number of decimal places.
706 \item \member{rounding} specifies the rounding mode. The \module{decimal}
707 module has constants for the various possibilities:
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000708 \constant{ROUND_DOWN}, \constant{ROUND_CEILING},
709 \constant{ROUND_HALF_EVEN}, and various others.
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000710 \item \member{traps} is a dictionary specifying what happens on
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000711encountering certain error conditions: either an exception is raised or
712a value is returned. Some examples of error conditions are
713division by zero, loss of precision, and overflow.
714\end{itemize}
715
716There's a thread-local default context available by calling
717\function{getcontext()}; you can change the properties of this context
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000718to alter the default precision, rounding, or trap handling. The
719following example shows the effect of changing the precision of the default
720context:
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000721
722\begin{verbatim}
723>>> decimal.getcontext().prec
72428
725>>> decimal.Decimal(1) / decimal.Decimal(7)
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000726Decimal("0.1428571428571428571428571429")
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000727>>> decimal.getcontext().prec = 9
728>>> decimal.Decimal(1) / decimal.Decimal(7)
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000729Decimal("0.142857143")
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000730\end{verbatim}
731
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000732The default action for error conditions is selectable; the module can
733either return a special value such as infinity or not-a-number, or
734exceptions can be raised:
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000735
736\begin{verbatim}
737>>> decimal.Decimal(1) / decimal.Decimal(0)
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000738Traceback (most recent call last):
739 ...
740decimal.DivisionByZero: x / 0
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000741>>> decimal.getcontext().traps[decimal.DivisionByZero] = False
742>>> decimal.Decimal(1) / decimal.Decimal(0)
743Decimal("Infinity")
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000744>>>
745\end{verbatim}
746
747The \class{Context} instance also has various methods for formatting
748numbers such as \method{to_eng_string()} and \method{to_sci_string()}.
749
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000750For more information, see the documentation for the \module{decimal}
751module, which includes a quick-start tutorial and a reference.
752
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000753\begin{seealso}
754\seepep{327}{Decimal Data Type}{Written by Facundo Batista and implemented
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000755 by Facundo Batista, Eric Price, Raymond Hettinger, Aahz, and Tim Peters.}
756
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000757\seeurl{http://research.microsoft.com/\textasciitilde hollasch/cgindex/coding/ieeefloat.html}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000758{A more detailed overview of the IEEE-754 representation.}
759
760\seeurl{http://www.lahey.com/float.htm}
761{The article uses Fortran code to illustrate many of the problems
762that floating-point inaccuracy can cause.}
763
764\seeurl{http://www2.hursley.ibm.com/decimal/}
765{A description of a decimal-based representation. This representation
766is being proposed as a standard, and underlies the new Python decimal
767type. Much of this material was written by Mike Cowlishaw, designer of the
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000768Rexx language.}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000769
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000770\end{seealso}
771
772
773%======================================================================
Andrew M. Kuchling3294e9d2004-08-31 11:26:23 +0000774\section{PEP 328: Multi-line Imports}
775
776One language change is a small syntactic tweak aimed at making it
777easier to import many names from a module. In a
778\code{from \var{module} import \var{names}} statement,
779\var{names} is a sequence of names separated by commas. If the sequence is
780very long, you can either write multiple imports from the same module,
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000781or you can use backslashes to escape the line endings like this:
Andrew M. Kuchling3294e9d2004-08-31 11:26:23 +0000782
783\begin{verbatim}
784from SimpleXMLRPCServer import SimpleXMLRPCServer,\
785 SimpleXMLRPCRequestHandler,\
786 CGIXMLRPCRequestHandler,\
787 resolve_dotted_attribute
788\end{verbatim}
789
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000790The syntactic change in Python 2.4 simply allows putting the names
791within parentheses. Python ignores newlines within a parenthesized
Andrew M. Kuchling3294e9d2004-08-31 11:26:23 +0000792expression, so the backslashes are no longer needed:
793
794\begin{verbatim}
795from SimpleXMLRPCServer import (SimpleXMLRPCServer,
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000796 SimpleXMLRPCRequestHandler,
797 CGIXMLRPCRequestHandler,
798 resolve_dotted_attribute)
Andrew M. Kuchling3294e9d2004-08-31 11:26:23 +0000799\end{verbatim}
800
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000801The PEP also proposes that all \keyword{import} statements be absolute
802imports, with a leading \samp{.} character to indicate a relative
803import. This part of the PEP is not yet implemented, and will have to
804wait for Python 2.5 or some other future version.
Andrew M. Kuchling3294e9d2004-08-31 11:26:23 +0000805
806\begin{seealso}
Fred Drake410eb842004-09-01 04:05:08 +0000807\seepep{328}{Imports: Multi-Line and Absolute/Relative}
808 {Written by Aahz. Multi-line imports were implemented by
809 Dima Dorfman.}
810\end{seealso}
Andrew M. Kuchling3294e9d2004-08-31 11:26:23 +0000811
812
813%======================================================================
Andrew M. Kuchling65a33322004-07-21 12:41:38 +0000814\section{PEP 331: Locale-Independent Float/String Conversions}
815
816The \module{locale} modules lets Python software select various
817conversions and display conventions that are localized to a particular
818country or language. However, the module was careful to not change
819the numeric locale because various functions in Python's
820implementation required that the numeric locale remain set to the
821\code{'C'} locale. Often this was because the code was using the C library's
822\cfunction{atof()} function.
823
824Not setting the numeric locale caused trouble for extensions that used
825third-party C libraries, however, because they wouldn't have the
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000826% XXX is it GTK or GTk?
Andrew M. Kuchling65a33322004-07-21 12:41:38 +0000827correct locale set. The motivating example was GTK+, whose user
828interface widgets weren't displaying numbers in the current locale.
829
830The solution described in the PEP is to add three new functions to the
831Python API that perform ASCII-only conversions, ignoring the locale
832setting:
833
834\begin{itemize}
835 \item \cfunction{PyOS_ascii_strtod(\var{str}, \var{ptr})}
836and \cfunction{PyOS_ascii_atof(\var{str}, \var{ptr})}
837both convert a string to a C \ctype{double}.
838 \item \cfunction{PyOS_ascii_formatd(\var{buffer}, \var{buf_len}, \var{format}, \var{d})} converts a \ctype{double} to an ASCII string.
839\end{itemize}
840
841The code for these functions came from the GLib library
842(\url{http://developer.gnome.org/arch/gtk/glib.html}), whose
843developers kindly relicensed the relevant functions and donated them
844to the Python Software Foundation. The \module{locale} module
845can now change the numeric locale, letting extensions such as GTK+
846produce the correct results.
847
848\begin{seealso}
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000849\seepep{331}{Locale-Independent Float/String Conversions}
850{Written by Christian R. Reis, and implemented by Gustavo Carneiro.}
Andrew M. Kuchling65a33322004-07-21 12:41:38 +0000851\end{seealso}
852
853%======================================================================
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000854\section{Other Language Changes}
855
856Here are all of the changes that Python 2.4 makes to the core Python
857language.
858
859\begin{itemize}
Raymond Hettingerd4462302003-11-26 17:52:45 +0000860
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000861\item Decorators for functions and methods were added (\pep{318}).
862
863\item Built-in \function{set} and \function{frozenset} types were
864added (\pep{218}). Other new built-ins include the \function{reversed(\var{seq})} function (\pep{322}).
865
866\item Generator expressions were added (\pep{289}).
867
868\item Certain numeric expressions no longer return values restricted to 32 or 64 bits (\pep{237}).
869
870\item You can now put parentheses around the list of names in a
871\code{from \var{module} import \var{names}} statement (\pep{328}).
872
Raymond Hettinger31017ae2004-03-04 08:25:44 +0000873\item The \method{dict.update()} method now accepts the same
874argument forms as the \class{dict} constructor. This includes any
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +0000875mapping, any iterable of key/value pairs, and keyword arguments.
876(Contributed by Raymond Hettinger.)
Raymond Hettinger31017ae2004-03-04 08:25:44 +0000877
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000878\item The string methods \method{ljust()}, \method{rjust()}, and
Andrew M. Kuchling67087562003-11-26 18:03:48 +0000879\method{center()} now take an optional argument for specifying a
Raymond Hettingerd4462302003-11-26 17:52:45 +0000880fill character other than a space.
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +0000881(Contributed by Raymond Hettinger.)
Raymond Hettingerd4462302003-11-26 17:52:45 +0000882
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000883\item Strings also gained an \method{rsplit()} method that
Raymond Hettingered54d912003-12-31 01:59:18 +0000884works like the \method{split()} method but splits from the end of
Andrew M. Kuchling44a31e12004-01-01 18:33:34 +0000885the string.
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000886
887\begin{verbatim}
Raymond Hettinger7a6d2972004-02-13 19:00:07 +0000888>>> 'www.python.org'.split('.', 1)
889['www', 'python.org']
890'www.python.org'.rsplit('.', 1)
891['www.python', 'org']
892\end{verbatim}
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000893
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000894\item Three keyword parameters, \var{cmp}, \var{key}, and
895\var{reverse}, were added to the \method{sort()} method of lists.
896These parameters make some common usages of \method{sort()} simpler.
897All of these parameters are optional.
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000898
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000899For the \var{cmp} parameter, the value should be a comparison function
900that takes two parameters and returns -1, 0, or +1 depending on how
901the parameters compare. This function will then be used to sort the
902list. Previously this was the only parameter that could be provided
903to \method{sort()}.
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000904
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000905\var{key} should be a single-parameter function that takes a list
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000906element and returns a comparison key for the element. The list is
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000907then sorted using the comparison keys. The following example sorts a
908list case-insensitively:
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000909
910\begin{verbatim}
911>>> L = ['A', 'b', 'c', 'D']
912>>> L.sort() # Case-sensitive sort
913>>> L
914['A', 'D', 'b', 'c']
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000915>>> # Using 'key' parameter to sort list
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000916>>> L.sort(key=lambda x: x.lower())
917>>> L
918['A', 'b', 'c', 'D']
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000919>>> # Old-fashioned way
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000920>>> L.sort(cmp=lambda x,y: cmp(x.lower(), y.lower()))
921>>> L
922['A', 'b', 'c', 'D']
923\end{verbatim}
924
925The last example, which uses the \var{cmp} parameter, is the old way
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000926to perform a case-insensitive sort. It works but is slower than using
927a \var{key} parameter. Using \var{key} calls \method{lower()} method
928once for each element in the list while using \var{cmp} will call it
929twice for each comparison, so using \var{key} saves on invocations of
930the \method{lower()} method.
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000931
Andrew M. Kuchling981a9182003-11-13 21:33:26 +0000932For simple key functions and comparison functions, it is often
933possible to avoid a \keyword{lambda} expression by using an unbound
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000934method instead. For example, the above case-insensitive sort is best
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000935written as:
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000936
937\begin{verbatim}
938>>> L.sort(key=str.lower)
939>>> L
940['A', 'b', 'c', 'D']
941\end{verbatim}
942
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000943Finally, the \var{reverse} parameter takes a Boolean value. If the
944value is true, the list will be sorted into reverse order.
945Instead of \code{L.sort() ; L.reverse()}, you can now write
946\code{L.sort(reverse=True)}.
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000947
Andrew M. Kuchling981a9182003-11-13 21:33:26 +0000948The results of sorting are now guaranteed to be stable. This means
949that two entries with equal keys will be returned in the same order as
950they were input. For example, you can sort a list of people by name,
951and then sort the list by age, resulting in a list sorted by age where
952people with the same age are in name-sorted order.
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000953
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +0000954(All changes to \method{sort()} contributed by Raymond Hettinger.)
955
Fred Drake56fcc232004-05-06 02:55:35 +0000956\item There is a new built-in function
957\function{sorted(\var{iterable})} that works like the in-place
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000958\method{list.sort()} method but can be used in
Fred Drake56fcc232004-05-06 02:55:35 +0000959expressions. The differences are:
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000960 \begin{itemize}
Raymond Hettinger7d1dd042003-11-12 16:42:10 +0000961 \item the input may be any iterable;
962 \item a newly formed copy is sorted, leaving the original intact; and
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000963 \item the expression returns the new sorted copy
964 \end{itemize}
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000965
966\begin{verbatim}
967>>> L = [9,7,8,3,2,4,1,6,5]
Raymond Hettinger64958a12003-12-17 20:43:33 +0000968>>> [10+i for i in sorted(L)] # usable in a list comprehension
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000969[11, 12, 13, 14, 15, 16, 17, 18, 19]
Hye-Shik Chang2b052482004-07-17 13:53:48 +0000970>>> L # original is left unchanged
Andrew M. Kuchlinge3e1eca2004-07-26 18:52:48 +0000971[9,7,8,3,2,4,1,6,5]
972>>> sorted('Monty Python') # any iterable may be an input
973[' ', 'M', 'P', 'h', 'n', 'n', 'o', 'o', 't', 't', 'y', 'y']
Raymond Hettingerd4462302003-11-26 17:52:45 +0000974
975>>> # List the contents of a dict sorted by key values
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000976>>> colormap = dict(red=1, blue=2, green=3, black=4, yellow=5)
Raymond Hettinger64958a12003-12-17 20:43:33 +0000977>>> for k, v in sorted(colormap.iteritems()):
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000978... print k, v
979...
980black 4
981blue 2
982green 3
983red 1
984yellow 5
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000985\end{verbatim}
986
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +0000987(Contributed by Raymond Hettinger.)
988
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +0000989\item Integer operations will no longer trigger an \exception{OverflowWarning}.
990The \exception{OverflowWarning} warning will disappear in Python 2.5.
991
Andrew M. Kuchling5e3f9232004-10-07 12:00:33 +0000992\item The interpreter gained a new switch, \programopt{-m}, that
993takes a name, searches for the corresponding module on \code{sys.path},
994and runs the module as a script. For example,
995you can now run the Python profiler with \code{python -m profile}.
996(Contributed by Nick Coghlan.)
997
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +0000998\item The \function{eval(\var{expr}, \var{globals}, \var{locals})}
Andrew M. Kuchling1455f792004-08-02 12:09:58 +0000999and \function{execfile(\var{filename}, \var{globals}, \var{locals})}
1000functions and the \keyword{exec} statement now accept any mapping type
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001001for the \var{locals} parameter. Previously this had to be a regular
Andrew M. Kuchling1455f792004-08-02 12:09:58 +00001002Python dictionary. (Contributed by Raymond Hettinger.)
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +00001003
Raymond Hettinger607c00f2003-11-12 16:27:50 +00001004\item The \function{zip()} built-in function and \function{itertools.izip()}
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +00001005 now return an empty list if called with no arguments.
1006 Previously they raised a \exception{TypeError}
1007 exception. This makes them more
Raymond Hettinger607c00f2003-11-12 16:27:50 +00001008 suitable for use with variable length argument lists:
1009
1010\begin{verbatim}
1011>>> def transpose(array):
1012... return zip(*array)
1013...
1014>>> transpose([(1,2,3), (4,5,6)])
1015[(1, 4), (2, 5), (3, 6)]
1016>>> transpose([])
1017[]
1018\end{verbatim}
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001019(Contributed by Raymond Hettinger.)
1020
Andrew M. Kuchlingd91fcbe2004-08-02 12:44:28 +00001021\item Encountering a failure while importing a module no longer leaves
1022a partially-initialized module object in \code{sys.modules}. The
1023incomplete module object left behind would fool further imports of the
1024same module into succeeding, leading to confusing errors.
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001025% (XXX contributed by Tim?)
Andrew M. Kuchlingd91fcbe2004-08-02 12:44:28 +00001026
Andrew M. Kuchling65a33322004-07-21 12:41:38 +00001027\item \constant{None} is now a constant; code that binds a new value to
1028the name \samp{None} is now a syntax error.
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001029(Contributed by Raymond Hettinger.)
Andrew M. Kuchling65a33322004-07-21 12:41:38 +00001030
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001031\end{itemize}
1032
1033
1034%======================================================================
1035\subsection{Optimizations}
1036
1037\begin{itemize}
1038
Raymond Hettingerca1a7752004-07-12 13:00:45 +00001039\item The inner loops for list and tuple slicing
Andrew M. Kuchling65a33322004-07-21 12:41:38 +00001040 were optimized and now run about one-third faster. The inner loops
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001041 for dictionaries were also optimized , resulting in performance boosts for
Andrew M. Kuchling65a33322004-07-21 12:41:38 +00001042 \method{keys()}, \method{values()}, \method{items()},
1043 \method{iterkeys()}, \method{itervalues()}, and \method{iteritems()}.
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001044 (Contributed by Raymond Hettinger.)
Raymond Hettingerb7d05db2004-03-08 07:25:05 +00001045
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +00001046\item The machinery for growing and shrinking lists was optimized for
1047 speed and for space efficiency. Appending and popping from lists now
1048 runs faster due to more efficient code paths and less frequent use of
1049 the underlying system \cfunction{realloc()}. List comprehensions
1050 also benefit. \method{list.extend()} was also optimized and no
1051 longer converts its argument into a temporary list before extending
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001052 the base list. (Contributed by Raymond Hettinger.)
Raymond Hettinger7a6d2972004-02-13 19:00:07 +00001053
Raymond Hettinger97ef8de2004-01-05 00:29:57 +00001054\item \function{list()}, \function{tuple()}, \function{map()},
1055 \function{filter()}, and \function{zip()} now run several times
1056 faster with non-sequence arguments that supply a \method{__len__()}
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001057 method. (Contributed by Raymond Hettinger.)
Raymond Hettinger97ef8de2004-01-05 00:29:57 +00001058
Raymond Hettinger23a0f4e2004-01-05 08:15:20 +00001059\item The methods \method{list.__getitem__()},
Raymond Hettinger97ef8de2004-01-05 00:29:57 +00001060 \method{dict.__getitem__()}, and \method{dict.__contains__()} are
1061 are now implemented as \class{method_descriptor} objects rather
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001062 than \class{wrapper_descriptor} objects. This form of
Raymond Hettinger97ef8de2004-01-05 00:29:57 +00001063 access doubles their performance and makes them more suitable for
Raymond Hettinger23a0f4e2004-01-05 08:15:20 +00001064 use as arguments to functionals:
1065 \samp{map(mydict.__getitem__, keylist)}.
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001066 (Contributed by Raymond Hettinger.)
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001067
Fred Draked6d35d92004-06-03 13:31:22 +00001068\item Added a new opcode, \code{LIST_APPEND}, that simplifies
Raymond Hettingerdd80f762004-03-07 07:31:06 +00001069 the generated bytecode for list comprehensions and speeds them up
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001070 by about a third. (Contributed by Raymond Hettinger.)
Raymond Hettingerdd80f762004-03-07 07:31:06 +00001071
Andrew M. Kuchling0c789562004-09-23 20:15:41 +00001072\item The peephole bytecode optimizer has been improved to
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001073produce shorter, faster bytecode; remarkably, the resulting bytecode is
Andrew M. Kuchling0c789562004-09-23 20:15:41 +00001074more readable. (Enhanced by Raymond Hettinger.)
1075
Andrew M. Kuchlingac642872004-08-07 13:13:31 +00001076\item String concatenations in statements of the form \code{s = s +
1077"abc"} and \code{s += "abc"} are now performed more efficiently in
1078certain circumstances. This optimization won't be present in other
1079Python implementations such as Jython, so you shouldn't rely on it;
1080using the \method{join()} method of strings is still recommended when
1081you want to efficiently glue a large number of strings together.
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001082(Contributed by Armin Rigo.)
Andrew M. Kuchlingac642872004-08-07 13:13:31 +00001083
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001084\end{itemize}
1085
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001086% XXX fill in these figures
Raymond Hettingerb2d5a8e2004-11-18 05:51:53 +00001087% pystone is almost useless for comparing different versions of Python;
1088% instead, it excels at predicting relative Python performance on
1089% different machines.
1090% So, this section would be more informative if it used other tools
1091% such as pybench and parrotbench. For a more application oriented
1092% benchmark, try comparing the timings of test_decimal.py under 2.3
1093% and 2.4.
1094
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001095The net result of the 2.4 optimizations is that Python 2.4 runs the
1096pystone benchmark around XX\% faster than Python 2.3 and YY\% faster
1097than Python 2.2.
1098
1099
1100%======================================================================
1101\section{New, Improved, and Deprecated Modules}
1102
1103As usual, Python's standard library received a number of enhancements and
1104bug fixes. Here's a partial list of the most notable changes, sorted
1105alphabetically by module name. Consult the
1106\file{Misc/NEWS} file in the source tree for a more
1107complete list of changes, or look through the CVS logs for all the
1108details.
1109
1110\begin{itemize}
1111
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001112\item The \module{asyncore} module's \function{loop()} function now
1113 has a \var{count} parameter that lets you perform a limited number
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +00001114 of passes through the polling loop. The default is still to loop
1115 forever.
1116
Andrew M. Kuchlinga331e862004-09-10 13:05:22 +00001117\item The \module{base64} module now has more complete RFC 3548 support
1118 for Base64, Base32, and Base16 encoding and decoding, including
1119 optional case folding and optional alternative alphabets.
1120 (Contributed by Barry Warsaw.)
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +00001121
Raymond Hettinger0c410272004-01-05 10:13:35 +00001122\item The \module{bisect} module now has an underlying C implementation
1123 for improved performance.
1124 (Contributed by Dmitry Vasiliev.)
1125
Andrew M. Kuchling5303a962004-01-18 15:55:51 +00001126\item The CJKCodecs collections of East Asian codecs, maintained
1127by Hye-Shik Chang, was integrated into 2.4.
1128The new encodings are:
1129
1130\begin{itemize}
Andrew M. Kuchling671c5062004-07-28 15:29:39 +00001131 \item Chinese (PRC): gb2312, gbk, gb18030, big5hkscs, hz
Andrew M. Kuchling5303a962004-01-18 15:55:51 +00001132 \item Chinese (ROC): big5, cp950
Andrew M. Kuchling671c5062004-07-28 15:29:39 +00001133 \item Japanese: cp932, euc-jis-2004, euc-jp,
Andrew M. Kuchling5303a962004-01-18 15:55:51 +00001134euc-jisx0213, iso-2022-jp, iso-2022-jp-1, iso-2022-jp-2,
Andrew M. Kuchling671c5062004-07-28 15:29:39 +00001135 iso-2022-jp-3, iso-2022-jp-ext, iso-2022-jp-2004,
1136 shift-jis, shift-jisx0213, shift-jis-2004
Andrew M. Kuchling5303a962004-01-18 15:55:51 +00001137 \item Korean: cp949, euc-kr, johab, iso-2022-kr
1138\end{itemize}
1139
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001140\item Some other new encodings were added: HP Roman8,
1141ISO_8859-11, ISO_8859-16, PCTP-154, and TIS-620.
1142
Andrew M. Kuchling579b3e22004-10-05 20:23:34 +00001143\item The UTF-8 and UTF-16 codecs now cope better with receiving partial input.
1144Previously the \class{StreamReader} class would try to read more data,
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001145making it impossible to resume decoding from the stream. The
Andrew M. Kuchling579b3e22004-10-05 20:23:34 +00001146\method{read()} method will now return as much data as it can and future
1147calls will resume decoding where previous ones left off.
1148(Implemented by Walter D\"orwald.)
1149
Andrew M. Kuchlingfd0e4942004-02-09 13:23:34 +00001150\item There is a new \module{collections} module for
1151 various specialized collection datatypes.
1152 Currently it contains just one type, \class{deque},
1153 a double-ended queue that supports efficiently adding and removing
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001154 elements from either end:
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001155
1156\begin{verbatim}
1157>>> from collections import deque
1158>>> d = deque('ghi') # make a new deque with three items
1159>>> d.append('j') # add a new entry to the right side
1160>>> d.appendleft('f') # add a new entry to the left side
1161>>> d # show the representation of the deque
1162deque(['f', 'g', 'h', 'i', 'j'])
1163>>> d.pop() # return and remove the rightmost item
1164'j'
1165>>> d.popleft() # return and remove the leftmost item
1166'f'
1167>>> list(d) # list the contents of the deque
1168['g', 'h', 'i']
1169>>> 'h' in d # search the deque
1170True
1171\end{verbatim}
1172
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001173Several modules, such as the \module{Queue} and \module{threading}
1174modules, now take advantage of \class{collections.deque} for improved
1175performance. (Contributed by Raymond Hettinger.)
Andrew M. Kuchling5303a962004-01-18 15:55:51 +00001176
Fred Drake9f15b5c2004-05-18 04:30:00 +00001177\item The \module{ConfigParser} classes have been enhanced slightly.
1178 The \method{read()} method now returns a list of the files that
1179 were successfully parsed, and the \method{set()} method raises
1180 \exception{TypeError} if passed a \var{value} argument that isn't a
1181 string.
1182
Andrew M. Kuchlinga331e862004-09-10 13:05:22 +00001183\item The \module{curses} module now supports the ncurses extension
1184 \function{use_default_colors()}. On platforms where the terminal
1185 supports transparency, this makes it possible to use a transparent
1186 background. (Contributed by J\"org Lehmann.)
1187
1188\item The \module{difflib} module now includes an \class{HtmlDiff} class
1189that creates an HTML table showing a side by side comparison
1190of two versions of a text. (Contributed by Dan Gass.)
1191
Andrew M. Kuchling579b3e22004-10-05 20:23:34 +00001192\item The \module{email} package was updated to version 3.0,
1193which dropped various deprecated APIs and removes support for Python
1194versions earlier than 2.3. The 3.0 version of the package uses a new
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001195incremental parser for MIME messages, available in the
Andrew M. Kuchling579b3e22004-10-05 20:23:34 +00001196\module{email.FeedParser} module. The new parser doesn't require
1197reading the entire message into memory, and doesn't throw exceptions
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001198if a message is malformed; instead it records any problems in the
Andrew M. Kuchling579b3e22004-10-05 20:23:34 +00001199\member{defect} attribute of the message. (Developed by Anthony
1200Baxter, Barry Warsaw, Thomas Wouters, and others.)
Andrew M. Kuchlinga331e862004-09-10 13:05:22 +00001201
Raymond Hettinger607c00f2003-11-12 16:27:50 +00001202\item The \module{heapq} module has been converted to C. The resulting
Andrew M. Kuchlingfd0e4942004-02-09 13:23:34 +00001203 tenfold improvement in speed makes the module suitable for handling
Raymond Hettinger33ecffb2004-06-10 05:03:17 +00001204 high volumes of data. In addition, the module has two new functions
1205 \function{nlargest()} and \function{nsmallest()} that use heaps to
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +00001206 find the N largest or smallest values in a dataset without the
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001207 expense of a full sort. (Contributed by Raymond Hettinger.)
Andrew M. Kuchling1a420252003-11-08 15:58:49 +00001208
Andrew M. Kuchling0c789562004-09-23 20:15:41 +00001209\item The \module{httplib} module now contains constants for HTTP
1210status codes defined in various HTTP-related RFC documents. Constants
1211have names such as \constant{OK}, \constant{CREATED},
1212\constant{CONTINUE}, and \constant{MOVED_PERMANENTLY}; use pydoc to
1213get a full list. (Contributed by Andrew Eland.)
1214
Andrew M. Kuchlingce4bae62004-07-27 12:13:25 +00001215\item The \module{imaplib} module now supports IMAP's THREAD command
1216(contributed by Yves Dionne) and new \method{deleteacl()} and
1217\method{myrights()} methods (contributed by Arnaud Mazin).
Andrew M. Kuchlingdff9dbd2003-11-20 22:22:19 +00001218
Andrew M. Kuchlingad809552003-12-06 23:19:23 +00001219\item The \module{itertools} module gained a
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +00001220 \function{groupby(\var{iterable}\optional{, \var{func}})} function.
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001221 \var{iterable} is something that can be iterated over to return a
1222 stream of elements, and the optional \var{func} parameter is a
1223 function that takes an element and returns a key value; if omitted,
1224 the key is simply the element itself. \function{groupby()} then
1225 groups the elements into subsequences which have matching values of
1226 the key, and returns a series of 2-tuples containing the key value
1227 and an iterator over the subsequence.
Andrew M. Kuchlingad809552003-12-06 23:19:23 +00001228
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001229Here's an example to make this clearer. The \var{key} function simply
1230returns whether a number is even or odd, so the result of
1231\function{groupby()} is to return consecutive runs of odd or even
1232numbers.
Andrew M. Kuchlingad809552003-12-06 23:19:23 +00001233
1234\begin{verbatim}
1235>>> import itertools
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001236>>> L = [2, 4, 6, 7, 8, 9, 11, 12, 14]
Andrew M. Kuchlingad809552003-12-06 23:19:23 +00001237>>> for key_val, it in itertools.groupby(L, lambda x: x % 2):
1238... print key_val, list(it)
1239...
12400 [2, 4, 6]
12411 [7]
12420 [8]
12431 [9, 11]
12440 [12, 14]
1245>>>
1246\end{verbatim}
1247
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +00001248\function{groupby()} is typically used with sorted input. The logic
1249for \function{groupby()} is similar to the \UNIX{} \code{uniq} filter
1250which makes it handy for eliminating, counting, or identifying
1251duplicate elements:
Raymond Hettingerfeb78c92003-12-12 13:13:47 +00001252
1253\begin{verbatim}
1254>>> word = 'abracadabra'
Raymond Hettingered54d912003-12-31 01:59:18 +00001255>>> letters = sorted(word) # Turn string into a sorted list of letters
Raymond Hettinger64958a12003-12-17 20:43:33 +00001256>>> letters
Andrew M. Kuchling4612bc52003-12-16 20:59:37 +00001257['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r']
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +00001258>>> for k, g in itertools.groupby(letters):
1259... print k, list(g)
1260...
1261a ['a', 'a', 'a', 'a', 'a']
1262b ['b', 'b']
1263c ['c']
1264d ['d']
1265r ['r', 'r']
1266>>> # List unique letters
1267>>> [k for k, g in groupby(letters)]
Raymond Hettingerfeb78c92003-12-12 13:13:47 +00001268['a', 'b', 'c', 'd', 'r']
Johannes Gijsbersd3452252004-09-11 16:50:06 +00001269>>> # Count letter occurrences
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +00001270>>> [(k, len(list(g))) for k, g in groupby(letters)]
Raymond Hettingerfeb78c92003-12-12 13:13:47 +00001271[('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)]
Raymond Hettingerfeb78c92003-12-12 13:13:47 +00001272\end{verbatim}
1273
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001274(Contributed by Hye-Shik Chang.)
1275
Raymond Hettingered54d912003-12-31 01:59:18 +00001276\item \module{itertools} also gained a function named
1277\function{tee(\var{iterator}, \var{N})} that returns \var{N} independent
1278iterators that replicate \var{iterator}. If \var{N} is omitted, the
1279default is 2.
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +00001280
1281\begin{verbatim}
1282>>> L = [1,2,3]
1283>>> i1, i2 = itertools.tee(L)
1284>>> i1,i2
1285(<itertools.tee object at 0x402c2080>, <itertools.tee object at 0x402c2090>)
Raymond Hettingered54d912003-12-31 01:59:18 +00001286>>> list(i1) # Run the first iterator to exhaustion
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +00001287[1, 2, 3]
Raymond Hettingered54d912003-12-31 01:59:18 +00001288>>> list(i2) # Run the second iterator to exhaustion
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +00001289[1, 2, 3]
1290>\end{verbatim}
1291
1292Note that \function{tee()} has to keep copies of the values returned
Raymond Hettingered54d912003-12-31 01:59:18 +00001293by the iterator; in the worst case, it may need to keep all of them.
Andrew M. Kuchling44a31e12004-01-01 18:33:34 +00001294This should therefore be used carefully if the leading iterator
Raymond Hettingered54d912003-12-31 01:59:18 +00001295can run far ahead of the trailing iterator in a long stream of inputs.
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +00001296If the separation is large, then you might as well use
Raymond Hettingered54d912003-12-31 01:59:18 +00001297\function{list()} instead. When the iterators track closely with one
1298another, \function{tee()} is ideal. Possible applications include
1299bookmarking, windowing, or lookahead iterators.
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001300(Contributed by Raymond Hettinger.)
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +00001301
Andrew M. Kuchling5785a132004-07-26 19:28:46 +00001302\item A number of functions were added to the \module{locale}
1303module, such as \function{bind_textdomain_codeset()} to specify a
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001304particular encoding and a family of \function{l*gettext()} functions
Andrew M. Kuchling5785a132004-07-26 19:28:46 +00001305that return messages in the chosen encoding.
1306(Contributed by Gustavo Niemeyer.)
1307
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001308\item Some keyword arguments were added to the \module{logging}
1309package's \function{basicConfig} function to simplify log
1310configuration. The default behavior is to log messages to standard
1311error, but various keyword arguments can be specified to log to a
1312particular file, change the logging format, or set the logging level.
1313For example:
Andrew M. Kuchlingbcefe692004-07-07 13:01:53 +00001314
1315\begin{verbatim}
1316import logging
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001317logging.basicConfig(filename='/var/log/application.log',
1318 level=0, # Log all messages
Andrew M. Kuchlingbcefe692004-07-07 13:01:53 +00001319 format='%(levelname):%(process):%(thread):%(message)')
1320\end{verbatim}
1321
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001322Other additions to the \module{logging} package include a
1323\method{log(\var{level}, \var{msg})} convenience method, as well as a
1324\class{TimedRotatingFileHandler} class that rotates its log files at a
1325timed interval. The module already had \class{RotatingFileHandler},
Andrew M. Kuchlingbcefe692004-07-07 13:01:53 +00001326which rotated logs once the file exceeded a certain size. Both
1327classes derive from a new \class{BaseRotatingHandler} class that can
1328be used to implement other rotating handlers.
1329
Andrew M. Kuchling579b3e22004-10-05 20:23:34 +00001330(Changes implemented by Vinay Sajip.)
1331
Andrew M. Kuchling0c789562004-09-23 20:15:41 +00001332\item The \module{marshal} module now shares interned strings on unpacking a
1333data structure. This may shrink the size of certain pickle strings,
1334but the primary effect is to make \file{.pyc} files significantly smaller.
1335(Contributed by Martin von Loewis.)
1336
Andrew M. Kuchling5785a132004-07-26 19:28:46 +00001337\item The \module{nntplib} module's \class{NNTP} class gained
1338\method{description()} and \method{descriptions()} methods to retrieve
1339newsgroup descriptions for a single group or for a range of groups.
1340(Contributed by J\"urgen A. Erhard.)
1341
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001342\item Two new functions were added to the \module{operator} module,
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +00001343\function{attrgetter(\var{attr})} and \function{itemgetter(\var{index})}.
1344Both functions return callables that take a single argument and return
Raymond Hettingered54d912003-12-31 01:59:18 +00001345the corresponding attribute or item; these callables make excellent
Andrew M. Kuchlingbcefe692004-07-07 13:01:53 +00001346data extractors when used with \function{map()} or
1347\function{sorted()}. For example:
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +00001348
1349\begin{verbatim}
Raymond Hettingered54d912003-12-31 01:59:18 +00001350>>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +00001351>>> map(operator.itemgetter(0), L)
1352['c', 'd', 'a', 'b']
1353>>> map(operator.itemgetter(1), L)
Raymond Hettingered54d912003-12-31 01:59:18 +00001354[2, 1, 4, 3]
1355>>> sorted(L, key=operator.itemgetter(1)) # Sort list by second tuple item
1356[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +00001357\end{verbatim}
1358
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001359(Contributed by Raymond Hettinger.)
1360
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001361\item The \module{optparse} module was updated in various ways. The
1362module now passes its messages through \function{gettext.gettext()},
1363making it possible to internationalize Optik's help and error
1364messages. Help messages for options can now include the string
1365\code{'\%default'}, which will be replaced by the option's default
1366value. (Contributed by Greg Ward.)
Andrew M. Kuchlinge30c4d42004-08-07 13:58:02 +00001367
Andrew M. Kuchlingf3958f12004-10-11 19:20:06 +00001368\item The long-term plan is to deprecate the \module{rfc822} module
1369in some future Python release in favor of the \module{email} package.
1370To this end, the \function{email.Utils.formatdate()} function has been
1371changed to make it usable as a replacement for
1372\function{rfc822.formatdate()}. You may want to write new e-mail
1373processing code with this in mind. (Change implemented by Anthony
1374Baxter.)
1375
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001376\item A new \function{urandom(\var{n})} function was added to the
1377\module{os} module, returning a string containing \var{n} bytes of
1378random data. This function provides access to platform-specific
1379sources of randomness such as \file{/dev/urandom} on Linux or the
1380Windows CryptoAPI. (Contributed by Trevor Perrin.)
Andrew M. Kuchlingcb7b3f32004-08-30 11:58:04 +00001381
1382\item Another new function: \function{os.path.lexists(\var{path})}
1383returns true if the file specified by \var{path} exists, whether or
1384not it's a symbolic link. This differs from the existing
1385\function{os.path.exists(\var{path})} function, which returns false if
1386\var{path} is a symlink that points to a destination that doesn't exist.
1387(Contributed by Beni Cherniavsky.)
1388
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +00001389\item A new \function{getsid()} function was added to the
1390\module{posix} module that underlies the \module{os} module.
1391(Contributed by J. Raynor.)
1392
1393\item The \module{poplib} module now supports POP over SSL.
1394
1395\item The \module{profile} module can now profile C extension functions.
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001396% XXX more to say about this?
1397(Contributed by Nick Bastin.)
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +00001398
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001399\item The \module{random} module has a new method called
1400 \method{getrandbits(\var{N})} that returns a long integer \var{N}
1401 bits in length. The existing \method{randrange()} method now uses
1402 \method{getrandbits()} where appropriate, making generation of
1403 arbitrarily large random numbers more efficient. (Contributed by
1404 Raymond Hettinger.)
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +00001405
1406\item The regular expression language accepted by the \module{re} module
1407 was extended with simple conditional expressions, written as
Andrew M. Kuchlingab778222004-08-31 12:07:43 +00001408 \regexp{(?(\var{group})\var{A}|\var{B})}. \var{group} is either a
1409 numeric group ID or a group name defined with \regexp{(?P<group>...)}
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +00001410 earlier in the expression. If the specified group matched, the
1411 regular expression pattern \var{A} will be tested against the string; if
1412 the group didn't match, the pattern \var{B} will be used instead.
Raymond Hettinger874ebd52004-05-31 03:15:02 +00001413
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001414\item The \module{re} module is also no longer recursive, thanks to a
1415massive amount of work by Gustavo Niemeyer. In a recursive regular
1416expression engine, certain patterns result in a large amount of C
1417stack space being consumed, and it was possible to overflow the stack.
1418For example, if you matched a 30000-byte string of \samp{a} characters
1419against the expression \regexp{(a|b)+}, one stack frame was consumed
1420per character. Python 2.3 tried to check for stack overflow and raise
1421a \exception{RuntimeError} exception, but certain patterns could
1422sidestep the checking and if you were unlucky Python could segfault.
1423Python 2.4's regular expression engine can match this pattern without
1424problems.
Andrew M. Kuchlingab778222004-08-31 12:07:43 +00001425
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001426\item A new \function{socketpair()} function, returning a pair of
1427connected sockets, was added to the \module{socket} module.
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +00001428(Contributed by Dave Cole.)
Andrew M. Kuchling7f203b82004-08-09 14:48:28 +00001429
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +00001430\item The \function{sys.exitfunc()} function has been deprecated. Code
1431should be using the existing \module{atexit} module, which correctly
1432handles calling multiple exit functions. Eventually
1433\function{sys.exitfunc()} will become a purely internal interface,
1434accessed only by \module{atexit}.
1435
1436\item The \module{tarfile} module now generates GNU-format tar files
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001437by default. (Contributed by Lars Gustaebel.)
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +00001438
Andrew M. Kuchling00457172004-07-15 11:52:40 +00001439\item The \module{threading} module now has an elegantly simple way to support
1440thread-local data. The module contains a \class{local} class whose
1441attribute values are local to different threads.
1442
1443\begin{verbatim}
1444import threading
1445
1446data = threading.local()
1447data.number = 42
1448data.url = ('www.python.org', 80)
1449\end{verbatim}
1450
1451Other threads can assign and retrieve their own values for the
1452\member{number} and \member{url} attributes. You can subclass
1453\class{local} to initialize attributes or to add methods.
1454(Contributed by Jim Fulton.)
1455
Andrew M. Kuchlinga331e862004-09-10 13:05:22 +00001456\item The \module{timeit} module now automatically disables periodic
1457 garbarge collection during the timing loop. This change makes
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001458 consecutive timings more comparable. (Contributed by Raymond Hettinger.)
Andrew M. Kuchlinga331e862004-09-10 13:05:22 +00001459
Raymond Hettinger874ebd52004-05-31 03:15:02 +00001460\item The \module{weakref} module now supports a wider variety of objects
1461 including Python functions, class instances, sets, frozensets, deques,
1462 arrays, files, sockets, and regular expression pattern objects.
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001463 (Contributed by Raymond Hettinger.)
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +00001464
1465\item The \module{xmlrpclib} module now supports a multi-call extension for
Andrew M. Kuchling00457172004-07-15 11:52:40 +00001466transmitting multiple XML-RPC calls in a single HTTP operation.
Andrew M. Kuchling3d3db962004-08-31 13:57:02 +00001467
1468\item The \module{mpz}, \module{rotor}, and \module{xreadlines} modules have
1469been removed.
Andrew M. Kuchling69f31eb2003-08-13 23:11:04 +00001470
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001471\end{itemize}
1472
1473
1474%======================================================================
Raymond Hettingerca1a7752004-07-12 13:00:45 +00001475% whole new modules get described in subsections here
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001476
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001477%=====================
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001478\subsection{cookielib}
1479
1480The \module{cookielib} library supports client-side handling for HTTP
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001481cookies, mirroring the \module{Cookie} module's server-side cookie
1482support. Cookies are stored in cookie jars; the library transparently
1483stores cookies offered by the web server in the cookie jar, and
1484fetches the cookie from the jar when connecting to the server. As in
1485web browsers, policy objects control whether cookies are accepted or
1486not.
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001487
1488In order to store cookies across sessions, two implementations of
1489cookie jars are provided: one that stores cookies in the Netscape
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001490format so applications can use the Mozilla or Lynx cookie files, and
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001491one that stores cookies in the same format as the Perl libwww libary.
1492
1493\module{urllib2} has been changed to interact with \module{cookielib}:
1494\class{HTTPCookieProcessor} manages a cookie jar that is used when
1495accessing URLs.
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001496
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001497% ==================
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +00001498\subsection{doctest}
1499
1500The \module{doctest} module underwent considerable refactoring thanks
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001501to Edward Loper and Tim Peters. Testing can still be as simple as
1502running \function{doctest.testmod()}, but the refactorings allow
1503customizing the module's operation in various ways
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +00001504
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001505The new \class{DocTestFinder} class extracts the tests from a given
1506object's docstrings:
1507
1508\begin{verbatim}
1509def f (x, y):
1510 """>>> f(2,2)
15114
1512>>> f(3,2)
15136
1514 """
1515 return x*y
1516
1517finder = doctest.DocTestFinder()
1518
1519# Get list of DocTest instances
1520tests = finder.find(f)
1521\end{verbatim}
1522
1523The new \class{DocTestRunner} class then runs individual tests and can
1524produce a summary of the results:
1525
1526\begin{verbatim}
1527runner = doctest.DocTestRunner()
1528for t in tests:
1529 tried, failed = runner.run(t)
1530
1531runner.summarize(verbose=1)
1532\end{verbatim}
1533
1534The above example produces the following output:
1535
1536\begin{verbatim}
15371 items passed all tests:
1538 2 tests in f
15392 tests in 1 items.
15402 passed and 0 failed.
1541Test passed.
1542\end{verbatim}
1543
1544\class{DocTestRunner} uses an instance of the \class{OutputChecker}
1545class to compare the expected output with the actual output. This
1546class takes a number of different flags that customize its behaviour;
1547ambitious users can also write a completely new subclass of
1548\class{OutputChecker}.
1549
1550The default output checker provides a number of handy features.
1551For example, with the \constant{doctest.ELLIPSIS} option flag,
1552an ellipsis (\samp{...}) in the expected output matches any substring,
1553making it easier to accommodate outputs that vary in minor ways:
1554
1555\begin{verbatim}
1556def o (n):
1557 """>>> o(1)
1558<__main__.C instance at 0x...>
1559>>>
1560"""
1561\end{verbatim}
1562
1563Another special string, \samp{<BLANKLINE>}, matches a blank line:
1564
1565\begin{verbatim}
1566def p (n):
1567 """>>> p(1)
1568<BLANKLINE>
1569>>>
1570"""
1571\end{verbatim}
1572
1573Another new capability is producing a diff-style display of the output
1574by specifying the \constant{doctest.REPORT_UDIFF} (unified diffs),
1575\constant{doctest.REPORT_CDIFF} (context diffs), or
1576\constant{doctest.REPORT_NDIFF} (delta-style) option flags. For example:
1577
1578\begin{verbatim}
1579def g (n):
1580 """>>> g(4)
1581here
1582is
1583a
1584lengthy
1585>>>"""
1586 L = 'here is a rather lengthy list of words'.split()
1587 for word in L[:n]:
1588 print word
1589\end{verbatim}
1590
1591Running the above function's tests with
1592\constant{doctest.REPORT_UDIFF} specified, you get the following output:
1593
1594\begin{verbatim}
1595**********************************************************************
1596File ``t.py'', line 15, in g
1597Failed example:
1598 g(4)
1599Differences (unified diff with -expected +actual):
1600 @@ -2,3 +2,3 @@
1601 is
1602 a
1603 -lengthy
1604 +rather
1605**********************************************************************
1606\end{verbatim}
1607
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +00001608
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001609% ======================================================================
1610\section{Build and C API Changes}
1611
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001612Some of the changes to Python's build process and to the C API are:
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001613
1614\begin{itemize}
1615
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +00001616 \item Three new convenience macros were added for common return
1617 values from extension functions: \csimplemacro{Py_RETURN_NONE},
1618 \csimplemacro{Py_RETURN_TRUE}, and \csimplemacro{Py_RETURN_FALSE}.
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001619 (Contributed by Brett Cannon.)
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +00001620
Andrew M. Kuchling5785a132004-07-26 19:28:46 +00001621 \item Another new macro, \csimplemacro{Py_CLEAR(\var{obj})},
1622 decreases the reference count of \var{obj} and sets \var{obj} to the
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001623 null pointer. (Contributed by Jim Fulton.)
Andrew M. Kuchling5785a132004-07-26 19:28:46 +00001624
Fred Drakece3caf22004-02-12 18:13:12 +00001625 \item A new function, \cfunction{PyTuple_Pack(\var{N}, \var{obj1},
1626 \var{obj2}, ..., \var{objN})}, constructs tuples from a variable
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001627 length argument list of Python objects. (Contributed by Raymond Hettinger.)
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001628
Fred Drakece3caf22004-02-12 18:13:12 +00001629 \item A new function, \cfunction{PyDict_Contains(\var{d}, \var{k})},
1630 implements fast dictionary lookups without masking exceptions raised
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001631 during the look-up process. (Contributed by Raymond Hettinger.)
Raymond Hettingerd4462302003-11-26 17:52:45 +00001632
Andrew M. Kuchling0c789562004-09-23 20:15:41 +00001633 \item The \csimplemacro{Py_IS_NAN(\var{X})} macro returns 1 if
1634 its float or double argument \var{X} is a NaN.
1635 (Contributed by Tim Peters.)
1636
Andrew M. Kuchlingf3958f12004-10-11 19:20:06 +00001637 \item C code can avoid unnecessary locking by using the new
1638 \cfunction{PyEval_ThreadsInitialized()} function to tell
1639 if any thread operations have been performed. If this function
1640 returns false, no lock operations are needed.
1641 (Contributed by Nick Coghlan.)
1642
Andrew M. Kuchlinge30c4d42004-08-07 13:58:02 +00001643 \item A new function, \cfunction{PyArg_VaParseTupleAndKeywords()},
1644 is the same as \cfunction{PyArg_ParseTupleAndKeywords()} but takes a
1645 \ctype{va_list} instead of a number of arguments.
1646 (Contributed by Greg Chapman.)
1647
Fred Drakece3caf22004-02-12 18:13:12 +00001648 \item A new method flag, \constant{METH_COEXISTS}, allows a function
Andrew M. Kuchling71432f12004-07-05 01:40:07 +00001649 defined in slots to co-exist with a \ctype{PyCFunction} having the
1650 same name. This can halve the access time for a method such as
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001651 \method{set.__contains__()}. (Contributed by Raymond Hettinger.)
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +00001652
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +00001653 \item Python can now be built with additional profiling for the
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001654 interpreter itself, intended as an aid to people developing the
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +00001655 Python core. Providing \longprogramopt{--enable-profiling} to the
1656 \program{configure} script will let you profile the interpreter with
1657 \program{gprof}, and providing the \longprogramopt{--with-tsc}
1658 switch enables profiling using the Pentium's Time-Stamp-Counter
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001659 register. (The \longprogramopt{--with-tsc} switch is slightly
1660 misnamed, because the profiling feature also works on the PowerPC
1661 platform, though that processor architecture doesn't call that
1662 register ``the TSC register''.)
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +00001663
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +00001664 \item The \ctype{tracebackobject} type has been renamed to \ctype{PyTracebackObject}.
Raymond Hettinger97ef8de2004-01-05 00:29:57 +00001665
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001666\end{itemize}
1667
1668
1669%======================================================================
1670\subsection{Port-Specific Changes}
1671
Raymond Hettinger97ef8de2004-01-05 00:29:57 +00001672\begin{itemize}
1673
1674\item The Windows port now builds under MSVC++ 7.1 as well as version 6.
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001675 (Contributed by Martin von Loewis.)
Raymond Hettinger97ef8de2004-01-05 00:29:57 +00001676
1677\end{itemize}
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001678
1679
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001680
1681%======================================================================
1682\section{Porting to Python 2.4}
1683
1684This section lists previously described changes that may require
1685changes to your code:
1686
1687\begin{itemize}
1688
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001689\item Left shifts and hexadecimal/octal constants that are too
1690 large no longer trigger a \exception{FutureWarning} and return
1691 a value limited to 32 or 64 bits; instead they return a long integer.
1692
1693\item Integer operations will no longer trigger an \exception{OverflowWarning}.
1694The \exception{OverflowWarning} warning will disappear in Python 2.5.
1695
Raymond Hettinger607c00f2003-11-12 16:27:50 +00001696\item The \function{zip()} built-in function and \function{itertools.izip()}
1697 now return an empty list instead of raising a \exception{TypeError}
1698 exception if called with no arguments.
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001699 (Contributed by Raymond Hettinger.)
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +00001700
1701\item \function{dircache.listdir()} now passes exceptions to the caller
1702 instead of returning empty lists.
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001703
Andrew M. Kuchling71432f12004-07-05 01:40:07 +00001704\item \function{LexicalHandler.startDTD()} used to receive the public and
1705 system IDs in the wrong order. This has been corrected; applications
Fred Drake56fcc232004-05-06 02:55:35 +00001706 relying on the wrong order need to be fixed.
Martin v. Löwis456ab1d2004-05-06 01:54:36 +00001707
Andrew M. Kuchling71432f12004-07-05 01:40:07 +00001708\item \function{fcntl.ioctl} now warns if the \var{mutate}
1709 argument is omitted and relevant.
Martin v. Löwis77ca6c42004-06-03 12:47:26 +00001710
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +00001711\item The \module{tarfile} module now generates GNU-format tar files
1712by default.
1713
Andrew M. Kuchlingf8c075c2004-11-09 02:58:02 +00001714\item Encountering a failure while importing a module no longer leaves
1715a partially-initialized module object in \code{sys.modules}.
1716
1717\item \constant{None} is now a constant; code that binds a new value to
1718the name \samp{None} is now a syntax error.
1719
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001720\end{itemize}
1721
1722
1723%======================================================================
1724\section{Acknowledgements \label{acks}}
1725
1726The author would like to thank the following people for offering
1727suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchlingb6ffc272004-10-12 16:36:57 +00001728article: Hye-Shik Chang, Michael Dyck, Raymond Hettinger, Hamish Lawson,
1729Fredrik Lundh.
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001730
1731\end{document}