blob: 0fd88c95770a9a958b02d428540373446d81584a [file] [log] [blame]
Fred Drake03e10312002-03-26 19:17:43 +00001\documentclass{howto}
Fred Drake693aea22003-02-07 14:52:18 +00002\usepackage{distutils}
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00003% $Id$
4
5\title{What's New in Python 2.3}
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00006\release{0.90}
Fred Drakeaac8c582003-01-17 22:50:10 +00007\author{A.M.\ Kuchling}
Andrew M. Kuchlingbc5e3cc2002-11-05 00:26:33 +00008\authoraddress{\email{amk@amk.ca}}
Fred Drake03e10312002-03-26 19:17:43 +00009
10\begin{document}
11\maketitle
12\tableofcontents
13
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +000014% To do:
Andrew M. Kuchlingc760c6c2003-07-16 20:12:33 +000015% PYTHONINSPECT
Andrew M. Kuchlingc760c6c2003-07-16 20:12:33 +000016% doctest extensions
17% new version of IDLE
18% XML-RPC nil extension
Andrew M. Kuchlingc61ec522002-08-04 01:20:05 +000019% MacOS framework-related changes (section of its own, probably)
Andrew M. Kuchlingf70a0a82002-06-10 13:22:46 +000020
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +000021%\section{Introduction \label{intro}}
22
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +000023This article explains the new features in Python 2.3. The tentative
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +000024release date of Python 2.3 is currently scheduled for August 2003.
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +000025
26This article doesn't attempt to provide a complete specification of
27the new features, but instead provides a convenient overview. For
28full details, you should refer to the documentation for Python 2.3,
Fred Drake693aea22003-02-07 14:52:18 +000029such as the \citetitle[../lib/lib.html]{Python Library Reference} and
30the \citetitle[../ref/ref.html]{Python Reference Manual}. If you want
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +000031to understand the complete implementation and design rationale,
32refer to the PEP for a particular new feature.
Fred Drake03e10312002-03-26 19:17:43 +000033
34
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +000035%======================================================================
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000036\section{PEP 218: A Standard Set Datatype}
37
38The new \module{sets} module contains an implementation of a set
39datatype. The \class{Set} class is for mutable sets, sets that can
40have members added and removed. The \class{ImmutableSet} class is for
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +000041sets that can't be modified, and instances of \class{ImmutableSet} can
42therefore be used as dictionary keys. Sets are built on top of
43dictionaries, so the elements within a set must be hashable.
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000044
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +000045Here's a simple example:
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000046
47\begin{verbatim}
48>>> import sets
49>>> S = sets.Set([1,2,3])
50>>> S
51Set([1, 2, 3])
52>>> 1 in S
53True
54>>> 0 in S
55False
56>>> S.add(5)
57>>> S.remove(3)
58>>> S
59Set([1, 2, 5])
Fred Drake5c4cf152002-11-13 14:59:06 +000060>>>
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000061\end{verbatim}
62
63The union and intersection of sets can be computed with the
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +000064\method{union()} and \method{intersection()} methods; an alternative
65notation uses the bitwise operators \code{\&} and \code{|}.
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000066Mutable sets also have in-place versions of these methods,
67\method{union_update()} and \method{intersection_update()}.
68
69\begin{verbatim}
70>>> S1 = sets.Set([1,2,3])
71>>> S2 = sets.Set([4,5,6])
72>>> S1.union(S2)
73Set([1, 2, 3, 4, 5, 6])
74>>> S1 | S2 # Alternative notation
75Set([1, 2, 3, 4, 5, 6])
Fred Drake5c4cf152002-11-13 14:59:06 +000076>>> S1.intersection(S2)
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000077Set([])
78>>> S1 & S2 # Alternative notation
79Set([])
80>>> S1.union_update(S2)
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000081>>> S1
82Set([1, 2, 3, 4, 5, 6])
Fred Drake5c4cf152002-11-13 14:59:06 +000083>>>
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000084\end{verbatim}
85
86It's also possible to take the symmetric difference of two sets. This
87is the set of all elements in the union that aren't in the
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +000088intersection. Another way of putting it is that the symmetric
89difference contains all elements that are in exactly one
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +000090set. Again, there's an alternative notation (\code{\^}), and an
91in-place version with the ungainly name
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000092\method{symmetric_difference_update()}.
93
94\begin{verbatim}
95>>> S1 = sets.Set([1,2,3,4])
96>>> S2 = sets.Set([3,4,5,6])
97>>> S1.symmetric_difference(S2)
98Set([1, 2, 5, 6])
99>>> S1 ^ S2
100Set([1, 2, 5, 6])
101>>>
102\end{verbatim}
103
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000104There are also \method{issubset()} and \method{issuperset()} methods
Michael W. Hudson065f5fa2003-02-10 19:24:50 +0000105for checking whether one set is a subset or superset of another:
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +0000106
107\begin{verbatim}
108>>> S1 = sets.Set([1,2,3])
109>>> S2 = sets.Set([2,3])
110>>> S2.issubset(S1)
111True
112>>> S1.issubset(S2)
113False
114>>> S1.issuperset(S2)
115True
116>>>
117\end{verbatim}
118
119
120\begin{seealso}
121
122\seepep{218}{Adding a Built-In Set Object Type}{PEP written by Greg V. Wilson.
123Implemented by Greg V. Wilson, Alex Martelli, and GvR.}
124
125\end{seealso}
126
127
128
129%======================================================================
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000130\section{PEP 255: Simple Generators\label{section-generators}}
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000131
132In Python 2.2, generators were added as an optional feature, to be
133enabled by a \code{from __future__ import generators} directive. In
1342.3 generators no longer need to be specially enabled, and are now
135always present; this means that \keyword{yield} is now always a
136keyword. The rest of this section is a copy of the description of
137generators from the ``What's New in Python 2.2'' document; if you read
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000138it back when Python 2.2 came out, you can skip the rest of this section.
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000139
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000140You're doubtless familiar with how function calls work in Python or C.
141When you call a function, it gets a private namespace where its local
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000142variables are created. When the function reaches a \keyword{return}
143statement, the local variables are destroyed and the resulting value
144is returned to the caller. A later call to the same function will get
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000145a fresh new set of local variables. But, what if the local variables
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000146weren't thrown away on exiting a function? What if you could later
147resume the function where it left off? This is what generators
148provide; they can be thought of as resumable functions.
149
150Here's the simplest example of a generator function:
151
152\begin{verbatim}
153def generate_ints(N):
154 for i in range(N):
155 yield i
156\end{verbatim}
157
158A new keyword, \keyword{yield}, was introduced for generators. Any
159function containing a \keyword{yield} statement is a generator
160function; this is detected by Python's bytecode compiler which
Fred Drake5c4cf152002-11-13 14:59:06 +0000161compiles the function specially as a result.
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000162
163When you call a generator function, it doesn't return a single value;
164instead it returns a generator object that supports the iterator
165protocol. On executing the \keyword{yield} statement, the generator
166outputs the value of \code{i}, similar to a \keyword{return}
167statement. The big difference between \keyword{yield} and a
168\keyword{return} statement is that on reaching a \keyword{yield} the
169generator's state of execution is suspended and local variables are
170preserved. On the next call to the generator's \code{.next()} method,
171the function will resume executing immediately after the
172\keyword{yield} statement. (For complicated reasons, the
173\keyword{yield} statement isn't allowed inside the \keyword{try} block
Fred Drakeaac8c582003-01-17 22:50:10 +0000174of a \keyword{try}...\keyword{finally} statement; read \pep{255} for a full
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000175explanation of the interaction between \keyword{yield} and
176exceptions.)
177
Fred Drakeaac8c582003-01-17 22:50:10 +0000178Here's a sample usage of the \function{generate_ints()} generator:
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000179
180\begin{verbatim}
181>>> gen = generate_ints(3)
182>>> gen
183<generator object at 0x8117f90>
184>>> gen.next()
1850
186>>> gen.next()
1871
188>>> gen.next()
1892
190>>> gen.next()
191Traceback (most recent call last):
Andrew M. Kuchling9f6e1042002-06-17 13:40:04 +0000192 File "stdin", line 1, in ?
193 File "stdin", line 2, in generate_ints
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000194StopIteration
195\end{verbatim}
196
197You could equally write \code{for i in generate_ints(5)}, or
198\code{a,b,c = generate_ints(3)}.
199
200Inside a generator function, the \keyword{return} statement can only
201be used without a value, and signals the end of the procession of
202values; afterwards the generator cannot return any further values.
203\keyword{return} with a value, such as \code{return 5}, is a syntax
204error inside a generator function. The end of the generator's results
205can also be indicated by raising \exception{StopIteration} manually,
206or by just letting the flow of execution fall off the bottom of the
207function.
208
209You could achieve the effect of generators manually by writing your
210own class and storing all the local variables of the generator as
211instance variables. For example, returning a list of integers could
212be done by setting \code{self.count} to 0, and having the
213\method{next()} method increment \code{self.count} and return it.
214However, for a moderately complicated generator, writing a
215corresponding class would be much messier.
216\file{Lib/test/test_generators.py} contains a number of more
217interesting examples. The simplest one implements an in-order
218traversal of a tree using generators recursively.
219
220\begin{verbatim}
221# A recursive generator that generates Tree leaves in in-order.
222def inorder(t):
223 if t:
224 for x in inorder(t.left):
225 yield x
226 yield t.label
227 for x in inorder(t.right):
228 yield x
229\end{verbatim}
230
231Two other examples in \file{Lib/test/test_generators.py} produce
232solutions for the N-Queens problem (placing $N$ queens on an $NxN$
233chess board so that no queen threatens another) and the Knight's Tour
234(a route that takes a knight to every square of an $NxN$ chessboard
Fred Drake5c4cf152002-11-13 14:59:06 +0000235without visiting any square twice).
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000236
237The idea of generators comes from other programming languages,
238especially Icon (\url{http://www.cs.arizona.edu/icon/}), where the
239idea of generators is central. In Icon, every
240expression and function call behaves like a generator. One example
241from ``An Overview of the Icon Programming Language'' at
242\url{http://www.cs.arizona.edu/icon/docs/ipd266.htm} gives an idea of
243what this looks like:
244
245\begin{verbatim}
246sentence := "Store it in the neighboring harbor"
247if (i := find("or", sentence)) > 5 then write(i)
248\end{verbatim}
249
250In Icon the \function{find()} function returns the indexes at which the
251substring ``or'' is found: 3, 23, 33. In the \keyword{if} statement,
252\code{i} is first assigned a value of 3, but 3 is less than 5, so the
253comparison fails, and Icon retries it with the second value of 23. 23
254is greater than 5, so the comparison now succeeds, and the code prints
255the value 23 to the screen.
256
257Python doesn't go nearly as far as Icon in adopting generators as a
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000258central concept. Generators are considered part of the core
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000259Python language, but learning or using them isn't compulsory; if they
260don't solve any problems that you have, feel free to ignore them.
261One novel feature of Python's interface as compared to
262Icon's is that a generator's state is represented as a concrete object
263(the iterator) that can be passed around to other functions or stored
264in a data structure.
265
266\begin{seealso}
267
268\seepep{255}{Simple Generators}{Written by Neil Schemenauer, Tim
269Peters, Magnus Lie Hetland. Implemented mostly by Neil Schemenauer
270and Tim Peters, with other fixes from the Python Labs crew.}
271
272\end{seealso}
273
274
275%======================================================================
Fred Drake13090e12002-08-22 16:51:08 +0000276\section{PEP 263: Source Code Encodings \label{section-encodings}}
Andrew M. Kuchling950725f2002-08-06 01:40:48 +0000277
278Python source files can now be declared as being in different
279character set encodings. Encodings are declared by including a
280specially formatted comment in the first or second line of the source
281file. For example, a UTF-8 file can be declared with:
282
283\begin{verbatim}
284#!/usr/bin/env python
285# -*- coding: UTF-8 -*-
286\end{verbatim}
287
288Without such an encoding declaration, the default encoding used is
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +00002897-bit ASCII. Executing or importing modules that contain string
290literals with 8-bit characters and have no encoding declaration will result
Andrew M. Kuchlingacddabc2003-02-18 00:43:24 +0000291in a \exception{DeprecationWarning} being signalled by Python 2.3; in
2922.4 this will be a syntax error.
Andrew M. Kuchling950725f2002-08-06 01:40:48 +0000293
Andrew M. Kuchlingacddabc2003-02-18 00:43:24 +0000294The encoding declaration only affects Unicode string literals, which
295will be converted to Unicode using the specified encoding. Note that
296Python identifiers are still restricted to ASCII characters, so you
297can't have variable names that use characters outside of the usual
298alphanumerics.
Andrew M. Kuchling950725f2002-08-06 01:40:48 +0000299
300\begin{seealso}
301
302\seepep{263}{Defining Python Source Code Encodings}{Written by
Andrew M. Kuchlingfcf6b3e2003-05-07 17:00:35 +0000303Marc-Andr\'e Lemburg and Martin von~L\"owis; implemented by Suzuki
304Hisao and Martin von~L\"owis.}
Andrew M. Kuchling950725f2002-08-06 01:40:48 +0000305
306\end{seealso}
307
308
309%======================================================================
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000310\section{PEP 277: Unicode file name support for Windows NT}
Andrew M. Kuchling0f345562002-10-04 22:34:11 +0000311
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000312On Windows NT, 2000, and XP, the system stores file names as Unicode
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000313strings. Traditionally, Python has represented file names as byte
314strings, which is inadequate because it renders some file names
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000315inaccessible.
316
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000317Python now allows using arbitrary Unicode strings (within the
318limitations of the file system) for all functions that expect file
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000319names, most notably the \function{open()} built-in function. If a Unicode
320string is passed to \function{os.listdir()}, Python now returns a list
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000321of Unicode strings. A new function, \function{os.getcwdu()}, returns
322the current directory as a Unicode string.
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000323
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000324Byte strings still work as file names, and on Windows Python will
325transparently convert them to Unicode using the \code{mbcs} encoding.
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000326
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000327Other systems also allow Unicode strings as file names but convert
328them to byte strings before passing them to the system, which can
329cause a \exception{UnicodeError} to be raised. Applications can test
330whether arbitrary Unicode strings are supported as file names by
Andrew M. Kuchlingb9ba4e62003-02-03 15:16:15 +0000331checking \member{os.path.supports_unicode_filenames}, a Boolean value.
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000332
Andrew M. Kuchling563389f2003-03-02 02:31:58 +0000333Under MacOS, \function{os.listdir()} may now return Unicode filenames.
334
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000335\begin{seealso}
336
337\seepep{277}{Unicode file name support for Windows NT}{Written by Neil
Andrew M. Kuchlingfcf6b3e2003-05-07 17:00:35 +0000338Hodgson; implemented by Neil Hodgson, Martin von~L\"owis, and Mark
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000339Hammond.}
340
341\end{seealso}
Andrew M. Kuchling0f345562002-10-04 22:34:11 +0000342
343
344%======================================================================
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000345\section{PEP 278: Universal Newline Support}
346
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000347The three major operating systems used today are Microsoft Windows,
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000348Apple's Macintosh OS, and the various \UNIX\ derivatives. A minor
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +0000349irritation of cross-platform work
350is that these three platforms all use different characters
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000351to mark the ends of lines in text files. \UNIX\ uses the linefeed
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +0000352(ASCII character 10), MacOS uses the carriage return (ASCII
353character 13), and Windows uses a two-character sequence of a
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000354carriage return plus a newline.
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000355
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000356Python's file objects can now support end of line conventions other
357than the one followed by the platform on which Python is running.
Fred Drake5c4cf152002-11-13 14:59:06 +0000358Opening a file with the mode \code{'U'} or \code{'rU'} will open a file
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000359for reading in universal newline mode. All three line ending
Fred Drake5c4cf152002-11-13 14:59:06 +0000360conventions will be translated to a \character{\e n} in the strings
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000361returned by the various file methods such as \method{read()} and
Fred Drake5c4cf152002-11-13 14:59:06 +0000362\method{readline()}.
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000363
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000364Universal newline support is also used when importing modules and when
365executing a file with the \function{execfile()} function. This means
366that Python modules can be shared between all three operating systems
367without needing to convert the line-endings.
368
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +0000369This feature can be disabled when compiling Python by specifying
370the \longprogramopt{without-universal-newlines} switch when running Python's
Fred Drake5c4cf152002-11-13 14:59:06 +0000371\program{configure} script.
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000372
373\begin{seealso}
374
Fred Drake5c4cf152002-11-13 14:59:06 +0000375\seepep{278}{Universal Newline Support}{Written
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000376and implemented by Jack Jansen.}
377
378\end{seealso}
379
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +0000380
381%======================================================================
Andrew M. Kuchling433307b2003-05-13 14:23:54 +0000382\section{PEP 279: enumerate()\label{section-enumerate}}
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +0000383
384A new built-in function, \function{enumerate()}, will make
385certain loops a bit clearer. \code{enumerate(thing)}, where
386\var{thing} is either an iterator or a sequence, returns a iterator
Fred Drake3605ae52003-07-16 03:26:31 +0000387that will return \code{(0, \var{thing}[0])}, \code{(1,
388\var{thing}[1])}, \code{(2, \var{thing}[2])}, and so forth.
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000389
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +0000390A common idiom to change every element of a list looks like this:
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +0000391
392\begin{verbatim}
393for i in range(len(L)):
394 item = L[i]
395 # ... compute some result based on item ...
396 L[i] = result
397\end{verbatim}
398
399This can be rewritten using \function{enumerate()} as:
400
401\begin{verbatim}
402for i, item in enumerate(L):
403 # ... compute some result based on item ...
404 L[i] = result
405\end{verbatim}
406
407
408\begin{seealso}
409
Fred Drake5c4cf152002-11-13 14:59:06 +0000410\seepep{279}{The enumerate() built-in function}{Written
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000411and implemented by Raymond D. Hettinger.}
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +0000412
413\end{seealso}
414
415
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000416%======================================================================
Andrew M. Kuchling433307b2003-05-13 14:23:54 +0000417\section{PEP 282: The logging Package}
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000418
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000419A standard package for writing logs, \module{logging}, has been added
420to Python 2.3. It provides a powerful and flexible mechanism for
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000421generating logging output which can then be filtered and processed in
422various ways. A configuration file written in a standard format can
423be used to control the logging behavior of a program. Python
424includes handlers that will write log records to
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000425standard error or to a file or socket, send them to the system log, or
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000426even e-mail them to a particular address; of course, it's also
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000427possible to write your own handler classes.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000428
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000429The \class{Logger} class is the primary class.
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000430Most application code will deal with one or more \class{Logger}
431objects, each one used by a particular subsystem of the application.
432Each \class{Logger} is identified by a name, and names are organized
433into a hierarchy using \samp{.} as the component separator. For
434example, you might have \class{Logger} instances named \samp{server},
435\samp{server.auth} and \samp{server.network}. The latter two
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000436instances are below \samp{server} in the hierarchy. This means that
437if you turn up the verbosity for \samp{server} or direct \samp{server}
438messages to a different handler, the changes will also apply to
439records logged to \samp{server.auth} and \samp{server.network}.
440There's also a root \class{Logger} that's the parent of all other
441loggers.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000442
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000443For simple uses, the \module{logging} package contains some
444convenience functions that always use the root log:
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000445
446\begin{verbatim}
447import logging
448
449logging.debug('Debugging information')
450logging.info('Informational message')
Andrew M. Kuchling37495072003-02-19 13:46:18 +0000451logging.warning('Warning:config file %s not found', 'server.conf')
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000452logging.error('Error occurred')
453logging.critical('Critical error -- shutting down')
454\end{verbatim}
455
456This produces the following output:
457
458\begin{verbatim}
Andrew M. Kuchling37495072003-02-19 13:46:18 +0000459WARNING:root:Warning:config file server.conf not found
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000460ERROR:root:Error occurred
461CRITICAL:root:Critical error -- shutting down
462\end{verbatim}
463
464In the default configuration, informational and debugging messages are
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000465suppressed and the output is sent to standard error. You can enable
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000466the display of informational and debugging messages by calling the
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000467\method{setLevel()} method on the root logger.
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000468
Andrew M. Kuchling37495072003-02-19 13:46:18 +0000469Notice the \function{warning()} call's use of string formatting
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000470operators; all of the functions for logging messages take the
471arguments \code{(\var{msg}, \var{arg1}, \var{arg2}, ...)} and log the
472string resulting from \code{\var{msg} \% (\var{arg1}, \var{arg2},
473...)}.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000474
475There's also an \function{exception()} function that records the most
476recent traceback. Any of the other functions will also record the
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000477traceback if you specify a true value for the keyword argument
Fred Drakeaac8c582003-01-17 22:50:10 +0000478\var{exc_info}.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000479
480\begin{verbatim}
481def f():
482 try: 1/0
483 except: logging.exception('Problem recorded')
484
485f()
486\end{verbatim}
487
488This produces the following output:
489
490\begin{verbatim}
491ERROR:root:Problem recorded
492Traceback (most recent call last):
493 File "t.py", line 6, in f
494 1/0
495ZeroDivisionError: integer division or modulo by zero
496\end{verbatim}
497
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000498Slightly more advanced programs will use a logger other than the root
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000499logger. The \function{getLogger(\var{name})} function is used to get
500a particular log, creating it if it doesn't exist yet.
Andrew M. Kuchlingb1e4bf92002-12-03 13:35:17 +0000501\function{getLogger(None)} returns the root logger.
502
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000503
504\begin{verbatim}
505log = logging.getLogger('server')
506 ...
507log.info('Listening on port %i', port)
508 ...
509log.critical('Disk full')
510 ...
511\end{verbatim}
512
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000513Log records are usually propagated up the hierarchy, so a message
514logged to \samp{server.auth} is also seen by \samp{server} and
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +0000515\samp{root}, but a \class{Logger} can prevent this by setting its
Fred Drakeaac8c582003-01-17 22:50:10 +0000516\member{propagate} attribute to \constant{False}.
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000517
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000518There are more classes provided by the \module{logging} package that
519can be customized. When a \class{Logger} instance is told to log a
520message, it creates a \class{LogRecord} instance that is sent to any
521number of different \class{Handler} instances. Loggers and handlers
522can also have an attached list of filters, and each filter can cause
523the \class{LogRecord} to be ignored or can modify the record before
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +0000524passing it along. When they're finally output, \class{LogRecord}
525instances are converted to text by a \class{Formatter} class. All of
526these classes can be replaced by your own specially-written classes.
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000527
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000528With all of these features the \module{logging} package should provide
529enough flexibility for even the most complicated applications. This
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +0000530is only an incomplete overview of its features, so please see the
531\ulink{package's reference documentation}{../lib/module-logging.html}
532for all of the details. Reading \pep{282} will also be helpful.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000533
534
535\begin{seealso}
536
537\seepep{282}{A Logging System}{Written by Vinay Sajip and Trent Mick;
538implemented by Vinay Sajip.}
539
540\end{seealso}
541
542
543%======================================================================
Andrew M. Kuchling433307b2003-05-13 14:23:54 +0000544\section{PEP 285: A Boolean Type\label{section-bool}}
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000545
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000546A Boolean type was added to Python 2.3. Two new constants were added
547to the \module{__builtin__} module, \constant{True} and
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000548\constant{False}. (\constant{True} and
549\constant{False} constants were added to the built-ins
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000550in Python 2.2.1, but the 2.2.1 versions are simply set to integer values of
Andrew M. Kuchling5a224532003-01-03 16:52:27 +00005511 and 0 and aren't a different type.)
552
553The type object for this new type is named
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000554\class{bool}; the constructor for it takes any Python value and
555converts it to \constant{True} or \constant{False}.
556
557\begin{verbatim}
558>>> bool(1)
559True
560>>> bool(0)
561False
562>>> bool([])
563False
564>>> bool( (1,) )
565True
566\end{verbatim}
567
568Most of the standard library modules and built-in functions have been
569changed to return Booleans.
570
571\begin{verbatim}
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000572>>> obj = []
573>>> hasattr(obj, 'append')
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000574True
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000575>>> isinstance(obj, list)
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000576True
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000577>>> isinstance(obj, tuple)
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000578False
579\end{verbatim}
580
581Python's Booleans were added with the primary goal of making code
582clearer. For example, if you're reading a function and encounter the
Fred Drake5c4cf152002-11-13 14:59:06 +0000583statement \code{return 1}, you might wonder whether the \code{1}
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000584represents a Boolean truth value, an index, or a
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000585coefficient that multiplies some other quantity. If the statement is
586\code{return True}, however, the meaning of the return value is quite
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000587clear.
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000588
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000589Python's Booleans were \emph{not} added for the sake of strict
590type-checking. A very strict language such as Pascal would also
591prevent you performing arithmetic with Booleans, and would require
592that the expression in an \keyword{if} statement always evaluate to a
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000593Boolean result. Python is not this strict and never will be, as
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000594\pep{285} explicitly says. This means you can still use any
595expression in an \keyword{if} statement, even ones that evaluate to a
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000596list or tuple or some random object. The Boolean type is a
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000597subclass of the \class{int} class so that arithmetic using a Boolean
598still works.
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000599
600\begin{verbatim}
601>>> True + 1
6022
603>>> False + 1
6041
605>>> False * 75
6060
607>>> True * 75
60875
609\end{verbatim}
610
611To sum up \constant{True} and \constant{False} in a sentence: they're
612alternative ways to spell the integer values 1 and 0, with the single
613difference that \function{str()} and \function{repr()} return the
Fred Drake5c4cf152002-11-13 14:59:06 +0000614strings \code{'True'} and \code{'False'} instead of \code{'1'} and
615\code{'0'}.
Andrew M. Kuchling3a52ff62002-04-03 22:44:47 +0000616
617\begin{seealso}
618
619\seepep{285}{Adding a bool type}{Written and implemented by GvR.}
620
621\end{seealso}
622
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000623
Andrew M. Kuchling65b72822002-09-03 00:53:21 +0000624%======================================================================
625\section{PEP 293: Codec Error Handling Callbacks}
626
Martin v. Löwis20eae692002-10-07 19:01:07 +0000627When encoding a Unicode string into a byte string, unencodable
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000628characters may be encountered. So far, Python has allowed specifying
629the error processing as either ``strict'' (raising
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000630\exception{UnicodeError}), ``ignore'' (skipping the character), or
631``replace'' (using a question mark in the output string), with
632``strict'' being the default behavior. It may be desirable to specify
633alternative processing of such errors, such as inserting an XML
634character reference or HTML entity reference into the converted
635string.
Martin v. Löwis20eae692002-10-07 19:01:07 +0000636
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +0000637Python now has a flexible framework to add different processing
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000638strategies. New error handlers can be added with
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000639\function{codecs.register_error}, and codecs then can access the error
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000640handler with \function{codecs.lookup_error}. An equivalent C API has
641been added for codecs written in C. The error handler gets the
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000642necessary state information such as the string being converted, the
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000643position in the string where the error was detected, and the target
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000644encoding. The handler can then either raise an exception or return a
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000645replacement string.
Martin v. Löwis20eae692002-10-07 19:01:07 +0000646
647Two additional error handlers have been implemented using this
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000648framework: ``backslashreplace'' uses Python backslash quoting to
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +0000649represent unencodable characters and ``xmlcharrefreplace'' emits
Martin v. Löwis20eae692002-10-07 19:01:07 +0000650XML character references.
Andrew M. Kuchling65b72822002-09-03 00:53:21 +0000651
652\begin{seealso}
653
Fred Drake5c4cf152002-11-13 14:59:06 +0000654\seepep{293}{Codec Error Handling Callbacks}{Written and implemented by
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000655Walter D\"orwald.}
Andrew M. Kuchling65b72822002-09-03 00:53:21 +0000656
657\end{seealso}
658
659
660%======================================================================
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000661\section{PEP 273: Importing Modules from Zip Archives}
662
663The new \module{zipimport} module adds support for importing
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000664modules from a ZIP-format archive. You don't need to import the
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000665module explicitly; it will be automatically imported if a ZIP
666archive's filename is added to \code{sys.path}. For example:
667
668\begin{verbatim}
669amk@nyman:~/src/python$ unzip -l /tmp/example.zip
670Archive: /tmp/example.zip
671 Length Date Time Name
672 -------- ---- ---- ----
673 8467 11-26-02 22:30 jwzthreading.py
674 -------- -------
675 8467 1 file
676amk@nyman:~/src/python$ ./python
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000677Python 2.3 (#1, Aug 1 2003, 19:54:32)
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000678>>> import sys
679>>> sys.path.insert(0, '/tmp/example.zip') # Add .zip file to front of path
680>>> import jwzthreading
681>>> jwzthreading.__file__
682'/tmp/example.zip/jwzthreading.py'
683>>>
684\end{verbatim}
685
686An entry in \code{sys.path} can now be the filename of a ZIP archive.
687The ZIP archive can contain any kind of files, but only files named
Fred Drakeaac8c582003-01-17 22:50:10 +0000688\file{*.py}, \file{*.pyc}, or \file{*.pyo} can be imported. If an
689archive only contains \file{*.py} files, Python will not attempt to
690modify the archive by adding the corresponding \file{*.pyc} file, meaning
691that if a ZIP archive doesn't contain \file{*.pyc} files, importing may be
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000692rather slow.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000693
694A path within the archive can also be specified to only import from a
695subdirectory; for example, the path \file{/tmp/example.zip/lib/}
696would only import from the \file{lib/} subdirectory within the
697archive.
698
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000699\begin{seealso}
700
701\seepep{273}{Import Modules from Zip Archives}{Written by James C. Ahlstrom,
702who also provided an implementation.
703Python 2.3 follows the specification in \pep{273},
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +0000704but uses an implementation written by Just van~Rossum
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000705that uses the import hooks described in \pep{302}.
706See section~\ref{section-pep302} for a description of the new import hooks.
707}
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000708
709\end{seealso}
710
711%======================================================================
Fred Drake693aea22003-02-07 14:52:18 +0000712\section{PEP 301: Package Index and Metadata for
713Distutils\label{section-pep301}}
Andrew M. Kuchling87cebbf2003-01-03 16:24:28 +0000714
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000715Support for the long-requested Python catalog makes its first
716appearance in 2.3.
717
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000718The heart of the catalog is the new Distutils \command{register} command.
Fred Drake693aea22003-02-07 14:52:18 +0000719Running \code{python setup.py register} will collect the metadata
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000720describing a package, such as its name, version, maintainer,
Andrew M. Kuchlingc61402b2003-02-26 19:00:52 +0000721description, \&c., and send it to a central catalog server. The
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000722resulting catalog is available from \url{http://www.python.org/pypi}.
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000723
724To make the catalog a bit more useful, a new optional
Fred Drake693aea22003-02-07 14:52:18 +0000725\var{classifiers} keyword argument has been added to the Distutils
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000726\function{setup()} function. A list of
Fred Drake693aea22003-02-07 14:52:18 +0000727\ulink{Trove}{http://catb.org/\textasciitilde esr/trove/}-style
728strings can be supplied to help classify the software.
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000729
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +0000730Here's an example \file{setup.py} with classifiers, written to be compatible
731with older versions of the Distutils:
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000732
733\begin{verbatim}
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +0000734from distutils import core
Fred Drake693aea22003-02-07 14:52:18 +0000735kw = {'name': "Quixote",
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +0000736 'version': "0.5.1",
737 'description': "A highly Pythonic Web application framework",
Fred Drake693aea22003-02-07 14:52:18 +0000738 # ...
739 }
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +0000740
Andrew M. Kuchlinga6b1c752003-04-09 17:26:38 +0000741if (hasattr(core, 'setup_keywords') and
742 'classifiers' in core.setup_keywords):
Fred Drake693aea22003-02-07 14:52:18 +0000743 kw['classifiers'] = \
744 ['Topic :: Internet :: WWW/HTTP :: Dynamic Content',
745 'Environment :: No Input/Output (Daemon)',
746 'Intended Audience :: Developers'],
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +0000747
Fred Drake693aea22003-02-07 14:52:18 +0000748core.setup(**kw)
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000749\end{verbatim}
750
751The full list of classifiers can be obtained by running
752\code{python setup.py register --list-classifiers}.
Andrew M. Kuchling87cebbf2003-01-03 16:24:28 +0000753
754\begin{seealso}
755
Fred Drake693aea22003-02-07 14:52:18 +0000756\seepep{301}{Package Index and Metadata for Distutils}{Written and
757implemented by Richard Jones.}
Andrew M. Kuchling87cebbf2003-01-03 16:24:28 +0000758
759\end{seealso}
760
761
762%======================================================================
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000763\section{PEP 302: New Import Hooks \label{section-pep302}}
764
765While it's been possible to write custom import hooks ever since the
766\module{ihooks} module was introduced in Python 1.3, no one has ever
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000767been really happy with it because writing new import hooks is
768difficult and messy. There have been various proposed alternatives
769such as the \module{imputil} and \module{iu} modules, but none of them
770has ever gained much acceptance, and none of them were easily usable
771from \C{} code.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000772
773\pep{302} borrows ideas from its predecessors, especially from
774Gordon McMillan's \module{iu} module. Three new items
775are added to the \module{sys} module:
776
777\begin{itemize}
Andrew M. Kuchlingd5ac8d02003-01-02 21:33:15 +0000778 \item \code{sys.path_hooks} is a list of callable objects; most
Fred Drakeaac8c582003-01-17 22:50:10 +0000779 often they'll be classes. Each callable takes a string containing a
780 path and either returns an importer object that will handle imports
781 from this path or raises an \exception{ImportError} exception if it
782 can't handle this path.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000783
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000784 \item \code{sys.path_importer_cache} caches importer objects for
Fred Drakeaac8c582003-01-17 22:50:10 +0000785 each path, so \code{sys.path_hooks} will only need to be traversed
786 once for each path.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000787
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000788 \item \code{sys.meta_path} is a list of importer objects that will
789 be traversed before \code{sys.path} is checked. This list is
790 initially empty, but user code can add objects to it. Additional
791 built-in and frozen modules can be imported by an object added to
792 this list.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000793
794\end{itemize}
795
796Importer objects must have a single method,
797\method{find_module(\var{fullname}, \var{path}=None)}. \var{fullname}
798will be a module or package name, e.g. \samp{string} or
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000799\samp{distutils.core}. \method{find_module()} must return a loader object
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000800that has a single method, \method{load_module(\var{fullname})}, that
801creates and returns the corresponding module object.
802
803Pseudo-code for Python's new import logic, therefore, looks something
804like this (simplified a bit; see \pep{302} for the full details):
805
806\begin{verbatim}
807for mp in sys.meta_path:
808 loader = mp(fullname)
809 if loader is not None:
Andrew M. Kuchlingd5ac8d02003-01-02 21:33:15 +0000810 <module> = loader.load_module(fullname)
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000811
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000812for path in sys.path:
813 for hook in sys.path_hooks:
Andrew M. Kuchlingd5ac8d02003-01-02 21:33:15 +0000814 try:
815 importer = hook(path)
816 except ImportError:
817 # ImportError, so try the other path hooks
818 pass
819 else:
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000820 loader = importer.find_module(fullname)
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000821 <module> = loader.load_module(fullname)
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000822
823# Not found!
824raise ImportError
825\end{verbatim}
826
827\begin{seealso}
828
829\seepep{302}{New Import Hooks}{Written by Just van~Rossum and Paul Moore.
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +0000830Implemented by Just van~Rossum.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000831}
832
833\end{seealso}
834
835
836%======================================================================
Andrew M. Kuchlinga978e102003-03-21 18:10:12 +0000837\section{PEP 305: Comma-separated Files \label{section-pep305}}
838
839Comma-separated files are a format frequently used for exporting data
840from databases and spreadsheets. Python 2.3 adds a parser for
841comma-separated files.
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000842
843Comma-separated format is deceptively simple at first glance:
Andrew M. Kuchlinga978e102003-03-21 18:10:12 +0000844
845\begin{verbatim}
846Costs,150,200,3.95
847\end{verbatim}
848
849Read a line and call \code{line.split(',')}: what could be simpler?
850But toss in string data that can contain commas, and things get more
851complicated:
852
853\begin{verbatim}
854"Costs",150,200,3.95,"Includes taxes, shipping, and sundry items"
855\end{verbatim}
856
857A big ugly regular expression can parse this, but using the new
858\module{csv} package is much simpler:
859
860\begin{verbatim}
Andrew M. Kuchlingba887bb2003-04-13 21:13:02 +0000861import csv
Andrew M. Kuchlinga978e102003-03-21 18:10:12 +0000862
863input = open('datafile', 'rb')
864reader = csv.reader(input)
865for line in reader:
866 print line
867\end{verbatim}
868
869The \function{reader} function takes a number of different options.
870The field separator isn't limited to the comma and can be changed to
871any character, and so can the quoting and line-ending characters.
872
873Different dialects of comma-separated files can be defined and
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000874registered; currently there are two dialects, both used by Microsoft Excel.
Andrew M. Kuchlinga978e102003-03-21 18:10:12 +0000875A separate \class{csv.writer} class will generate comma-separated files
876from a succession of tuples or lists, quoting strings that contain the
877delimiter.
878
879\begin{seealso}
880
881\seepep{305}{CSV File API}{Written and implemented
882by Kevin Altis, Dave Cole, Andrew McNamara, Skip Montanaro, Cliff Wells.
883}
884
885\end{seealso}
886
887%======================================================================
Andrew M. Kuchlinga092ba12003-03-21 18:32:43 +0000888\section{PEP 307: Pickle Enhancements \label{section-pep305}}
889
890The \module{pickle} and \module{cPickle} modules received some
891attention during the 2.3 development cycle. In 2.2, new-style classes
Andrew M. Kuchlinga6b1c752003-04-09 17:26:38 +0000892could be pickled without difficulty, but they weren't pickled very
Andrew M. Kuchlinga092ba12003-03-21 18:32:43 +0000893compactly; \pep{307} quotes a trivial example where a new-style class
894results in a pickled string three times longer than that for a classic
895class.
896
897The solution was to invent a new pickle protocol. The
898\function{pickle.dumps()} function has supported a text-or-binary flag
899for a long time. In 2.3, this flag is redefined from a Boolean to an
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000900integer: 0 is the old text-mode pickle format, 1 is the old binary
901format, and now 2 is a new 2.3-specific format. A new constant,
Andrew M. Kuchlinga092ba12003-03-21 18:32:43 +0000902\constant{pickle.HIGHEST_PROTOCOL}, can be used to select the fanciest
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000903protocol available.
Andrew M. Kuchlinga092ba12003-03-21 18:32:43 +0000904
905Unpickling is no longer considered a safe operation. 2.2's
906\module{pickle} provided hooks for trying to prevent unsafe classes
907from being unpickled (specifically, a
908\member{__safe_for_unpickling__} attribute), but none of this code
909was ever audited and therefore it's all been ripped out in 2.3. You
910should not unpickle untrusted data in any version of Python.
911
912To reduce the pickling overhead for new-style classes, a new interface
913for customizing pickling was added using three special methods:
914\method{__getstate__}, \method{__setstate__}, and
915\method{__getnewargs__}. Consult \pep{307} for the full semantics
916of these methods.
917
918As a way to compress pickles yet further, it's now possible to use
919integer codes instead of long strings to identify pickled classes.
920The Python Software Foundation will maintain a list of standardized
921codes; there's also a range of codes for private use. Currently no
922codes have been specified.
923
924\begin{seealso}
925
926\seepep{307}{Extensions to the pickle protocol}{Written and implemented
927by Guido van Rossum and Tim Peters.}
928
929\end{seealso}
930
931%======================================================================
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000932\section{Extended Slices\label{section-slices}}
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000933
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000934Ever since Python 1.4, the slicing syntax has supported an optional
935third ``step'' or ``stride'' argument. For example, these are all
936legal Python syntax: \code{L[1:10:2]}, \code{L[:-1:1]},
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000937\code{L[::-1]}. This was added to Python at the request of
938the developers of Numerical Python, which uses the third argument
939extensively. However, Python's built-in list, tuple, and string
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000940sequence types have never supported this feature, raising a
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000941\exception{TypeError} if you tried it. Michael Hudson contributed a
942patch to fix this shortcoming.
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000943
944For example, you can now easily extract the elements of a list that
945have even indexes:
Fred Drakedf872a22002-07-03 12:02:01 +0000946
947\begin{verbatim}
948>>> L = range(10)
949>>> L[::2]
950[0, 2, 4, 6, 8]
951\end{verbatim}
952
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000953Negative values also work to make a copy of the same list in reverse
954order:
Fred Drakedf872a22002-07-03 12:02:01 +0000955
956\begin{verbatim}
957>>> L[::-1]
958[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
959\end{verbatim}
Andrew M. Kuchling3a52ff62002-04-03 22:44:47 +0000960
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000961This also works for tuples, arrays, and strings:
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000962
963\begin{verbatim}
964>>> s='abcd'
965>>> s[::2]
966'ac'
967>>> s[::-1]
968'dcba'
969\end{verbatim}
970
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000971If you have a mutable sequence such as a list or an array you can
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000972assign to or delete an extended slice, but there are some differences
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000973between assignment to extended and regular slices. Assignment to a
974regular slice can be used to change the length of the sequence:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000975
976\begin{verbatim}
977>>> a = range(3)
978>>> a
979[0, 1, 2]
980>>> a[1:3] = [4, 5, 6]
981>>> a
982[0, 4, 5, 6]
983\end{verbatim}
984
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000985Extended slices aren't this flexible. When assigning to an extended
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000986slice, the list on the right hand side of the statement must contain
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000987the same number of items as the slice it is replacing:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000988
989\begin{verbatim}
990>>> a = range(4)
991>>> a
992[0, 1, 2, 3]
993>>> a[::2]
994[0, 2]
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000995>>> a[::2] = [0, -1]
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000996>>> a
997[0, 1, -1, 3]
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000998>>> a[::2] = [0,1,2]
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000999Traceback (most recent call last):
1000 File "<stdin>", line 1, in ?
Raymond Hettingeree1bded2003-01-17 16:20:23 +00001001ValueError: attempt to assign sequence of size 3 to extended slice of size 2
Michael W. Hudson4da01ed2002-07-19 15:48:56 +00001002\end{verbatim}
1003
1004Deletion is more straightforward:
1005
1006\begin{verbatim}
1007>>> a = range(4)
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001008>>> a
1009[0, 1, 2, 3]
Michael W. Hudson4da01ed2002-07-19 15:48:56 +00001010>>> a[::2]
1011[0, 2]
1012>>> del a[::2]
1013>>> a
1014[1, 3]
1015\end{verbatim}
1016
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001017One can also now pass slice objects to the
1018\method{__getitem__} methods of the built-in sequences:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +00001019
1020\begin{verbatim}
1021>>> range(10).__getitem__(slice(0, 5, 2))
1022[0, 2, 4]
1023\end{verbatim}
1024
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001025Or use slice objects directly in subscripts:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +00001026
1027\begin{verbatim}
1028>>> range(10)[slice(0, 5, 2)]
1029[0, 2, 4]
1030\end{verbatim}
1031
Andrew M. Kuchlingb6f79592002-11-29 19:43:45 +00001032To simplify implementing sequences that support extended slicing,
1033slice objects now have a method \method{indices(\var{length})} which,
Fred Drakeaac8c582003-01-17 22:50:10 +00001034given the length of a sequence, returns a \code{(\var{start},
1035\var{stop}, \var{step})} tuple that can be passed directly to
1036\function{range()}.
Andrew M. Kuchlingb6f79592002-11-29 19:43:45 +00001037\method{indices()} handles omitted and out-of-bounds indices in a
1038manner consistent with regular slices (and this innocuous phrase hides
1039a welter of confusing details!). The method is intended to be used
1040like this:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +00001041
1042\begin{verbatim}
1043class FakeSeq:
1044 ...
1045 def calc_item(self, i):
1046 ...
1047 def __getitem__(self, item):
1048 if isinstance(item, slice):
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001049 indices = item.indices(len(self))
1050 return FakeSeq([self.calc_item(i) in range(*indices)])
Fred Drake5c4cf152002-11-13 14:59:06 +00001051 else:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +00001052 return self.calc_item(i)
1053\end{verbatim}
1054
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001055From this example you can also see that the built-in \class{slice}
Andrew M. Kuchling90e9a792002-08-15 00:40:21 +00001056object is now the type object for the slice type, and is no longer a
1057function. This is consistent with Python 2.2, where \class{int},
1058\class{str}, etc., underwent the same change.
1059
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001060
Andrew M. Kuchling3a52ff62002-04-03 22:44:47 +00001061%======================================================================
Fred Drakedf872a22002-07-03 12:02:01 +00001062\section{Other Language Changes}
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001063
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001064Here are all of the changes that Python 2.3 makes to the core Python
1065language.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001066
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001067\begin{itemize}
1068\item The \keyword{yield} statement is now always a keyword, as
1069described in section~\ref{section-generators} of this document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001070
Fred Drake5c4cf152002-11-13 14:59:06 +00001071\item A new built-in function \function{enumerate()}
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001072was added, as described in section~\ref{section-enumerate} of this
1073document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001074
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001075\item Two new constants, \constant{True} and \constant{False} were
1076added along with the built-in \class{bool} type, as described in
1077section~\ref{section-bool} of this document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001078
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00001079\item The \function{int()} type constructor will now return a long
1080integer instead of raising an \exception{OverflowError} when a string
1081or floating-point number is too large to fit into an integer. This
1082can lead to the paradoxical result that
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001083\code{isinstance(int(\var{expression}), int)} is false, but that seems
1084unlikely to cause problems in practice.
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00001085
Fred Drake5c4cf152002-11-13 14:59:06 +00001086\item Built-in types now support the extended slicing syntax,
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001087as described in section~\ref{section-slices} of this document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001088
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001089\item A new built-in function, \function{sum(\var{iterable}, \var{start}=0)},
1090adds up the numeric items in the iterable object and returns their sum.
1091\function{sum()} only accepts numbers, meaning that you can't use it
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +00001092to concatenate a bunch of strings. (Contributed by Alex
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001093Martelli.)
1094
Andrew M. Kuchlingfcf6b3e2003-05-07 17:00:35 +00001095\item \code{list.insert(\var{pos}, \var{value})} used to
1096insert \var{value} at the front of the list when \var{pos} was
1097negative. The behaviour has now been changed to be consistent with
1098slice indexing, so when \var{pos} is -1 the value will be inserted
1099before the last element, and so forth.
1100
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +00001101\item \code{list.index(\var{value})}, which searches for \var{value}
1102within the list and returns its index, now takes optional
1103\var{start} and \var{stop} arguments to limit the search to
1104only part of the list.
1105
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +00001106\item Dictionaries have a new method, \method{pop(\var{key}\optional{,
1107\var{default}})}, that returns the value corresponding to \var{key}
1108and removes that key/value pair from the dictionary. If the requested
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001109key isn't present in the dictionary, \var{default} is returned if it's
1110specified and \exception{KeyError} raised if it isn't.
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001111
1112\begin{verbatim}
1113>>> d = {1:2}
1114>>> d
1115{1: 2}
1116>>> d.pop(4)
1117Traceback (most recent call last):
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +00001118 File "stdin", line 1, in ?
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001119KeyError: 4
1120>>> d.pop(1)
11212
1122>>> d.pop(1)
1123Traceback (most recent call last):
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +00001124 File "stdin", line 1, in ?
Raymond Hettingeree1bded2003-01-17 16:20:23 +00001125KeyError: 'pop(): dictionary is empty'
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001126>>> d
1127{}
1128>>>
1129\end{verbatim}
1130
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001131There's also a new class method,
1132\method{dict.fromkeys(\var{iterable}, \var{value})}, that
1133creates a dictionary with keys taken from the supplied iterator
1134\var{iterable} and all values set to \var{value}, defaulting to
1135\code{None}.
1136
1137(Patches contributed by Raymond Hettinger.)
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001138
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001139Also, the \function{dict()} constructor now accepts keyword arguments to
Raymond Hettinger45bda572002-12-14 20:20:45 +00001140simplify creating small dictionaries:
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001141
1142\begin{verbatim}
1143>>> dict(red=1, blue=2, green=3, black=4)
1144{'blue': 2, 'black': 4, 'green': 3, 'red': 1}
1145\end{verbatim}
1146
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +00001147(Contributed by Just van~Rossum.)
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001148
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +00001149\item The \keyword{assert} statement no longer checks the \code{__debug__}
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001150flag, so you can no longer disable assertions by assigning to \code{__debug__}.
Fred Drake5c4cf152002-11-13 14:59:06 +00001151Running Python with the \programopt{-O} switch will still generate
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001152code that doesn't execute any assertions.
1153
1154\item Most type objects are now callable, so you can use them
1155to create new objects such as functions, classes, and modules. (This
1156means that the \module{new} module can be deprecated in a future
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001157Python version, because you can now use the type objects available in
1158the \module{types} module.)
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001159% XXX should new.py use PendingDeprecationWarning?
1160For example, you can create a new module object with the following code:
1161
1162\begin{verbatim}
1163>>> import types
1164>>> m = types.ModuleType('abc','docstring')
1165>>> m
1166<module 'abc' (built-in)>
1167>>> m.__doc__
1168'docstring'
1169\end{verbatim}
1170
Fred Drake5c4cf152002-11-13 14:59:06 +00001171\item
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001172A new warning, \exception{PendingDeprecationWarning} was added to
1173indicate features which are in the process of being
1174deprecated. The warning will \emph{not} be printed by default. To
1175check for use of features that will be deprecated in the future,
1176supply \programopt{-Walways::PendingDeprecationWarning::} on the
1177command line or use \function{warnings.filterwarnings()}.
1178
Andrew M. Kuchlingc1dd1742003-01-13 13:59:22 +00001179\item The process of deprecating string-based exceptions, as
1180in \code{raise "Error occurred"}, has begun. Raising a string will
1181now trigger \exception{PendingDeprecationWarning}.
1182
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001183\item Using \code{None} as a variable name will now result in a
1184\exception{SyntaxWarning} warning. In a future version of Python,
1185\code{None} may finally become a keyword.
1186
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001187\item The \method{xreadlines()} method of file objects, introduced in
1188Python 2.1, is no longer necessary because files now behave as their
1189own iterator. \method{xreadlines()} was originally introduced as a
1190faster way to loop over all the lines in a file, but now you can
1191simply write \code{for line in file_obj}. File objects also have a
1192new read-only \member{encoding} attribute that gives the encoding used
1193by the file; Unicode strings written to the file will be automatically
1194converted to bytes using the given encoding.
1195
Andrew M. Kuchlingb60ea3f2002-11-15 14:37:10 +00001196\item The method resolution order used by new-style classes has
1197changed, though you'll only notice the difference if you have a really
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +00001198complicated inheritance hierarchy. Classic classes are unaffected by
1199this change. Python 2.2 originally used a topological sort of a
Andrew M. Kuchlingb60ea3f2002-11-15 14:37:10 +00001200class's ancestors, but 2.3 now uses the C3 algorithm as described in
Andrew M. Kuchling6f429c32002-11-19 13:09:00 +00001201the paper \ulink{``A Monotonic Superclass Linearization for
1202Dylan''}{http://www.webcom.com/haahr/dylan/linearization-oopsla96.html}.
Andrew M. Kuchlingc1dd1742003-01-13 13:59:22 +00001203To understand the motivation for this change,
1204read Michele Simionato's article
Fred Drake693aea22003-02-07 14:52:18 +00001205\ulink{``Python 2.3 Method Resolution Order''}
Andrew M. Kuchlingb8a39052003-02-07 20:22:33 +00001206 {http://www.python.org/2.3/mro.html}, or
Andrew M. Kuchlingc1dd1742003-01-13 13:59:22 +00001207read the thread on python-dev starting with the message at
Andrew M. Kuchlingb60ea3f2002-11-15 14:37:10 +00001208\url{http://mail.python.org/pipermail/python-dev/2002-October/029035.html}.
1209Samuele Pedroni first pointed out the problem and also implemented the
1210fix by coding the C3 algorithm.
1211
Andrew M. Kuchlingdcfd8252002-09-13 22:21:42 +00001212\item Python runs multithreaded programs by switching between threads
1213after executing N bytecodes. The default value for N has been
1214increased from 10 to 100 bytecodes, speeding up single-threaded
1215applications by reducing the switching overhead. Some multithreaded
1216applications may suffer slower response time, but that's easily fixed
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001217by setting the limit back to a lower number using
Andrew M. Kuchlingdcfd8252002-09-13 22:21:42 +00001218\function{sys.setcheckinterval(\var{N})}.
Andrew M. Kuchlingc760c6c2003-07-16 20:12:33 +00001219The limit can be retrieved with the new
1220\function{sys.getcheckinterval()} function.
Andrew M. Kuchlingdcfd8252002-09-13 22:21:42 +00001221
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001222\item One minor but far-reaching change is that the names of extension
1223types defined by the modules included with Python now contain the
Fred Drake5c4cf152002-11-13 14:59:06 +00001224module and a \character{.} in front of the type name. For example, in
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001225Python 2.2, if you created a socket and printed its
1226\member{__class__}, you'd get this output:
1227
1228\begin{verbatim}
1229>>> s = socket.socket()
1230>>> s.__class__
1231<type 'socket'>
1232\end{verbatim}
1233
1234In 2.3, you get this:
1235\begin{verbatim}
1236>>> s.__class__
1237<type '_socket.socket'>
1238\end{verbatim}
1239
Michael W. Hudson96bc3b42002-11-26 14:48:23 +00001240\item One of the noted incompatibilities between old- and new-style
1241 classes has been removed: you can now assign to the
1242 \member{__name__} and \member{__bases__} attributes of new-style
1243 classes. There are some restrictions on what can be assigned to
1244 \member{__bases__} along the lines of those relating to assigning to
1245 an instance's \member{__class__} attribute.
1246
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001247\end{itemize}
1248
1249
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001250%======================================================================
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001251\subsection{String Changes}
1252
1253\begin{itemize}
1254
Fred Drakeaac8c582003-01-17 22:50:10 +00001255\item The \keyword{in} operator now works differently for strings.
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001256Previously, when evaluating \code{\var{X} in \var{Y}} where \var{X}
1257and \var{Y} are strings, \var{X} could only be a single character.
1258That's now changed; \var{X} can be a string of any length, and
1259\code{\var{X} in \var{Y}} will return \constant{True} if \var{X} is a
1260substring of \var{Y}. If \var{X} is the empty string, the result is
1261always \constant{True}.
1262
1263\begin{verbatim}
1264>>> 'ab' in 'abcd'
1265True
1266>>> 'ad' in 'abcd'
1267False
1268>>> '' in 'abcd'
1269True
1270\end{verbatim}
1271
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001272Note that this doesn't tell you where the substring starts; if you
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +00001273need that information, use the \method{find()} string method.
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001274
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001275\item The \method{strip()}, \method{lstrip()}, and \method{rstrip()}
1276string methods now have an optional argument for specifying the
1277characters to strip. The default is still to remove all whitespace
1278characters:
1279
1280\begin{verbatim}
1281>>> ' abc '.strip()
1282'abc'
1283>>> '><><abc<><><>'.strip('<>')
1284'abc'
1285>>> '><><abc<><><>\n'.strip('<>')
1286'abc<><><>\n'
1287>>> u'\u4000\u4001abc\u4000'.strip(u'\u4000')
1288u'\u4001abc'
1289>>>
1290\end{verbatim}
1291
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001292(Suggested by Simon Brunning and implemented by Walter D\"orwald.)
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00001293
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001294\item The \method{startswith()} and \method{endswith()}
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001295string methods now accept negative numbers for the \var{start} and \var{end}
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001296parameters.
1297
1298\item Another new string method is \method{zfill()}, originally a
1299function in the \module{string} module. \method{zfill()} pads a
1300numeric string with zeros on the left until it's the specified width.
1301Note that the \code{\%} operator is still more flexible and powerful
1302than \method{zfill()}.
1303
1304\begin{verbatim}
1305>>> '45'.zfill(4)
1306'0045'
1307>>> '12345'.zfill(4)
1308'12345'
1309>>> 'goofy'.zfill(6)
1310'0goofy'
1311\end{verbatim}
1312
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00001313(Contributed by Walter D\"orwald.)
1314
Fred Drake5c4cf152002-11-13 14:59:06 +00001315\item A new type object, \class{basestring}, has been added.
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001316 Both 8-bit strings and Unicode strings inherit from this type, so
1317 \code{isinstance(obj, basestring)} will return \constant{True} for
1318 either kind of string. It's a completely abstract type, so you
1319 can't create \class{basestring} instances.
1320
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001321\item Interned strings are no longer immortal and will now be
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001322garbage-collected in the usual way when the only reference to them is
1323from the internal dictionary of interned strings. (Implemented by
1324Oren Tirosh.)
1325
1326\end{itemize}
1327
1328
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001329%======================================================================
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001330\subsection{Optimizations}
1331
1332\begin{itemize}
1333
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001334\item The creation of new-style class instances has been made much
1335faster; they're now faster than classic classes!
1336
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001337\item The \method{sort()} method of list objects has been extensively
1338rewritten by Tim Peters, and the implementation is significantly
1339faster.
1340
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001341\item Multiplication of large long integers is now much faster thanks
1342to an implementation of Karatsuba multiplication, an algorithm that
1343scales better than the O(n*n) required for the grade-school
1344multiplication algorithm. (Original patch by Christopher A. Craig,
1345and significantly reworked by Tim Peters.)
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001346
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001347\item The \code{SET_LINENO} opcode is now gone. This may provide a
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001348small speed increase, depending on your compiler's idiosyncrasies.
1349See section~\ref{section-other} for a longer explanation.
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001350(Removed by Michael Hudson.)
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001351
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001352\item \function{xrange()} objects now have their own iterator, making
1353\code{for i in xrange(n)} slightly faster than
1354\code{for i in range(n)}. (Patch by Raymond Hettinger.)
1355
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001356\item A number of small rearrangements have been made in various
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001357hotspots to improve performance, such as inlining a function or removing
1358some code. (Implemented mostly by GvR, but lots of people have
1359contributed single changes.)
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001360
1361\end{itemize}
Neal Norwitzd68f5172002-05-29 15:54:55 +00001362
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001363The net result of the 2.3 optimizations is that Python 2.3 runs the
1364pystone benchmark around 25\% faster than Python 2.2.
1365
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001366
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001367%======================================================================
Andrew M. Kuchlingef893fe2003-01-06 20:04:17 +00001368\section{New, Improved, and Deprecated Modules}
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00001369
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001370As usual, Python's standard library received a number of enhancements and
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001371bug fixes. Here's a partial list of the most notable changes, sorted
1372alphabetically by module name. Consult the
1373\file{Misc/NEWS} file in the source tree for a more
1374complete list of changes, or look through the CVS logs for all the
1375details.
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00001376
1377\begin{itemize}
1378
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001379\item The \module{array} module now supports arrays of Unicode
Fred Drake5c4cf152002-11-13 14:59:06 +00001380characters using the \character{u} format character. Arrays also now
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001381support using the \code{+=} assignment operator to add another array's
1382contents, and the \code{*=} assignment operator to repeat an array.
1383(Contributed by Jason Orendorff.)
1384
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001385\item The \module{bsddb} module has been replaced by version 4.1.1
Andrew M. Kuchling669249e2002-11-19 13:05:33 +00001386of the \ulink{PyBSDDB}{http://pybsddb.sourceforge.net} package,
1387providing a more complete interface to the transactional features of
1388the BerkeleyDB library.
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001389
Andrew M. Kuchling669249e2002-11-19 13:05:33 +00001390The old version of the module has been renamed to
1391\module{bsddb185} and is no longer built automatically; you'll
1392have to edit \file{Modules/Setup} to enable it. Note that the new
1393\module{bsddb} package is intended to be compatible with the
1394old module, so be sure to file bugs if you discover any
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001395incompatibilities. When upgrading to Python 2.3, if the new interpreter is compiled
1396with a new version of
Skip Montanaro959c7722003-03-07 15:45:15 +00001397the underlying BerkeleyDB library, you will almost certainly have to
1398convert your database files to the new version. You can do this
1399fairly easily with the new scripts \file{db2pickle.py} and
1400\file{pickle2db.py} which you will find in the distribution's
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001401\file{Tools/scripts} directory. If you've already been using the PyBSDDB
Andrew M. Kuchlinge36b6902003-04-19 15:38:47 +00001402package and importing it as \module{bsddb3}, you will have to change your
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001403\code{import} statements to import it as \module{bsddb}.
Andrew M. Kuchlinge36b6902003-04-19 15:38:47 +00001404
1405\item The new \module{bz2} module is an interface to the bz2 data
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001406compression library. bz2-compressed data is usually smaller than
1407corresponding \module{zlib}-compressed data. (Contributed by Gustavo Niemeyer.)
Andrew M. Kuchling669249e2002-11-19 13:05:33 +00001408
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001409\item A set of standard date/type types has been added in the new \module{datetime}
1410module. See the following section for more details.
1411
Fred Drake5c4cf152002-11-13 14:59:06 +00001412\item The Distutils \class{Extension} class now supports
1413an extra constructor argument named \var{depends} for listing
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001414additional source files that an extension depends on. This lets
1415Distutils recompile the module if any of the dependency files are
Fred Drake5c4cf152002-11-13 14:59:06 +00001416modified. For example, if \file{sampmodule.c} includes the header
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001417file \file{sample.h}, you would create the \class{Extension} object like
1418this:
1419
1420\begin{verbatim}
1421ext = Extension("samp",
1422 sources=["sampmodule.c"],
1423 depends=["sample.h"])
1424\end{verbatim}
1425
1426Modifying \file{sample.h} would then cause the module to be recompiled.
1427(Contributed by Jeremy Hylton.)
1428
Andrew M. Kuchlingdc3f7e12002-11-04 20:05:10 +00001429\item Other minor changes to Distutils:
1430it now checks for the \envvar{CC}, \envvar{CFLAGS}, \envvar{CPP},
1431\envvar{LDFLAGS}, and \envvar{CPPFLAGS} environment variables, using
1432them to override the settings in Python's configuration (contributed
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +00001433by Robert Weber).
Andrew M. Kuchlingdc3f7e12002-11-04 20:05:10 +00001434
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001435\item Previously the \module{doctest} module would only search the
1436docstrings of public methods and functions for test cases, but it now
1437also examines private ones as well. The \function{DocTestSuite(}
1438function creates a \class{unittest.TestSuite} object from a set of
1439\module{doctest} tests.
1440
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001441\item The new \function{gc.get_referents(\var{object})} function returns a
1442list of all the objects referenced by \var{object}.
1443
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001444\item The \module{getopt} module gained a new function,
1445\function{gnu_getopt()}, that supports the same arguments as the existing
Fred Drake5c4cf152002-11-13 14:59:06 +00001446\function{getopt()} function but uses GNU-style scanning mode.
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001447The existing \function{getopt()} stops processing options as soon as a
1448non-option argument is encountered, but in GNU-style mode processing
1449continues, meaning that options and arguments can be mixed. For
1450example:
1451
1452\begin{verbatim}
1453>>> getopt.getopt(['-f', 'filename', 'output', '-v'], 'f:v')
1454([('-f', 'filename')], ['output', '-v'])
1455>>> getopt.gnu_getopt(['-f', 'filename', 'output', '-v'], 'f:v')
1456([('-f', 'filename'), ('-v', '')], ['output'])
1457\end{verbatim}
1458
1459(Contributed by Peter \AA{strand}.)
1460
1461\item The \module{grp}, \module{pwd}, and \module{resource} modules
Fred Drake5c4cf152002-11-13 14:59:06 +00001462now return enhanced tuples:
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001463
1464\begin{verbatim}
1465>>> import grp
1466>>> g = grp.getgrnam('amk')
1467>>> g.gr_name, g.gr_gid
1468('amk', 500)
1469\end{verbatim}
1470
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001471\item The \module{gzip} module can now handle files exceeding 2~Gb.
1472
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001473\item The new \module{heapq} module contains an implementation of a
1474heap queue algorithm. A heap is an array-like data structure that
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001475keeps items in a partially sorted order such that, for every index
1476\var{k}, \code{heap[\var{k}] <= heap[2*\var{k}+1]} and
1477\code{heap[\var{k}] <= heap[2*\var{k}+2]}. This makes it quick to
1478remove the smallest item, and inserting a new item while maintaining
1479the heap property is O(lg~n). (See
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001480\url{http://www.nist.gov/dads/HTML/priorityque.html} for more
1481information about the priority queue data structure.)
1482
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001483The \module{heapq} module provides \function{heappush()} and
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001484\function{heappop()} functions for adding and removing items while
1485maintaining the heap property on top of some other mutable Python
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001486sequence type. Here's an example that uses a Python list:
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001487
1488\begin{verbatim}
1489>>> import heapq
1490>>> heap = []
1491>>> for item in [3, 7, 5, 11, 1]:
1492... heapq.heappush(heap, item)
1493...
1494>>> heap
1495[1, 3, 5, 11, 7]
1496>>> heapq.heappop(heap)
14971
1498>>> heapq.heappop(heap)
14993
1500>>> heap
1501[5, 7, 11]
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001502\end{verbatim}
1503
1504(Contributed by Kevin O'Connor.)
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001505
Andrew M. Kuchling87cebbf2003-01-03 16:24:28 +00001506\item The \module{imaplib} module now supports IMAP over SSL.
1507(Contributed by Piers Lauder and Tino Lange.)
1508
Andrew M. Kuchling41c3e002003-03-02 02:13:52 +00001509\item The \module{itertools} contains a number of useful functions for
1510use with iterators, inspired by various functions provided by the ML
1511and Haskell languages. For example,
1512\code{itertools.ifilter(predicate, iterator)} returns all elements in
1513the iterator for which the function \function{predicate()} returns
Andrew M. Kuchling563389f2003-03-02 02:31:58 +00001514\constant{True}, and \code{itertools.repeat(obj, \var{N})} returns
Andrew M. Kuchling41c3e002003-03-02 02:13:52 +00001515\code{obj} \var{N} times. There are a number of other functions in
1516the module; see the \ulink{package's reference
1517documentation}{../lib/module-itertools.html} for details.
Raymond Hettinger5284b442003-03-09 07:19:38 +00001518(Contributed by Raymond Hettinger.)
Fred Drakecade7132003-02-19 16:08:08 +00001519
Fred Drake5c4cf152002-11-13 14:59:06 +00001520\item Two new functions in the \module{math} module,
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001521\function{degrees(\var{rads})} and \function{radians(\var{degs})},
Fred Drake5c4cf152002-11-13 14:59:06 +00001522convert between radians and degrees. Other functions in the
Andrew M. Kuchling8e5b53b2002-12-15 20:17:38 +00001523\module{math} module such as \function{math.sin()} and
1524\function{math.cos()} have always required input values measured in
1525radians. Also, an optional \var{base} argument was added to
1526\function{math.log()} to make it easier to compute logarithms for
1527bases other than \code{e} and \code{10}. (Contributed by Raymond
1528Hettinger.)
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001529
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001530\item Several new POSIX functions (\function{getpgid()}, \function{killpg()},
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +00001531\function{lchown()}, \function{loadavg()}, \function{major()}, \function{makedev()},
1532\function{minor()}, and \function{mknod()}) were added to the
Andrew M. Kuchlingc309cca2002-10-10 16:04:08 +00001533\module{posix} module that underlies the \module{os} module.
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +00001534(Contributed by Gustavo Niemeyer, Geert Jansen, and Denis S. Otkidach.)
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001535
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001536\item In the \module{os} module, the \function{*stat()} family of
1537functions can now report fractions of a second in a timestamp. Such
1538time stamps are represented as floats, similar to
1539the value returned by \function{time.time()}.
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001540
1541During testing, it was found that some applications will break if time
1542stamps are floats. For compatibility, when using the tuple interface
1543of the \class{stat_result} time stamps will be represented as integers.
1544When using named fields (a feature first introduced in Python 2.2),
1545time stamps are still represented as integers, unless
1546\function{os.stat_float_times()} is invoked to enable float return
1547values:
1548
1549\begin{verbatim}
1550>>> os.stat("/tmp").st_mtime
15511034791200
1552>>> os.stat_float_times(True)
1553>>> os.stat("/tmp").st_mtime
15541034791200.6335014
1555\end{verbatim}
1556
1557In Python 2.4, the default will change to always returning floats.
1558
1559Application developers should enable this feature only if all their
1560libraries work properly when confronted with floating point time
1561stamps, or if they use the tuple API. If used, the feature should be
1562activated on an application level instead of trying to enable it on a
1563per-use basis.
1564
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001565\item The \module{optparse} module contains a new parser for command-line arguments
1566that can convert option values to a particular Python type
1567and will automatically generate a usage message. See the following section for
1568more details.
1569
Andrew M. Kuchling53262572002-12-01 14:00:21 +00001570\item The old and never-documented \module{linuxaudiodev} module has
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001571been deprecated, and a new version named \module{ossaudiodev} has been
1572added. The module was renamed because the OSS sound drivers can be
1573used on platforms other than Linux, and the interface has also been
1574tidied and brought up to date in various ways. (Contributed by Greg
Greg Wardaa1d3aa2003-01-03 18:03:21 +00001575Ward and Nicholas FitzRoy-Dale.)
Andrew M. Kuchling53262572002-12-01 14:00:21 +00001576
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001577\item The new \module{platform} module contains a number of functions
1578that try to determine various properties of the platform you're
1579running on. There are functions for getting the architecture, CPU
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001580type, the Windows OS version, and even the Linux distribution version.
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001581(Contributed by Marc-Andr\'e Lemburg.)
1582
Fred Drake5c4cf152002-11-13 14:59:06 +00001583\item The parser objects provided by the \module{pyexpat} module
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001584can now optionally buffer character data, resulting in fewer calls to
1585your character data handler and therefore faster performance. Setting
Fred Drake5c4cf152002-11-13 14:59:06 +00001586the parser object's \member{buffer_text} attribute to \constant{True}
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001587will enable buffering.
1588
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001589\item The \function{sample(\var{population}, \var{k})} function was
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001590added to the \module{random} module. \var{population} is a sequence or
1591\class{xrange} object containing the elements of a population, and
1592\function{sample()} chooses \var{k} elements from the population without
1593replacing chosen elements. \var{k} can be any value up to
1594\code{len(\var{population})}. For example:
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001595
1596\begin{verbatim}
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001597>>> days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'St', 'Sn']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001598>>> random.sample(days, 3) # Choose 3 elements
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001599['St', 'Sn', 'Th']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001600>>> random.sample(days, 7) # Choose 7 elements
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001601['Tu', 'Th', 'Mo', 'We', 'St', 'Fr', 'Sn']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001602>>> random.sample(days, 7) # Choose 7 again
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001603['We', 'Mo', 'Sn', 'Fr', 'Tu', 'St', 'Th']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001604>>> random.sample(days, 8) # Can't choose eight
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001605Traceback (most recent call last):
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +00001606 File "<stdin>", line 1, in ?
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001607 File "random.py", line 414, in sample
1608 raise ValueError, "sample larger than population"
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001609ValueError: sample larger than population
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001610>>> random.sample(xrange(1,10000,2), 10) # Choose ten odd nos. under 10000
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001611[3407, 3805, 1505, 7023, 2401, 2267, 9733, 3151, 8083, 9195]
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001612\end{verbatim}
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001613
1614The \module{random} module now uses a new algorithm, the Mersenne
1615Twister, implemented in C. It's faster and more extensively studied
1616than the previous algorithm.
1617
1618(All changes contributed by Raymond Hettinger.)
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001619
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001620\item The \module{readline} module also gained a number of new
1621functions: \function{get_history_item()},
1622\function{get_current_history_length()}, and \function{redisplay()}.
1623
Andrew M. Kuchlingef893fe2003-01-06 20:04:17 +00001624\item The \module{rexec} and \module{Bastion} modules have been
1625declared dead, and attempts to import them will fail with a
1626\exception{RuntimeError}. New-style classes provide new ways to break
1627out of the restricted execution environment provided by
1628\module{rexec}, and no one has interest in fixing them or time to do
1629so. If you have applications using \module{rexec}, rewrite them to
1630use something else.
1631
1632(Sticking with Python 2.2 or 2.1 will not make your applications any
Andrew M. Kuchling13b4c412003-04-24 13:23:43 +00001633safer because there are known bugs in the \module{rexec} module in
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001634those versions. To repeat: if you're using \module{rexec}, stop using
Andrew M. Kuchlingef893fe2003-01-06 20:04:17 +00001635it immediately.)
1636
Andrew M. Kuchling13b4c412003-04-24 13:23:43 +00001637\item The \module{rotor} module has been deprecated because the
1638 algorithm it uses for encryption is not believed to be secure. If
1639 you need encryption, use one of the several AES Python modules
1640 that are available separately.
1641
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001642\item The \module{shutil} module gained a \function{move(\var{src},
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001643\var{dest})} function that recursively moves a file or directory to a new
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001644location.
1645
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001646\item Support for more advanced POSIX signal handling was added
Michael W. Hudson43ed43b2003-03-13 13:56:53 +00001647to the \module{signal} but then removed again as it proved impossible
1648to make it work reliably across platforms.
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001649
1650\item The \module{socket} module now supports timeouts. You
1651can call the \method{settimeout(\var{t})} method on a socket object to
1652set a timeout of \var{t} seconds. Subsequent socket operations that
1653take longer than \var{t} seconds to complete will abort and raise a
Andrew M. Kuchlingc760c6c2003-07-16 20:12:33 +00001654\exception{socket.timeout} exception.
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001655
1656The original timeout implementation was by Tim O'Malley. Michael
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001657Gilfix integrated it into the Python \module{socket} module and
1658shepherded it through a lengthy review. After the code was checked
1659in, Guido van~Rossum rewrote parts of it. (This is a good example of
1660a collaborative development process in action.)
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001661
Mark Hammond8af50bc2002-12-03 06:13:35 +00001662\item On Windows, the \module{socket} module now ships with Secure
Michael W. Hudson065f5fa2003-02-10 19:24:50 +00001663Sockets Layer (SSL) support.
Mark Hammond8af50bc2002-12-03 06:13:35 +00001664
Andrew M. Kuchling563389f2003-03-02 02:31:58 +00001665\item The value of the C \constant{PYTHON_API_VERSION} macro is now
1666exposed at the Python level as \code{sys.api_version}. The current
1667exception can be cleared by calling the new \function{sys.exc_clear()}
1668function.
Andrew M. Kuchlingdcfd8252002-09-13 22:21:42 +00001669
Andrew M. Kuchling674b0bf2003-01-07 00:07:19 +00001670\item The new \module{tarfile} module
Neal Norwitz55d555f2003-01-08 05:27:42 +00001671allows reading from and writing to \program{tar}-format archive files.
Andrew M. Kuchling674b0bf2003-01-07 00:07:19 +00001672(Contributed by Lars Gust\"abel.)
1673
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001674\item The new \module{textwrap} module contains functions for wrapping
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001675strings containing paragraphs of text. The \function{wrap(\var{text},
1676\var{width})} function takes a string and returns a list containing
1677the text split into lines of no more than the chosen width. The
1678\function{fill(\var{text}, \var{width})} function returns a single
1679string, reformatted to fit into lines no longer than the chosen width.
1680(As you can guess, \function{fill()} is built on top of
1681\function{wrap()}. For example:
1682
1683\begin{verbatim}
1684>>> import textwrap
1685>>> paragraph = "Not a whit, we defy augury: ... more text ..."
1686>>> textwrap.wrap(paragraph, 60)
Fred Drake5c4cf152002-11-13 14:59:06 +00001687["Not a whit, we defy augury: there's a special providence in",
1688 "the fall of a sparrow. If it be now, 'tis not to come; if it",
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001689 ...]
1690>>> print textwrap.fill(paragraph, 35)
1691Not a whit, we defy augury: there's
1692a special providence in the fall of
1693a sparrow. If it be now, 'tis not
1694to come; if it be not to come, it
1695will be now; if it be not now, yet
1696it will come: the readiness is all.
Fred Drake5c4cf152002-11-13 14:59:06 +00001697>>>
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001698\end{verbatim}
1699
1700The module also contains a \class{TextWrapper} class that actually
Fred Drake5c4cf152002-11-13 14:59:06 +00001701implements the text wrapping strategy. Both the
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001702\class{TextWrapper} class and the \function{wrap()} and
1703\function{fill()} functions support a number of additional keyword
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +00001704arguments for fine-tuning the formatting; consult the \ulink{module's
1705documentation}{../lib/module-textwrap.html} for details.
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001706(Contributed by Greg Ward.)
1707
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001708\item The \module{thread} and \module{threading} modules now have
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001709companion modules, \module{dummy_thread} and \module{dummy_threading},
1710that provide a do-nothing implementation of the \module{thread}
1711module's interface for platforms where threads are not supported. The
1712intention is to simplify thread-aware modules (ones that \emph{don't}
1713rely on threads to run) by putting the following code at the top:
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001714
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001715\begin{verbatim}
1716try:
1717 import threading as _threading
1718except ImportError:
1719 import dummy_threading as _threading
1720\end{verbatim}
1721
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001722In this example, \module{_threading} is used as the module name to make
1723it clear that the module being used is not necessarily the actual
1724\module{threading} module. Code can call functions and use classes in
1725\module{_threading} whether or not threads are supported, avoiding an
1726\keyword{if} statement and making the code slightly clearer. This
1727module will not magically make multithreaded code run without threads;
1728code that waits for another thread to return or to do something will
1729simply hang forever.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001730
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001731\item The \module{time} module's \function{strptime()} function has
Fred Drake5c4cf152002-11-13 14:59:06 +00001732long been an annoyance because it uses the platform C library's
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001733\function{strptime()} implementation, and different platforms
1734sometimes have odd bugs. Brett Cannon contributed a portable
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001735implementation that's written in pure Python and should behave
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001736identically on all platforms.
1737
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +00001738\item The new \module{timeit} module helps measure how long snippets
1739of Python code take to execute. The \file{timeit.py} file can be run
1740directly from the command line, or the module's \class{Timer} class
1741can be imported and used directly. Here's a short example that
1742figures out whether it's faster to convert an 8-bit string to Unicode
1743by appending an empty Unicode string to it or by using the
1744\function{unicode()} function:
1745
1746\begin{verbatim}
1747import timeit
1748
1749timer1 = timeit.Timer('unicode("abc")')
1750timer2 = timeit.Timer('"abc" + u""')
1751
1752# Run three trials
1753print timer1.repeat(repeat=3, number=100000)
1754print timer2.repeat(repeat=3, number=100000)
1755
1756# On my laptop this outputs:
1757# [0.36831796169281006, 0.37441694736480713, 0.35304892063140869]
1758# [0.17574405670166016, 0.18193507194519043, 0.17565798759460449]
1759\end{verbatim}
1760
Raymond Hettinger8ccf4d72003-07-10 15:48:33 +00001761\item The \module{Tix} module has received various bug fixes and
Andrew M. Kuchlingef893fe2003-01-06 20:04:17 +00001762updates for the current version of the Tix package.
1763
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001764\item The \module{Tkinter} module now works with a thread-enabled
1765version of Tcl. Tcl's threading model requires that widgets only be
1766accessed from the thread in which they're created; accesses from
1767another thread can cause Tcl to panic. For certain Tcl interfaces,
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001768\module{Tkinter} will now automatically avoid this
1769when a widget is accessed from a different thread by marshalling a
1770command, passing it to the correct thread, and waiting for the
1771results. Other interfaces can't be handled automatically but
1772\module{Tkinter} will now raise an exception on such an access so that
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001773you can at least find out about the problem. See
Fred Drakeb876bcc2003-04-30 15:03:46 +00001774\url{http://mail.python.org/pipermail/python-dev/2002-December/031107.html} %
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001775for a more detailed explanation of this change. (Implemented by
Andrew M. Kuchlingfcf6b3e2003-05-07 17:00:35 +00001776Martin von~L\"owis.)
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001777
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001778\item Calling Tcl methods through \module{_tkinter} no longer
1779returns only strings. Instead, if Tcl returns other objects those
1780objects are converted to their Python equivalent, if one exists, or
1781wrapped with a \class{_tkinter.Tcl_Obj} object if no Python equivalent
Raymond Hettinger45bda572002-12-14 20:20:45 +00001782exists. This behavior can be controlled through the
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001783\method{wantobjects()} method of \class{tkapp} objects.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001784
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001785When using \module{_tkinter} through the \module{Tkinter} module (as
1786most Tkinter applications will), this feature is always activated. It
1787should not cause compatibility problems, since Tkinter would always
1788convert string results to Python types where possible.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001789
Raymond Hettinger45bda572002-12-14 20:20:45 +00001790If any incompatibilities are found, the old behavior can be restored
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001791by setting the \member{wantobjects} variable in the \module{Tkinter}
1792module to false before creating the first \class{tkapp} object.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001793
1794\begin{verbatim}
1795import Tkinter
Martin v. Löwis8c8aa5d2002-11-26 21:39:48 +00001796Tkinter.wantobjects = 0
Martin v. Löwis39b48522002-11-26 09:47:25 +00001797\end{verbatim}
1798
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001799Any breakage caused by this change should be reported as a bug.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001800
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001801\item The \module{UserDict} module has a new \class{DictMixin} class which
1802defines all dictionary methods for classes that already have a minimum
1803mapping interface. This greatly simplifies writing classes that need
1804to be substitutable for dictionaries, such as the classes in
1805the \module{shelve} module.
1806
1807Adding the mix-in as a superclass provides the full dictionary
1808interface whenever the class defines \method{__getitem__},
1809\method{__setitem__}, \method{__delitem__}, and \method{keys}.
1810For example:
1811
1812\begin{verbatim}
1813>>> import UserDict
1814>>> class SeqDict(UserDict.DictMixin):
1815... """Dictionary lookalike implemented with lists."""
1816... def __init__(self):
1817... self.keylist = []
1818... self.valuelist = []
1819... def __getitem__(self, key):
1820... try:
1821... i = self.keylist.index(key)
1822... except ValueError:
1823... raise KeyError
1824... return self.valuelist[i]
1825... def __setitem__(self, key, value):
1826... try:
1827... i = self.keylist.index(key)
1828... self.valuelist[i] = value
1829... except ValueError:
1830... self.keylist.append(key)
1831... self.valuelist.append(value)
1832... def __delitem__(self, key):
1833... try:
1834... i = self.keylist.index(key)
1835... except ValueError:
1836... raise KeyError
1837... self.keylist.pop(i)
1838... self.valuelist.pop(i)
1839... def keys(self):
1840... return list(self.keylist)
1841...
1842>>> s = SeqDict()
1843>>> dir(s) # See that other dictionary methods are implemented
1844['__cmp__', '__contains__', '__delitem__', '__doc__', '__getitem__',
1845 '__init__', '__iter__', '__len__', '__module__', '__repr__',
1846 '__setitem__', 'clear', 'get', 'has_key', 'items', 'iteritems',
1847 'iterkeys', 'itervalues', 'keylist', 'keys', 'pop', 'popitem',
1848 'setdefault', 'update', 'valuelist', 'values']
1849\end{verbatim}
1850
1851(Contributed by Raymond Hettinger.)
1852
1853
Andrew M. Kuchlinge36b6902003-04-19 15:38:47 +00001854\item The DOM implementation
1855in \module{xml.dom.minidom} can now generate XML output in a
1856particular encoding by providing an optional encoding argument to
1857the \method{toxml()} and \method{toprettyxml()} methods of DOM nodes.
1858
1859\item The new \module{DocXMLRPCServer} module allows writing
1860self-documenting XML-RPC servers. Run it in demo mode (as a program)
1861to see it in action. Pointing the Web browser to the RPC server
1862produces pydoc-style documentation; pointing xmlrpclib to the
1863server allows invoking the actual methods.
1864(Contributed by Brian Quinlan.)
1865
Martin v. Löwis2548c732003-04-18 10:39:54 +00001866\item Support for internationalized domain names (RFCs 3454, 3490,
18673491, and 3492) has been added. The ``idna'' encoding can be used
1868to convert between a Unicode domain name and the ASCII-compatible
Andrew M. Kuchlinge36b6902003-04-19 15:38:47 +00001869encoding (ACE) of that name.
Martin v. Löwis2548c732003-04-18 10:39:54 +00001870
Martin v. Löwisfaf71ea2003-04-18 21:48:56 +00001871\begin{alltt}
Fred Drake15b3dba2003-07-16 04:00:14 +00001872>{}>{}> u"www.Alliancefran\c caise.nu".encode("idna")
Martin v. Löwis2548c732003-04-18 10:39:54 +00001873'www.xn--alliancefranaise-npb.nu'
Martin v. Löwisfaf71ea2003-04-18 21:48:56 +00001874\end{alltt}
Martin v. Löwis2548c732003-04-18 10:39:54 +00001875
Andrew M. Kuchlinge36b6902003-04-19 15:38:47 +00001876The \module{socket} module has also been extended to transparently
1877convert Unicode hostnames to the ACE version before passing them to
1878the C library. Modules that deal with hostnames such as
1879\module{httplib} and \module{ftplib}) also support Unicode host names;
1880\module{httplib} also sends HTTP \samp{Host} headers using the ACE
1881version of the domain name. \module{urllib} supports Unicode URLs
1882with non-ASCII host names as long as the \code{path} part of the URL
1883is ASCII only.
Martin v. Löwis2548c732003-04-18 10:39:54 +00001884
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001885To implement this change, the \module{stringprep} module, the
1886\code{mkstringprep} tool and the \code{punycode} encoding have been added.
Martin v. Löwis281b2c62003-04-18 21:04:39 +00001887
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00001888\end{itemize}
1889
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00001890
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001891%======================================================================
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001892\subsection{Date/Time Type}
1893
1894Date and time types suitable for expressing timestamps were added as
1895the \module{datetime} module. The types don't support different
1896calendars or many fancy features, and just stick to the basics of
1897representing time.
1898
1899The three primary types are: \class{date}, representing a day, month,
1900and year; \class{time}, consisting of hour, minute, and second; and
1901\class{datetime}, which contains all the attributes of both
Andrew M. Kuchlingc71bb972003-03-21 17:23:07 +00001902\class{date} and \class{time}. There's also a
1903\class{timedelta} class representing differences between two points
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001904in time, and time zone logic is implemented by classes inheriting from
1905the abstract \class{tzinfo} class.
1906
1907You can create instances of \class{date} and \class{time} by either
1908supplying keyword arguments to the appropriate constructor,
1909e.g. \code{datetime.date(year=1972, month=10, day=15)}, or by using
Andrew M. Kuchlingc71bb972003-03-21 17:23:07 +00001910one of a number of class methods. For example, the \method{date.today()}
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001911class method returns the current local date.
1912
1913Once created, instances of the date/time classes are all immutable.
1914There are a number of methods for producing formatted strings from
1915objects:
1916
1917\begin{verbatim}
1918>>> import datetime
1919>>> now = datetime.datetime.now()
1920>>> now.isoformat()
1921'2002-12-30T21:27:03.994956'
1922>>> now.ctime() # Only available on date, datetime
1923'Mon Dec 30 21:27:03 2002'
Raymond Hettingeree1bded2003-01-17 16:20:23 +00001924>>> now.strftime('%Y %d %b')
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001925'2002 30 Dec'
1926\end{verbatim}
1927
1928The \method{replace()} method allows modifying one or more fields
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001929of a \class{date} or \class{datetime} instance, returning a new instance:
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001930
1931\begin{verbatim}
1932>>> d = datetime.datetime.now()
1933>>> d
1934datetime.datetime(2002, 12, 30, 22, 15, 38, 827738)
1935>>> d.replace(year=2001, hour = 12)
1936datetime.datetime(2001, 12, 30, 12, 15, 38, 827738)
1937>>>
1938\end{verbatim}
1939
1940Instances can be compared, hashed, and converted to strings (the
1941result is the same as that of \method{isoformat()}). \class{date} and
1942\class{datetime} instances can be subtracted from each other, and
Andrew M. Kuchlingc71bb972003-03-21 17:23:07 +00001943added to \class{timedelta} instances. The largest missing feature is
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001944that there's no standard library support for parsing strings and getting back a
Andrew M. Kuchlingc71bb972003-03-21 17:23:07 +00001945\class{date} or \class{datetime}.
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001946
1947For more information, refer to the \ulink{module's reference
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +00001948documentation}{../lib/module-datetime.html}.
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001949(Contributed by Tim Peters.)
1950
1951
1952%======================================================================
Andrew M. Kuchling8d177092003-05-13 14:26:54 +00001953\subsection{The optparse Module}
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001954
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001955The \module{getopt} module provides simple parsing of command-line
1956arguments. The new \module{optparse} module (originally named Optik)
1957provides more elaborate command-line parsing that follows the Unix
1958conventions, automatically creates the output for \longprogramopt{help},
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001959and can perform different actions for different options.
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001960
1961You start by creating an instance of \class{OptionParser} and telling
1962it what your program's options are.
1963
1964\begin{verbatim}
Andrew M. Kuchling7ee9b512003-02-18 00:48:23 +00001965import sys
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001966from optparse import OptionParser
1967
1968op = OptionParser()
1969op.add_option('-i', '--input',
1970 action='store', type='string', dest='input',
1971 help='set input filename')
1972op.add_option('-l', '--length',
1973 action='store', type='int', dest='length',
1974 help='set maximum length of output')
1975\end{verbatim}
1976
1977Parsing a command line is then done by calling the \method{parse_args()}
1978method.
1979
1980\begin{verbatim}
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001981options, args = op.parse_args(sys.argv[1:])
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001982print options
1983print args
1984\end{verbatim}
1985
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001986This returns an object containing all of the option values,
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001987and a list of strings containing the remaining arguments.
1988
1989Invoking the script with the various arguments now works as you'd
1990expect it to. Note that the length argument is automatically
1991converted to an integer.
1992
1993\begin{verbatim}
1994$ ./python opt.py -i data arg1
1995<Values at 0x400cad4c: {'input': 'data', 'length': None}>
1996['arg1']
1997$ ./python opt.py --input=data --length=4
1998<Values at 0x400cad2c: {'input': 'data', 'length': 4}>
Andrew M. Kuchling7ee9b512003-02-18 00:48:23 +00001999[]
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00002000$
2001\end{verbatim}
2002
2003The help message is automatically generated for you:
2004
2005\begin{verbatim}
2006$ ./python opt.py --help
2007usage: opt.py [options]
2008
2009options:
2010 -h, --help show this help message and exit
2011 -iINPUT, --input=INPUT
2012 set input filename
2013 -lLENGTH, --length=LENGTH
2014 set maximum length of output
2015$
2016\end{verbatim}
Andrew M. Kuchling669249e2002-11-19 13:05:33 +00002017% $ prevent Emacs tex-mode from getting confused
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00002018
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +00002019See the \ulink{module's documentation}{../lib/module-optparse.html}
2020for more details.
2021
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00002022Optik was written by Greg Ward, with suggestions from the readers of
2023the Getopt SIG.
2024
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00002025
2026%======================================================================
Andrew M. Kuchling8d177092003-05-13 14:26:54 +00002027\section{Pymalloc: A Specialized Object Allocator\label{section-pymalloc}}
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002028
Andrew M. Kuchlingc71bb972003-03-21 17:23:07 +00002029Pymalloc, a specialized object allocator written by Vladimir
2030Marangozov, was a feature added to Python 2.1. Pymalloc is intended
2031to be faster than the system \cfunction{malloc()} and to have less
2032memory overhead for allocation patterns typical of Python programs.
2033The allocator uses C's \cfunction{malloc()} function to get large
2034pools of memory and then fulfills smaller memory requests from these
2035pools.
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002036
2037In 2.1 and 2.2, pymalloc was an experimental feature and wasn't
Andrew M. Kuchlingc71bb972003-03-21 17:23:07 +00002038enabled by default; you had to explicitly enable it when compiling
2039Python by providing the
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002040\longprogramopt{with-pymalloc} option to the \program{configure}
2041script. In 2.3, pymalloc has had further enhancements and is now
2042enabled by default; you'll have to supply
2043\longprogramopt{without-pymalloc} to disable it.
2044
2045This change is transparent to code written in Python; however,
2046pymalloc may expose bugs in C extensions. Authors of C extension
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002047modules should test their code with pymalloc enabled,
2048because some incorrect code may cause core dumps at runtime.
2049
2050There's one particularly common error that causes problems. There are
2051a number of memory allocation functions in Python's C API that have
2052previously just been aliases for the C library's \cfunction{malloc()}
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002053and \cfunction{free()}, meaning that if you accidentally called
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002054mismatched functions the error wouldn't be noticeable. When the
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002055object allocator is enabled, these functions aren't aliases of
2056\cfunction{malloc()} and \cfunction{free()} any more, and calling the
2057wrong function to free memory may get you a core dump. For example,
2058if memory was allocated using \cfunction{PyObject_Malloc()}, it has to
2059be freed using \cfunction{PyObject_Free()}, not \cfunction{free()}. A
2060few modules included with Python fell afoul of this and had to be
2061fixed; doubtless there are more third-party modules that will have the
2062same problem.
2063
2064As part of this change, the confusing multiple interfaces for
2065allocating memory have been consolidated down into two API families.
2066Memory allocated with one family must not be manipulated with
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002067functions from the other family. There is one family for allocating
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002068chunks of memory and another family of functions specifically for
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002069allocating Python objects.
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002070
2071\begin{itemize}
2072 \item To allocate and free an undistinguished chunk of memory use
2073 the ``raw memory'' family: \cfunction{PyMem_Malloc()},
2074 \cfunction{PyMem_Realloc()}, and \cfunction{PyMem_Free()}.
2075
2076 \item The ``object memory'' family is the interface to the pymalloc
2077 facility described above and is biased towards a large number of
2078 ``small'' allocations: \cfunction{PyObject_Malloc},
2079 \cfunction{PyObject_Realloc}, and \cfunction{PyObject_Free}.
2080
2081 \item To allocate and free Python objects, use the ``object'' family
2082 \cfunction{PyObject_New()}, \cfunction{PyObject_NewVar()}, and
2083 \cfunction{PyObject_Del()}.
2084\end{itemize}
2085
2086Thanks to lots of work by Tim Peters, pymalloc in 2.3 also provides
2087debugging features to catch memory overwrites and doubled frees in
2088both extension modules and in the interpreter itself. To enable this
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002089support, compile a debugging version of the Python interpreter by
2090running \program{configure} with \longprogramopt{with-pydebug}.
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002091
2092To aid extension writers, a header file \file{Misc/pymemcompat.h} is
2093distributed with the source to Python 2.3 that allows Python
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002094extensions to use the 2.3 interfaces to memory allocation while
2095compiling against any version of Python since 1.5.2. You would copy
2096the file from Python's source distribution and bundle it with the
2097source of your extension.
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002098
2099\begin{seealso}
2100
2101\seeurl{http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Objects/obmalloc.c}
2102{For the full details of the pymalloc implementation, see
2103the comments at the top of the file \file{Objects/obmalloc.c} in the
2104Python source code. The above link points to the file within the
2105SourceForge CVS browser.}
2106
2107\end{seealso}
2108
2109
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00002110% ======================================================================
2111\section{Build and C API Changes}
2112
Andrew M. Kuchling3c305d92002-07-22 18:50:11 +00002113Changes to Python's build process and to the C API include:
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00002114
2115\begin{itemize}
2116
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002117\item The C-level interface to the garbage collector has been changed
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002118to make it easier to write extension types that support garbage
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002119collection and to debug misuses of the functions.
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002120Various functions have slightly different semantics, so a bunch of
2121functions had to be renamed. Extensions that use the old API will
2122still compile but will \emph{not} participate in garbage collection,
2123so updating them for 2.3 should be considered fairly high priority.
2124
2125To upgrade an extension module to the new API, perform the following
2126steps:
2127
2128\begin{itemize}
2129
2130\item Rename \cfunction{Py_TPFLAGS_GC} to \cfunction{PyTPFLAGS_HAVE_GC}.
2131
2132\item Use \cfunction{PyObject_GC_New} or \cfunction{PyObject_GC_NewVar} to
2133allocate objects, and \cfunction{PyObject_GC_Del} to deallocate them.
2134
2135\item Rename \cfunction{PyObject_GC_Init} to \cfunction{PyObject_GC_Track} and
2136\cfunction{PyObject_GC_Fini} to \cfunction{PyObject_GC_UnTrack}.
2137
2138\item Remove \cfunction{PyGC_HEAD_SIZE} from object size calculations.
2139
2140\item Remove calls to \cfunction{PyObject_AS_GC} and \cfunction{PyObject_FROM_GC}.
2141
2142\end{itemize}
2143
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002144\item The cycle detection implementation used by the garbage collection
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002145has proven to be stable, so it's now been made mandatory. You can no
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002146longer compile Python without it, and the
2147\longprogramopt{with-cycle-gc} switch to \program{configure} has been removed.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00002148
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002149\item Python can now optionally be built as a shared library
2150(\file{libpython2.3.so}) by supplying \longprogramopt{enable-shared}
Fred Drake5c4cf152002-11-13 14:59:06 +00002151when running Python's \program{configure} script. (Contributed by Ondrej
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +00002152Palkovsky.)
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +00002153
Michael W. Hudsondd32a912002-08-15 14:59:02 +00002154\item The \csimplemacro{DL_EXPORT} and \csimplemacro{DL_IMPORT} macros
2155are now deprecated. Initialization functions for Python extension
2156modules should now be declared using the new macro
Andrew M. Kuchling3c305d92002-07-22 18:50:11 +00002157\csimplemacro{PyMODINIT_FUNC}, while the Python core will generally
2158use the \csimplemacro{PyAPI_FUNC} and \csimplemacro{PyAPI_DATA}
2159macros.
Neal Norwitzbba23a82002-07-22 13:18:59 +00002160
Fred Drake5c4cf152002-11-13 14:59:06 +00002161\item The interpreter can be compiled without any docstrings for
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00002162the built-in functions and modules by supplying
Fred Drake5c4cf152002-11-13 14:59:06 +00002163\longprogramopt{without-doc-strings} to the \program{configure} script.
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00002164This makes the Python executable about 10\% smaller, but will also
2165mean that you can't get help for Python's built-ins. (Contributed by
2166Gustavo Niemeyer.)
2167
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002168\item The \cfunction{PyArg_NoArgs()} macro is now deprecated, and code
Andrew M. Kuchling7845e7c2002-07-11 19:27:46 +00002169that uses it should be changed. For Python 2.2 and later, the method
2170definition table can specify the
Fred Drake5c4cf152002-11-13 14:59:06 +00002171\constant{METH_NOARGS} flag, signalling that there are no arguments, and
Andrew M. Kuchling7845e7c2002-07-11 19:27:46 +00002172the argument checking can then be removed. If compatibility with
2173pre-2.2 versions of Python is important, the code could use
Fred Drakeaac8c582003-01-17 22:50:10 +00002174\code{PyArg_ParseTuple(\var{args}, "")} instead, but this will be slower
Andrew M. Kuchling7845e7c2002-07-11 19:27:46 +00002175than using \constant{METH_NOARGS}.
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00002176
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002177\item A new function, \cfunction{PyObject_DelItemString(\var{mapping},
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002178char *\var{key})} was added as shorthand for
Raymond Hettingera685f522003-07-12 04:42:30 +00002179\code{PyObject_DelItem(\var{mapping}, PyString_New(\var{key}))}.
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00002180
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002181\item File objects now manage their internal string buffer
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002182differently, increasing it exponentially when needed. This results in
2183the benchmark tests in \file{Lib/test/test_bufio.py} speeding up
2184considerably (from 57 seconds to 1.7 seconds, according to one
2185measurement).
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002186
Andrew M. Kuchling72b58e02002-05-29 17:30:34 +00002187\item It's now possible to define class and static methods for a C
2188extension type by setting either the \constant{METH_CLASS} or
2189\constant{METH_STATIC} flags in a method's \ctype{PyMethodDef}
2190structure.
Andrew M. Kuchling45afd542002-04-02 14:25:25 +00002191
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00002192\item Python now includes a copy of the Expat XML parser's source code,
2193removing any dependence on a system version or local installation of
Fred Drake5c4cf152002-11-13 14:59:06 +00002194Expat.
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00002195
Michael W. Hudson3e245d82003-02-11 14:19:56 +00002196\item If you dynamically allocate type objects in your extension, you
Neal Norwitzada859c2003-02-11 14:30:39 +00002197should be aware of a change in the rules relating to the
Michael W. Hudson3e245d82003-02-11 14:19:56 +00002198\member{__module__} and \member{__name__} attributes. In summary,
2199you will want to ensure the type's dictionary contains a
2200\code{'__module__'} key; making the module name the part of the type
2201name leading up to the final period will no longer have the desired
2202effect. For more detail, read the API reference documentation or the
2203source.
2204
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00002205\end{itemize}
2206
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00002207
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00002208%======================================================================
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00002209\subsection{Port-Specific Changes}
2210
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00002211Support for a port to IBM's OS/2 using the EMX runtime environment was
2212merged into the main Python source tree. EMX is a POSIX emulation
2213layer over the OS/2 system APIs. The Python port for EMX tries to
2214support all the POSIX-like capability exposed by the EMX runtime, and
2215mostly succeeds; \function{fork()} and \function{fcntl()} are
2216restricted by the limitations of the underlying emulation layer. The
2217standard OS/2 port, which uses IBM's Visual Age compiler, also gained
2218support for case-sensitive import semantics as part of the integration
2219of the EMX port into CVS. (Contributed by Andrew MacIntyre.)
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00002220
Andrew M. Kuchling72b58e02002-05-29 17:30:34 +00002221On MacOS, most toolbox modules have been weaklinked to improve
2222backward compatibility. This means that modules will no longer fail
2223to load if a single routine is missing on the curent OS version.
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00002224Instead calling the missing routine will raise an exception.
2225(Contributed by Jack Jansen.)
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00002226
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00002227The RPM spec files, found in the \file{Misc/RPM/} directory in the
2228Python source distribution, were updated for 2.3. (Contributed by
2229Sean Reifschneider.)
Fred Drake03e10312002-03-26 19:17:43 +00002230
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002231Other new platforms now supported by Python include AtheOS
Fred Drake693aea22003-02-07 14:52:18 +00002232(\url{http://www.atheos.cx/}), GNU/Hurd, and OpenVMS.
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00002233
Fred Drake03e10312002-03-26 19:17:43 +00002234
2235%======================================================================
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002236\section{Other Changes and Fixes \label{section-other}}
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002237
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +00002238As usual, there were a bunch of other improvements and bugfixes
2239scattered throughout the source tree. A search through the CVS change
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +00002240logs finds there were 523 patches applied and 514 bugs fixed between
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +00002241Python 2.2 and 2.3. Both figures are likely to be underestimates.
2242
2243Some of the more notable changes are:
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002244
2245\begin{itemize}
2246
Fred Drake54fe3fd2002-11-26 22:07:35 +00002247\item The \file{regrtest.py} script now provides a way to allow ``all
2248resources except \var{foo}.'' A resource name passed to the
2249\programopt{-u} option can now be prefixed with a hyphen
2250(\character{-}) to mean ``remove this resource.'' For example, the
2251option `\code{\programopt{-u}all,-bsddb}' could be used to enable the
2252use of all resources except \code{bsddb}.
2253
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002254\item The tools used to build the documentation now work under Cygwin
2255as well as \UNIX.
2256
Michael W. Hudsondd32a912002-08-15 14:59:02 +00002257\item The \code{SET_LINENO} opcode has been removed. Back in the
2258mists of time, this opcode was needed to produce line numbers in
2259tracebacks and support trace functions (for, e.g., \module{pdb}).
2260Since Python 1.5, the line numbers in tracebacks have been computed
2261using a different mechanism that works with ``python -O''. For Python
22622.3 Michael Hudson implemented a similar scheme to determine when to
2263call the trace function, removing the need for \code{SET_LINENO}
2264entirely.
2265
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +00002266It would be difficult to detect any resulting difference from Python
2267code, apart from a slight speed up when Python is run without
Michael W. Hudsondd32a912002-08-15 14:59:02 +00002268\programopt{-O}.
2269
2270C extensions that access the \member{f_lineno} field of frame objects
2271should instead call \code{PyCode_Addr2Line(f->f_code, f->f_lasti)}.
2272This will have the added effect of making the code work as desired
2273under ``python -O'' in earlier versions of Python.
2274
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002275A nifty new feature is that trace functions can now assign to the
2276\member{f_lineno} attribute of frame objects, changing the line that
2277will be executed next. A \samp{jump} command has been added to the
2278\module{pdb} debugger taking advantage of this new feature.
2279(Implemented by Richie Hindle.)
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00002280
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002281\end{itemize}
2282
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00002283
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002284%======================================================================
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00002285\section{Porting to Python 2.3}
2286
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002287This section lists previously described changes that may require
2288changes to your code:
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002289
2290\begin{itemize}
2291
2292\item \keyword{yield} is now always a keyword; if it's used as a
2293variable name in your code, a different name must be chosen.
2294
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002295\item For strings \var{X} and \var{Y}, \code{\var{X} in \var{Y}} now works
2296if \var{X} is more than one character long.
2297
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00002298\item The \function{int()} type constructor will now return a long
2299integer instead of raising an \exception{OverflowError} when a string
2300or floating-point number is too large to fit into an integer.
2301
Andrew M. Kuchlingacddabc2003-02-18 00:43:24 +00002302\item If you have Unicode strings that contain 8-bit characters, you
2303must declare the file's encoding (UTF-8, Latin-1, or whatever) by
2304adding a comment to the top of the file. See
2305section~\ref{section-encodings} for more information.
2306
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00002307\item Calling Tcl methods through \module{_tkinter} no longer
2308returns only strings. Instead, if Tcl returns other objects those
2309objects are converted to their Python equivalent, if one exists, or
2310wrapped with a \class{_tkinter.Tcl_Obj} object if no Python equivalent
2311exists.
2312
Andrew M. Kuchling80fd7852003-02-06 15:14:04 +00002313\item Large octal and hex literals such as
Andrew M. Kuchling72df65a2003-02-10 15:08:16 +00002314\code{0xffffffff} now trigger a \exception{FutureWarning}. Currently
Andrew M. Kuchling80fd7852003-02-06 15:14:04 +00002315they're stored as 32-bit numbers and result in a negative value, but
Andrew M. Kuchling72df65a2003-02-10 15:08:16 +00002316in Python 2.4 they'll become positive long integers.
2317
2318There are a few ways to fix this warning. If you really need a
2319positive number, just add an \samp{L} to the end of the literal. If
2320you're trying to get a 32-bit integer with low bits set and have
2321previously used an expression such as \code{~(1 << 31)}, it's probably
2322clearest to start with all bits set and clear the desired upper bits.
2323For example, to clear just the top bit (bit 31), you could write
2324\code{0xffffffffL {\&}{\textasciitilde}(1L<<31)}.
Andrew M. Kuchling80fd7852003-02-06 15:14:04 +00002325
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00002326\item You can no longer disable assertions by assigning to \code{__debug__}.
2327
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002328\item The Distutils \function{setup()} function has gained various new
Fred Drake5c4cf152002-11-13 14:59:06 +00002329keyword arguments such as \var{depends}. Old versions of the
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002330Distutils will abort if passed unknown keywords. A solution is to check
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002331for the presence of the new \function{get_distutil_options()} function
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002332in your \file{setup.py} and only uses the new keywords
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002333with a version of the Distutils that supports them:
2334
2335\begin{verbatim}
2336from distutils import core
2337
2338kw = {'sources': 'foo.c', ...}
2339if hasattr(core, 'get_distutil_options'):
2340 kw['depends'] = ['foo.h']
Fred Drake5c4cf152002-11-13 14:59:06 +00002341ext = Extension(**kw)
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002342\end{verbatim}
2343
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00002344\item Using \code{None} as a variable name will now result in a
2345\exception{SyntaxWarning} warning.
2346
2347\item Names of extension types defined by the modules included with
2348Python now contain the module and a \character{.} in front of the type
2349name.
2350
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002351\end{itemize}
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00002352
2353
2354%======================================================================
Fred Drake03e10312002-03-26 19:17:43 +00002355\section{Acknowledgements \label{acks}}
2356
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00002357The author would like to thank the following people for offering
2358suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +00002359article: Jeff Bauer, Simon Brunning, Brett Cannon, Michael Chermside,
2360Andrew Dalke, Scott David Daniels, Fred~L. Drake, Jr., Kelly Gerber,
2361Raymond Hettinger, Michael Hudson, Chris Lambert, Detlef Lannert,
Andrew M. Kuchlingfcf6b3e2003-05-07 17:00:35 +00002362Martin von~L\"owis, Andrew MacIntyre, Lalo Martins, Chad Netzer,
2363Gustavo Niemeyer, Neal Norwitz, Hans Nowak, Chris Reedy, Francesco
2364Ricciardi, Vinay Sajip, Neil Schemenauer, Roman Suzi, Jason Tishler,
2365Just van~Rossum.
Fred Drake03e10312002-03-26 19:17:43 +00002366
2367\end{document}