blob: ad88b54a626e512b29ac21091c32eef53e9e2a9d [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. Kuchlingc61ec522002-08-04 01:20:05 +000015% MacOS framework-related changes (section of its own, probably)
Andrew M. Kuchlingf70a0a82002-06-10 13:22:46 +000016
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +000017%\section{Introduction \label{intro}}
18
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +000019This article explains the new features in Python 2.3. The tentative
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +000020release date of Python 2.3 is currently scheduled for August 2003.
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +000021
22This article doesn't attempt to provide a complete specification of
23the new features, but instead provides a convenient overview. For
24full details, you should refer to the documentation for Python 2.3,
Fred Drake693aea22003-02-07 14:52:18 +000025such as the \citetitle[../lib/lib.html]{Python Library Reference} and
26the \citetitle[../ref/ref.html]{Python Reference Manual}. If you want
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +000027to understand the complete implementation and design rationale,
28refer to the PEP for a particular new feature.
Fred Drake03e10312002-03-26 19:17:43 +000029
30
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +000031%======================================================================
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000032\section{PEP 218: A Standard Set Datatype}
33
34The new \module{sets} module contains an implementation of a set
35datatype. The \class{Set} class is for mutable sets, sets that can
36have members added and removed. The \class{ImmutableSet} class is for
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +000037sets that can't be modified, and instances of \class{ImmutableSet} can
38therefore be used as dictionary keys. Sets are built on top of
39dictionaries, so the elements within a set must be hashable.
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000040
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +000041Here's a simple example:
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000042
43\begin{verbatim}
44>>> import sets
45>>> S = sets.Set([1,2,3])
46>>> S
47Set([1, 2, 3])
48>>> 1 in S
49True
50>>> 0 in S
51False
52>>> S.add(5)
53>>> S.remove(3)
54>>> S
55Set([1, 2, 5])
Fred Drake5c4cf152002-11-13 14:59:06 +000056>>>
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000057\end{verbatim}
58
59The union and intersection of sets can be computed with the
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +000060\method{union()} and \method{intersection()} methods; an alternative
61notation uses the bitwise operators \code{\&} and \code{|}.
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000062Mutable sets also have in-place versions of these methods,
63\method{union_update()} and \method{intersection_update()}.
64
65\begin{verbatim}
66>>> S1 = sets.Set([1,2,3])
67>>> S2 = sets.Set([4,5,6])
68>>> S1.union(S2)
69Set([1, 2, 3, 4, 5, 6])
70>>> S1 | S2 # Alternative notation
71Set([1, 2, 3, 4, 5, 6])
Fred Drake5c4cf152002-11-13 14:59:06 +000072>>> S1.intersection(S2)
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000073Set([])
74>>> S1 & S2 # Alternative notation
75Set([])
76>>> S1.union_update(S2)
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000077>>> S1
78Set([1, 2, 3, 4, 5, 6])
Fred Drake5c4cf152002-11-13 14:59:06 +000079>>>
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000080\end{verbatim}
81
82It's also possible to take the symmetric difference of two sets. This
83is the set of all elements in the union that aren't in the
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +000084intersection. Another way of putting it is that the symmetric
85difference contains all elements that are in exactly one
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +000086set. Again, there's an alternative notation (\code{\^}), and an
87in-place version with the ungainly name
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000088\method{symmetric_difference_update()}.
89
90\begin{verbatim}
91>>> S1 = sets.Set([1,2,3,4])
92>>> S2 = sets.Set([3,4,5,6])
93>>> S1.symmetric_difference(S2)
94Set([1, 2, 5, 6])
95>>> S1 ^ S2
96Set([1, 2, 5, 6])
97>>>
98\end{verbatim}
99
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000100There are also \method{issubset()} and \method{issuperset()} methods
Michael W. Hudson065f5fa2003-02-10 19:24:50 +0000101for checking whether one set is a subset or superset of another:
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +0000102
103\begin{verbatim}
104>>> S1 = sets.Set([1,2,3])
105>>> S2 = sets.Set([2,3])
106>>> S2.issubset(S1)
107True
108>>> S1.issubset(S2)
109False
110>>> S1.issuperset(S2)
111True
112>>>
113\end{verbatim}
114
115
116\begin{seealso}
117
118\seepep{218}{Adding a Built-In Set Object Type}{PEP written by Greg V. Wilson.
119Implemented by Greg V. Wilson, Alex Martelli, and GvR.}
120
121\end{seealso}
122
123
124
125%======================================================================
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000126\section{PEP 255: Simple Generators\label{section-generators}}
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000127
128In Python 2.2, generators were added as an optional feature, to be
129enabled by a \code{from __future__ import generators} directive. In
1302.3 generators no longer need to be specially enabled, and are now
131always present; this means that \keyword{yield} is now always a
132keyword. The rest of this section is a copy of the description of
133generators from the ``What's New in Python 2.2'' document; if you read
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000134it back when Python 2.2 came out, you can skip the rest of this section.
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000135
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000136You're doubtless familiar with how function calls work in Python or C.
137When you call a function, it gets a private namespace where its local
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000138variables are created. When the function reaches a \keyword{return}
139statement, the local variables are destroyed and the resulting value
140is returned to the caller. A later call to the same function will get
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000141a fresh new set of local variables. But, what if the local variables
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000142weren't thrown away on exiting a function? What if you could later
143resume the function where it left off? This is what generators
144provide; they can be thought of as resumable functions.
145
146Here's the simplest example of a generator function:
147
148\begin{verbatim}
149def generate_ints(N):
150 for i in range(N):
151 yield i
152\end{verbatim}
153
154A new keyword, \keyword{yield}, was introduced for generators. Any
155function containing a \keyword{yield} statement is a generator
156function; this is detected by Python's bytecode compiler which
Fred Drake5c4cf152002-11-13 14:59:06 +0000157compiles the function specially as a result.
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000158
159When you call a generator function, it doesn't return a single value;
160instead it returns a generator object that supports the iterator
161protocol. On executing the \keyword{yield} statement, the generator
162outputs the value of \code{i}, similar to a \keyword{return}
163statement. The big difference between \keyword{yield} and a
164\keyword{return} statement is that on reaching a \keyword{yield} the
165generator's state of execution is suspended and local variables are
166preserved. On the next call to the generator's \code{.next()} method,
167the function will resume executing immediately after the
168\keyword{yield} statement. (For complicated reasons, the
169\keyword{yield} statement isn't allowed inside the \keyword{try} block
Fred Drakeaac8c582003-01-17 22:50:10 +0000170of a \keyword{try}...\keyword{finally} statement; read \pep{255} for a full
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000171explanation of the interaction between \keyword{yield} and
172exceptions.)
173
Fred Drakeaac8c582003-01-17 22:50:10 +0000174Here's a sample usage of the \function{generate_ints()} generator:
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000175
176\begin{verbatim}
177>>> gen = generate_ints(3)
178>>> gen
179<generator object at 0x8117f90>
180>>> gen.next()
1810
182>>> gen.next()
1831
184>>> gen.next()
1852
186>>> gen.next()
187Traceback (most recent call last):
Andrew M. Kuchling9f6e1042002-06-17 13:40:04 +0000188 File "stdin", line 1, in ?
189 File "stdin", line 2, in generate_ints
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000190StopIteration
191\end{verbatim}
192
193You could equally write \code{for i in generate_ints(5)}, or
194\code{a,b,c = generate_ints(3)}.
195
196Inside a generator function, the \keyword{return} statement can only
197be used without a value, and signals the end of the procession of
198values; afterwards the generator cannot return any further values.
199\keyword{return} with a value, such as \code{return 5}, is a syntax
200error inside a generator function. The end of the generator's results
201can also be indicated by raising \exception{StopIteration} manually,
202or by just letting the flow of execution fall off the bottom of the
203function.
204
205You could achieve the effect of generators manually by writing your
206own class and storing all the local variables of the generator as
207instance variables. For example, returning a list of integers could
208be done by setting \code{self.count} to 0, and having the
209\method{next()} method increment \code{self.count} and return it.
210However, for a moderately complicated generator, writing a
211corresponding class would be much messier.
212\file{Lib/test/test_generators.py} contains a number of more
213interesting examples. The simplest one implements an in-order
214traversal of a tree using generators recursively.
215
216\begin{verbatim}
217# A recursive generator that generates Tree leaves in in-order.
218def inorder(t):
219 if t:
220 for x in inorder(t.left):
221 yield x
222 yield t.label
223 for x in inorder(t.right):
224 yield x
225\end{verbatim}
226
227Two other examples in \file{Lib/test/test_generators.py} produce
228solutions for the N-Queens problem (placing $N$ queens on an $NxN$
229chess board so that no queen threatens another) and the Knight's Tour
230(a route that takes a knight to every square of an $NxN$ chessboard
Fred Drake5c4cf152002-11-13 14:59:06 +0000231without visiting any square twice).
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000232
233The idea of generators comes from other programming languages,
234especially Icon (\url{http://www.cs.arizona.edu/icon/}), where the
235idea of generators is central. In Icon, every
236expression and function call behaves like a generator. One example
237from ``An Overview of the Icon Programming Language'' at
238\url{http://www.cs.arizona.edu/icon/docs/ipd266.htm} gives an idea of
239what this looks like:
240
241\begin{verbatim}
242sentence := "Store it in the neighboring harbor"
243if (i := find("or", sentence)) > 5 then write(i)
244\end{verbatim}
245
246In Icon the \function{find()} function returns the indexes at which the
247substring ``or'' is found: 3, 23, 33. In the \keyword{if} statement,
248\code{i} is first assigned a value of 3, but 3 is less than 5, so the
249comparison fails, and Icon retries it with the second value of 23. 23
250is greater than 5, so the comparison now succeeds, and the code prints
251the value 23 to the screen.
252
253Python doesn't go nearly as far as Icon in adopting generators as a
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000254central concept. Generators are considered part of the core
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000255Python language, but learning or using them isn't compulsory; if they
256don't solve any problems that you have, feel free to ignore them.
257One novel feature of Python's interface as compared to
258Icon's is that a generator's state is represented as a concrete object
259(the iterator) that can be passed around to other functions or stored
260in a data structure.
261
262\begin{seealso}
263
264\seepep{255}{Simple Generators}{Written by Neil Schemenauer, Tim
265Peters, Magnus Lie Hetland. Implemented mostly by Neil Schemenauer
266and Tim Peters, with other fixes from the Python Labs crew.}
267
268\end{seealso}
269
270
271%======================================================================
Fred Drake13090e12002-08-22 16:51:08 +0000272\section{PEP 263: Source Code Encodings \label{section-encodings}}
Andrew M. Kuchling950725f2002-08-06 01:40:48 +0000273
274Python source files can now be declared as being in different
275character set encodings. Encodings are declared by including a
276specially formatted comment in the first or second line of the source
277file. For example, a UTF-8 file can be declared with:
278
279\begin{verbatim}
280#!/usr/bin/env python
281# -*- coding: UTF-8 -*-
282\end{verbatim}
283
284Without such an encoding declaration, the default encoding used is
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +00002857-bit ASCII. Executing or importing modules that contain string
286literals with 8-bit characters and have no encoding declaration will result
Andrew M. Kuchlingacddabc2003-02-18 00:43:24 +0000287in a \exception{DeprecationWarning} being signalled by Python 2.3; in
2882.4 this will be a syntax error.
Andrew M. Kuchling950725f2002-08-06 01:40:48 +0000289
Andrew M. Kuchlingacddabc2003-02-18 00:43:24 +0000290The encoding declaration only affects Unicode string literals, which
291will be converted to Unicode using the specified encoding. Note that
292Python identifiers are still restricted to ASCII characters, so you
293can't have variable names that use characters outside of the usual
294alphanumerics.
Andrew M. Kuchling950725f2002-08-06 01:40:48 +0000295
296\begin{seealso}
297
298\seepep{263}{Defining Python Source Code Encodings}{Written by
Andrew M. Kuchlingfcf6b3e2003-05-07 17:00:35 +0000299Marc-Andr\'e Lemburg and Martin von~L\"owis; implemented by Suzuki
300Hisao and Martin von~L\"owis.}
Andrew M. Kuchling950725f2002-08-06 01:40:48 +0000301
302\end{seealso}
303
304
305%======================================================================
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000306\section{PEP 277: Unicode file name support for Windows NT}
Andrew M. Kuchling0f345562002-10-04 22:34:11 +0000307
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000308On Windows NT, 2000, and XP, the system stores file names as Unicode
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000309strings. Traditionally, Python has represented file names as byte
310strings, which is inadequate because it renders some file names
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000311inaccessible.
312
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000313Python now allows using arbitrary Unicode strings (within the
314limitations of the file system) for all functions that expect file
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000315names, most notably the \function{open()} built-in function. If a Unicode
316string is passed to \function{os.listdir()}, Python now returns a list
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000317of Unicode strings. A new function, \function{os.getcwdu()}, returns
318the current directory as a Unicode string.
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000319
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000320Byte strings still work as file names, and on Windows Python will
321transparently convert them to Unicode using the \code{mbcs} encoding.
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000322
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000323Other systems also allow Unicode strings as file names but convert
324them to byte strings before passing them to the system, which can
325cause a \exception{UnicodeError} to be raised. Applications can test
326whether arbitrary Unicode strings are supported as file names by
Andrew M. Kuchlingb9ba4e62003-02-03 15:16:15 +0000327checking \member{os.path.supports_unicode_filenames}, a Boolean value.
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000328
Andrew M. Kuchling563389f2003-03-02 02:31:58 +0000329Under MacOS, \function{os.listdir()} may now return Unicode filenames.
330
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000331\begin{seealso}
332
333\seepep{277}{Unicode file name support for Windows NT}{Written by Neil
Andrew M. Kuchlingfcf6b3e2003-05-07 17:00:35 +0000334Hodgson; implemented by Neil Hodgson, Martin von~L\"owis, and Mark
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000335Hammond.}
336
337\end{seealso}
Andrew M. Kuchling0f345562002-10-04 22:34:11 +0000338
339
340%======================================================================
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000341\section{PEP 278: Universal Newline Support}
342
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000343The three major operating systems used today are Microsoft Windows,
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000344Apple's Macintosh OS, and the various \UNIX\ derivatives. A minor
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +0000345irritation of cross-platform work
346is that these three platforms all use different characters
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000347to mark the ends of lines in text files. \UNIX\ uses the linefeed
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +0000348(ASCII character 10), MacOS uses the carriage return (ASCII
349character 13), and Windows uses a two-character sequence of a
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000350carriage return plus a newline.
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000351
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000352Python's file objects can now support end of line conventions other
353than the one followed by the platform on which Python is running.
Fred Drake5c4cf152002-11-13 14:59:06 +0000354Opening a file with the mode \code{'U'} or \code{'rU'} will open a file
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000355for reading in universal newline mode. All three line ending
Fred Drake5c4cf152002-11-13 14:59:06 +0000356conventions will be translated to a \character{\e n} in the strings
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000357returned by the various file methods such as \method{read()} and
Fred Drake5c4cf152002-11-13 14:59:06 +0000358\method{readline()}.
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000359
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000360Universal newline support is also used when importing modules and when
361executing a file with the \function{execfile()} function. This means
362that Python modules can be shared between all three operating systems
363without needing to convert the line-endings.
364
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +0000365This feature can be disabled when compiling Python by specifying
366the \longprogramopt{without-universal-newlines} switch when running Python's
Fred Drake5c4cf152002-11-13 14:59:06 +0000367\program{configure} script.
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000368
369\begin{seealso}
370
Fred Drake5c4cf152002-11-13 14:59:06 +0000371\seepep{278}{Universal Newline Support}{Written
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000372and implemented by Jack Jansen.}
373
374\end{seealso}
375
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +0000376
377%======================================================================
Andrew M. Kuchling433307b2003-05-13 14:23:54 +0000378\section{PEP 279: enumerate()\label{section-enumerate}}
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +0000379
380A new built-in function, \function{enumerate()}, will make
381certain loops a bit clearer. \code{enumerate(thing)}, where
382\var{thing} is either an iterator or a sequence, returns a iterator
Fred Drake3605ae52003-07-16 03:26:31 +0000383that will return \code{(0, \var{thing}[0])}, \code{(1,
384\var{thing}[1])}, \code{(2, \var{thing}[2])}, and so forth.
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000385
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +0000386A common idiom to change every element of a list looks like this:
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +0000387
388\begin{verbatim}
389for i in range(len(L)):
390 item = L[i]
391 # ... compute some result based on item ...
392 L[i] = result
393\end{verbatim}
394
395This can be rewritten using \function{enumerate()} as:
396
397\begin{verbatim}
398for i, item in enumerate(L):
399 # ... compute some result based on item ...
400 L[i] = result
401\end{verbatim}
402
403
404\begin{seealso}
405
Fred Drake5c4cf152002-11-13 14:59:06 +0000406\seepep{279}{The enumerate() built-in function}{Written
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000407and implemented by Raymond D. Hettinger.}
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +0000408
409\end{seealso}
410
411
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000412%======================================================================
Andrew M. Kuchling433307b2003-05-13 14:23:54 +0000413\section{PEP 282: The logging Package}
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000414
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000415A standard package for writing logs, \module{logging}, has been added
416to Python 2.3. It provides a powerful and flexible mechanism for
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000417generating logging output which can then be filtered and processed in
418various ways. A configuration file written in a standard format can
419be used to control the logging behavior of a program. Python
420includes handlers that will write log records to
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000421standard error or to a file or socket, send them to the system log, or
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000422even e-mail them to a particular address; of course, it's also
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000423possible to write your own handler classes.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000424
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000425The \class{Logger} class is the primary class.
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000426Most application code will deal with one or more \class{Logger}
427objects, each one used by a particular subsystem of the application.
428Each \class{Logger} is identified by a name, and names are organized
429into a hierarchy using \samp{.} as the component separator. For
430example, you might have \class{Logger} instances named \samp{server},
431\samp{server.auth} and \samp{server.network}. The latter two
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000432instances are below \samp{server} in the hierarchy. This means that
433if you turn up the verbosity for \samp{server} or direct \samp{server}
434messages to a different handler, the changes will also apply to
435records logged to \samp{server.auth} and \samp{server.network}.
436There's also a root \class{Logger} that's the parent of all other
437loggers.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000438
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000439For simple uses, the \module{logging} package contains some
440convenience functions that always use the root log:
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000441
442\begin{verbatim}
443import logging
444
445logging.debug('Debugging information')
446logging.info('Informational message')
Andrew M. Kuchling37495072003-02-19 13:46:18 +0000447logging.warning('Warning:config file %s not found', 'server.conf')
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000448logging.error('Error occurred')
449logging.critical('Critical error -- shutting down')
450\end{verbatim}
451
452This produces the following output:
453
454\begin{verbatim}
Andrew M. Kuchling37495072003-02-19 13:46:18 +0000455WARNING:root:Warning:config file server.conf not found
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000456ERROR:root:Error occurred
457CRITICAL:root:Critical error -- shutting down
458\end{verbatim}
459
460In the default configuration, informational and debugging messages are
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000461suppressed and the output is sent to standard error. You can enable
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000462the display of informational and debugging messages by calling the
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000463\method{setLevel()} method on the root logger.
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000464
Andrew M. Kuchling37495072003-02-19 13:46:18 +0000465Notice the \function{warning()} call's use of string formatting
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000466operators; all of the functions for logging messages take the
467arguments \code{(\var{msg}, \var{arg1}, \var{arg2}, ...)} and log the
468string resulting from \code{\var{msg} \% (\var{arg1}, \var{arg2},
469...)}.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000470
471There's also an \function{exception()} function that records the most
472recent traceback. Any of the other functions will also record the
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000473traceback if you specify a true value for the keyword argument
Fred Drakeaac8c582003-01-17 22:50:10 +0000474\var{exc_info}.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000475
476\begin{verbatim}
477def f():
478 try: 1/0
479 except: logging.exception('Problem recorded')
480
481f()
482\end{verbatim}
483
484This produces the following output:
485
486\begin{verbatim}
487ERROR:root:Problem recorded
488Traceback (most recent call last):
489 File "t.py", line 6, in f
490 1/0
491ZeroDivisionError: integer division or modulo by zero
492\end{verbatim}
493
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000494Slightly more advanced programs will use a logger other than the root
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000495logger. The \function{getLogger(\var{name})} function is used to get
496a particular log, creating it if it doesn't exist yet.
Andrew M. Kuchlingb1e4bf92002-12-03 13:35:17 +0000497\function{getLogger(None)} returns the root logger.
498
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000499
500\begin{verbatim}
501log = logging.getLogger('server')
502 ...
503log.info('Listening on port %i', port)
504 ...
505log.critical('Disk full')
506 ...
507\end{verbatim}
508
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000509Log records are usually propagated up the hierarchy, so a message
510logged to \samp{server.auth} is also seen by \samp{server} and
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +0000511\samp{root}, but a \class{Logger} can prevent this by setting its
Fred Drakeaac8c582003-01-17 22:50:10 +0000512\member{propagate} attribute to \constant{False}.
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000513
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000514There are more classes provided by the \module{logging} package that
515can be customized. When a \class{Logger} instance is told to log a
516message, it creates a \class{LogRecord} instance that is sent to any
517number of different \class{Handler} instances. Loggers and handlers
518can also have an attached list of filters, and each filter can cause
519the \class{LogRecord} to be ignored or can modify the record before
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +0000520passing it along. When they're finally output, \class{LogRecord}
521instances are converted to text by a \class{Formatter} class. All of
522these classes can be replaced by your own specially-written classes.
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000523
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000524With all of these features the \module{logging} package should provide
525enough flexibility for even the most complicated applications. This
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +0000526is only an incomplete overview of its features, so please see the
527\ulink{package's reference documentation}{../lib/module-logging.html}
528for all of the details. Reading \pep{282} will also be helpful.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000529
530
531\begin{seealso}
532
533\seepep{282}{A Logging System}{Written by Vinay Sajip and Trent Mick;
534implemented by Vinay Sajip.}
535
536\end{seealso}
537
538
539%======================================================================
Andrew M. Kuchling433307b2003-05-13 14:23:54 +0000540\section{PEP 285: A Boolean Type\label{section-bool}}
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000541
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000542A Boolean type was added to Python 2.3. Two new constants were added
543to the \module{__builtin__} module, \constant{True} and
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000544\constant{False}. (\constant{True} and
545\constant{False} constants were added to the built-ins
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000546in 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 +00005471 and 0 and aren't a different type.)
548
549The type object for this new type is named
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000550\class{bool}; the constructor for it takes any Python value and
551converts it to \constant{True} or \constant{False}.
552
553\begin{verbatim}
554>>> bool(1)
555True
556>>> bool(0)
557False
558>>> bool([])
559False
560>>> bool( (1,) )
561True
562\end{verbatim}
563
564Most of the standard library modules and built-in functions have been
565changed to return Booleans.
566
567\begin{verbatim}
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000568>>> obj = []
569>>> hasattr(obj, 'append')
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000570True
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000571>>> isinstance(obj, list)
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000572True
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000573>>> isinstance(obj, tuple)
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000574False
575\end{verbatim}
576
577Python's Booleans were added with the primary goal of making code
578clearer. For example, if you're reading a function and encounter the
Fred Drake5c4cf152002-11-13 14:59:06 +0000579statement \code{return 1}, you might wonder whether the \code{1}
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000580represents a Boolean truth value, an index, or a
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000581coefficient that multiplies some other quantity. If the statement is
582\code{return True}, however, the meaning of the return value is quite
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000583clear.
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000584
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000585Python's Booleans were \emph{not} added for the sake of strict
586type-checking. A very strict language such as Pascal would also
587prevent you performing arithmetic with Booleans, and would require
588that the expression in an \keyword{if} statement always evaluate to a
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000589Boolean result. Python is not this strict and never will be, as
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000590\pep{285} explicitly says. This means you can still use any
591expression in an \keyword{if} statement, even ones that evaluate to a
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000592list or tuple or some random object. The Boolean type is a
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000593subclass of the \class{int} class so that arithmetic using a Boolean
594still works.
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000595
596\begin{verbatim}
597>>> True + 1
5982
599>>> False + 1
6001
601>>> False * 75
6020
603>>> True * 75
60475
605\end{verbatim}
606
607To sum up \constant{True} and \constant{False} in a sentence: they're
608alternative ways to spell the integer values 1 and 0, with the single
609difference that \function{str()} and \function{repr()} return the
Fred Drake5c4cf152002-11-13 14:59:06 +0000610strings \code{'True'} and \code{'False'} instead of \code{'1'} and
611\code{'0'}.
Andrew M. Kuchling3a52ff62002-04-03 22:44:47 +0000612
613\begin{seealso}
614
615\seepep{285}{Adding a bool type}{Written and implemented by GvR.}
616
617\end{seealso}
618
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000619
Andrew M. Kuchling65b72822002-09-03 00:53:21 +0000620%======================================================================
621\section{PEP 293: Codec Error Handling Callbacks}
622
Martin v. Löwis20eae692002-10-07 19:01:07 +0000623When encoding a Unicode string into a byte string, unencodable
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000624characters may be encountered. So far, Python has allowed specifying
625the error processing as either ``strict'' (raising
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000626\exception{UnicodeError}), ``ignore'' (skipping the character), or
627``replace'' (using a question mark in the output string), with
628``strict'' being the default behavior. It may be desirable to specify
629alternative processing of such errors, such as inserting an XML
630character reference or HTML entity reference into the converted
631string.
Martin v. Löwis20eae692002-10-07 19:01:07 +0000632
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +0000633Python now has a flexible framework to add different processing
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000634strategies. New error handlers can be added with
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000635\function{codecs.register_error}, and codecs then can access the error
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000636handler with \function{codecs.lookup_error}. An equivalent C API has
637been added for codecs written in C. The error handler gets the
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000638necessary state information such as the string being converted, the
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000639position in the string where the error was detected, and the target
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000640encoding. The handler can then either raise an exception or return a
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000641replacement string.
Martin v. Löwis20eae692002-10-07 19:01:07 +0000642
643Two additional error handlers have been implemented using this
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000644framework: ``backslashreplace'' uses Python backslash quoting to
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +0000645represent unencodable characters and ``xmlcharrefreplace'' emits
Martin v. Löwis20eae692002-10-07 19:01:07 +0000646XML character references.
Andrew M. Kuchling65b72822002-09-03 00:53:21 +0000647
648\begin{seealso}
649
Fred Drake5c4cf152002-11-13 14:59:06 +0000650\seepep{293}{Codec Error Handling Callbacks}{Written and implemented by
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000651Walter D\"orwald.}
Andrew M. Kuchling65b72822002-09-03 00:53:21 +0000652
653\end{seealso}
654
655
656%======================================================================
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000657\section{PEP 273: Importing Modules from Zip Archives}
658
659The new \module{zipimport} module adds support for importing
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000660modules from a ZIP-format archive. You don't need to import the
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000661module explicitly; it will be automatically imported if a ZIP
662archive's filename is added to \code{sys.path}. For example:
663
664\begin{verbatim}
665amk@nyman:~/src/python$ unzip -l /tmp/example.zip
666Archive: /tmp/example.zip
667 Length Date Time Name
668 -------- ---- ---- ----
669 8467 11-26-02 22:30 jwzthreading.py
670 -------- -------
671 8467 1 file
672amk@nyman:~/src/python$ ./python
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000673Python 2.3 (#1, Aug 1 2003, 19:54:32)
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000674>>> import sys
675>>> sys.path.insert(0, '/tmp/example.zip') # Add .zip file to front of path
676>>> import jwzthreading
677>>> jwzthreading.__file__
678'/tmp/example.zip/jwzthreading.py'
679>>>
680\end{verbatim}
681
682An entry in \code{sys.path} can now be the filename of a ZIP archive.
683The ZIP archive can contain any kind of files, but only files named
Fred Drakeaac8c582003-01-17 22:50:10 +0000684\file{*.py}, \file{*.pyc}, or \file{*.pyo} can be imported. If an
685archive only contains \file{*.py} files, Python will not attempt to
686modify the archive by adding the corresponding \file{*.pyc} file, meaning
687that if a ZIP archive doesn't contain \file{*.pyc} files, importing may be
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000688rather slow.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000689
690A path within the archive can also be specified to only import from a
691subdirectory; for example, the path \file{/tmp/example.zip/lib/}
692would only import from the \file{lib/} subdirectory within the
693archive.
694
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000695\begin{seealso}
696
697\seepep{273}{Import Modules from Zip Archives}{Written by James C. Ahlstrom,
698who also provided an implementation.
699Python 2.3 follows the specification in \pep{273},
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +0000700but uses an implementation written by Just van~Rossum
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000701that uses the import hooks described in \pep{302}.
702See section~\ref{section-pep302} for a description of the new import hooks.
703}
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000704
705\end{seealso}
706
707%======================================================================
Fred Drake693aea22003-02-07 14:52:18 +0000708\section{PEP 301: Package Index and Metadata for
709Distutils\label{section-pep301}}
Andrew M. Kuchling87cebbf2003-01-03 16:24:28 +0000710
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000711Support for the long-requested Python catalog makes its first
712appearance in 2.3.
713
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000714The heart of the catalog is the new Distutils \command{register} command.
Fred Drake693aea22003-02-07 14:52:18 +0000715Running \code{python setup.py register} will collect the metadata
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000716describing a package, such as its name, version, maintainer,
Andrew M. Kuchlingc61402b2003-02-26 19:00:52 +0000717description, \&c., and send it to a central catalog server. The
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000718resulting catalog is available from \url{http://www.python.org/pypi}.
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000719
720To make the catalog a bit more useful, a new optional
Fred Drake693aea22003-02-07 14:52:18 +0000721\var{classifiers} keyword argument has been added to the Distutils
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000722\function{setup()} function. A list of
Fred Drake693aea22003-02-07 14:52:18 +0000723\ulink{Trove}{http://catb.org/\textasciitilde esr/trove/}-style
724strings can be supplied to help classify the software.
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000725
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +0000726Here's an example \file{setup.py} with classifiers, written to be compatible
727with older versions of the Distutils:
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000728
729\begin{verbatim}
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +0000730from distutils import core
Fred Drake693aea22003-02-07 14:52:18 +0000731kw = {'name': "Quixote",
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +0000732 'version': "0.5.1",
733 'description': "A highly Pythonic Web application framework",
Fred Drake693aea22003-02-07 14:52:18 +0000734 # ...
735 }
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +0000736
Andrew M. Kuchlinga6b1c752003-04-09 17:26:38 +0000737if (hasattr(core, 'setup_keywords') and
738 'classifiers' in core.setup_keywords):
Fred Drake693aea22003-02-07 14:52:18 +0000739 kw['classifiers'] = \
740 ['Topic :: Internet :: WWW/HTTP :: Dynamic Content',
741 'Environment :: No Input/Output (Daemon)',
742 'Intended Audience :: Developers'],
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +0000743
Fred Drake693aea22003-02-07 14:52:18 +0000744core.setup(**kw)
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000745\end{verbatim}
746
747The full list of classifiers can be obtained by running
748\code{python setup.py register --list-classifiers}.
Andrew M. Kuchling87cebbf2003-01-03 16:24:28 +0000749
750\begin{seealso}
751
Fred Drake693aea22003-02-07 14:52:18 +0000752\seepep{301}{Package Index and Metadata for Distutils}{Written and
753implemented by Richard Jones.}
Andrew M. Kuchling87cebbf2003-01-03 16:24:28 +0000754
755\end{seealso}
756
757
758%======================================================================
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000759\section{PEP 302: New Import Hooks \label{section-pep302}}
760
761While it's been possible to write custom import hooks ever since the
762\module{ihooks} module was introduced in Python 1.3, no one has ever
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000763been really happy with it because writing new import hooks is
764difficult and messy. There have been various proposed alternatives
765such as the \module{imputil} and \module{iu} modules, but none of them
766has ever gained much acceptance, and none of them were easily usable
767from \C{} code.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000768
769\pep{302} borrows ideas from its predecessors, especially from
770Gordon McMillan's \module{iu} module. Three new items
771are added to the \module{sys} module:
772
773\begin{itemize}
Andrew M. Kuchlingd5ac8d02003-01-02 21:33:15 +0000774 \item \code{sys.path_hooks} is a list of callable objects; most
Fred Drakeaac8c582003-01-17 22:50:10 +0000775 often they'll be classes. Each callable takes a string containing a
776 path and either returns an importer object that will handle imports
777 from this path or raises an \exception{ImportError} exception if it
778 can't handle this path.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000779
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000780 \item \code{sys.path_importer_cache} caches importer objects for
Fred Drakeaac8c582003-01-17 22:50:10 +0000781 each path, so \code{sys.path_hooks} will only need to be traversed
782 once for each path.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000783
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000784 \item \code{sys.meta_path} is a list of importer objects that will
785 be traversed before \code{sys.path} is checked. This list is
786 initially empty, but user code can add objects to it. Additional
787 built-in and frozen modules can be imported by an object added to
788 this list.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000789
790\end{itemize}
791
792Importer objects must have a single method,
793\method{find_module(\var{fullname}, \var{path}=None)}. \var{fullname}
794will be a module or package name, e.g. \samp{string} or
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000795\samp{distutils.core}. \method{find_module()} must return a loader object
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000796that has a single method, \method{load_module(\var{fullname})}, that
797creates and returns the corresponding module object.
798
799Pseudo-code for Python's new import logic, therefore, looks something
800like this (simplified a bit; see \pep{302} for the full details):
801
802\begin{verbatim}
803for mp in sys.meta_path:
804 loader = mp(fullname)
805 if loader is not None:
Andrew M. Kuchlingd5ac8d02003-01-02 21:33:15 +0000806 <module> = loader.load_module(fullname)
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000807
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000808for path in sys.path:
809 for hook in sys.path_hooks:
Andrew M. Kuchlingd5ac8d02003-01-02 21:33:15 +0000810 try:
811 importer = hook(path)
812 except ImportError:
813 # ImportError, so try the other path hooks
814 pass
815 else:
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000816 loader = importer.find_module(fullname)
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000817 <module> = loader.load_module(fullname)
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000818
819# Not found!
820raise ImportError
821\end{verbatim}
822
823\begin{seealso}
824
825\seepep{302}{New Import Hooks}{Written by Just van~Rossum and Paul Moore.
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +0000826Implemented by Just van~Rossum.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000827}
828
829\end{seealso}
830
831
832%======================================================================
Andrew M. Kuchlinga978e102003-03-21 18:10:12 +0000833\section{PEP 305: Comma-separated Files \label{section-pep305}}
834
835Comma-separated files are a format frequently used for exporting data
836from databases and spreadsheets. Python 2.3 adds a parser for
837comma-separated files.
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000838
839Comma-separated format is deceptively simple at first glance:
Andrew M. Kuchlinga978e102003-03-21 18:10:12 +0000840
841\begin{verbatim}
842Costs,150,200,3.95
843\end{verbatim}
844
845Read a line and call \code{line.split(',')}: what could be simpler?
846But toss in string data that can contain commas, and things get more
847complicated:
848
849\begin{verbatim}
850"Costs",150,200,3.95,"Includes taxes, shipping, and sundry items"
851\end{verbatim}
852
853A big ugly regular expression can parse this, but using the new
854\module{csv} package is much simpler:
855
856\begin{verbatim}
Andrew M. Kuchlingba887bb2003-04-13 21:13:02 +0000857import csv
Andrew M. Kuchlinga978e102003-03-21 18:10:12 +0000858
859input = open('datafile', 'rb')
860reader = csv.reader(input)
861for line in reader:
862 print line
863\end{verbatim}
864
865The \function{reader} function takes a number of different options.
866The field separator isn't limited to the comma and can be changed to
867any character, and so can the quoting and line-ending characters.
868
869Different dialects of comma-separated files can be defined and
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000870registered; currently there are two dialects, both used by Microsoft Excel.
Andrew M. Kuchlinga978e102003-03-21 18:10:12 +0000871A separate \class{csv.writer} class will generate comma-separated files
872from a succession of tuples or lists, quoting strings that contain the
873delimiter.
874
875\begin{seealso}
876
877\seepep{305}{CSV File API}{Written and implemented
878by Kevin Altis, Dave Cole, Andrew McNamara, Skip Montanaro, Cliff Wells.
879}
880
881\end{seealso}
882
883%======================================================================
Andrew M. Kuchlinga092ba12003-03-21 18:32:43 +0000884\section{PEP 307: Pickle Enhancements \label{section-pep305}}
885
886The \module{pickle} and \module{cPickle} modules received some
887attention during the 2.3 development cycle. In 2.2, new-style classes
Andrew M. Kuchlinga6b1c752003-04-09 17:26:38 +0000888could be pickled without difficulty, but they weren't pickled very
Andrew M. Kuchlinga092ba12003-03-21 18:32:43 +0000889compactly; \pep{307} quotes a trivial example where a new-style class
890results in a pickled string three times longer than that for a classic
891class.
892
893The solution was to invent a new pickle protocol. The
894\function{pickle.dumps()} function has supported a text-or-binary flag
895for a long time. In 2.3, this flag is redefined from a Boolean to an
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000896integer: 0 is the old text-mode pickle format, 1 is the old binary
897format, and now 2 is a new 2.3-specific format. A new constant,
Andrew M. Kuchlinga092ba12003-03-21 18:32:43 +0000898\constant{pickle.HIGHEST_PROTOCOL}, can be used to select the fanciest
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000899protocol available.
Andrew M. Kuchlinga092ba12003-03-21 18:32:43 +0000900
901Unpickling is no longer considered a safe operation. 2.2's
902\module{pickle} provided hooks for trying to prevent unsafe classes
903from being unpickled (specifically, a
904\member{__safe_for_unpickling__} attribute), but none of this code
905was ever audited and therefore it's all been ripped out in 2.3. You
906should not unpickle untrusted data in any version of Python.
907
908To reduce the pickling overhead for new-style classes, a new interface
909for customizing pickling was added using three special methods:
910\method{__getstate__}, \method{__setstate__}, and
911\method{__getnewargs__}. Consult \pep{307} for the full semantics
912of these methods.
913
914As a way to compress pickles yet further, it's now possible to use
915integer codes instead of long strings to identify pickled classes.
916The Python Software Foundation will maintain a list of standardized
917codes; there's also a range of codes for private use. Currently no
918codes have been specified.
919
920\begin{seealso}
921
922\seepep{307}{Extensions to the pickle protocol}{Written and implemented
923by Guido van Rossum and Tim Peters.}
924
925\end{seealso}
926
927%======================================================================
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000928\section{Extended Slices\label{section-slices}}
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000929
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000930Ever since Python 1.4, the slicing syntax has supported an optional
931third ``step'' or ``stride'' argument. For example, these are all
932legal Python syntax: \code{L[1:10:2]}, \code{L[:-1:1]},
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000933\code{L[::-1]}. This was added to Python at the request of
934the developers of Numerical Python, which uses the third argument
935extensively. However, Python's built-in list, tuple, and string
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000936sequence types have never supported this feature, raising a
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000937\exception{TypeError} if you tried it. Michael Hudson contributed a
938patch to fix this shortcoming.
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000939
940For example, you can now easily extract the elements of a list that
941have even indexes:
Fred Drakedf872a22002-07-03 12:02:01 +0000942
943\begin{verbatim}
944>>> L = range(10)
945>>> L[::2]
946[0, 2, 4, 6, 8]
947\end{verbatim}
948
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000949Negative values also work to make a copy of the same list in reverse
950order:
Fred Drakedf872a22002-07-03 12:02:01 +0000951
952\begin{verbatim}
953>>> L[::-1]
954[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
955\end{verbatim}
Andrew M. Kuchling3a52ff62002-04-03 22:44:47 +0000956
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000957This also works for tuples, arrays, and strings:
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000958
959\begin{verbatim}
960>>> s='abcd'
961>>> s[::2]
962'ac'
963>>> s[::-1]
964'dcba'
965\end{verbatim}
966
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000967If you have a mutable sequence such as a list or an array you can
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000968assign to or delete an extended slice, but there are some differences
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000969between assignment to extended and regular slices. Assignment to a
970regular slice can be used to change the length of the sequence:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000971
972\begin{verbatim}
973>>> a = range(3)
974>>> a
975[0, 1, 2]
976>>> a[1:3] = [4, 5, 6]
977>>> a
978[0, 4, 5, 6]
979\end{verbatim}
980
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000981Extended slices aren't this flexible. When assigning to an extended
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000982slice, the list on the right hand side of the statement must contain
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000983the same number of items as the slice it is replacing:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000984
985\begin{verbatim}
986>>> a = range(4)
987>>> a
988[0, 1, 2, 3]
989>>> a[::2]
990[0, 2]
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000991>>> a[::2] = [0, -1]
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000992>>> a
993[0, 1, -1, 3]
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000994>>> a[::2] = [0,1,2]
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000995Traceback (most recent call last):
996 File "<stdin>", line 1, in ?
Raymond Hettingeree1bded2003-01-17 16:20:23 +0000997ValueError: attempt to assign sequence of size 3 to extended slice of size 2
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000998\end{verbatim}
999
1000Deletion is more straightforward:
1001
1002\begin{verbatim}
1003>>> a = range(4)
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001004>>> a
1005[0, 1, 2, 3]
Michael W. Hudson4da01ed2002-07-19 15:48:56 +00001006>>> a[::2]
1007[0, 2]
1008>>> del a[::2]
1009>>> a
1010[1, 3]
1011\end{verbatim}
1012
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001013One can also now pass slice objects to the
1014\method{__getitem__} methods of the built-in sequences:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +00001015
1016\begin{verbatim}
1017>>> range(10).__getitem__(slice(0, 5, 2))
1018[0, 2, 4]
1019\end{verbatim}
1020
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001021Or use slice objects directly in subscripts:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +00001022
1023\begin{verbatim}
1024>>> range(10)[slice(0, 5, 2)]
1025[0, 2, 4]
1026\end{verbatim}
1027
Andrew M. Kuchlingb6f79592002-11-29 19:43:45 +00001028To simplify implementing sequences that support extended slicing,
1029slice objects now have a method \method{indices(\var{length})} which,
Fred Drakeaac8c582003-01-17 22:50:10 +00001030given the length of a sequence, returns a \code{(\var{start},
1031\var{stop}, \var{step})} tuple that can be passed directly to
1032\function{range()}.
Andrew M. Kuchlingb6f79592002-11-29 19:43:45 +00001033\method{indices()} handles omitted and out-of-bounds indices in a
1034manner consistent with regular slices (and this innocuous phrase hides
1035a welter of confusing details!). The method is intended to be used
1036like this:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +00001037
1038\begin{verbatim}
1039class FakeSeq:
1040 ...
1041 def calc_item(self, i):
1042 ...
1043 def __getitem__(self, item):
1044 if isinstance(item, slice):
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001045 indices = item.indices(len(self))
1046 return FakeSeq([self.calc_item(i) in range(*indices)])
Fred Drake5c4cf152002-11-13 14:59:06 +00001047 else:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +00001048 return self.calc_item(i)
1049\end{verbatim}
1050
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001051From this example you can also see that the built-in \class{slice}
Andrew M. Kuchling90e9a792002-08-15 00:40:21 +00001052object is now the type object for the slice type, and is no longer a
1053function. This is consistent with Python 2.2, where \class{int},
1054\class{str}, etc., underwent the same change.
1055
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001056
Andrew M. Kuchling3a52ff62002-04-03 22:44:47 +00001057%======================================================================
Fred Drakedf872a22002-07-03 12:02:01 +00001058\section{Other Language Changes}
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001059
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001060Here are all of the changes that Python 2.3 makes to the core Python
1061language.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001062
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001063\begin{itemize}
1064\item The \keyword{yield} statement is now always a keyword, as
1065described in section~\ref{section-generators} of this document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001066
Fred Drake5c4cf152002-11-13 14:59:06 +00001067\item A new built-in function \function{enumerate()}
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001068was added, as described in section~\ref{section-enumerate} of this
1069document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001070
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001071\item Two new constants, \constant{True} and \constant{False} were
1072added along with the built-in \class{bool} type, as described in
1073section~\ref{section-bool} of this document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001074
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00001075\item The \function{int()} type constructor will now return a long
1076integer instead of raising an \exception{OverflowError} when a string
1077or floating-point number is too large to fit into an integer. This
1078can lead to the paradoxical result that
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001079\code{isinstance(int(\var{expression}), int)} is false, but that seems
1080unlikely to cause problems in practice.
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00001081
Fred Drake5c4cf152002-11-13 14:59:06 +00001082\item Built-in types now support the extended slicing syntax,
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001083as described in section~\ref{section-slices} of this document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001084
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001085\item A new built-in function, \function{sum(\var{iterable}, \var{start}=0)},
1086adds up the numeric items in the iterable object and returns their sum.
1087\function{sum()} only accepts numbers, meaning that you can't use it
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +00001088to concatenate a bunch of strings. (Contributed by Alex
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001089Martelli.)
1090
Andrew M. Kuchlingfcf6b3e2003-05-07 17:00:35 +00001091\item \code{list.insert(\var{pos}, \var{value})} used to
1092insert \var{value} at the front of the list when \var{pos} was
1093negative. The behaviour has now been changed to be consistent with
1094slice indexing, so when \var{pos} is -1 the value will be inserted
1095before the last element, and so forth.
1096
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +00001097\item \code{list.index(\var{value})}, which searches for \var{value}
1098within the list and returns its index, now takes optional
1099\var{start} and \var{stop} arguments to limit the search to
1100only part of the list.
1101
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +00001102\item Dictionaries have a new method, \method{pop(\var{key}\optional{,
1103\var{default}})}, that returns the value corresponding to \var{key}
1104and removes that key/value pair from the dictionary. If the requested
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001105key isn't present in the dictionary, \var{default} is returned if it's
1106specified and \exception{KeyError} raised if it isn't.
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001107
1108\begin{verbatim}
1109>>> d = {1:2}
1110>>> d
1111{1: 2}
1112>>> d.pop(4)
1113Traceback (most recent call last):
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +00001114 File "stdin", line 1, in ?
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001115KeyError: 4
1116>>> d.pop(1)
11172
1118>>> d.pop(1)
1119Traceback (most recent call last):
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +00001120 File "stdin", line 1, in ?
Raymond Hettingeree1bded2003-01-17 16:20:23 +00001121KeyError: 'pop(): dictionary is empty'
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001122>>> d
1123{}
1124>>>
1125\end{verbatim}
1126
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001127There's also a new class method,
1128\method{dict.fromkeys(\var{iterable}, \var{value})}, that
1129creates a dictionary with keys taken from the supplied iterator
1130\var{iterable} and all values set to \var{value}, defaulting to
1131\code{None}.
1132
1133(Patches contributed by Raymond Hettinger.)
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001134
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001135Also, the \function{dict()} constructor now accepts keyword arguments to
Raymond Hettinger45bda572002-12-14 20:20:45 +00001136simplify creating small dictionaries:
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001137
1138\begin{verbatim}
1139>>> dict(red=1, blue=2, green=3, black=4)
1140{'blue': 2, 'black': 4, 'green': 3, 'red': 1}
1141\end{verbatim}
1142
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +00001143(Contributed by Just van~Rossum.)
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001144
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +00001145\item The \keyword{assert} statement no longer checks the \code{__debug__}
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001146flag, so you can no longer disable assertions by assigning to \code{__debug__}.
Fred Drake5c4cf152002-11-13 14:59:06 +00001147Running Python with the \programopt{-O} switch will still generate
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001148code that doesn't execute any assertions.
1149
1150\item Most type objects are now callable, so you can use them
1151to create new objects such as functions, classes, and modules. (This
1152means that the \module{new} module can be deprecated in a future
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001153Python version, because you can now use the type objects available in
1154the \module{types} module.)
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001155% XXX should new.py use PendingDeprecationWarning?
1156For example, you can create a new module object with the following code:
1157
1158\begin{verbatim}
1159>>> import types
1160>>> m = types.ModuleType('abc','docstring')
1161>>> m
1162<module 'abc' (built-in)>
1163>>> m.__doc__
1164'docstring'
1165\end{verbatim}
1166
Fred Drake5c4cf152002-11-13 14:59:06 +00001167\item
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001168A new warning, \exception{PendingDeprecationWarning} was added to
1169indicate features which are in the process of being
1170deprecated. The warning will \emph{not} be printed by default. To
1171check for use of features that will be deprecated in the future,
1172supply \programopt{-Walways::PendingDeprecationWarning::} on the
1173command line or use \function{warnings.filterwarnings()}.
1174
Andrew M. Kuchlingc1dd1742003-01-13 13:59:22 +00001175\item The process of deprecating string-based exceptions, as
1176in \code{raise "Error occurred"}, has begun. Raising a string will
1177now trigger \exception{PendingDeprecationWarning}.
1178
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001179\item Using \code{None} as a variable name will now result in a
1180\exception{SyntaxWarning} warning. In a future version of Python,
1181\code{None} may finally become a keyword.
1182
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001183\item The \method{xreadlines()} method of file objects, introduced in
1184Python 2.1, is no longer necessary because files now behave as their
1185own iterator. \method{xreadlines()} was originally introduced as a
1186faster way to loop over all the lines in a file, but now you can
1187simply write \code{for line in file_obj}. File objects also have a
1188new read-only \member{encoding} attribute that gives the encoding used
1189by the file; Unicode strings written to the file will be automatically
1190converted to bytes using the given encoding.
1191
Andrew M. Kuchlingb60ea3f2002-11-15 14:37:10 +00001192\item The method resolution order used by new-style classes has
1193changed, though you'll only notice the difference if you have a really
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +00001194complicated inheritance hierarchy. Classic classes are unaffected by
1195this change. Python 2.2 originally used a topological sort of a
Andrew M. Kuchlingb60ea3f2002-11-15 14:37:10 +00001196class's ancestors, but 2.3 now uses the C3 algorithm as described in
Andrew M. Kuchling6f429c32002-11-19 13:09:00 +00001197the paper \ulink{``A Monotonic Superclass Linearization for
1198Dylan''}{http://www.webcom.com/haahr/dylan/linearization-oopsla96.html}.
Andrew M. Kuchlingc1dd1742003-01-13 13:59:22 +00001199To understand the motivation for this change,
1200read Michele Simionato's article
Fred Drake693aea22003-02-07 14:52:18 +00001201\ulink{``Python 2.3 Method Resolution Order''}
Andrew M. Kuchlingb8a39052003-02-07 20:22:33 +00001202 {http://www.python.org/2.3/mro.html}, or
Andrew M. Kuchlingc1dd1742003-01-13 13:59:22 +00001203read the thread on python-dev starting with the message at
Andrew M. Kuchlingb60ea3f2002-11-15 14:37:10 +00001204\url{http://mail.python.org/pipermail/python-dev/2002-October/029035.html}.
1205Samuele Pedroni first pointed out the problem and also implemented the
1206fix by coding the C3 algorithm.
1207
Andrew M. Kuchlingdcfd8252002-09-13 22:21:42 +00001208\item Python runs multithreaded programs by switching between threads
1209after executing N bytecodes. The default value for N has been
1210increased from 10 to 100 bytecodes, speeding up single-threaded
1211applications by reducing the switching overhead. Some multithreaded
1212applications may suffer slower response time, but that's easily fixed
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001213by setting the limit back to a lower number using
Andrew M. Kuchlingdcfd8252002-09-13 22:21:42 +00001214\function{sys.setcheckinterval(\var{N})}.
Andrew M. Kuchlingc760c6c2003-07-16 20:12:33 +00001215The limit can be retrieved with the new
1216\function{sys.getcheckinterval()} function.
Andrew M. Kuchlingdcfd8252002-09-13 22:21:42 +00001217
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001218\item One minor but far-reaching change is that the names of extension
1219types defined by the modules included with Python now contain the
Fred Drake5c4cf152002-11-13 14:59:06 +00001220module and a \character{.} in front of the type name. For example, in
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001221Python 2.2, if you created a socket and printed its
1222\member{__class__}, you'd get this output:
1223
1224\begin{verbatim}
1225>>> s = socket.socket()
1226>>> s.__class__
1227<type 'socket'>
1228\end{verbatim}
1229
1230In 2.3, you get this:
1231\begin{verbatim}
1232>>> s.__class__
1233<type '_socket.socket'>
1234\end{verbatim}
1235
Michael W. Hudson96bc3b42002-11-26 14:48:23 +00001236\item One of the noted incompatibilities between old- and new-style
1237 classes has been removed: you can now assign to the
1238 \member{__name__} and \member{__bases__} attributes of new-style
1239 classes. There are some restrictions on what can be assigned to
1240 \member{__bases__} along the lines of those relating to assigning to
1241 an instance's \member{__class__} attribute.
1242
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001243\end{itemize}
1244
1245
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001246%======================================================================
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001247\subsection{String Changes}
1248
1249\begin{itemize}
1250
Fred Drakeaac8c582003-01-17 22:50:10 +00001251\item The \keyword{in} operator now works differently for strings.
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001252Previously, when evaluating \code{\var{X} in \var{Y}} where \var{X}
1253and \var{Y} are strings, \var{X} could only be a single character.
1254That's now changed; \var{X} can be a string of any length, and
1255\code{\var{X} in \var{Y}} will return \constant{True} if \var{X} is a
1256substring of \var{Y}. If \var{X} is the empty string, the result is
1257always \constant{True}.
1258
1259\begin{verbatim}
1260>>> 'ab' in 'abcd'
1261True
1262>>> 'ad' in 'abcd'
1263False
1264>>> '' in 'abcd'
1265True
1266\end{verbatim}
1267
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001268Note that this doesn't tell you where the substring starts; if you
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +00001269need that information, use the \method{find()} string method.
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001270
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001271\item The \method{strip()}, \method{lstrip()}, and \method{rstrip()}
1272string methods now have an optional argument for specifying the
1273characters to strip. The default is still to remove all whitespace
1274characters:
1275
1276\begin{verbatim}
1277>>> ' abc '.strip()
1278'abc'
1279>>> '><><abc<><><>'.strip('<>')
1280'abc'
1281>>> '><><abc<><><>\n'.strip('<>')
1282'abc<><><>\n'
1283>>> u'\u4000\u4001abc\u4000'.strip(u'\u4000')
1284u'\u4001abc'
1285>>>
1286\end{verbatim}
1287
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001288(Suggested by Simon Brunning and implemented by Walter D\"orwald.)
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00001289
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001290\item The \method{startswith()} and \method{endswith()}
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001291string methods now accept negative numbers for the \var{start} and \var{end}
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001292parameters.
1293
1294\item Another new string method is \method{zfill()}, originally a
1295function in the \module{string} module. \method{zfill()} pads a
1296numeric string with zeros on the left until it's the specified width.
1297Note that the \code{\%} operator is still more flexible and powerful
1298than \method{zfill()}.
1299
1300\begin{verbatim}
1301>>> '45'.zfill(4)
1302'0045'
1303>>> '12345'.zfill(4)
1304'12345'
1305>>> 'goofy'.zfill(6)
1306'0goofy'
1307\end{verbatim}
1308
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00001309(Contributed by Walter D\"orwald.)
1310
Fred Drake5c4cf152002-11-13 14:59:06 +00001311\item A new type object, \class{basestring}, has been added.
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001312 Both 8-bit strings and Unicode strings inherit from this type, so
1313 \code{isinstance(obj, basestring)} will return \constant{True} for
1314 either kind of string. It's a completely abstract type, so you
1315 can't create \class{basestring} instances.
1316
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001317\item Interned strings are no longer immortal and will now be
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001318garbage-collected in the usual way when the only reference to them is
1319from the internal dictionary of interned strings. (Implemented by
1320Oren Tirosh.)
1321
1322\end{itemize}
1323
1324
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001325%======================================================================
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001326\subsection{Optimizations}
1327
1328\begin{itemize}
1329
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001330\item The creation of new-style class instances has been made much
1331faster; they're now faster than classic classes!
1332
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001333\item The \method{sort()} method of list objects has been extensively
1334rewritten by Tim Peters, and the implementation is significantly
1335faster.
1336
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001337\item Multiplication of large long integers is now much faster thanks
1338to an implementation of Karatsuba multiplication, an algorithm that
1339scales better than the O(n*n) required for the grade-school
1340multiplication algorithm. (Original patch by Christopher A. Craig,
1341and significantly reworked by Tim Peters.)
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001342
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001343\item The \code{SET_LINENO} opcode is now gone. This may provide a
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001344small speed increase, depending on your compiler's idiosyncrasies.
1345See section~\ref{section-other} for a longer explanation.
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001346(Removed by Michael Hudson.)
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001347
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001348\item \function{xrange()} objects now have their own iterator, making
1349\code{for i in xrange(n)} slightly faster than
1350\code{for i in range(n)}. (Patch by Raymond Hettinger.)
1351
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001352\item A number of small rearrangements have been made in various
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001353hotspots to improve performance, such as inlining a function or removing
1354some code. (Implemented mostly by GvR, but lots of people have
1355contributed single changes.)
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001356
1357\end{itemize}
Neal Norwitzd68f5172002-05-29 15:54:55 +00001358
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001359The net result of the 2.3 optimizations is that Python 2.3 runs the
1360pystone benchmark around 25\% faster than Python 2.2.
1361
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001362
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001363%======================================================================
Andrew M. Kuchlingef893fe2003-01-06 20:04:17 +00001364\section{New, Improved, and Deprecated Modules}
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00001365
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001366As usual, Python's standard library received a number of enhancements and
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001367bug fixes. Here's a partial list of the most notable changes, sorted
1368alphabetically by module name. Consult the
1369\file{Misc/NEWS} file in the source tree for a more
1370complete list of changes, or look through the CVS logs for all the
1371details.
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00001372
1373\begin{itemize}
1374
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001375\item The \module{array} module now supports arrays of Unicode
Fred Drake5c4cf152002-11-13 14:59:06 +00001376characters using the \character{u} format character. Arrays also now
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001377support using the \code{+=} assignment operator to add another array's
1378contents, and the \code{*=} assignment operator to repeat an array.
1379(Contributed by Jason Orendorff.)
1380
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001381\item The \module{bsddb} module has been replaced by version 4.1.1
Andrew M. Kuchling669249e2002-11-19 13:05:33 +00001382of the \ulink{PyBSDDB}{http://pybsddb.sourceforge.net} package,
1383providing a more complete interface to the transactional features of
1384the BerkeleyDB library.
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001385
Andrew M. Kuchling669249e2002-11-19 13:05:33 +00001386The old version of the module has been renamed to
1387\module{bsddb185} and is no longer built automatically; you'll
1388have to edit \file{Modules/Setup} to enable it. Note that the new
1389\module{bsddb} package is intended to be compatible with the
1390old module, so be sure to file bugs if you discover any
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001391incompatibilities. When upgrading to Python 2.3, if the new interpreter is compiled
1392with a new version of
Skip Montanaro959c7722003-03-07 15:45:15 +00001393the underlying BerkeleyDB library, you will almost certainly have to
1394convert your database files to the new version. You can do this
1395fairly easily with the new scripts \file{db2pickle.py} and
1396\file{pickle2db.py} which you will find in the distribution's
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001397\file{Tools/scripts} directory. If you've already been using the PyBSDDB
Andrew M. Kuchlinge36b6902003-04-19 15:38:47 +00001398package and importing it as \module{bsddb3}, you will have to change your
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001399\code{import} statements to import it as \module{bsddb}.
Andrew M. Kuchlinge36b6902003-04-19 15:38:47 +00001400
1401\item The new \module{bz2} module is an interface to the bz2 data
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001402compression library. bz2-compressed data is usually smaller than
1403corresponding \module{zlib}-compressed data. (Contributed by Gustavo Niemeyer.)
Andrew M. Kuchling669249e2002-11-19 13:05:33 +00001404
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001405\item A set of standard date/type types has been added in the new \module{datetime}
1406module. See the following section for more details.
1407
Fred Drake5c4cf152002-11-13 14:59:06 +00001408\item The Distutils \class{Extension} class now supports
1409an extra constructor argument named \var{depends} for listing
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001410additional source files that an extension depends on. This lets
1411Distutils recompile the module if any of the dependency files are
Fred Drake5c4cf152002-11-13 14:59:06 +00001412modified. For example, if \file{sampmodule.c} includes the header
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001413file \file{sample.h}, you would create the \class{Extension} object like
1414this:
1415
1416\begin{verbatim}
1417ext = Extension("samp",
1418 sources=["sampmodule.c"],
1419 depends=["sample.h"])
1420\end{verbatim}
1421
1422Modifying \file{sample.h} would then cause the module to be recompiled.
1423(Contributed by Jeremy Hylton.)
1424
Andrew M. Kuchlingdc3f7e12002-11-04 20:05:10 +00001425\item Other minor changes to Distutils:
1426it now checks for the \envvar{CC}, \envvar{CFLAGS}, \envvar{CPP},
1427\envvar{LDFLAGS}, and \envvar{CPPFLAGS} environment variables, using
1428them to override the settings in Python's configuration (contributed
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +00001429by Robert Weber).
Andrew M. Kuchlingdc3f7e12002-11-04 20:05:10 +00001430
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001431\item Previously the \module{doctest} module would only search the
1432docstrings of public methods and functions for test cases, but it now
1433also examines private ones as well. The \function{DocTestSuite(}
1434function creates a \class{unittest.TestSuite} object from a set of
1435\module{doctest} tests.
1436
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001437\item The new \function{gc.get_referents(\var{object})} function returns a
1438list of all the objects referenced by \var{object}.
1439
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001440\item The \module{getopt} module gained a new function,
1441\function{gnu_getopt()}, that supports the same arguments as the existing
Fred Drake5c4cf152002-11-13 14:59:06 +00001442\function{getopt()} function but uses GNU-style scanning mode.
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001443The existing \function{getopt()} stops processing options as soon as a
1444non-option argument is encountered, but in GNU-style mode processing
1445continues, meaning that options and arguments can be mixed. For
1446example:
1447
1448\begin{verbatim}
1449>>> getopt.getopt(['-f', 'filename', 'output', '-v'], 'f:v')
1450([('-f', 'filename')], ['output', '-v'])
1451>>> getopt.gnu_getopt(['-f', 'filename', 'output', '-v'], 'f:v')
1452([('-f', 'filename'), ('-v', '')], ['output'])
1453\end{verbatim}
1454
1455(Contributed by Peter \AA{strand}.)
1456
1457\item The \module{grp}, \module{pwd}, and \module{resource} modules
Fred Drake5c4cf152002-11-13 14:59:06 +00001458now return enhanced tuples:
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001459
1460\begin{verbatim}
1461>>> import grp
1462>>> g = grp.getgrnam('amk')
1463>>> g.gr_name, g.gr_gid
1464('amk', 500)
1465\end{verbatim}
1466
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001467\item The \module{gzip} module can now handle files exceeding 2~Gb.
1468
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001469\item The new \module{heapq} module contains an implementation of a
1470heap queue algorithm. A heap is an array-like data structure that
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001471keeps items in a partially sorted order such that, for every index
1472\var{k}, \code{heap[\var{k}] <= heap[2*\var{k}+1]} and
1473\code{heap[\var{k}] <= heap[2*\var{k}+2]}. This makes it quick to
1474remove the smallest item, and inserting a new item while maintaining
1475the heap property is O(lg~n). (See
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001476\url{http://www.nist.gov/dads/HTML/priorityque.html} for more
1477information about the priority queue data structure.)
1478
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001479The \module{heapq} module provides \function{heappush()} and
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001480\function{heappop()} functions for adding and removing items while
1481maintaining the heap property on top of some other mutable Python
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001482sequence type. Here's an example that uses a Python list:
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001483
1484\begin{verbatim}
1485>>> import heapq
1486>>> heap = []
1487>>> for item in [3, 7, 5, 11, 1]:
1488... heapq.heappush(heap, item)
1489...
1490>>> heap
1491[1, 3, 5, 11, 7]
1492>>> heapq.heappop(heap)
14931
1494>>> heapq.heappop(heap)
14953
1496>>> heap
1497[5, 7, 11]
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001498\end{verbatim}
1499
1500(Contributed by Kevin O'Connor.)
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001501
Andrew M. Kuchling6e73f9e2003-07-18 01:15:51 +00001502\item The IDLE integrated development environment has been updated
1503using the code from the IDLEfork project
1504(\url{http://idlefork.sf.net}). The most notable feature is that the
1505code being developed is now executed in a subprocess, meaning that
1506there's no longer any need for manual \code{reload()} operations.
1507IDLE's core code has been incorporated into the standard library as the
1508\module{idlelib} package.
1509
Andrew M. Kuchling87cebbf2003-01-03 16:24:28 +00001510\item The \module{imaplib} module now supports IMAP over SSL.
1511(Contributed by Piers Lauder and Tino Lange.)
1512
Andrew M. Kuchling41c3e002003-03-02 02:13:52 +00001513\item The \module{itertools} contains a number of useful functions for
1514use with iterators, inspired by various functions provided by the ML
1515and Haskell languages. For example,
1516\code{itertools.ifilter(predicate, iterator)} returns all elements in
1517the iterator for which the function \function{predicate()} returns
Andrew M. Kuchling563389f2003-03-02 02:31:58 +00001518\constant{True}, and \code{itertools.repeat(obj, \var{N})} returns
Andrew M. Kuchling41c3e002003-03-02 02:13:52 +00001519\code{obj} \var{N} times. There are a number of other functions in
1520the module; see the \ulink{package's reference
1521documentation}{../lib/module-itertools.html} for details.
Raymond Hettinger5284b442003-03-09 07:19:38 +00001522(Contributed by Raymond Hettinger.)
Fred Drakecade7132003-02-19 16:08:08 +00001523
Fred Drake5c4cf152002-11-13 14:59:06 +00001524\item Two new functions in the \module{math} module,
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001525\function{degrees(\var{rads})} and \function{radians(\var{degs})},
Fred Drake5c4cf152002-11-13 14:59:06 +00001526convert between radians and degrees. Other functions in the
Andrew M. Kuchling8e5b53b2002-12-15 20:17:38 +00001527\module{math} module such as \function{math.sin()} and
1528\function{math.cos()} have always required input values measured in
1529radians. Also, an optional \var{base} argument was added to
1530\function{math.log()} to make it easier to compute logarithms for
1531bases other than \code{e} and \code{10}. (Contributed by Raymond
1532Hettinger.)
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001533
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001534\item Several new POSIX functions (\function{getpgid()}, \function{killpg()},
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +00001535\function{lchown()}, \function{loadavg()}, \function{major()}, \function{makedev()},
1536\function{minor()}, and \function{mknod()}) were added to the
Andrew M. Kuchlingc309cca2002-10-10 16:04:08 +00001537\module{posix} module that underlies the \module{os} module.
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +00001538(Contributed by Gustavo Niemeyer, Geert Jansen, and Denis S. Otkidach.)
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001539
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001540\item In the \module{os} module, the \function{*stat()} family of
1541functions can now report fractions of a second in a timestamp. Such
1542time stamps are represented as floats, similar to
1543the value returned by \function{time.time()}.
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001544
1545During testing, it was found that some applications will break if time
1546stamps are floats. For compatibility, when using the tuple interface
1547of the \class{stat_result} time stamps will be represented as integers.
1548When using named fields (a feature first introduced in Python 2.2),
1549time stamps are still represented as integers, unless
1550\function{os.stat_float_times()} is invoked to enable float return
1551values:
1552
1553\begin{verbatim}
1554>>> os.stat("/tmp").st_mtime
15551034791200
1556>>> os.stat_float_times(True)
1557>>> os.stat("/tmp").st_mtime
15581034791200.6335014
1559\end{verbatim}
1560
1561In Python 2.4, the default will change to always returning floats.
1562
1563Application developers should enable this feature only if all their
1564libraries work properly when confronted with floating point time
1565stamps, or if they use the tuple API. If used, the feature should be
1566activated on an application level instead of trying to enable it on a
1567per-use basis.
1568
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001569\item The \module{optparse} module contains a new parser for command-line arguments
1570that can convert option values to a particular Python type
1571and will automatically generate a usage message. See the following section for
1572more details.
1573
Andrew M. Kuchling53262572002-12-01 14:00:21 +00001574\item The old and never-documented \module{linuxaudiodev} module has
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001575been deprecated, and a new version named \module{ossaudiodev} has been
1576added. The module was renamed because the OSS sound drivers can be
1577used on platforms other than Linux, and the interface has also been
1578tidied and brought up to date in various ways. (Contributed by Greg
Greg Wardaa1d3aa2003-01-03 18:03:21 +00001579Ward and Nicholas FitzRoy-Dale.)
Andrew M. Kuchling53262572002-12-01 14:00:21 +00001580
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001581\item The new \module{platform} module contains a number of functions
1582that try to determine various properties of the platform you're
1583running on. There are functions for getting the architecture, CPU
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001584type, the Windows OS version, and even the Linux distribution version.
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001585(Contributed by Marc-Andr\'e Lemburg.)
1586
Fred Drake5c4cf152002-11-13 14:59:06 +00001587\item The parser objects provided by the \module{pyexpat} module
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001588can now optionally buffer character data, resulting in fewer calls to
1589your character data handler and therefore faster performance. Setting
Fred Drake5c4cf152002-11-13 14:59:06 +00001590the parser object's \member{buffer_text} attribute to \constant{True}
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001591will enable buffering.
1592
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001593\item The \function{sample(\var{population}, \var{k})} function was
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001594added to the \module{random} module. \var{population} is a sequence or
1595\class{xrange} object containing the elements of a population, and
1596\function{sample()} chooses \var{k} elements from the population without
1597replacing chosen elements. \var{k} can be any value up to
1598\code{len(\var{population})}. For example:
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001599
1600\begin{verbatim}
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001601>>> days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'St', 'Sn']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001602>>> random.sample(days, 3) # Choose 3 elements
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001603['St', 'Sn', 'Th']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001604>>> random.sample(days, 7) # Choose 7 elements
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001605['Tu', 'Th', 'Mo', 'We', 'St', 'Fr', 'Sn']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001606>>> random.sample(days, 7) # Choose 7 again
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001607['We', 'Mo', 'Sn', 'Fr', 'Tu', 'St', 'Th']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001608>>> random.sample(days, 8) # Can't choose eight
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001609Traceback (most recent call last):
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +00001610 File "<stdin>", line 1, in ?
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001611 File "random.py", line 414, in sample
1612 raise ValueError, "sample larger than population"
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001613ValueError: sample larger than population
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001614>>> random.sample(xrange(1,10000,2), 10) # Choose ten odd nos. under 10000
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001615[3407, 3805, 1505, 7023, 2401, 2267, 9733, 3151, 8083, 9195]
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001616\end{verbatim}
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001617
1618The \module{random} module now uses a new algorithm, the Mersenne
1619Twister, implemented in C. It's faster and more extensively studied
1620than the previous algorithm.
1621
1622(All changes contributed by Raymond Hettinger.)
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001623
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001624\item The \module{readline} module also gained a number of new
1625functions: \function{get_history_item()},
1626\function{get_current_history_length()}, and \function{redisplay()}.
1627
Andrew M. Kuchlingef893fe2003-01-06 20:04:17 +00001628\item The \module{rexec} and \module{Bastion} modules have been
1629declared dead, and attempts to import them will fail with a
1630\exception{RuntimeError}. New-style classes provide new ways to break
1631out of the restricted execution environment provided by
1632\module{rexec}, and no one has interest in fixing them or time to do
1633so. If you have applications using \module{rexec}, rewrite them to
1634use something else.
1635
1636(Sticking with Python 2.2 or 2.1 will not make your applications any
Andrew M. Kuchling13b4c412003-04-24 13:23:43 +00001637safer because there are known bugs in the \module{rexec} module in
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001638those versions. To repeat: if you're using \module{rexec}, stop using
Andrew M. Kuchlingef893fe2003-01-06 20:04:17 +00001639it immediately.)
1640
Andrew M. Kuchling13b4c412003-04-24 13:23:43 +00001641\item The \module{rotor} module has been deprecated because the
1642 algorithm it uses for encryption is not believed to be secure. If
1643 you need encryption, use one of the several AES Python modules
1644 that are available separately.
1645
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001646\item The \module{shutil} module gained a \function{move(\var{src},
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001647\var{dest})} function that recursively moves a file or directory to a new
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001648location.
1649
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001650\item Support for more advanced POSIX signal handling was added
Michael W. Hudson43ed43b2003-03-13 13:56:53 +00001651to the \module{signal} but then removed again as it proved impossible
1652to make it work reliably across platforms.
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001653
1654\item The \module{socket} module now supports timeouts. You
1655can call the \method{settimeout(\var{t})} method on a socket object to
1656set a timeout of \var{t} seconds. Subsequent socket operations that
1657take longer than \var{t} seconds to complete will abort and raise a
Andrew M. Kuchlingc760c6c2003-07-16 20:12:33 +00001658\exception{socket.timeout} exception.
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001659
1660The original timeout implementation was by Tim O'Malley. Michael
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001661Gilfix integrated it into the Python \module{socket} module and
1662shepherded it through a lengthy review. After the code was checked
1663in, Guido van~Rossum rewrote parts of it. (This is a good example of
1664a collaborative development process in action.)
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001665
Mark Hammond8af50bc2002-12-03 06:13:35 +00001666\item On Windows, the \module{socket} module now ships with Secure
Michael W. Hudson065f5fa2003-02-10 19:24:50 +00001667Sockets Layer (SSL) support.
Mark Hammond8af50bc2002-12-03 06:13:35 +00001668
Andrew M. Kuchling563389f2003-03-02 02:31:58 +00001669\item The value of the C \constant{PYTHON_API_VERSION} macro is now
1670exposed at the Python level as \code{sys.api_version}. The current
1671exception can be cleared by calling the new \function{sys.exc_clear()}
1672function.
Andrew M. Kuchlingdcfd8252002-09-13 22:21:42 +00001673
Andrew M. Kuchling674b0bf2003-01-07 00:07:19 +00001674\item The new \module{tarfile} module
Neal Norwitz55d555f2003-01-08 05:27:42 +00001675allows reading from and writing to \program{tar}-format archive files.
Andrew M. Kuchling674b0bf2003-01-07 00:07:19 +00001676(Contributed by Lars Gust\"abel.)
1677
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001678\item The new \module{textwrap} module contains functions for wrapping
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001679strings containing paragraphs of text. The \function{wrap(\var{text},
1680\var{width})} function takes a string and returns a list containing
1681the text split into lines of no more than the chosen width. The
1682\function{fill(\var{text}, \var{width})} function returns a single
1683string, reformatted to fit into lines no longer than the chosen width.
1684(As you can guess, \function{fill()} is built on top of
1685\function{wrap()}. For example:
1686
1687\begin{verbatim}
1688>>> import textwrap
1689>>> paragraph = "Not a whit, we defy augury: ... more text ..."
1690>>> textwrap.wrap(paragraph, 60)
Fred Drake5c4cf152002-11-13 14:59:06 +00001691["Not a whit, we defy augury: there's a special providence in",
1692 "the fall of a sparrow. If it be now, 'tis not to come; if it",
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001693 ...]
1694>>> print textwrap.fill(paragraph, 35)
1695Not a whit, we defy augury: there's
1696a special providence in the fall of
1697a sparrow. If it be now, 'tis not
1698to come; if it be not to come, it
1699will be now; if it be not now, yet
1700it will come: the readiness is all.
Fred Drake5c4cf152002-11-13 14:59:06 +00001701>>>
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001702\end{verbatim}
1703
1704The module also contains a \class{TextWrapper} class that actually
Fred Drake5c4cf152002-11-13 14:59:06 +00001705implements the text wrapping strategy. Both the
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001706\class{TextWrapper} class and the \function{wrap()} and
1707\function{fill()} functions support a number of additional keyword
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +00001708arguments for fine-tuning the formatting; consult the \ulink{module's
1709documentation}{../lib/module-textwrap.html} for details.
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001710(Contributed by Greg Ward.)
1711
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001712\item The \module{thread} and \module{threading} modules now have
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001713companion modules, \module{dummy_thread} and \module{dummy_threading},
1714that provide a do-nothing implementation of the \module{thread}
1715module's interface for platforms where threads are not supported. The
1716intention is to simplify thread-aware modules (ones that \emph{don't}
1717rely on threads to run) by putting the following code at the top:
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001718
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001719\begin{verbatim}
1720try:
1721 import threading as _threading
1722except ImportError:
1723 import dummy_threading as _threading
1724\end{verbatim}
1725
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001726In this example, \module{_threading} is used as the module name to make
1727it clear that the module being used is not necessarily the actual
1728\module{threading} module. Code can call functions and use classes in
1729\module{_threading} whether or not threads are supported, avoiding an
1730\keyword{if} statement and making the code slightly clearer. This
1731module will not magically make multithreaded code run without threads;
1732code that waits for another thread to return or to do something will
1733simply hang forever.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001734
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001735\item The \module{time} module's \function{strptime()} function has
Fred Drake5c4cf152002-11-13 14:59:06 +00001736long been an annoyance because it uses the platform C library's
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001737\function{strptime()} implementation, and different platforms
1738sometimes have odd bugs. Brett Cannon contributed a portable
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001739implementation that's written in pure Python and should behave
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001740identically on all platforms.
1741
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +00001742\item The new \module{timeit} module helps measure how long snippets
1743of Python code take to execute. The \file{timeit.py} file can be run
1744directly from the command line, or the module's \class{Timer} class
1745can be imported and used directly. Here's a short example that
1746figures out whether it's faster to convert an 8-bit string to Unicode
1747by appending an empty Unicode string to it or by using the
1748\function{unicode()} function:
1749
1750\begin{verbatim}
1751import timeit
1752
1753timer1 = timeit.Timer('unicode("abc")')
1754timer2 = timeit.Timer('"abc" + u""')
1755
1756# Run three trials
1757print timer1.repeat(repeat=3, number=100000)
1758print timer2.repeat(repeat=3, number=100000)
1759
1760# On my laptop this outputs:
1761# [0.36831796169281006, 0.37441694736480713, 0.35304892063140869]
1762# [0.17574405670166016, 0.18193507194519043, 0.17565798759460449]
1763\end{verbatim}
1764
Raymond Hettinger8ccf4d72003-07-10 15:48:33 +00001765\item The \module{Tix} module has received various bug fixes and
Andrew M. Kuchlingef893fe2003-01-06 20:04:17 +00001766updates for the current version of the Tix package.
1767
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001768\item The \module{Tkinter} module now works with a thread-enabled
1769version of Tcl. Tcl's threading model requires that widgets only be
1770accessed from the thread in which they're created; accesses from
1771another thread can cause Tcl to panic. For certain Tcl interfaces,
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001772\module{Tkinter} will now automatically avoid this
1773when a widget is accessed from a different thread by marshalling a
1774command, passing it to the correct thread, and waiting for the
1775results. Other interfaces can't be handled automatically but
1776\module{Tkinter} will now raise an exception on such an access so that
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001777you can at least find out about the problem. See
Fred Drakeb876bcc2003-04-30 15:03:46 +00001778\url{http://mail.python.org/pipermail/python-dev/2002-December/031107.html} %
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001779for a more detailed explanation of this change. (Implemented by
Andrew M. Kuchlingfcf6b3e2003-05-07 17:00:35 +00001780Martin von~L\"owis.)
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001781
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001782\item Calling Tcl methods through \module{_tkinter} no longer
1783returns only strings. Instead, if Tcl returns other objects those
1784objects are converted to their Python equivalent, if one exists, or
1785wrapped with a \class{_tkinter.Tcl_Obj} object if no Python equivalent
Raymond Hettinger45bda572002-12-14 20:20:45 +00001786exists. This behavior can be controlled through the
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001787\method{wantobjects()} method of \class{tkapp} objects.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001788
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001789When using \module{_tkinter} through the \module{Tkinter} module (as
1790most Tkinter applications will), this feature is always activated. It
1791should not cause compatibility problems, since Tkinter would always
1792convert string results to Python types where possible.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001793
Raymond Hettinger45bda572002-12-14 20:20:45 +00001794If any incompatibilities are found, the old behavior can be restored
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001795by setting the \member{wantobjects} variable in the \module{Tkinter}
1796module to false before creating the first \class{tkapp} object.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001797
1798\begin{verbatim}
1799import Tkinter
Martin v. Löwis8c8aa5d2002-11-26 21:39:48 +00001800Tkinter.wantobjects = 0
Martin v. Löwis39b48522002-11-26 09:47:25 +00001801\end{verbatim}
1802
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001803Any breakage caused by this change should be reported as a bug.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001804
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001805\item The \module{UserDict} module has a new \class{DictMixin} class which
1806defines all dictionary methods for classes that already have a minimum
1807mapping interface. This greatly simplifies writing classes that need
1808to be substitutable for dictionaries, such as the classes in
1809the \module{shelve} module.
1810
1811Adding the mix-in as a superclass provides the full dictionary
1812interface whenever the class defines \method{__getitem__},
1813\method{__setitem__}, \method{__delitem__}, and \method{keys}.
1814For example:
1815
1816\begin{verbatim}
1817>>> import UserDict
1818>>> class SeqDict(UserDict.DictMixin):
1819... """Dictionary lookalike implemented with lists."""
1820... def __init__(self):
1821... self.keylist = []
1822... self.valuelist = []
1823... def __getitem__(self, key):
1824... try:
1825... i = self.keylist.index(key)
1826... except ValueError:
1827... raise KeyError
1828... return self.valuelist[i]
1829... def __setitem__(self, key, value):
1830... try:
1831... i = self.keylist.index(key)
1832... self.valuelist[i] = value
1833... except ValueError:
1834... self.keylist.append(key)
1835... self.valuelist.append(value)
1836... def __delitem__(self, key):
1837... try:
1838... i = self.keylist.index(key)
1839... except ValueError:
1840... raise KeyError
1841... self.keylist.pop(i)
1842... self.valuelist.pop(i)
1843... def keys(self):
1844... return list(self.keylist)
1845...
1846>>> s = SeqDict()
1847>>> dir(s) # See that other dictionary methods are implemented
1848['__cmp__', '__contains__', '__delitem__', '__doc__', '__getitem__',
1849 '__init__', '__iter__', '__len__', '__module__', '__repr__',
1850 '__setitem__', 'clear', 'get', 'has_key', 'items', 'iteritems',
1851 'iterkeys', 'itervalues', 'keylist', 'keys', 'pop', 'popitem',
1852 'setdefault', 'update', 'valuelist', 'values']
1853\end{verbatim}
1854
1855(Contributed by Raymond Hettinger.)
1856
Andrew M. Kuchlinge36b6902003-04-19 15:38:47 +00001857\item The DOM implementation
1858in \module{xml.dom.minidom} can now generate XML output in a
1859particular encoding by providing an optional encoding argument to
1860the \method{toxml()} and \method{toprettyxml()} methods of DOM nodes.
1861
Andrew M. Kuchling6e73f9e2003-07-18 01:15:51 +00001862\item The \module{xmlrpclib} module now supports an XML-RPC extension
1863for handling nil data values such as Python's \code{None}. Nil values
1864are always supported on unmarshalling an XML-RPC response. To
1865generate requests containing \code{None}, you must supply a true value
1866for the \var{allow_none} parameter when creating a \class{Marshaller}
1867instance.
1868
Andrew M. Kuchlinge36b6902003-04-19 15:38:47 +00001869\item The new \module{DocXMLRPCServer} module allows writing
1870self-documenting XML-RPC servers. Run it in demo mode (as a program)
1871to see it in action. Pointing the Web browser to the RPC server
1872produces pydoc-style documentation; pointing xmlrpclib to the
1873server allows invoking the actual methods.
1874(Contributed by Brian Quinlan.)
1875
Martin v. Löwis2548c732003-04-18 10:39:54 +00001876\item Support for internationalized domain names (RFCs 3454, 3490,
18773491, and 3492) has been added. The ``idna'' encoding can be used
1878to convert between a Unicode domain name and the ASCII-compatible
Andrew M. Kuchlinge36b6902003-04-19 15:38:47 +00001879encoding (ACE) of that name.
Martin v. Löwis2548c732003-04-18 10:39:54 +00001880
Martin v. Löwisfaf71ea2003-04-18 21:48:56 +00001881\begin{alltt}
Fred Drake15b3dba2003-07-16 04:00:14 +00001882>{}>{}> u"www.Alliancefran\c caise.nu".encode("idna")
Martin v. Löwis2548c732003-04-18 10:39:54 +00001883'www.xn--alliancefranaise-npb.nu'
Martin v. Löwisfaf71ea2003-04-18 21:48:56 +00001884\end{alltt}
Martin v. Löwis2548c732003-04-18 10:39:54 +00001885
Andrew M. Kuchlinge36b6902003-04-19 15:38:47 +00001886The \module{socket} module has also been extended to transparently
1887convert Unicode hostnames to the ACE version before passing them to
1888the C library. Modules that deal with hostnames such as
1889\module{httplib} and \module{ftplib}) also support Unicode host names;
1890\module{httplib} also sends HTTP \samp{Host} headers using the ACE
1891version of the domain name. \module{urllib} supports Unicode URLs
1892with non-ASCII host names as long as the \code{path} part of the URL
1893is ASCII only.
Martin v. Löwis2548c732003-04-18 10:39:54 +00001894
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001895To implement this change, the \module{stringprep} module, the
1896\code{mkstringprep} tool and the \code{punycode} encoding have been added.
Martin v. Löwis281b2c62003-04-18 21:04:39 +00001897
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00001898\end{itemize}
1899
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00001900
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001901%======================================================================
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001902\subsection{Date/Time Type}
1903
1904Date and time types suitable for expressing timestamps were added as
1905the \module{datetime} module. The types don't support different
1906calendars or many fancy features, and just stick to the basics of
1907representing time.
1908
1909The three primary types are: \class{date}, representing a day, month,
1910and year; \class{time}, consisting of hour, minute, and second; and
1911\class{datetime}, which contains all the attributes of both
Andrew M. Kuchlingc71bb972003-03-21 17:23:07 +00001912\class{date} and \class{time}. There's also a
1913\class{timedelta} class representing differences between two points
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001914in time, and time zone logic is implemented by classes inheriting from
1915the abstract \class{tzinfo} class.
1916
1917You can create instances of \class{date} and \class{time} by either
1918supplying keyword arguments to the appropriate constructor,
1919e.g. \code{datetime.date(year=1972, month=10, day=15)}, or by using
Andrew M. Kuchlingc71bb972003-03-21 17:23:07 +00001920one of a number of class methods. For example, the \method{date.today()}
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001921class method returns the current local date.
1922
1923Once created, instances of the date/time classes are all immutable.
1924There are a number of methods for producing formatted strings from
1925objects:
1926
1927\begin{verbatim}
1928>>> import datetime
1929>>> now = datetime.datetime.now()
1930>>> now.isoformat()
1931'2002-12-30T21:27:03.994956'
1932>>> now.ctime() # Only available on date, datetime
1933'Mon Dec 30 21:27:03 2002'
Raymond Hettingeree1bded2003-01-17 16:20:23 +00001934>>> now.strftime('%Y %d %b')
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001935'2002 30 Dec'
1936\end{verbatim}
1937
1938The \method{replace()} method allows modifying one or more fields
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001939of a \class{date} or \class{datetime} instance, returning a new instance:
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001940
1941\begin{verbatim}
1942>>> d = datetime.datetime.now()
1943>>> d
1944datetime.datetime(2002, 12, 30, 22, 15, 38, 827738)
1945>>> d.replace(year=2001, hour = 12)
1946datetime.datetime(2001, 12, 30, 12, 15, 38, 827738)
1947>>>
1948\end{verbatim}
1949
1950Instances can be compared, hashed, and converted to strings (the
1951result is the same as that of \method{isoformat()}). \class{date} and
1952\class{datetime} instances can be subtracted from each other, and
Andrew M. Kuchlingc71bb972003-03-21 17:23:07 +00001953added to \class{timedelta} instances. The largest missing feature is
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001954that there's no standard library support for parsing strings and getting back a
Andrew M. Kuchlingc71bb972003-03-21 17:23:07 +00001955\class{date} or \class{datetime}.
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001956
1957For more information, refer to the \ulink{module's reference
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +00001958documentation}{../lib/module-datetime.html}.
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001959(Contributed by Tim Peters.)
1960
1961
1962%======================================================================
Andrew M. Kuchling8d177092003-05-13 14:26:54 +00001963\subsection{The optparse Module}
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001964
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001965The \module{getopt} module provides simple parsing of command-line
1966arguments. The new \module{optparse} module (originally named Optik)
1967provides more elaborate command-line parsing that follows the Unix
1968conventions, automatically creates the output for \longprogramopt{help},
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001969and can perform different actions for different options.
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001970
1971You start by creating an instance of \class{OptionParser} and telling
1972it what your program's options are.
1973
1974\begin{verbatim}
Andrew M. Kuchling7ee9b512003-02-18 00:48:23 +00001975import sys
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001976from optparse import OptionParser
1977
1978op = OptionParser()
1979op.add_option('-i', '--input',
1980 action='store', type='string', dest='input',
1981 help='set input filename')
1982op.add_option('-l', '--length',
1983 action='store', type='int', dest='length',
1984 help='set maximum length of output')
1985\end{verbatim}
1986
1987Parsing a command line is then done by calling the \method{parse_args()}
1988method.
1989
1990\begin{verbatim}
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001991options, args = op.parse_args(sys.argv[1:])
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001992print options
1993print args
1994\end{verbatim}
1995
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001996This returns an object containing all of the option values,
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001997and a list of strings containing the remaining arguments.
1998
1999Invoking the script with the various arguments now works as you'd
2000expect it to. Note that the length argument is automatically
2001converted to an integer.
2002
2003\begin{verbatim}
2004$ ./python opt.py -i data arg1
2005<Values at 0x400cad4c: {'input': 'data', 'length': None}>
2006['arg1']
2007$ ./python opt.py --input=data --length=4
2008<Values at 0x400cad2c: {'input': 'data', 'length': 4}>
Andrew M. Kuchling7ee9b512003-02-18 00:48:23 +00002009[]
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00002010$
2011\end{verbatim}
2012
2013The help message is automatically generated for you:
2014
2015\begin{verbatim}
2016$ ./python opt.py --help
2017usage: opt.py [options]
2018
2019options:
2020 -h, --help show this help message and exit
2021 -iINPUT, --input=INPUT
2022 set input filename
2023 -lLENGTH, --length=LENGTH
2024 set maximum length of output
2025$
2026\end{verbatim}
Andrew M. Kuchling669249e2002-11-19 13:05:33 +00002027% $ prevent Emacs tex-mode from getting confused
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00002028
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +00002029See the \ulink{module's documentation}{../lib/module-optparse.html}
2030for more details.
2031
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00002032Optik was written by Greg Ward, with suggestions from the readers of
2033the Getopt SIG.
2034
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00002035
2036%======================================================================
Andrew M. Kuchling8d177092003-05-13 14:26:54 +00002037\section{Pymalloc: A Specialized Object Allocator\label{section-pymalloc}}
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002038
Andrew M. Kuchlingc71bb972003-03-21 17:23:07 +00002039Pymalloc, a specialized object allocator written by Vladimir
2040Marangozov, was a feature added to Python 2.1. Pymalloc is intended
2041to be faster than the system \cfunction{malloc()} and to have less
2042memory overhead for allocation patterns typical of Python programs.
2043The allocator uses C's \cfunction{malloc()} function to get large
2044pools of memory and then fulfills smaller memory requests from these
2045pools.
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002046
2047In 2.1 and 2.2, pymalloc was an experimental feature and wasn't
Andrew M. Kuchlingc71bb972003-03-21 17:23:07 +00002048enabled by default; you had to explicitly enable it when compiling
2049Python by providing the
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002050\longprogramopt{with-pymalloc} option to the \program{configure}
2051script. In 2.3, pymalloc has had further enhancements and is now
2052enabled by default; you'll have to supply
2053\longprogramopt{without-pymalloc} to disable it.
2054
2055This change is transparent to code written in Python; however,
2056pymalloc may expose bugs in C extensions. Authors of C extension
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002057modules should test their code with pymalloc enabled,
2058because some incorrect code may cause core dumps at runtime.
2059
2060There's one particularly common error that causes problems. There are
2061a number of memory allocation functions in Python's C API that have
2062previously just been aliases for the C library's \cfunction{malloc()}
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002063and \cfunction{free()}, meaning that if you accidentally called
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002064mismatched functions the error wouldn't be noticeable. When the
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002065object allocator is enabled, these functions aren't aliases of
2066\cfunction{malloc()} and \cfunction{free()} any more, and calling the
2067wrong function to free memory may get you a core dump. For example,
2068if memory was allocated using \cfunction{PyObject_Malloc()}, it has to
2069be freed using \cfunction{PyObject_Free()}, not \cfunction{free()}. A
2070few modules included with Python fell afoul of this and had to be
2071fixed; doubtless there are more third-party modules that will have the
2072same problem.
2073
2074As part of this change, the confusing multiple interfaces for
2075allocating memory have been consolidated down into two API families.
2076Memory allocated with one family must not be manipulated with
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002077functions from the other family. There is one family for allocating
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002078chunks of memory and another family of functions specifically for
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002079allocating Python objects.
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002080
2081\begin{itemize}
2082 \item To allocate and free an undistinguished chunk of memory use
2083 the ``raw memory'' family: \cfunction{PyMem_Malloc()},
2084 \cfunction{PyMem_Realloc()}, and \cfunction{PyMem_Free()}.
2085
2086 \item The ``object memory'' family is the interface to the pymalloc
2087 facility described above and is biased towards a large number of
2088 ``small'' allocations: \cfunction{PyObject_Malloc},
2089 \cfunction{PyObject_Realloc}, and \cfunction{PyObject_Free}.
2090
2091 \item To allocate and free Python objects, use the ``object'' family
2092 \cfunction{PyObject_New()}, \cfunction{PyObject_NewVar()}, and
2093 \cfunction{PyObject_Del()}.
2094\end{itemize}
2095
2096Thanks to lots of work by Tim Peters, pymalloc in 2.3 also provides
2097debugging features to catch memory overwrites and doubled frees in
2098both extension modules and in the interpreter itself. To enable this
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002099support, compile a debugging version of the Python interpreter by
2100running \program{configure} with \longprogramopt{with-pydebug}.
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002101
2102To aid extension writers, a header file \file{Misc/pymemcompat.h} is
2103distributed with the source to Python 2.3 that allows Python
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002104extensions to use the 2.3 interfaces to memory allocation while
2105compiling against any version of Python since 1.5.2. You would copy
2106the file from Python's source distribution and bundle it with the
2107source of your extension.
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002108
2109\begin{seealso}
2110
2111\seeurl{http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Objects/obmalloc.c}
2112{For the full details of the pymalloc implementation, see
2113the comments at the top of the file \file{Objects/obmalloc.c} in the
2114Python source code. The above link points to the file within the
2115SourceForge CVS browser.}
2116
2117\end{seealso}
2118
2119
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00002120% ======================================================================
2121\section{Build and C API Changes}
2122
Andrew M. Kuchling3c305d92002-07-22 18:50:11 +00002123Changes to Python's build process and to the C API include:
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00002124
2125\begin{itemize}
2126
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002127\item The C-level interface to the garbage collector has been changed
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002128to make it easier to write extension types that support garbage
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002129collection and to debug misuses of the functions.
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002130Various functions have slightly different semantics, so a bunch of
2131functions had to be renamed. Extensions that use the old API will
2132still compile but will \emph{not} participate in garbage collection,
2133so updating them for 2.3 should be considered fairly high priority.
2134
2135To upgrade an extension module to the new API, perform the following
2136steps:
2137
2138\begin{itemize}
2139
2140\item Rename \cfunction{Py_TPFLAGS_GC} to \cfunction{PyTPFLAGS_HAVE_GC}.
2141
2142\item Use \cfunction{PyObject_GC_New} or \cfunction{PyObject_GC_NewVar} to
2143allocate objects, and \cfunction{PyObject_GC_Del} to deallocate them.
2144
2145\item Rename \cfunction{PyObject_GC_Init} to \cfunction{PyObject_GC_Track} and
2146\cfunction{PyObject_GC_Fini} to \cfunction{PyObject_GC_UnTrack}.
2147
2148\item Remove \cfunction{PyGC_HEAD_SIZE} from object size calculations.
2149
2150\item Remove calls to \cfunction{PyObject_AS_GC} and \cfunction{PyObject_FROM_GC}.
2151
2152\end{itemize}
2153
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002154\item The cycle detection implementation used by the garbage collection
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002155has proven to be stable, so it's now been made mandatory. You can no
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002156longer compile Python without it, and the
2157\longprogramopt{with-cycle-gc} switch to \program{configure} has been removed.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00002158
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002159\item Python can now optionally be built as a shared library
2160(\file{libpython2.3.so}) by supplying \longprogramopt{enable-shared}
Fred Drake5c4cf152002-11-13 14:59:06 +00002161when running Python's \program{configure} script. (Contributed by Ondrej
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +00002162Palkovsky.)
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +00002163
Michael W. Hudsondd32a912002-08-15 14:59:02 +00002164\item The \csimplemacro{DL_EXPORT} and \csimplemacro{DL_IMPORT} macros
2165are now deprecated. Initialization functions for Python extension
2166modules should now be declared using the new macro
Andrew M. Kuchling3c305d92002-07-22 18:50:11 +00002167\csimplemacro{PyMODINIT_FUNC}, while the Python core will generally
2168use the \csimplemacro{PyAPI_FUNC} and \csimplemacro{PyAPI_DATA}
2169macros.
Neal Norwitzbba23a82002-07-22 13:18:59 +00002170
Fred Drake5c4cf152002-11-13 14:59:06 +00002171\item The interpreter can be compiled without any docstrings for
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00002172the built-in functions and modules by supplying
Fred Drake5c4cf152002-11-13 14:59:06 +00002173\longprogramopt{without-doc-strings} to the \program{configure} script.
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00002174This makes the Python executable about 10\% smaller, but will also
2175mean that you can't get help for Python's built-ins. (Contributed by
2176Gustavo Niemeyer.)
2177
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002178\item The \cfunction{PyArg_NoArgs()} macro is now deprecated, and code
Andrew M. Kuchling7845e7c2002-07-11 19:27:46 +00002179that uses it should be changed. For Python 2.2 and later, the method
2180definition table can specify the
Fred Drake5c4cf152002-11-13 14:59:06 +00002181\constant{METH_NOARGS} flag, signalling that there are no arguments, and
Andrew M. Kuchling7845e7c2002-07-11 19:27:46 +00002182the argument checking can then be removed. If compatibility with
2183pre-2.2 versions of Python is important, the code could use
Fred Drakeaac8c582003-01-17 22:50:10 +00002184\code{PyArg_ParseTuple(\var{args}, "")} instead, but this will be slower
Andrew M. Kuchling7845e7c2002-07-11 19:27:46 +00002185than using \constant{METH_NOARGS}.
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00002186
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002187\item A new function, \cfunction{PyObject_DelItemString(\var{mapping},
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002188char *\var{key})} was added as shorthand for
Raymond Hettingera685f522003-07-12 04:42:30 +00002189\code{PyObject_DelItem(\var{mapping}, PyString_New(\var{key}))}.
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00002190
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002191\item File objects now manage their internal string buffer
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002192differently, increasing it exponentially when needed. This results in
2193the benchmark tests in \file{Lib/test/test_bufio.py} speeding up
2194considerably (from 57 seconds to 1.7 seconds, according to one
2195measurement).
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002196
Andrew M. Kuchling72b58e02002-05-29 17:30:34 +00002197\item It's now possible to define class and static methods for a C
2198extension type by setting either the \constant{METH_CLASS} or
2199\constant{METH_STATIC} flags in a method's \ctype{PyMethodDef}
2200structure.
Andrew M. Kuchling45afd542002-04-02 14:25:25 +00002201
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00002202\item Python now includes a copy of the Expat XML parser's source code,
2203removing any dependence on a system version or local installation of
Fred Drake5c4cf152002-11-13 14:59:06 +00002204Expat.
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00002205
Michael W. Hudson3e245d82003-02-11 14:19:56 +00002206\item If you dynamically allocate type objects in your extension, you
Neal Norwitzada859c2003-02-11 14:30:39 +00002207should be aware of a change in the rules relating to the
Michael W. Hudson3e245d82003-02-11 14:19:56 +00002208\member{__module__} and \member{__name__} attributes. In summary,
2209you will want to ensure the type's dictionary contains a
2210\code{'__module__'} key; making the module name the part of the type
2211name leading up to the final period will no longer have the desired
2212effect. For more detail, read the API reference documentation or the
2213source.
2214
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00002215\end{itemize}
2216
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00002217
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00002218%======================================================================
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00002219\subsection{Port-Specific Changes}
2220
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00002221Support for a port to IBM's OS/2 using the EMX runtime environment was
2222merged into the main Python source tree. EMX is a POSIX emulation
2223layer over the OS/2 system APIs. The Python port for EMX tries to
2224support all the POSIX-like capability exposed by the EMX runtime, and
2225mostly succeeds; \function{fork()} and \function{fcntl()} are
2226restricted by the limitations of the underlying emulation layer. The
2227standard OS/2 port, which uses IBM's Visual Age compiler, also gained
2228support for case-sensitive import semantics as part of the integration
2229of the EMX port into CVS. (Contributed by Andrew MacIntyre.)
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00002230
Andrew M. Kuchling72b58e02002-05-29 17:30:34 +00002231On MacOS, most toolbox modules have been weaklinked to improve
2232backward compatibility. This means that modules will no longer fail
2233to load if a single routine is missing on the curent OS version.
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00002234Instead calling the missing routine will raise an exception.
2235(Contributed by Jack Jansen.)
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00002236
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00002237The RPM spec files, found in the \file{Misc/RPM/} directory in the
2238Python source distribution, were updated for 2.3. (Contributed by
2239Sean Reifschneider.)
Fred Drake03e10312002-03-26 19:17:43 +00002240
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002241Other new platforms now supported by Python include AtheOS
Fred Drake693aea22003-02-07 14:52:18 +00002242(\url{http://www.atheos.cx/}), GNU/Hurd, and OpenVMS.
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00002243
Fred Drake03e10312002-03-26 19:17:43 +00002244
2245%======================================================================
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002246\section{Other Changes and Fixes \label{section-other}}
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002247
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +00002248As usual, there were a bunch of other improvements and bugfixes
2249scattered throughout the source tree. A search through the CVS change
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +00002250logs finds there were 523 patches applied and 514 bugs fixed between
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +00002251Python 2.2 and 2.3. Both figures are likely to be underestimates.
2252
2253Some of the more notable changes are:
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002254
2255\begin{itemize}
2256
Andrew M. Kuchling6e73f9e2003-07-18 01:15:51 +00002257\item If the \envvar{PYTHONINSPECT} environment variable is set, the
2258Python interpreter will enter the interactive prompt after running a
2259Python program, as if Python had been invoked with the \programopt{-i}
2260option. The environment variable can be set before running the Python
2261interpreter, or it can be set by the Python program as part of its
2262execution.
2263
Fred Drake54fe3fd2002-11-26 22:07:35 +00002264\item The \file{regrtest.py} script now provides a way to allow ``all
2265resources except \var{foo}.'' A resource name passed to the
2266\programopt{-u} option can now be prefixed with a hyphen
2267(\character{-}) to mean ``remove this resource.'' For example, the
2268option `\code{\programopt{-u}all,-bsddb}' could be used to enable the
2269use of all resources except \code{bsddb}.
2270
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002271\item The tools used to build the documentation now work under Cygwin
2272as well as \UNIX.
2273
Michael W. Hudsondd32a912002-08-15 14:59:02 +00002274\item The \code{SET_LINENO} opcode has been removed. Back in the
2275mists of time, this opcode was needed to produce line numbers in
2276tracebacks and support trace functions (for, e.g., \module{pdb}).
2277Since Python 1.5, the line numbers in tracebacks have been computed
2278using a different mechanism that works with ``python -O''. For Python
22792.3 Michael Hudson implemented a similar scheme to determine when to
2280call the trace function, removing the need for \code{SET_LINENO}
2281entirely.
2282
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +00002283It would be difficult to detect any resulting difference from Python
2284code, apart from a slight speed up when Python is run without
Michael W. Hudsondd32a912002-08-15 14:59:02 +00002285\programopt{-O}.
2286
2287C extensions that access the \member{f_lineno} field of frame objects
2288should instead call \code{PyCode_Addr2Line(f->f_code, f->f_lasti)}.
2289This will have the added effect of making the code work as desired
2290under ``python -O'' in earlier versions of Python.
2291
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002292A nifty new feature is that trace functions can now assign to the
2293\member{f_lineno} attribute of frame objects, changing the line that
2294will be executed next. A \samp{jump} command has been added to the
2295\module{pdb} debugger taking advantage of this new feature.
2296(Implemented by Richie Hindle.)
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00002297
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002298\end{itemize}
2299
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00002300
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002301%======================================================================
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00002302\section{Porting to Python 2.3}
2303
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002304This section lists previously described changes that may require
2305changes to your code:
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002306
2307\begin{itemize}
2308
2309\item \keyword{yield} is now always a keyword; if it's used as a
2310variable name in your code, a different name must be chosen.
2311
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002312\item For strings \var{X} and \var{Y}, \code{\var{X} in \var{Y}} now works
2313if \var{X} is more than one character long.
2314
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00002315\item The \function{int()} type constructor will now return a long
2316integer instead of raising an \exception{OverflowError} when a string
2317or floating-point number is too large to fit into an integer.
2318
Andrew M. Kuchlingacddabc2003-02-18 00:43:24 +00002319\item If you have Unicode strings that contain 8-bit characters, you
2320must declare the file's encoding (UTF-8, Latin-1, or whatever) by
2321adding a comment to the top of the file. See
2322section~\ref{section-encodings} for more information.
2323
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00002324\item Calling Tcl methods through \module{_tkinter} no longer
2325returns only strings. Instead, if Tcl returns other objects those
2326objects are converted to their Python equivalent, if one exists, or
2327wrapped with a \class{_tkinter.Tcl_Obj} object if no Python equivalent
2328exists.
2329
Andrew M. Kuchling80fd7852003-02-06 15:14:04 +00002330\item Large octal and hex literals such as
Andrew M. Kuchling72df65a2003-02-10 15:08:16 +00002331\code{0xffffffff} now trigger a \exception{FutureWarning}. Currently
Andrew M. Kuchling80fd7852003-02-06 15:14:04 +00002332they're stored as 32-bit numbers and result in a negative value, but
Andrew M. Kuchling72df65a2003-02-10 15:08:16 +00002333in Python 2.4 they'll become positive long integers.
2334
2335There are a few ways to fix this warning. If you really need a
2336positive number, just add an \samp{L} to the end of the literal. If
2337you're trying to get a 32-bit integer with low bits set and have
2338previously used an expression such as \code{~(1 << 31)}, it's probably
2339clearest to start with all bits set and clear the desired upper bits.
2340For example, to clear just the top bit (bit 31), you could write
2341\code{0xffffffffL {\&}{\textasciitilde}(1L<<31)}.
Andrew M. Kuchling80fd7852003-02-06 15:14:04 +00002342
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00002343\item You can no longer disable assertions by assigning to \code{__debug__}.
2344
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002345\item The Distutils \function{setup()} function has gained various new
Fred Drake5c4cf152002-11-13 14:59:06 +00002346keyword arguments such as \var{depends}. Old versions of the
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002347Distutils will abort if passed unknown keywords. A solution is to check
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002348for the presence of the new \function{get_distutil_options()} function
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002349in your \file{setup.py} and only uses the new keywords
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002350with a version of the Distutils that supports them:
2351
2352\begin{verbatim}
2353from distutils import core
2354
2355kw = {'sources': 'foo.c', ...}
2356if hasattr(core, 'get_distutil_options'):
2357 kw['depends'] = ['foo.h']
Fred Drake5c4cf152002-11-13 14:59:06 +00002358ext = Extension(**kw)
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002359\end{verbatim}
2360
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00002361\item Using \code{None} as a variable name will now result in a
2362\exception{SyntaxWarning} warning.
2363
2364\item Names of extension types defined by the modules included with
2365Python now contain the module and a \character{.} in front of the type
2366name.
2367
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002368\end{itemize}
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00002369
2370
2371%======================================================================
Fred Drake03e10312002-03-26 19:17:43 +00002372\section{Acknowledgements \label{acks}}
2373
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00002374The author would like to thank the following people for offering
2375suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +00002376article: Jeff Bauer, Simon Brunning, Brett Cannon, Michael Chermside,
2377Andrew Dalke, Scott David Daniels, Fred~L. Drake, Jr., Kelly Gerber,
2378Raymond Hettinger, Michael Hudson, Chris Lambert, Detlef Lannert,
Andrew M. Kuchlingfcf6b3e2003-05-07 17:00:35 +00002379Martin von~L\"owis, Andrew MacIntyre, Lalo Martins, Chad Netzer,
2380Gustavo Niemeyer, Neal Norwitz, Hans Nowak, Chris Reedy, Francesco
2381Ricciardi, Vinay Sajip, Neil Schemenauer, Roman Suzi, Jason Tishler,
2382Just van~Rossum.
Fred Drake03e10312002-03-26 19:17:43 +00002383
2384\end{document}