blob: b4293e6cd9ec563936c007893e5749e518e50815 [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. Kuchling2cc0c302004-09-10 12:38:36 +000013\release{0.4}
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. Kuchling9fa544c2004-09-23 20:17:26 +000024This article explains the new features in Python 2.4 beta1, scheduled
25for release in mid-October. The final version of Python 2.4 is
Andrew M. Kuchling3294e9d2004-08-31 11:26:23 +000026expected to be released around December 2004.
Fred Drakeed0fa3d2003-07-30 19:14:09 +000027
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +000028Python 2.4 is a medium-sized release. It doesn't introduce as many
Andrew M. Kuchling3b790912004-07-04 16:39:40 +000029changes as the radical Python 2.2, but introduces more features than
30the conservative 2.3 release did. The most significant new language
Andrew M. Kuchling3294e9d2004-08-31 11:26:23 +000031features (as of this writing) are function decorators and generator
32expressions; most other changes are to the standard library.
Andrew M. Kuchlinga331e862004-09-10 13:05:22 +000033% XXX update these figures as we go
34According to the CVS change logs, there were 421 patches applied and
35413 bugs fixed between Python 2.3 and 2.4. Both figures are likely to
36be underestimates.
37
Fred Drakeed0fa3d2003-07-30 19:14:09 +000038
39This article doesn't attempt to provide a complete specification of
Andrew M. Kuchling3b790912004-07-04 16:39:40 +000040every single new feature, but instead provides a convenient overview.
41For full details, you should refer to the documentation for Python
422.4, such as the \citetitle[../lib/lib.html]{Python Library Reference}
43and the \citetitle[../ref/ref.html]{Python Reference Manual}. If you
44want to understand the complete implementation and design rationale,
45refer to the PEP for a particular new feature or to the module
46documentation.
Fred Drakeed0fa3d2003-07-30 19:14:09 +000047
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +000048
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000049%======================================================================
50\section{PEP 218: Built-In Set Objects}
51
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +000052Python 2.3 introduced the \module{sets} module. C implementations of
53set data types have now been added to the Python core as two new
54built-in types, \function{set(\var{iterable})} and
55\function{frozenset(\var{iterable})}. They provide high speed
56operations for membership testing, for eliminating duplicates from
57sequences, and for mathematical operations like unions, intersections,
58differences, and symmetric differences.
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000059
60\begin{verbatim}
61>>> a = set('abracadabra') # form a set from a string
62>>> 'z' in a # fast membership testing
63False
64>>> a # unique letters in a
65set(['a', 'r', 'b', 'c', 'd'])
66>>> ''.join(a) # convert back into a string
67'arbcd'
Raymond Hettingerd4462302003-11-26 17:52:45 +000068
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000069>>> b = set('alacazam') # form a second set
70>>> a - b # letters in a but not in b
71set(['r', 'd', 'b'])
72>>> a | b # letters in either a or b
73set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
74>>> a & b # letters in both a and b
75set(['a', 'c'])
76>>> a ^ b # letters in a or b but not both
77set(['r', 'd', 'b', 'm', 'z', 'l'])
Raymond Hettingerd4462302003-11-26 17:52:45 +000078
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000079>>> a.add('z') # add a new element
80>>> a.update('wxy') # add multiple new elements
81>>> a
82set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'x', 'z'])
83>>> a.remove('x') # take one element out
84>>> a
85set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'z'])
86\end{verbatim}
87
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +000088The \function{frozenset} type is an immutable version of \function{set}.
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000089Since it is immutable and hashable, it may be used as a dictionary key or
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +000090as a member of another set.
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000091
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +000092The \module{sets} module remains in the standard library, and may be
93useful if you wish to subclass the \class{Set} or \class{ImmutableSet}
94classes. There are currently no plans to deprecate the module.
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +000095
Raymond Hettinger7e0282f2003-11-24 07:14:54 +000096\begin{seealso}
97\seepep{218}{Adding a Built-In Set Object Type}{Originally proposed by
98Greg Wilson and ultimately implemented by Raymond Hettinger.}
99\end{seealso}
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000100
101%======================================================================
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000102\section{PEP 237: Unifying Long Integers and Integers}
103
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000104The lengthy transition process for this PEP, begun in Python 2.2,
Andrew M. Kuchlingd4be86c2004-07-04 01:44:04 +0000105takes another step forward in Python 2.4. In 2.3, certain integer
106operations that would behave differently after int/long unification
107triggered \exception{FutureWarning} warnings and returned values
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000108limited to 32 or 64 bits (depending on your platform). In 2.4, these
109expressions no longer produce a warning and instead produce a
110different result that's usually a long integer.
Andrew M. Kuchlingd4be86c2004-07-04 01:44:04 +0000111
112The problematic expressions are primarily left shifts and lengthy
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000113hexadecimal and octal constants. For example,
114\code{2 \textless{}\textless{} 32} results
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000115in a warning in 2.3, evaluating to 0 on 32-bit platforms. In Python
1162.4, this expression now returns the correct answer, 8589934592.
Andrew M. Kuchlingd4be86c2004-07-04 01:44:04 +0000117
118\begin{seealso}
119\seepep{237}{Unifying Long Integers and Integers}{Original PEP
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000120written by Moshe Zadka and GvR. The changes for 2.4 were implemented by
Andrew M. Kuchlingd4be86c2004-07-04 01:44:04 +0000121Kalle Svensson.}
122\end{seealso}
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000123
124%======================================================================
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000125\section{PEP 289: Generator Expressions}
Raymond Hettinger354433a2004-05-19 08:20:33 +0000126
Andrew M. Kuchling38dc2a62004-08-07 13:24:12 +0000127The iterator feature introduced in Python 2.2 and the
128\module{itertools} module make it easier to write programs that loop
129through large data sets without having the entire data set in memory
130at one time. List comprehensions don't fit into this picture very
131well because they produce a Python list object containing all of the
132items, unavoidably pulling them all into memory. When trying to write
133a 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
152you're dealing with a large number of link objects the second form
Andrew M. Kuchling38dc2a62004-08-07 13:24:12 +0000153would have to be used to avoid having all link objects in memory at
154the same time.
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
191Some new classes in the standard library provide a
192alternative mechanism for substituting variables into strings that's
193better-suited for applications where untrained users need to edit templates.
194
195The usual way of substituting variables by name is the \code{\%}
196operator:
197
198\begin{verbatim}
199>>> '%(page)i: %(title)s' % {'page':2, 'title': 'The Best of Times'}
200'2: The Best of Times'
201\end{verbatim}
202
203When writing the template string, it can be easy to forget the
204\samp{i} or \samp{s} after the closing parenthesis. This isn't a big
205problem if the template is in a Python module, because you run the
206code, get an ``Unsupported format character'' \exception{ValueError},
207and fix the problem. However, consider an application such as Mailman
208where template strings or translations are being edited by users who
209aren't aware of the Python language; the syntax is complicated to
210explain to such users, and if they make a mistake, it's difficult to
211provide helpful feedback to them.
212
213PEP 292 adds a \class{Template} class to the \module{string} module
214that uses \samp{\$} to indicate a substitution. \class{Template} is a
215subclass of the built-in Unicode type, so the result is always a
216Unicode string:
217
218\begin{verbatim}
219>>> import string
220>>> t = string.Template('$page: $title')
Andrew M. Kuchlinga79ec222004-09-10 11:34:39 +0000221>>> t.substitute({'page':2, 'title': 'The Best of Times'})
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +0000222u'2: The Best of Times'
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +0000223\end{verbatim}
224
225% $ Terminate $-mode for Emacs
226
Andrew M. Kuchlinga79ec222004-09-10 11:34:39 +0000227If a key is missing from the dictionary, the \method{substitute} method
228will raise a \exception{KeyError}. There's also a \method{safe_substitute}
229method that ignores missing keys:
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +0000230
231\begin{verbatim}
232>>> t = string.SafeTemplate('$page: $title')
Andrew M. Kuchlinga79ec222004-09-10 11:34:39 +0000233>>> t.safe_substitute({'page':3})
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +0000234u'3: $title'
235\end{verbatim}
236
Andrew M. Kuchlinga331e862004-09-10 13:05:22 +0000237% $ Terminate math-mode for Emacs
238
239
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +0000240\begin{seealso}
241\seepep{292}{Simpler String Substitutions}{Written and implemented
242by Barry Warsaw.}
243\end{seealso}
244
245
Raymond Hettinger354433a2004-05-19 08:20:33 +0000246%======================================================================
Andrew M. Kuchlingd91fcbe2004-08-02 12:44:28 +0000247\section{PEP 318: Decorators for Functions, Methods and Classes}
248
Andrew M. Kuchling77a602f2004-08-02 13:48:18 +0000249Python 2.2 extended Python's object model by adding static methods and
250class methods, but it didn't extend Python's syntax to provide any new
251way of defining static or class methods. Instead, you had to write a
252\keyword{def} statement in the usual way, and pass the resulting
253method to a \function{staticmethod()} or \function{classmethod()}
254function that would wrap up the function as a method of the new type.
255Your code would look like this:
256
257\begin{verbatim}
258class C:
259 def meth (cls):
260 ...
261
262 meth = classmethod(meth) # Rebind name to wrapped-up class method
263\end{verbatim}
264
265If the method was very long, it would be easy to miss or forget the
266\function{classmethod()} invocation after the function body.
267
268The intention was always to add some syntax to make such definitions
269more readable, but at the time of 2.2's release a good syntax was not
270obvious. Years later, when Python 2.4 is coming out, a good syntax
271\emph{still} isn't obvious but users are asking for easier access to
272the feature, so a new syntactic feature has been added.
273
274The feature is called ``function decorators''. The name comes from
275the idea that \function{classmethod}, \function{staticmethod}, and
276friends are storing additional information on a function object; they're
277\emph{decorating} functions with more details.
278
Fred Drake3f5c6542004-08-06 03:34:20 +0000279The notation borrows from Java and uses the \character{@} character as an
Andrew M. Kuchling77a602f2004-08-02 13:48:18 +0000280indicator. Using the new syntax, the example above would be written:
281
282\begin{verbatim}
283class C:
284
285 @classmethod
286 def meth (cls):
287 ...
288
289\end{verbatim}
290
291The \code{@classmethod} is shorthand for the
Fred Drake3f5c6542004-08-06 03:34:20 +0000292\code{meth=classmethod(meth)} assignment. More generally, if you have
Andrew M. Kuchling77a602f2004-08-02 13:48:18 +0000293the following:
294
295\begin{verbatim}
296@A @B @C
297def f ():
298 ...
299\end{verbatim}
300
301It's equivalent to:
302
303\begin{verbatim}
304def f(): ...
Andrew M. Kuchlingcebdd3c2004-10-08 18:29:29 +0000305f = A(B(C(f)))
Andrew M. Kuchling77a602f2004-08-02 13:48:18 +0000306\end{verbatim}
307
308Decorators must come on the line before a function definition, and
309can't be on the same line, meaning that \code{@A def f(): ...} is
310illegal. You can only decorate function definitions, either at the
311module-level or inside a class; you can't decorate class definitions.
312
313A decorator is just a function that takes the function to be decorated
314as an argument and returns either the same function or some new
315callable thing. It's easy to write your own decorators. The
316following simple example just sets an attribute on the function
317object:
318
319\begin{verbatim}
320>>> def deco(func):
321... func.attr = 'decorated'
322... return func
323...
324>>> @deco
325... def f(): pass
326...
327>>> f
328<function f at 0x402ef0d4>
329>>> f.attr
330'decorated'
331>>>
332\end{verbatim}
333
334As a slightly more realistic example, the following decorator checks
335that the supplied argument is an integer:
336
337\begin{verbatim}
338def require_int (func):
339 def wrapper (arg):
340 assert isinstance(arg, int)
341 return func(arg)
342
343 return wrapper
344
345@require_int
346def p1 (arg):
347 print arg
348
349@require_int
350def p2(arg):
351 print arg*2
352\end{verbatim}
353
354An example in \pep{318} contains a fancier version of this idea that
355lets you specify the required type and check the returned type as
356well.
357
358Decorator functions can take arguments. If arguments are supplied,
359the decorator function is called with only those arguments and must
360return a new decorator function; this new function must take a single
361function 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. Kuchling77a602f2004-08-02 13:48:18 +0000378The new syntax was provisionally added in 2.4alpha2, and is subject to
Andrew M. Kuchling9fa544c2004-09-23 20:17:26 +0000379change during the 2.4beta release cycle depending on the Python
Andrew M. Kuchling77a602f2004-08-02 13:48:18 +0000380community's reaction. Post-2.4 versions of Python will preserve
381compatibility with whatever syntax is used in 2.4final.
Andrew M. Kuchlingd91fcbe2004-08-02 12:44:28 +0000382
383\begin{seealso}
384\seepep{318}{Decorators for Functions, Methods and Classes}{Written
Andrew M. Kuchling77a602f2004-08-02 13:48:18 +0000385by Kevin D. Smith, Jim Jewett, and Skip Montanaro. Several people
386wrote patches implementing function decorators, but the one that was
Fred Drakee72bd4d2004-08-02 21:50:26 +0000387actually checked in was patch \#979728, written by Mark Russell.}
Andrew M. Kuchlingd91fcbe2004-08-02 12:44:28 +0000388\end{seealso}
389
390%======================================================================
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000391\section{PEP 322: Reverse Iteration}
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000392
Fred Drake56fcc232004-05-06 02:55:35 +0000393A new built-in function, \function{reversed(\var{seq})}, takes a sequence
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000394and returns an iterator that loops over the elements of the sequence
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000395in reverse order.
396
397\begin{verbatim}
Raymond Hettingerbc3cba22003-11-12 16:39:30 +0000398>>> for i in reversed(xrange(1,4)):
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000399... print i
400...
4013
4022
4031
404\end{verbatim}
405
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000406Compared to extended slicing, such as \code{range(1,4)[::-1]},
407\function{reversed()} is easier to read, runs faster, and uses
408substantially less memory.
Raymond Hettingerbc3cba22003-11-12 16:39:30 +0000409
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000410Note that \function{reversed()} only accepts sequences, not arbitrary
Raymond Hettingerbc3cba22003-11-12 16:39:30 +0000411iterators. If you want to reverse an iterator, first convert it to
412a list with \function{list()}.
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000413
414\begin{verbatim}
Andrew M. Kuchling44a31e12004-01-01 18:33:34 +0000415>>> input= open('/etc/passwd', 'r')
416>>> for line in reversed(list(input)):
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000417... print line
418...
419root:*:0:0:System Administrator:/var/root:/bin/tcsh
420 ...
421\end{verbatim}
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000422
Andrew M. Kuchlingf7a6b672003-11-08 16:05:37 +0000423\begin{seealso}
424\seepep{322}{Reverse Iteration}{Written and implemented by Raymond Hettinger.}
425
426\end{seealso}
427
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000428
429%======================================================================
Andrew M. Kuchlingc9e7d772004-10-12 15:58:02 +0000430\section{PEP 324: New subprocess Module}
431
432The standard library provides a number of ways to
433execute a subprocess, each of which offers different features and
434levels of difficulty. \function{os.system(\var{command})} is easy, but
435slow -- it runs a shell process which executes the command --
436and dangerous -- you have to be careful about escaping metacharacters.
437The \module{popen2} module offers classes that can capture
438standard output and standard error from the subprocess, but the naming
439is confusing.
440
441The \module{subprocess} module cleans all this up, providing a unified
442interface that offers all the features you might need.
443
444% XXX finish writing this section by adding some examples
445
446
447\begin{seealso}
448\seepep{324}{subprocess - New process module}{Written and implemented by Peter Astrand, with assistance from Fredrik Lundh and others.}
449\end{seealso}
450
451%======================================================================
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000452\section{PEP 327: Decimal Data Type}
453
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000454Python has always supported floating-point (FP) numbers as a data
455type, based on the underlying C \ctype{double} type. However, while
456most programming languages provide a floating-point type, most people
457(even programmers) are unaware that computing with floating-point
458numbers entails certain unavoidable inaccuracies. The new decimal
459type provides a way to avoid these inaccuracies.
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000460
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000461\subsection{Why is Decimal needed?}
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000462
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000463The limitations arise from the representation used for floating-point numbers.
464FP numbers are made up of three components:
465
466\begin{itemize}
Andrew M. Kuchlinge34c3bd2004-08-31 12:21:44 +0000467\item The sign, which is positive or negative.
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000468\item The mantissa, which is a single-digit binary number
469followed by a fractional part. For example, \code{1.01} in base-2 notation
470is \code{1 + 0/2 + 1/4}, or 1.25 in decimal notation.
471\item The exponent, which tells where the decimal point is located in the number represented.
472\end{itemize}
473
Andrew M. Kuchlinge34c3bd2004-08-31 12:21:44 +0000474For example, the number 1.25 has positive sign, a mantissa value of
4751.01 (in binary), and an exponent of 0 (the decimal point doesn't need
476to be shifted). The number 5 has the same sign and mantissa, but the
477exponent is 2 because the mantissa is multiplied by 4 (2 to the power
478of the exponent 2).
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000479
480Modern systems usually provide floating-point support that conforms to
481a relevant standard called IEEE 754. C's \ctype{double} type is
482usually implemented as a 64-bit IEEE 754 number, which uses 52 bits of
483space for the mantissa. This means that numbers can only be specified
484to 52 bits of precision. If you're trying to represent numbers whose
485expansion repeats endlessly, the expansion is cut off after 52 bits.
486Unfortunately, most software needs to produce output in base 10, and
Andrew M. Kuchlinge34c3bd2004-08-31 12:21:44 +0000487base 10 often gives rise to such repeating decimals in the binary
488expansion. For example, 1.1 decimal is binary \code{1.0001100110011
489...}; .1 = 1/16 + 1/32 + 1/256 plus an infinite number of additional
490terms. IEEE 754 has to chop off that infinitely repeated decimal
491after 52 digits, so the representation is slightly inaccurate.
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000492
493Sometimes you can see this inaccuracy when the number is printed:
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000494\begin{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000495>>> 1.1
4961.1000000000000001
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000497\end{verbatim}
498
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000499The inaccuracy isn't always visible when you print the number because
Andrew M. Kuchlinge34c3bd2004-08-31 12:21:44 +0000500the FP-to-decimal-string conversion is provided by the C library, and
501most C libraries try to produce sensible output. Even if it's not
502displayed, however, the inaccuracy is still there and subsequent
503operations can magnify the error.
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000504
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000505For many applications this doesn't matter. If I'm plotting points and
506displaying them on my monitor, the difference between 1.1 and
5071.1000000000000001 is too small to be visible. Reports often limit
508output to a certain number of decimal places, and if you round the
509number to two or three or even eight decimal places, the error is
510never apparent. However, for applications where it does matter,
511it's a lot of work to implement your own custom arithmetic routines.
512
Andrew M. Kuchlinge34c3bd2004-08-31 12:21:44 +0000513Hence, the \class{Decimal} type was created.
514
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000515\subsection{The \class{Decimal} type}
516
517A new module, \module{decimal}, was added to Python's standard library.
518It contains two classes, \class{Decimal} and \class{Context}.
519\class{Decimal} instances represent numbers, and
520\class{Context} instances are used to wrap up various settings such as the precision and default rounding mode.
521
Andrew M. Kuchlinge34c3bd2004-08-31 12:21:44 +0000522\class{Decimal} instances, like regular Python integers and FP
523numbers, are immutable; once they've been created, you can't change
524the value it represents. \class{Decimal} instances can be created
525from integers or strings:
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000526
527\begin{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000528>>> import decimal
529>>> decimal.Decimal(1972)
530Decimal("1972")
531>>> decimal.Decimal("1.1")
532Decimal("1.1")
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000533\end{verbatim}
534
Andrew M. Kuchlinge34c3bd2004-08-31 12:21:44 +0000535You can also provide tuples containing the sign, the mantissa represented
536as a tuple of decimal digits, and the exponent:
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000537
538\begin{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000539>>> decimal.Decimal((1, (1, 4, 7, 5), -2))
540Decimal("-14.75")
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000541\end{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000542
Andrew M. Kuchlinge34c3bd2004-08-31 12:21:44 +0000543Cautionary note: the sign bit is a Boolean value, so 0 is positive and
5441 is negative.
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000545
Andrew M. Kuchlinge34c3bd2004-08-31 12:21:44 +0000546Converting from floating-point numbers poses a bit of a problem:
547should the FP number representing 1.1 turn into the decimal number for
548exactly 1.1, or for 1.1 plus whatever inaccuracies are introduced?
549The decision was to leave such a conversion out of the API. Instead,
550you should convert the floating-point number into a string using the
551desired precision and pass the string to the \class{Decimal}
552constructor:
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000553
554\begin{verbatim}
555>>> f = 1.1
556>>> decimal.Decimal(str(f))
557Decimal("1.1")
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000558>>> decimal.Decimal('%.12f' % f)
559Decimal("1.100000000000")
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000560\end{verbatim}
561
562Once you have \class{Decimal} instances, you can perform the usual
563mathematical operations on them. One limitation: exponentiation
564requires an integer exponent:
565
566\begin{verbatim}
567>>> a = decimal.Decimal('35.72')
568>>> b = decimal.Decimal('1.73')
569>>> a+b
570Decimal("37.45")
571>>> a-b
572Decimal("33.99")
573>>> a*b
574Decimal("61.7956")
575>>> a/b
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000576Decimal("20.64739884393063583815028902")
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000577>>> a ** 2
578Decimal("1275.9184")
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000579>>> a**b
580Traceback (most recent call last):
581 ...
582decimal.InvalidOperation: x ** (non-integer)
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000583\end{verbatim}
584
585You can combine \class{Decimal} instances with integers, but not with
586floating-point numbers:
587
588\begin{verbatim}
589>>> a + 4
590Decimal("39.72")
591>>> a + 4.5
592Traceback (most recent call last):
593 ...
594TypeError: You can interact Decimal only with int, long or Decimal data types.
595>>>
596\end{verbatim}
597
598\class{Decimal} numbers can be used with the \module{math} and
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000599\module{cmath} modules, but note that they'll be immediately converted to
600floating-point numbers before the operation is performed, resulting in
601a possible loss of precision and accuracy. You'll also get back a
602regular floating-point number and not a \class{Decimal}.
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000603
604\begin{verbatim}
605>>> import math, cmath
606>>> d = decimal.Decimal('123456789012.345')
607>>> math.sqrt(d)
608351364.18288201344
609>>> cmath.sqrt(-d)
610351364.18288201344j
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000611\end{verbatim}
612
613Instances also have a \method{sqrt()} method that returns a
614\class{Decimal}, but if you need other things such as trigonometric
615functions you'll have to implement them.
616
617\begin{verbatim}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000618>>> d.sqrt()
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000619Decimal("351364.1828820134592177245001")
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000620\end{verbatim}
621
622
623\subsection{The \class{Context} type}
624
625Instances of the \class{Context} class encapsulate several settings for
626decimal operations:
627
628\begin{itemize}
629 \item \member{prec} is the precision, the number of decimal places.
630 \item \member{rounding} specifies the rounding mode. The \module{decimal}
631 module has constants for the various possibilities:
632 \constant{ROUND_DOWN}, \constant{ROUND_CEILING}, \constant{ROUND_HALF_EVEN}, and various others.
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000633 \item \member{traps} is a dictionary specifying what happens on
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000634encountering certain error conditions: either an exception is raised or
635a value is returned. Some examples of error conditions are
636division by zero, loss of precision, and overflow.
637\end{itemize}
638
639There's a thread-local default context available by calling
640\function{getcontext()}; you can change the properties of this context
641to alter the default precision, rounding, or trap handling.
642
643\begin{verbatim}
644>>> decimal.getcontext().prec
64528
646>>> decimal.Decimal(1) / decimal.Decimal(7)
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000647Decimal("0.1428571428571428571428571429")
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000648>>> decimal.getcontext().prec = 9
649>>> decimal.Decimal(1) / decimal.Decimal(7)
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000650Decimal("0.142857143")
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000651\end{verbatim}
652
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000653The default action for error conditions is selectable; the module can
654either return a special value such as infinity or not-a-number, or
655exceptions can be raised:
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000656
657\begin{verbatim}
658>>> decimal.Decimal(1) / decimal.Decimal(0)
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000659Traceback (most recent call last):
660 ...
661decimal.DivisionByZero: x / 0
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000662>>> decimal.getcontext().traps[decimal.DivisionByZero] = False
663>>> decimal.Decimal(1) / decimal.Decimal(0)
664Decimal("Infinity")
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000665>>>
666\end{verbatim}
667
668The \class{Context} instance also has various methods for formatting
669numbers such as \method{to_eng_string()} and \method{to_sci_string()}.
670
Andrew M. Kuchling0ad20f12004-07-21 13:00:06 +0000671For more information, see the documentation for the \module{decimal}
672module, which includes a quick-start tutorial and a reference.
673
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000674\begin{seealso}
675\seepep{327}{Decimal Data Type}{Written by Facundo Batista and implemented
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000676 by Facundo Batista, Eric Price, Raymond Hettinger, Aahz, and Tim Peters.}
677
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000678\seeurl{http://research.microsoft.com/\textasciitilde hollasch/cgindex/coding/ieeefloat.html}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000679{A more detailed overview of the IEEE-754 representation.}
680
681\seeurl{http://www.lahey.com/float.htm}
682{The article uses Fortran code to illustrate many of the problems
683that floating-point inaccuracy can cause.}
684
685\seeurl{http://www2.hursley.ibm.com/decimal/}
686{A description of a decimal-based representation. This representation
687is being proposed as a standard, and underlies the new Python decimal
688type. Much of this material was written by Mike Cowlishaw, designer of the
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000689Rexx language.}
Andrew M. Kuchlingc8f8a812004-07-04 01:26:42 +0000690
Raymond Hettinger0fff62f2004-07-01 11:52:15 +0000691\end{seealso}
692
693
694%======================================================================
Andrew M. Kuchling3294e9d2004-08-31 11:26:23 +0000695\section{PEP 328: Multi-line Imports}
696
697One language change is a small syntactic tweak aimed at making it
698easier to import many names from a module. In a
699\code{from \var{module} import \var{names}} statement,
700\var{names} is a sequence of names separated by commas. If the sequence is
701very long, you can either write multiple imports from the same module,
702or you can use backslashes to escape the line endings:
703
704\begin{verbatim}
705from SimpleXMLRPCServer import SimpleXMLRPCServer,\
706 SimpleXMLRPCRequestHandler,\
707 CGIXMLRPCRequestHandler,\
708 resolve_dotted_attribute
709\end{verbatim}
710
711The syntactic change simply allows putting the names within
712parentheses. Python ignores newlines within a parenthesized
713expression, so the backslashes are no longer needed:
714
715\begin{verbatim}
716from SimpleXMLRPCServer import (SimpleXMLRPCServer,
717 SimpleXMLRPCRequestHandler,
718 CGIXMLRPCRequestHandler,
719 resolve_dotted_attribute)
720\end{verbatim}
721
722The PEP also proposes that all \keyword{import} statements be
723absolute imports, with a leading \samp{.} character to indicate a
724relative import. This part of the PEP is not yet implemented.
725
726\begin{seealso}
Fred Drake410eb842004-09-01 04:05:08 +0000727\seepep{328}{Imports: Multi-Line and Absolute/Relative}
728 {Written by Aahz. Multi-line imports were implemented by
729 Dima Dorfman.}
730\end{seealso}
Andrew M. Kuchling3294e9d2004-08-31 11:26:23 +0000731
732
733%======================================================================
Andrew M. Kuchling65a33322004-07-21 12:41:38 +0000734\section{PEP 331: Locale-Independent Float/String Conversions}
735
736The \module{locale} modules lets Python software select various
737conversions and display conventions that are localized to a particular
738country or language. However, the module was careful to not change
739the numeric locale because various functions in Python's
740implementation required that the numeric locale remain set to the
741\code{'C'} locale. Often this was because the code was using the C library's
742\cfunction{atof()} function.
743
744Not setting the numeric locale caused trouble for extensions that used
745third-party C libraries, however, because they wouldn't have the
746correct locale set. The motivating example was GTK+, whose user
747interface widgets weren't displaying numbers in the current locale.
748
749The solution described in the PEP is to add three new functions to the
750Python API that perform ASCII-only conversions, ignoring the locale
751setting:
752
753\begin{itemize}
754 \item \cfunction{PyOS_ascii_strtod(\var{str}, \var{ptr})}
755and \cfunction{PyOS_ascii_atof(\var{str}, \var{ptr})}
756both convert a string to a C \ctype{double}.
757 \item \cfunction{PyOS_ascii_formatd(\var{buffer}, \var{buf_len}, \var{format}, \var{d})} converts a \ctype{double} to an ASCII string.
758\end{itemize}
759
760The code for these functions came from the GLib library
761(\url{http://developer.gnome.org/arch/gtk/glib.html}), whose
762developers kindly relicensed the relevant functions and donated them
763to the Python Software Foundation. The \module{locale} module
764can now change the numeric locale, letting extensions such as GTK+
765produce the correct results.
766
767\begin{seealso}
768\seepep{331}{Locale-Independent Float/String Conversions}{Written by Christian R. Reis, and implemented by Gustavo Carneiro.}
769\end{seealso}
770
771%======================================================================
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000772\section{Other Language Changes}
773
774Here are all of the changes that Python 2.4 makes to the core Python
775language.
776
777\begin{itemize}
Raymond Hettingerd4462302003-11-26 17:52:45 +0000778
Raymond Hettinger31017ae2004-03-04 08:25:44 +0000779\item The \method{dict.update()} method now accepts the same
780argument forms as the \class{dict} constructor. This includes any
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +0000781mapping, any iterable of key/value pairs, and keyword arguments.
782(Contributed by Raymond Hettinger.)
Raymond Hettinger31017ae2004-03-04 08:25:44 +0000783
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000784\item The string methods \method{ljust()}, \method{rjust()}, and
Andrew M. Kuchling67087562003-11-26 18:03:48 +0000785\method{center()} now take an optional argument for specifying a
Raymond Hettingerd4462302003-11-26 17:52:45 +0000786fill character other than a space.
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +0000787(Contributed by Raymond Hettinger.)
Raymond Hettingerd4462302003-11-26 17:52:45 +0000788
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000789\item Strings also gained an \method{rsplit()} method that
Raymond Hettingered54d912003-12-31 01:59:18 +0000790works like the \method{split()} method but splits from the end of
Andrew M. Kuchling44a31e12004-01-01 18:33:34 +0000791the string.
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +0000792
793\begin{verbatim}
Raymond Hettinger7a6d2972004-02-13 19:00:07 +0000794>>> 'www.python.org'.split('.', 1)
795['www', 'python.org']
796'www.python.org'.rsplit('.', 1)
797['www.python', 'org']
798\end{verbatim}
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000799
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000800\item The \method{sort()} method of lists gained three keyword
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000801arguments: \var{cmp}, \var{key}, and \var{reverse}. These arguments
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000802make some common usages of \method{sort()} simpler. All are optional.
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +0000803(Contributed by Raymond Hettinger.)
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000804
805\var{cmp} is the same as the previous single argument to
806\method{sort()}; if provided, the value should be a comparison
807function that takes two arguments and returns -1, 0, or +1 depending
808on how the arguments compare.
809
810\var{key} should be a single-argument function that takes a list
811element and returns a comparison key for the element. The list is
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000812then sorted using the comparison keys. The following example sorts a
813list case-insensitively:
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000814
815\begin{verbatim}
816>>> L = ['A', 'b', 'c', 'D']
817>>> L.sort() # Case-sensitive sort
818>>> L
819['A', 'D', 'b', 'c']
820>>> L.sort(key=lambda x: x.lower())
821>>> L
822['A', 'b', 'c', 'D']
823>>> L.sort(cmp=lambda x,y: cmp(x.lower(), y.lower()))
824>>> L
825['A', 'b', 'c', 'D']
826\end{verbatim}
827
828The last example, which uses the \var{cmp} parameter, is the old way
Raymond Hettingered54d912003-12-31 01:59:18 +0000829to perform a case-insensitive sort. It works but is slower than
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000830using a \var{key} parameter. Using \var{key} results in calling the
831\method{lower()} method once for each element in the list while using
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000832\var{cmp} will call it twice for each comparison.
Andrew M. Kuchling2fb4d512003-10-21 12:31:16 +0000833
Andrew M. Kuchling981a9182003-11-13 21:33:26 +0000834For simple key functions and comparison functions, it is often
835possible to avoid a \keyword{lambda} expression by using an unbound
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000836method instead. For example, the above case-insensitive sort is best
837coded as:
838
839\begin{verbatim}
840>>> L.sort(key=str.lower)
841>>> L
842['A', 'b', 'c', 'D']
843\end{verbatim}
844
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000845The \var{reverse} parameter should have a Boolean value. If the value
846is \constant{True}, the list will be sorted into reverse order.
847Instead of \code{L.sort(lambda x,y: cmp(x.score, y.score)) ;
848L.reverse()}, you can now write: \code{L.sort(key = lambda x: x.score,
849reverse=True)}.
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000850
Andrew M. Kuchling981a9182003-11-13 21:33:26 +0000851The results of sorting are now guaranteed to be stable. This means
852that two entries with equal keys will be returned in the same order as
853they were input. For example, you can sort a list of people by name,
854and then sort the list by age, resulting in a list sorted by age where
855people with the same age are in name-sorted order.
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000856
Fred Drake56fcc232004-05-06 02:55:35 +0000857\item There is a new built-in function
858\function{sorted(\var{iterable})} that works like the in-place
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000859\method{list.sort()} method but can be used in
Fred Drake56fcc232004-05-06 02:55:35 +0000860expressions. The differences are:
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000861 \begin{itemize}
Raymond Hettinger7d1dd042003-11-12 16:42:10 +0000862 \item the input may be any iterable;
863 \item a newly formed copy is sorted, leaving the original intact; and
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000864 \item the expression returns the new sorted copy
865 \end{itemize}
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000866
867\begin{verbatim}
868>>> L = [9,7,8,3,2,4,1,6,5]
Raymond Hettinger64958a12003-12-17 20:43:33 +0000869>>> [10+i for i in sorted(L)] # usable in a list comprehension
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000870[11, 12, 13, 14, 15, 16, 17, 18, 19]
Hye-Shik Chang2b052482004-07-17 13:53:48 +0000871>>> L # original is left unchanged
Andrew M. Kuchlinge3e1eca2004-07-26 18:52:48 +0000872[9,7,8,3,2,4,1,6,5]
873>>> sorted('Monty Python') # any iterable may be an input
874[' ', 'M', 'P', 'h', 'n', 'n', 'o', 'o', 't', 't', 'y', 'y']
Raymond Hettingerd4462302003-11-26 17:52:45 +0000875
876>>> # List the contents of a dict sorted by key values
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000877>>> colormap = dict(red=1, blue=2, green=3, black=4, yellow=5)
Raymond Hettinger64958a12003-12-17 20:43:33 +0000878>>> for k, v in sorted(colormap.iteritems()):
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000879... print k, v
880...
881black 4
882blue 2
883green 3
884red 1
885yellow 5
Andrew M. Kuchling1a420252003-11-08 15:58:49 +0000886\end{verbatim}
887
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +0000888(Contributed by Raymond Hettinger.)
889
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +0000890\item Integer operations will no longer trigger an \exception{OverflowWarning}.
891The \exception{OverflowWarning} warning will disappear in Python 2.5.
892
Andrew M. Kuchling5e3f9232004-10-07 12:00:33 +0000893\item The interpreter gained a new switch, \programopt{-m}, that
894takes a name, searches for the corresponding module on \code{sys.path},
895and runs the module as a script. For example,
896you can now run the Python profiler with \code{python -m profile}.
897(Contributed by Nick Coghlan.)
898
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +0000899\item The \function{eval(\var{expr}, \var{globals}, \var{locals})}
Andrew M. Kuchling1455f792004-08-02 12:09:58 +0000900and \function{execfile(\var{filename}, \var{globals}, \var{locals})}
901functions and the \keyword{exec} statement now accept any mapping type
902for the \var{locals} argument. Previously this had to be a regular
903Python dictionary. (Contributed by Raymond Hettinger.)
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +0000904
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000905\item The \function{zip()} built-in function and \function{itertools.izip()}
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000906 now return an empty list if called with no arguments.
907 Previously they raised a \exception{TypeError}
908 exception. This makes them more
Raymond Hettinger607c00f2003-11-12 16:27:50 +0000909 suitable for use with variable length argument lists:
910
911\begin{verbatim}
912>>> def transpose(array):
913... return zip(*array)
914...
915>>> transpose([(1,2,3), (4,5,6)])
916[(1, 4), (2, 5), (3, 6)]
917>>> transpose([])
918[]
919\end{verbatim}
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +0000920(Contributed by Raymond Hettinger.)
921
Andrew M. Kuchlingd91fcbe2004-08-02 12:44:28 +0000922\item Encountering a failure while importing a module no longer leaves
923a partially-initialized module object in \code{sys.modules}. The
924incomplete module object left behind would fool further imports of the
925same module into succeeding, leading to confusing errors.
926
Andrew M. Kuchling65a33322004-07-21 12:41:38 +0000927\item \constant{None} is now a constant; code that binds a new value to
928the name \samp{None} is now a syntax error.
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +0000929(Contributed by Raymond Hettinger.)
Andrew M. Kuchling65a33322004-07-21 12:41:38 +0000930
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000931\end{itemize}
932
933
934%======================================================================
935\subsection{Optimizations}
936
937\begin{itemize}
938
Raymond Hettingerca1a7752004-07-12 13:00:45 +0000939\item The inner loops for list and tuple slicing
Andrew M. Kuchling65a33322004-07-21 12:41:38 +0000940 were optimized and now run about one-third faster. The inner loops
941 were also optimized for dictionaries, resulting in performance boosts for
942 \method{keys()}, \method{values()}, \method{items()},
943 \method{iterkeys()}, \method{itervalues()}, and \method{iteritems()}.
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +0000944 (Contributed by Raymond Hettinger.)
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000945
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +0000946\item The machinery for growing and shrinking lists was optimized for
947 speed and for space efficiency. Appending and popping from lists now
948 runs faster due to more efficient code paths and less frequent use of
949 the underlying system \cfunction{realloc()}. List comprehensions
950 also benefit. \method{list.extend()} was also optimized and no
951 longer converts its argument into a temporary list before extending
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +0000952 the base list. (Contributed by Raymond Hettinger.)
Raymond Hettinger7a6d2972004-02-13 19:00:07 +0000953
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000954\item \function{list()}, \function{tuple()}, \function{map()},
955 \function{filter()}, and \function{zip()} now run several times
956 faster with non-sequence arguments that supply a \method{__len__()}
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +0000957 method. (Contributed by Raymond Hettinger.)
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000958
Raymond Hettinger23a0f4e2004-01-05 08:15:20 +0000959\item The methods \method{list.__getitem__()},
Raymond Hettinger97ef8de2004-01-05 00:29:57 +0000960 \method{dict.__getitem__()}, and \method{dict.__contains__()} are
961 are now implemented as \class{method_descriptor} objects rather
962 than \class{wrapper_descriptor} objects. This form of optimized
963 access doubles their performance and makes them more suitable for
Raymond Hettinger23a0f4e2004-01-05 08:15:20 +0000964 use as arguments to functionals:
965 \samp{map(mydict.__getitem__, keylist)}.
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +0000966 (Contributed by Raymond Hettinger.)
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000967
Fred Draked6d35d92004-06-03 13:31:22 +0000968\item Added a new opcode, \code{LIST_APPEND}, that simplifies
Raymond Hettingerdd80f762004-03-07 07:31:06 +0000969 the generated bytecode for list comprehensions and speeds them up
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +0000970 by about a third. (Contributed by Raymond Hettinger.)
Raymond Hettingerdd80f762004-03-07 07:31:06 +0000971
Andrew M. Kuchling0c789562004-09-23 20:15:41 +0000972\item The peephole bytecode optimizer has been improved to
973produce shorter, faster bytecode; remarkably the resulting bytecode is
974more readable. (Enhanced by Raymond Hettinger.)
975
Andrew M. Kuchlingac642872004-08-07 13:13:31 +0000976\item String concatenations in statements of the form \code{s = s +
977"abc"} and \code{s += "abc"} are now performed more efficiently in
978certain circumstances. This optimization won't be present in other
979Python implementations such as Jython, so you shouldn't rely on it;
980using the \method{join()} method of strings is still recommended when
981you want to efficiently glue a large number of strings together.
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +0000982(Contributed by Armin Rigo.)
Andrew M. Kuchlingac642872004-08-07 13:13:31 +0000983
Fred Drakeed0fa3d2003-07-30 19:14:09 +0000984\end{itemize}
985
986The net result of the 2.4 optimizations is that Python 2.4 runs the
987pystone benchmark around XX\% faster than Python 2.3 and YY\% faster
988than Python 2.2.
989
990
991%======================================================================
992\section{New, Improved, and Deprecated Modules}
993
994As usual, Python's standard library received a number of enhancements and
995bug fixes. Here's a partial list of the most notable changes, sorted
996alphabetically by module name. Consult the
997\file{Misc/NEWS} file in the source tree for a more
998complete list of changes, or look through the CVS logs for all the
999details.
1000
1001\begin{itemize}
1002
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +00001003\item The \module{asyncore} module's \function{loop()} now has a
1004 \var{count} parameter that lets you perform a limited number
1005 of passes through the polling loop. The default is still to loop
1006 forever.
1007
Andrew M. Kuchlinga331e862004-09-10 13:05:22 +00001008\item The \module{base64} module now has more complete RFC 3548 support
1009 for Base64, Base32, and Base16 encoding and decoding, including
1010 optional case folding and optional alternative alphabets.
1011 (Contributed by Barry Warsaw.)
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +00001012
Raymond Hettinger0c410272004-01-05 10:13:35 +00001013\item The \module{bisect} module now has an underlying C implementation
1014 for improved performance.
1015 (Contributed by Dmitry Vasiliev.)
1016
Andrew M. Kuchling5303a962004-01-18 15:55:51 +00001017\item The CJKCodecs collections of East Asian codecs, maintained
1018by Hye-Shik Chang, was integrated into 2.4.
1019The new encodings are:
1020
1021\begin{itemize}
Andrew M. Kuchling671c5062004-07-28 15:29:39 +00001022 \item Chinese (PRC): gb2312, gbk, gb18030, big5hkscs, hz
Andrew M. Kuchling5303a962004-01-18 15:55:51 +00001023 \item Chinese (ROC): big5, cp950
Andrew M. Kuchling671c5062004-07-28 15:29:39 +00001024 \item Japanese: cp932, euc-jis-2004, euc-jp,
Andrew M. Kuchling5303a962004-01-18 15:55:51 +00001025euc-jisx0213, iso-2022-jp, iso-2022-jp-1, iso-2022-jp-2,
Andrew M. Kuchling671c5062004-07-28 15:29:39 +00001026 iso-2022-jp-3, iso-2022-jp-ext, iso-2022-jp-2004,
1027 shift-jis, shift-jisx0213, shift-jis-2004
Andrew M. Kuchling5303a962004-01-18 15:55:51 +00001028 \item Korean: cp949, euc-kr, johab, iso-2022-kr
1029\end{itemize}
1030
Andrew M. Kuchling579b3e22004-10-05 20:23:34 +00001031\item The UTF-8 and UTF-16 codecs now cope better with receiving partial input.
1032Previously the \class{StreamReader} class would try to read more data,
1033which made it impossible to resume decoding from the stream. The
1034\method{read()} method will now return as much data as it can and future
1035calls will resume decoding where previous ones left off.
1036(Implemented by Walter D\"orwald.)
1037
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +00001038\item Some other new encodings were added: HP Roman8,
Andrew M. Kuchling579b3e22004-10-05 20:23:34 +00001039ISO_8859-11, ISO_8859-16, PCTP-154, and TIS-620.
Andrew M. Kuchlinge30c4d42004-08-07 13:58:02 +00001040
Andrew M. Kuchlingfd0e4942004-02-09 13:23:34 +00001041\item There is a new \module{collections} module for
1042 various specialized collection datatypes.
1043 Currently it contains just one type, \class{deque},
1044 a double-ended queue that supports efficiently adding and removing
1045 elements from either end.
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001046
1047\begin{verbatim}
1048>>> from collections import deque
1049>>> d = deque('ghi') # make a new deque with three items
1050>>> d.append('j') # add a new entry to the right side
1051>>> d.appendleft('f') # add a new entry to the left side
1052>>> d # show the representation of the deque
1053deque(['f', 'g', 'h', 'i', 'j'])
1054>>> d.pop() # return and remove the rightmost item
1055'j'
1056>>> d.popleft() # return and remove the leftmost item
1057'f'
1058>>> list(d) # list the contents of the deque
1059['g', 'h', 'i']
1060>>> 'h' in d # search the deque
1061True
1062\end{verbatim}
1063
Andrew M. Kuchlingfd0e4942004-02-09 13:23:34 +00001064Several modules now take advantage of \class{collections.deque} for
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +00001065improved performance, such as the \module{Queue} and
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001066\module{threading} modules. (Contributed by Raymond Hettinger.)
Andrew M. Kuchling5303a962004-01-18 15:55:51 +00001067
Fred Drake9f15b5c2004-05-18 04:30:00 +00001068\item The \module{ConfigParser} classes have been enhanced slightly.
1069 The \method{read()} method now returns a list of the files that
1070 were successfully parsed, and the \method{set()} method raises
1071 \exception{TypeError} if passed a \var{value} argument that isn't a
1072 string.
1073
Andrew M. Kuchlinga331e862004-09-10 13:05:22 +00001074\item The \module{curses} module now supports the ncurses extension
1075 \function{use_default_colors()}. On platforms where the terminal
1076 supports transparency, this makes it possible to use a transparent
1077 background. (Contributed by J\"org Lehmann.)
1078
1079\item The \module{difflib} module now includes an \class{HtmlDiff} class
1080that creates an HTML table showing a side by side comparison
1081of two versions of a text. (Contributed by Dan Gass.)
1082
Andrew M. Kuchling579b3e22004-10-05 20:23:34 +00001083\item The \module{email} package was updated to version 3.0,
1084which dropped various deprecated APIs and removes support for Python
1085versions earlier than 2.3. The 3.0 version of the package uses a new
1086incremental parser for MIME message, available in the
1087\module{email.FeedParser} module. The new parser doesn't require
1088reading the entire message into memory, and doesn't throw exceptions
1089if a message is malformed; instead it records any problems as a
1090\member{defect} attribute of the message. (Developed by Anthony
1091Baxter, Barry Warsaw, Thomas Wouters, and others.)
Andrew M. Kuchlinga331e862004-09-10 13:05:22 +00001092
Raymond Hettinger607c00f2003-11-12 16:27:50 +00001093\item The \module{heapq} module has been converted to C. The resulting
Andrew M. Kuchlingfd0e4942004-02-09 13:23:34 +00001094 tenfold improvement in speed makes the module suitable for handling
Raymond Hettinger33ecffb2004-06-10 05:03:17 +00001095 high volumes of data. In addition, the module has two new functions
1096 \function{nlargest()} and \function{nsmallest()} that use heaps to
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +00001097 find the N largest or smallest values in a dataset without the
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001098 expense of a full sort. (Contributed by Raymond Hettinger.)
Andrew M. Kuchling1a420252003-11-08 15:58:49 +00001099
Andrew M. Kuchling0c789562004-09-23 20:15:41 +00001100\item The \module{httplib} module now contains constants for HTTP
1101status codes defined in various HTTP-related RFC documents. Constants
1102have names such as \constant{OK}, \constant{CREATED},
1103\constant{CONTINUE}, and \constant{MOVED_PERMANENTLY}; use pydoc to
1104get a full list. (Contributed by Andrew Eland.)
1105
Andrew M. Kuchlingce4bae62004-07-27 12:13:25 +00001106\item The \module{imaplib} module now supports IMAP's THREAD command
1107(contributed by Yves Dionne) and new \method{deleteacl()} and
1108\method{myrights()} methods (contributed by Arnaud Mazin).
Andrew M. Kuchlingdff9dbd2003-11-20 22:22:19 +00001109
Andrew M. Kuchlingad809552003-12-06 23:19:23 +00001110\item The \module{itertools} module gained a
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +00001111 \function{groupby(\var{iterable}\optional{, \var{func}})} function.
Andrew M. Kuchlingad809552003-12-06 23:19:23 +00001112 \var{iterable} returns a succession of elements, and the optional
1113 \var{func} is a function that takes an element and returns a key
1114 value; if omitted, the key is simply the element itself.
1115 \function{groupby()} then groups the elements into subsequences
1116 which have matching values of the key, and returns a series of 2-tuples
1117 containing the key value and an iterator over the subsequence.
1118
1119Here's an example. The \var{key} function simply returns whether a
1120number is even or odd, so the result of \function{groupby()} is to
1121return consecutive runs of odd or even numbers.
1122
1123\begin{verbatim}
1124>>> import itertools
1125>>> L = [2,4,6, 7,8,9,11, 12, 14]
1126>>> for key_val, it in itertools.groupby(L, lambda x: x % 2):
1127... print key_val, list(it)
1128...
11290 [2, 4, 6]
11301 [7]
11310 [8]
11321 [9, 11]
11330 [12, 14]
1134>>>
1135\end{verbatim}
1136
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +00001137\function{groupby()} is typically used with sorted input. The logic
1138for \function{groupby()} is similar to the \UNIX{} \code{uniq} filter
1139which makes it handy for eliminating, counting, or identifying
1140duplicate elements:
Raymond Hettingerfeb78c92003-12-12 13:13:47 +00001141
1142\begin{verbatim}
1143>>> word = 'abracadabra'
Raymond Hettingered54d912003-12-31 01:59:18 +00001144>>> letters = sorted(word) # Turn string into a sorted list of letters
Raymond Hettinger64958a12003-12-17 20:43:33 +00001145>>> letters
Andrew M. Kuchling4612bc52003-12-16 20:59:37 +00001146['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r']
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +00001147>>> for k, g in itertools.groupby(letters):
1148... print k, list(g)
1149...
1150a ['a', 'a', 'a', 'a', 'a']
1151b ['b', 'b']
1152c ['c']
1153d ['d']
1154r ['r', 'r']
1155>>> # List unique letters
1156>>> [k for k, g in groupby(letters)]
Raymond Hettingerfeb78c92003-12-12 13:13:47 +00001157['a', 'b', 'c', 'd', 'r']
Johannes Gijsbersd3452252004-09-11 16:50:06 +00001158>>> # Count letter occurrences
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +00001159>>> [(k, len(list(g))) for k, g in groupby(letters)]
Raymond Hettingerfeb78c92003-12-12 13:13:47 +00001160[('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)]
Raymond Hettingerfeb78c92003-12-12 13:13:47 +00001161\end{verbatim}
1162
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001163(Contributed by Hye-Shik Chang.)
1164
Raymond Hettingered54d912003-12-31 01:59:18 +00001165\item \module{itertools} also gained a function named
1166\function{tee(\var{iterator}, \var{N})} that returns \var{N} independent
1167iterators that replicate \var{iterator}. If \var{N} is omitted, the
1168default is 2.
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +00001169
1170\begin{verbatim}
1171>>> L = [1,2,3]
1172>>> i1, i2 = itertools.tee(L)
1173>>> i1,i2
1174(<itertools.tee object at 0x402c2080>, <itertools.tee object at 0x402c2090>)
Raymond Hettingered54d912003-12-31 01:59:18 +00001175>>> list(i1) # Run the first iterator to exhaustion
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +00001176[1, 2, 3]
Raymond Hettingered54d912003-12-31 01:59:18 +00001177>>> list(i2) # Run the second iterator to exhaustion
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +00001178[1, 2, 3]
1179>\end{verbatim}
1180
1181Note that \function{tee()} has to keep copies of the values returned
Raymond Hettingered54d912003-12-31 01:59:18 +00001182by the iterator; in the worst case, it may need to keep all of them.
Andrew M. Kuchling44a31e12004-01-01 18:33:34 +00001183This should therefore be used carefully if the leading iterator
Raymond Hettingered54d912003-12-31 01:59:18 +00001184can run far ahead of the trailing iterator in a long stream of inputs.
Andrew M. Kuchling3bf85f12004-07-05 01:37:07 +00001185If the separation is large, then you might as well use
Raymond Hettingered54d912003-12-31 01:59:18 +00001186\function{list()} instead. When the iterators track closely with one
1187another, \function{tee()} is ideal. Possible applications include
1188bookmarking, windowing, or lookahead iterators.
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001189(Contributed by Raymond Hettinger.)
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +00001190
Andrew M. Kuchling5785a132004-07-26 19:28:46 +00001191\item A number of functions were added to the \module{locale}
1192module, such as \function{bind_textdomain_codeset()} to specify a
1193particular encoding, and a family of \function{l*gettext()} functions
1194that return messages in the chosen encoding.
1195(Contributed by Gustavo Niemeyer.)
1196
Andrew M. Kuchling23406892004-07-15 11:44:42 +00001197\item The \module{logging} package's \function{basicConfig} function
1198gained some keyword arguments to simplify log configuration. The
1199default behavior is to log messages to standard error, but
1200various keyword arguments can be specified to log to a particular file,
1201change the logging format, or set the logging level. For example:
Andrew M. Kuchlingbcefe692004-07-07 13:01:53 +00001202
1203\begin{verbatim}
1204import logging
1205logging.basicConfig(filename = '/var/log/application.log',
1206 level=0, # Log all messages, including debugging,
1207 format='%(levelname):%(process):%(thread):%(message)')
1208\end{verbatim}
1209
Andrew M. Kuchling579b3e22004-10-05 20:23:34 +00001210Other additions to \module{logging} include a \method{log(\var{level},
1211\var{msg})} convenience method, and a
1212\class{TimedRotatingFileHandler} class that rotates its log files at
Andrew M. Kuchlingbcefe692004-07-07 13:01:53 +00001213a timed interval. The module already had \class{RotatingFileHandler},
1214which rotated logs once the file exceeded a certain size. Both
1215classes derive from a new \class{BaseRotatingHandler} class that can
1216be used to implement other rotating handlers.
1217
Andrew M. Kuchling579b3e22004-10-05 20:23:34 +00001218(Changes implemented by Vinay Sajip.)
1219
Andrew M. Kuchling0c789562004-09-23 20:15:41 +00001220\item The \module{marshal} module now shares interned strings on unpacking a
1221data structure. This may shrink the size of certain pickle strings,
1222but the primary effect is to make \file{.pyc} files significantly smaller.
1223(Contributed by Martin von Loewis.)
1224
Andrew M. Kuchling5785a132004-07-26 19:28:46 +00001225\item The \module{nntplib} module's \class{NNTP} class gained
1226\method{description()} and \method{descriptions()} methods to retrieve
1227newsgroup descriptions for a single group or for a range of groups.
1228(Contributed by J\"urgen A. Erhard.)
1229
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +00001230\item The \module{operator} module gained two new functions,
1231\function{attrgetter(\var{attr})} and \function{itemgetter(\var{index})}.
1232Both functions return callables that take a single argument and return
Raymond Hettingered54d912003-12-31 01:59:18 +00001233the corresponding attribute or item; these callables make excellent
Andrew M. Kuchlingbcefe692004-07-07 13:01:53 +00001234data extractors when used with \function{map()} or
1235\function{sorted()}. For example:
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +00001236
1237\begin{verbatim}
Raymond Hettingered54d912003-12-31 01:59:18 +00001238>>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +00001239>>> map(operator.itemgetter(0), L)
1240['c', 'd', 'a', 'b']
1241>>> map(operator.itemgetter(1), L)
Raymond Hettingered54d912003-12-31 01:59:18 +00001242[2, 1, 4, 3]
1243>>> sorted(L, key=operator.itemgetter(1)) # Sort list by second tuple item
1244[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
Andrew M. Kuchling35f2b052003-12-18 13:28:13 +00001245\end{verbatim}
1246
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001247(Contributed by Raymond Hettinger.)
1248
Andrew M. Kuchlinge30c4d42004-08-07 13:58:02 +00001249\item The \module{optparse} module was updated. The module now passes
1250its messages through \function{gettext.gettext()}, making it possible
1251to internationalize Optik's help and error messages. Help messages
Fred Drake9bae19e2004-08-07 14:28:37 +00001252for options can now include the string \code{'\%default'}, which will
Andrew M. Kuchlinge30c4d42004-08-07 13:58:02 +00001253be replaced by the option's default value.
1254
Andrew M. Kuchlingf3958f12004-10-11 19:20:06 +00001255\item The long-term plan is to deprecate the \module{rfc822} module
1256in some future Python release in favor of the \module{email} package.
1257To this end, the \function{email.Utils.formatdate()} function has been
1258changed to make it usable as a replacement for
1259\function{rfc822.formatdate()}. You may want to write new e-mail
1260processing code with this in mind. (Change implemented by Anthony
1261Baxter.)
1262
Andrew M. Kuchlingcb7b3f32004-08-30 11:58:04 +00001263\item A new \function{urandom(\var{n})} function
1264was added to the \module{os} module, providing access to
1265platform-specific sources of randomness such as
Johannes Gijsbersed047482004-08-30 15:03:23 +00001266\file{/dev/urandom} on Linux or the Windows CryptoAPI. The
Andrew M. Kuchlingcb7b3f32004-08-30 11:58:04 +00001267function returns a string containing \var{n} bytes of random data.
1268(Contributed by Trevor Perrin.)
1269
1270\item Another new function: \function{os.path.lexists(\var{path})}
1271returns true if the file specified by \var{path} exists, whether or
1272not it's a symbolic link. This differs from the existing
1273\function{os.path.exists(\var{path})} function, which returns false if
1274\var{path} is a symlink that points to a destination that doesn't exist.
1275(Contributed by Beni Cherniavsky.)
1276
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +00001277\item A new \function{getsid()} function was added to the
1278\module{posix} module that underlies the \module{os} module.
1279(Contributed by J. Raynor.)
1280
1281\item The \module{poplib} module now supports POP over SSL.
1282
1283\item The \module{profile} module can now profile C extension functions.
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001284% XXX more to say about this?
1285(Contributed by Nick Bastin.)
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +00001286
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +00001287\item The \module{random} module has a new method called \method{getrandbits(N)}
Raymond Hettinger607c00f2003-11-12 16:27:50 +00001288 which returns an N-bit long integer. This method supports the existing
1289 \method{randrange()} method, making it possible to efficiently generate
Andrew M. Kuchling44a31e12004-01-01 18:33:34 +00001290 arbitrarily large random numbers.
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001291 (Contributed by Raymond Hettinger.)
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +00001292
1293\item The regular expression language accepted by the \module{re} module
1294 was extended with simple conditional expressions, written as
Andrew M. Kuchlingab778222004-08-31 12:07:43 +00001295 \regexp{(?(\var{group})\var{A}|\var{B})}. \var{group} is either a
1296 numeric group ID or a group name defined with \regexp{(?P<group>...)}
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +00001297 earlier in the expression. If the specified group matched, the
1298 regular expression pattern \var{A} will be tested against the string; if
1299 the group didn't match, the pattern \var{B} will be used instead.
Raymond Hettinger874ebd52004-05-31 03:15:02 +00001300
Andrew M. Kuchlingab778222004-08-31 12:07:43 +00001301\item The \module{re} module is also no longer recursive, thanks
1302to a massive amount of work by Gustavo Niemeyer. In a recursive
1303regular expression engine, certain patterns result in a large amount
1304of C stack space being consumed, and it was possible to overflow the
1305stack. For example, if you matched a 30000-byte string of \samp{a}
1306characters against the expression \regexp{(a|b)+}, one stack frame was
1307consumed per character. Python 2.3 tried to check for stack overflow
1308and raise a \exception{RuntimeError} exception, but if you were
1309unlucky Python could dump core. Python 2.4's regular expression
1310engine can match this pattern without problems.
1311
Andrew M. Kuchling7f203b82004-08-09 14:48:28 +00001312\item A new \function{socketpair()} function was added to the
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +00001313\module{socket} module, returning a pair of connected sockets.
1314(Contributed by Dave Cole.)
Andrew M. Kuchling7f203b82004-08-09 14:48:28 +00001315
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +00001316\item The \function{sys.exitfunc()} function has been deprecated. Code
1317should be using the existing \module{atexit} module, which correctly
1318handles calling multiple exit functions. Eventually
1319\function{sys.exitfunc()} will become a purely internal interface,
1320accessed only by \module{atexit}.
1321
1322\item The \module{tarfile} module now generates GNU-format tar files
1323by default.
1324
Andrew M. Kuchling00457172004-07-15 11:52:40 +00001325\item The \module{threading} module now has an elegantly simple way to support
1326thread-local data. The module contains a \class{local} class whose
1327attribute values are local to different threads.
1328
1329\begin{verbatim}
1330import threading
1331
1332data = threading.local()
1333data.number = 42
1334data.url = ('www.python.org', 80)
1335\end{verbatim}
1336
1337Other threads can assign and retrieve their own values for the
1338\member{number} and \member{url} attributes. You can subclass
1339\class{local} to initialize attributes or to add methods.
1340(Contributed by Jim Fulton.)
1341
Andrew M. Kuchlinga331e862004-09-10 13:05:22 +00001342\item The \module{timeit} module now automatically disables periodic
1343 garbarge collection during the timing loop. This change makes
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001344 consecutive timings more comparable. (Contributed by Raymond Hettinger.)
Andrew M. Kuchlinga331e862004-09-10 13:05:22 +00001345
Raymond Hettinger874ebd52004-05-31 03:15:02 +00001346\item The \module{weakref} module now supports a wider variety of objects
1347 including Python functions, class instances, sets, frozensets, deques,
1348 arrays, files, sockets, and regular expression pattern objects.
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001349 (Contributed by Raymond Hettinger.)
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +00001350
1351\item The \module{xmlrpclib} module now supports a multi-call extension for
Andrew M. Kuchling00457172004-07-15 11:52:40 +00001352transmitting multiple XML-RPC calls in a single HTTP operation.
Andrew M. Kuchling3d3db962004-08-31 13:57:02 +00001353
1354\item The \module{mpz}, \module{rotor}, and \module{xreadlines} modules have
1355been removed.
Andrew M. Kuchling69f31eb2003-08-13 23:11:04 +00001356
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001357\end{itemize}
1358
1359
1360%======================================================================
Raymond Hettingerca1a7752004-07-12 13:00:45 +00001361% whole new modules get described in subsections here
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001362
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001363\subsection{cookielib}
1364
1365The \module{cookielib} library supports client-side handling for HTTP
1366cookies, just as the \module{Cookie} provides server-side cookie
Andrew M. Kuchling71432f12004-07-05 01:40:07 +00001367support in CGI scripts. Cookies are stored in cookie jars; the library
Martin v. Löwis2a6ba902004-05-31 18:22:40 +00001368transparently stores cookies offered by the web server in the cookie
1369jar, and fetches the cookie from the jar when connecting to the
1370server. Similar to web browsers, policy objects control whether
1371cookies are accepted or not.
1372
1373In order to store cookies across sessions, two implementations of
1374cookie jars are provided: one that stores cookies in the Netscape
1375format, so applications can use the Mozilla or Lynx cookie jars, and
1376one that stores cookies in the same format as the Perl libwww libary.
1377
1378\module{urllib2} has been changed to interact with \module{cookielib}:
1379\class{HTTPCookieProcessor} manages a cookie jar that is used when
1380accessing URLs.
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001381
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +00001382\subsection{doctest}
1383
1384The \module{doctest} module underwent considerable refactoring thanks
1385to Edward Loper and Tim Peters.
1386
1387% XXX describe this
1388
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001389% ======================================================================
1390\section{Build and C API Changes}
1391
1392Changes to Python's build process and to the C API include:
1393
1394\begin{itemize}
1395
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +00001396 \item Three new convenience macros were added for common return
1397 values from extension functions: \csimplemacro{Py_RETURN_NONE},
1398 \csimplemacro{Py_RETURN_TRUE}, and \csimplemacro{Py_RETURN_FALSE}.
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001399 (Contributed by Brett Cannon.)
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +00001400
Andrew M. Kuchling5785a132004-07-26 19:28:46 +00001401 \item Another new macro, \csimplemacro{Py_CLEAR(\var{obj})},
1402 decreases the reference count of \var{obj} and sets \var{obj} to the
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001403 null pointer. (Contributed by Jim Fulton.)
Andrew M. Kuchling5785a132004-07-26 19:28:46 +00001404
Fred Drakece3caf22004-02-12 18:13:12 +00001405 \item A new function, \cfunction{PyTuple_Pack(\var{N}, \var{obj1},
1406 \var{obj2}, ..., \var{objN})}, constructs tuples from a variable
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001407 length argument list of Python objects. (Contributed by Raymond Hettinger.)
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001408
Fred Drakece3caf22004-02-12 18:13:12 +00001409 \item A new function, \cfunction{PyDict_Contains(\var{d}, \var{k})},
1410 implements fast dictionary lookups without masking exceptions raised
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001411 during the look-up process. (Contributed by Raymond Hettinger.)
Raymond Hettingerd4462302003-11-26 17:52:45 +00001412
Andrew M. Kuchling0c789562004-09-23 20:15:41 +00001413 \item The \csimplemacro{Py_IS_NAN(\var{X})} macro returns 1 if
1414 its float or double argument \var{X} is a NaN.
1415 (Contributed by Tim Peters.)
1416
Andrew M. Kuchlingf3958f12004-10-11 19:20:06 +00001417 \item C code can avoid unnecessary locking by using the new
1418 \cfunction{PyEval_ThreadsInitialized()} function to tell
1419 if any thread operations have been performed. If this function
1420 returns false, no lock operations are needed.
1421 (Contributed by Nick Coghlan.)
1422
Andrew M. Kuchlinge30c4d42004-08-07 13:58:02 +00001423 \item A new function, \cfunction{PyArg_VaParseTupleAndKeywords()},
1424 is the same as \cfunction{PyArg_ParseTupleAndKeywords()} but takes a
1425 \ctype{va_list} instead of a number of arguments.
1426 (Contributed by Greg Chapman.)
1427
Fred Drakece3caf22004-02-12 18:13:12 +00001428 \item A new method flag, \constant{METH_COEXISTS}, allows a function
Andrew M. Kuchling71432f12004-07-05 01:40:07 +00001429 defined in slots to co-exist with a \ctype{PyCFunction} having the
1430 same name. This can halve the access time for a method such as
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001431 \method{set.__contains__()}. (Contributed by Raymond Hettinger.)
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +00001432
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +00001433 \item Python can now be built with additional profiling for the
1434 interpreter itself. This is intended for people developing on the
1435 Python core. Providing \longprogramopt{--enable-profiling} to the
1436 \program{configure} script will let you profile the interpreter with
1437 \program{gprof}, and providing the \longprogramopt{--with-tsc}
1438 switch enables profiling using the Pentium's Time-Stamp-Counter
1439 register. The switch is slightly misnamed, because the profiling
1440 feature also works on the PowerPC platform, though that processor
Raymond Hettinger468af712004-09-20 17:47:46 +00001441 architecture doesn't call that register a TSC.
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +00001442
Andrew M. Kuchlingd0b6d9d2004-07-04 15:35:00 +00001443 \item The \ctype{tracebackobject} type has been renamed to \ctype{PyTracebackObject}.
Raymond Hettinger97ef8de2004-01-05 00:29:57 +00001444
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001445\end{itemize}
1446
1447
1448%======================================================================
1449\subsection{Port-Specific Changes}
1450
Raymond Hettinger97ef8de2004-01-05 00:29:57 +00001451\begin{itemize}
1452
1453\item The Windows port now builds under MSVC++ 7.1 as well as version 6.
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001454 (Contributed by Martin von Loewis.)
Raymond Hettinger97ef8de2004-01-05 00:29:57 +00001455
1456\end{itemize}
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001457
1458
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001459
1460%======================================================================
1461\section{Porting to Python 2.4}
1462
1463This section lists previously described changes that may require
1464changes to your code:
1465
1466\begin{itemize}
1467
Raymond Hettinger607c00f2003-11-12 16:27:50 +00001468\item The \function{zip()} built-in function and \function{itertools.izip()}
1469 now return an empty list instead of raising a \exception{TypeError}
1470 exception if called with no arguments.
Andrew M. Kuchling7642f7a2004-09-13 15:06:50 +00001471 (Contributed by Raymond Hettinger.)
Andrew M. Kuchling6aedcfc2003-10-21 12:48:23 +00001472
1473\item \function{dircache.listdir()} now passes exceptions to the caller
1474 instead of returning empty lists.
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001475
Andrew M. Kuchling71432f12004-07-05 01:40:07 +00001476\item \function{LexicalHandler.startDTD()} used to receive the public and
1477 system IDs in the wrong order. This has been corrected; applications
Fred Drake56fcc232004-05-06 02:55:35 +00001478 relying on the wrong order need to be fixed.
Martin v. Löwis456ab1d2004-05-06 01:54:36 +00001479
Andrew M. Kuchling71432f12004-07-05 01:40:07 +00001480\item \function{fcntl.ioctl} now warns if the \var{mutate}
1481 argument is omitted and relevant.
Martin v. Löwis77ca6c42004-06-03 12:47:26 +00001482
Andrew M. Kuchling87c98b22004-08-25 13:38:46 +00001483\item The \module{tarfile} module now generates GNU-format tar files
1484by default.
1485
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001486\end{itemize}
1487
1488
1489%======================================================================
1490\section{Acknowledgements \label{acks}}
1491
1492The author would like to thank the following people for offering
1493suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchlingcebdd3c2004-10-08 18:29:29 +00001494article: Hye-Shik Chang, Michael Dyck, Raymond Hettinger, Hamish Lawson.
Fred Drakeed0fa3d2003-07-30 19:14:09 +00001495
1496\end{document}