blob: e29ecdd21f72f7aeab219ff80b707c26ef800efe [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. Kuchling50a25702003-10-23 18:08:03 +00006\release{1.01}
Fred Drakeaac8c582003-01-17 22:50:10 +00007\author{A.M.\ Kuchling}
Fred Drakeb914ef02004-01-02 06:57:50 +00008\authoraddress{
9 \strong{Python Software Foundation}\\
10 Email: \email{amk@amk.ca}
11}
Fred Drake03e10312002-03-26 19:17:43 +000012
13\begin{document}
14\maketitle
15\tableofcontents
16
Andrew M. Kuchlingb34ba3f2003-07-29 12:06:32 +000017This article explains the new features in Python 2.3. Python 2.3 was
18released on July 29, 2003.
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +000019
Andrew M. Kuchling95be8bd2003-07-18 02:12:16 +000020The main themes for Python 2.3 are polishing some of the features
21added in 2.2, adding various small but useful enhancements to the core
22language, and expanding the standard library. The new object model
23introduced in the previous version has benefited from 18 months of
24bugfixes and from optimization efforts that have improved the
25performance of new-style classes. A few new built-in functions have
26been added such as \function{sum()} and \function{enumerate()}. The
27\keyword{in} operator can now be used for substring searches (e.g.
28\code{"ab" in "abc"} returns \constant{True}).
29
30Some of the many new library features include Boolean, set, heap, and
31date/time data types, the ability to import modules from ZIP-format
32archives, metadata support for the long-awaited Python catalog, an
33updated version of IDLE, and modules for logging messages, wrapping
34text, parsing CSV files, processing command-line options, using BerkeleyDB
35databases... the list of new and enhanced modules is lengthy.
36
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +000037This article doesn't attempt to provide a complete specification of
38the new features, but instead provides a convenient overview. For
39full details, you should refer to the documentation for Python 2.3,
Fred Drake693aea22003-02-07 14:52:18 +000040such as the \citetitle[../lib/lib.html]{Python Library Reference} and
41the \citetitle[../ref/ref.html]{Python Reference Manual}. If you want
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +000042to understand the complete implementation and design rationale,
43refer to the PEP for a particular new feature.
Fred Drake03e10312002-03-26 19:17:43 +000044
45
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +000046%======================================================================
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000047\section{PEP 218: A Standard Set Datatype}
48
49The new \module{sets} module contains an implementation of a set
50datatype. The \class{Set} class is for mutable sets, sets that can
51have members added and removed. The \class{ImmutableSet} class is for
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +000052sets that can't be modified, and instances of \class{ImmutableSet} can
53therefore be used as dictionary keys. Sets are built on top of
54dictionaries, so the elements within a set must be hashable.
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000055
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +000056Here's a simple example:
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000057
58\begin{verbatim}
59>>> import sets
60>>> S = sets.Set([1,2,3])
61>>> S
62Set([1, 2, 3])
63>>> 1 in S
64True
65>>> 0 in S
66False
67>>> S.add(5)
68>>> S.remove(3)
69>>> S
70Set([1, 2, 5])
Fred Drake5c4cf152002-11-13 14:59:06 +000071>>>
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000072\end{verbatim}
73
74The union and intersection of sets can be computed with the
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +000075\method{union()} and \method{intersection()} methods; an alternative
76notation uses the bitwise operators \code{\&} and \code{|}.
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000077Mutable sets also have in-place versions of these methods,
78\method{union_update()} and \method{intersection_update()}.
79
80\begin{verbatim}
81>>> S1 = sets.Set([1,2,3])
82>>> S2 = sets.Set([4,5,6])
83>>> S1.union(S2)
84Set([1, 2, 3, 4, 5, 6])
85>>> S1 | S2 # Alternative notation
86Set([1, 2, 3, 4, 5, 6])
Fred Drake5c4cf152002-11-13 14:59:06 +000087>>> S1.intersection(S2)
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000088Set([])
89>>> S1 & S2 # Alternative notation
90Set([])
91>>> S1.union_update(S2)
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000092>>> S1
93Set([1, 2, 3, 4, 5, 6])
Fred Drake5c4cf152002-11-13 14:59:06 +000094>>>
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000095\end{verbatim}
96
97It's also possible to take the symmetric difference of two sets. This
98is the set of all elements in the union that aren't in the
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +000099intersection. Another way of putting it is that the symmetric
100difference contains all elements that are in exactly one
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000101set. Again, there's an alternative notation (\code{\^}), and an
102in-place version with the ungainly name
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +0000103\method{symmetric_difference_update()}.
104
105\begin{verbatim}
106>>> S1 = sets.Set([1,2,3,4])
107>>> S2 = sets.Set([3,4,5,6])
108>>> S1.symmetric_difference(S2)
109Set([1, 2, 5, 6])
110>>> S1 ^ S2
111Set([1, 2, 5, 6])
112>>>
113\end{verbatim}
114
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000115There are also \method{issubset()} and \method{issuperset()} methods
Michael W. Hudson065f5fa2003-02-10 19:24:50 +0000116for checking whether one set is a subset or superset of another:
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +0000117
118\begin{verbatim}
119>>> S1 = sets.Set([1,2,3])
120>>> S2 = sets.Set([2,3])
121>>> S2.issubset(S1)
122True
123>>> S1.issubset(S2)
124False
125>>> S1.issuperset(S2)
126True
127>>>
128\end{verbatim}
129
130
131\begin{seealso}
132
133\seepep{218}{Adding a Built-In Set Object Type}{PEP written by Greg V. Wilson.
134Implemented by Greg V. Wilson, Alex Martelli, and GvR.}
135
136\end{seealso}
137
138
139
140%======================================================================
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000141\section{PEP 255: Simple Generators\label{section-generators}}
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000142
143In Python 2.2, generators were added as an optional feature, to be
144enabled by a \code{from __future__ import generators} directive. In
1452.3 generators no longer need to be specially enabled, and are now
146always present; this means that \keyword{yield} is now always a
147keyword. The rest of this section is a copy of the description of
148generators from the ``What's New in Python 2.2'' document; if you read
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000149it back when Python 2.2 came out, you can skip the rest of this section.
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000150
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000151You're doubtless familiar with how function calls work in Python or C.
152When you call a function, it gets a private namespace where its local
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000153variables are created. When the function reaches a \keyword{return}
154statement, the local variables are destroyed and the resulting value
155is returned to the caller. A later call to the same function will get
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000156a fresh new set of local variables. But, what if the local variables
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000157weren't thrown away on exiting a function? What if you could later
158resume the function where it left off? This is what generators
159provide; they can be thought of as resumable functions.
160
161Here's the simplest example of a generator function:
162
163\begin{verbatim}
164def generate_ints(N):
165 for i in range(N):
166 yield i
167\end{verbatim}
168
169A new keyword, \keyword{yield}, was introduced for generators. Any
170function containing a \keyword{yield} statement is a generator
171function; this is detected by Python's bytecode compiler which
Fred Drake5c4cf152002-11-13 14:59:06 +0000172compiles the function specially as a result.
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000173
174When you call a generator function, it doesn't return a single value;
175instead it returns a generator object that supports the iterator
176protocol. On executing the \keyword{yield} statement, the generator
177outputs the value of \code{i}, similar to a \keyword{return}
178statement. The big difference between \keyword{yield} and a
179\keyword{return} statement is that on reaching a \keyword{yield} the
180generator's state of execution is suspended and local variables are
181preserved. On the next call to the generator's \code{.next()} method,
182the function will resume executing immediately after the
183\keyword{yield} statement. (For complicated reasons, the
184\keyword{yield} statement isn't allowed inside the \keyword{try} block
Fred Drakeaac8c582003-01-17 22:50:10 +0000185of a \keyword{try}...\keyword{finally} statement; read \pep{255} for a full
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000186explanation of the interaction between \keyword{yield} and
187exceptions.)
188
Fred Drakeaac8c582003-01-17 22:50:10 +0000189Here's a sample usage of the \function{generate_ints()} generator:
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000190
191\begin{verbatim}
192>>> gen = generate_ints(3)
193>>> gen
194<generator object at 0x8117f90>
195>>> gen.next()
1960
197>>> gen.next()
1981
199>>> gen.next()
2002
201>>> gen.next()
202Traceback (most recent call last):
Andrew M. Kuchling9f6e1042002-06-17 13:40:04 +0000203 File "stdin", line 1, in ?
204 File "stdin", line 2, in generate_ints
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000205StopIteration
206\end{verbatim}
207
208You could equally write \code{for i in generate_ints(5)}, or
209\code{a,b,c = generate_ints(3)}.
210
211Inside a generator function, the \keyword{return} statement can only
212be used without a value, and signals the end of the procession of
213values; afterwards the generator cannot return any further values.
214\keyword{return} with a value, such as \code{return 5}, is a syntax
215error inside a generator function. The end of the generator's results
216can also be indicated by raising \exception{StopIteration} manually,
217or by just letting the flow of execution fall off the bottom of the
218function.
219
220You could achieve the effect of generators manually by writing your
221own class and storing all the local variables of the generator as
222instance variables. For example, returning a list of integers could
223be done by setting \code{self.count} to 0, and having the
224\method{next()} method increment \code{self.count} and return it.
225However, for a moderately complicated generator, writing a
226corresponding class would be much messier.
227\file{Lib/test/test_generators.py} contains a number of more
228interesting examples. The simplest one implements an in-order
229traversal of a tree using generators recursively.
230
231\begin{verbatim}
232# A recursive generator that generates Tree leaves in in-order.
233def inorder(t):
234 if t:
235 for x in inorder(t.left):
236 yield x
237 yield t.label
238 for x in inorder(t.right):
239 yield x
240\end{verbatim}
241
242Two other examples in \file{Lib/test/test_generators.py} produce
243solutions for the N-Queens problem (placing $N$ queens on an $NxN$
244chess board so that no queen threatens another) and the Knight's Tour
245(a route that takes a knight to every square of an $NxN$ chessboard
Fred Drake5c4cf152002-11-13 14:59:06 +0000246without visiting any square twice).
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000247
248The idea of generators comes from other programming languages,
249especially Icon (\url{http://www.cs.arizona.edu/icon/}), where the
250idea of generators is central. In Icon, every
251expression and function call behaves like a generator. One example
252from ``An Overview of the Icon Programming Language'' at
253\url{http://www.cs.arizona.edu/icon/docs/ipd266.htm} gives an idea of
254what this looks like:
255
256\begin{verbatim}
257sentence := "Store it in the neighboring harbor"
258if (i := find("or", sentence)) > 5 then write(i)
259\end{verbatim}
260
261In Icon the \function{find()} function returns the indexes at which the
262substring ``or'' is found: 3, 23, 33. In the \keyword{if} statement,
263\code{i} is first assigned a value of 3, but 3 is less than 5, so the
264comparison fails, and Icon retries it with the second value of 23. 23
265is greater than 5, so the comparison now succeeds, and the code prints
266the value 23 to the screen.
267
268Python doesn't go nearly as far as Icon in adopting generators as a
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000269central concept. Generators are considered part of the core
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000270Python language, but learning or using them isn't compulsory; if they
271don't solve any problems that you have, feel free to ignore them.
272One novel feature of Python's interface as compared to
273Icon's is that a generator's state is represented as a concrete object
274(the iterator) that can be passed around to other functions or stored
275in a data structure.
276
277\begin{seealso}
278
279\seepep{255}{Simple Generators}{Written by Neil Schemenauer, Tim
280Peters, Magnus Lie Hetland. Implemented mostly by Neil Schemenauer
281and Tim Peters, with other fixes from the Python Labs crew.}
282
283\end{seealso}
284
285
286%======================================================================
Fred Drake13090e12002-08-22 16:51:08 +0000287\section{PEP 263: Source Code Encodings \label{section-encodings}}
Andrew M. Kuchling950725f2002-08-06 01:40:48 +0000288
289Python source files can now be declared as being in different
290character set encodings. Encodings are declared by including a
291specially formatted comment in the first or second line of the source
292file. For example, a UTF-8 file can be declared with:
293
294\begin{verbatim}
295#!/usr/bin/env python
296# -*- coding: UTF-8 -*-
297\end{verbatim}
298
299Without such an encoding declaration, the default encoding used is
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +00003007-bit ASCII. Executing or importing modules that contain string
301literals with 8-bit characters and have no encoding declaration will result
Andrew M. Kuchlingacddabc2003-02-18 00:43:24 +0000302in a \exception{DeprecationWarning} being signalled by Python 2.3; in
3032.4 this will be a syntax error.
Andrew M. Kuchling950725f2002-08-06 01:40:48 +0000304
Andrew M. Kuchlingacddabc2003-02-18 00:43:24 +0000305The encoding declaration only affects Unicode string literals, which
306will be converted to Unicode using the specified encoding. Note that
307Python identifiers are still restricted to ASCII characters, so you
308can't have variable names that use characters outside of the usual
309alphanumerics.
Andrew M. Kuchling950725f2002-08-06 01:40:48 +0000310
311\begin{seealso}
312
313\seepep{263}{Defining Python Source Code Encodings}{Written by
Andrew M. Kuchlingfcf6b3e2003-05-07 17:00:35 +0000314Marc-Andr\'e Lemburg and Martin von~L\"owis; implemented by Suzuki
315Hisao and Martin von~L\"owis.}
Andrew M. Kuchling950725f2002-08-06 01:40:48 +0000316
317\end{seealso}
318
319
320%======================================================================
Andrew M. Kuchling95be8bd2003-07-18 02:12:16 +0000321\section{PEP 273: Importing Modules from Zip Archives}
322
323The new \module{zipimport} module adds support for importing
324modules from a ZIP-format archive. You don't need to import the
325module explicitly; it will be automatically imported if a ZIP
326archive's filename is added to \code{sys.path}. For example:
327
328\begin{verbatim}
329amk@nyman:~/src/python$ unzip -l /tmp/example.zip
330Archive: /tmp/example.zip
331 Length Date Time Name
332 -------- ---- ---- ----
333 8467 11-26-02 22:30 jwzthreading.py
334 -------- -------
335 8467 1 file
336amk@nyman:~/src/python$ ./python
337Python 2.3 (#1, Aug 1 2003, 19:54:32)
338>>> import sys
339>>> sys.path.insert(0, '/tmp/example.zip') # Add .zip file to front of path
340>>> import jwzthreading
341>>> jwzthreading.__file__
342'/tmp/example.zip/jwzthreading.py'
343>>>
344\end{verbatim}
345
346An entry in \code{sys.path} can now be the filename of a ZIP archive.
347The ZIP archive can contain any kind of files, but only files named
348\file{*.py}, \file{*.pyc}, or \file{*.pyo} can be imported. If an
349archive only contains \file{*.py} files, Python will not attempt to
350modify the archive by adding the corresponding \file{*.pyc} file, meaning
351that if a ZIP archive doesn't contain \file{*.pyc} files, importing may be
352rather slow.
353
354A path within the archive can also be specified to only import from a
355subdirectory; for example, the path \file{/tmp/example.zip/lib/}
356would only import from the \file{lib/} subdirectory within the
357archive.
358
359\begin{seealso}
360
361\seepep{273}{Import Modules from Zip Archives}{Written by James C. Ahlstrom,
362who also provided an implementation.
363Python 2.3 follows the specification in \pep{273},
364but uses an implementation written by Just van~Rossum
365that uses the import hooks described in \pep{302}.
366See section~\ref{section-pep302} for a description of the new import hooks.
367}
368
369\end{seealso}
370
371%======================================================================
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000372\section{PEP 277: Unicode file name support for Windows NT}
Andrew M. Kuchling0f345562002-10-04 22:34:11 +0000373
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000374On Windows NT, 2000, and XP, the system stores file names as Unicode
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000375strings. Traditionally, Python has represented file names as byte
376strings, which is inadequate because it renders some file names
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000377inaccessible.
378
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000379Python now allows using arbitrary Unicode strings (within the
380limitations of the file system) for all functions that expect file
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000381names, most notably the \function{open()} built-in function. If a Unicode
382string is passed to \function{os.listdir()}, Python now returns a list
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000383of Unicode strings. A new function, \function{os.getcwdu()}, returns
384the current directory as a Unicode string.
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000385
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000386Byte strings still work as file names, and on Windows Python will
387transparently convert them to Unicode using the \code{mbcs} encoding.
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000388
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000389Other systems also allow Unicode strings as file names but convert
390them to byte strings before passing them to the system, which can
391cause a \exception{UnicodeError} to be raised. Applications can test
392whether arbitrary Unicode strings are supported as file names by
Andrew M. Kuchlingb9ba4e62003-02-03 15:16:15 +0000393checking \member{os.path.supports_unicode_filenames}, a Boolean value.
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000394
Andrew M. Kuchling563389f2003-03-02 02:31:58 +0000395Under MacOS, \function{os.listdir()} may now return Unicode filenames.
396
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000397\begin{seealso}
398
399\seepep{277}{Unicode file name support for Windows NT}{Written by Neil
Andrew M. Kuchlingfcf6b3e2003-05-07 17:00:35 +0000400Hodgson; implemented by Neil Hodgson, Martin von~L\"owis, and Mark
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000401Hammond.}
402
403\end{seealso}
Andrew M. Kuchling0f345562002-10-04 22:34:11 +0000404
405
406%======================================================================
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000407\section{PEP 278: Universal Newline Support}
408
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000409The three major operating systems used today are Microsoft Windows,
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000410Apple's Macintosh OS, and the various \UNIX\ derivatives. A minor
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +0000411irritation of cross-platform work
412is that these three platforms all use different characters
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000413to mark the ends of lines in text files. \UNIX\ uses the linefeed
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +0000414(ASCII character 10), MacOS uses the carriage return (ASCII
415character 13), and Windows uses a two-character sequence of a
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000416carriage return plus a newline.
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000417
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000418Python's file objects can now support end of line conventions other
419than the one followed by the platform on which Python is running.
Fred Drake5c4cf152002-11-13 14:59:06 +0000420Opening a file with the mode \code{'U'} or \code{'rU'} will open a file
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000421for reading in universal newline mode. All three line ending
Fred Drake5c4cf152002-11-13 14:59:06 +0000422conventions will be translated to a \character{\e n} in the strings
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000423returned by the various file methods such as \method{read()} and
Fred Drake5c4cf152002-11-13 14:59:06 +0000424\method{readline()}.
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000425
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000426Universal newline support is also used when importing modules and when
427executing a file with the \function{execfile()} function. This means
428that Python modules can be shared between all three operating systems
429without needing to convert the line-endings.
430
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +0000431This feature can be disabled when compiling Python by specifying
432the \longprogramopt{without-universal-newlines} switch when running Python's
Fred Drake5c4cf152002-11-13 14:59:06 +0000433\program{configure} script.
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000434
435\begin{seealso}
436
Fred Drake5c4cf152002-11-13 14:59:06 +0000437\seepep{278}{Universal Newline Support}{Written
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000438and implemented by Jack Jansen.}
439
440\end{seealso}
441
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +0000442
443%======================================================================
Andrew M. Kuchling433307b2003-05-13 14:23:54 +0000444\section{PEP 279: enumerate()\label{section-enumerate}}
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +0000445
446A new built-in function, \function{enumerate()}, will make
447certain loops a bit clearer. \code{enumerate(thing)}, where
448\var{thing} is either an iterator or a sequence, returns a iterator
Fred Drake3605ae52003-07-16 03:26:31 +0000449that will return \code{(0, \var{thing}[0])}, \code{(1,
450\var{thing}[1])}, \code{(2, \var{thing}[2])}, and so forth.
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000451
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +0000452A common idiom to change every element of a list looks like this:
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +0000453
454\begin{verbatim}
455for i in range(len(L)):
456 item = L[i]
457 # ... compute some result based on item ...
458 L[i] = result
459\end{verbatim}
460
461This can be rewritten using \function{enumerate()} as:
462
463\begin{verbatim}
464for i, item in enumerate(L):
465 # ... compute some result based on item ...
466 L[i] = result
467\end{verbatim}
468
469
470\begin{seealso}
471
Fred Drake5c4cf152002-11-13 14:59:06 +0000472\seepep{279}{The enumerate() built-in function}{Written
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000473and implemented by Raymond D. Hettinger.}
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +0000474
475\end{seealso}
476
477
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000478%======================================================================
Andrew M. Kuchling433307b2003-05-13 14:23:54 +0000479\section{PEP 282: The logging Package}
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000480
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000481A standard package for writing logs, \module{logging}, has been added
482to Python 2.3. It provides a powerful and flexible mechanism for
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000483generating logging output which can then be filtered and processed in
484various ways. A configuration file written in a standard format can
485be used to control the logging behavior of a program. Python
486includes handlers that will write log records to
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000487standard error or to a file or socket, send them to the system log, or
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000488even e-mail them to a particular address; of course, it's also
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000489possible to write your own handler classes.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000490
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000491The \class{Logger} class is the primary class.
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000492Most application code will deal with one or more \class{Logger}
493objects, each one used by a particular subsystem of the application.
494Each \class{Logger} is identified by a name, and names are organized
495into a hierarchy using \samp{.} as the component separator. For
496example, you might have \class{Logger} instances named \samp{server},
497\samp{server.auth} and \samp{server.network}. The latter two
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000498instances are below \samp{server} in the hierarchy. This means that
499if you turn up the verbosity for \samp{server} or direct \samp{server}
500messages to a different handler, the changes will also apply to
501records logged to \samp{server.auth} and \samp{server.network}.
502There's also a root \class{Logger} that's the parent of all other
503loggers.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000504
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000505For simple uses, the \module{logging} package contains some
506convenience functions that always use the root log:
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000507
508\begin{verbatim}
509import logging
510
511logging.debug('Debugging information')
512logging.info('Informational message')
Andrew M. Kuchling37495072003-02-19 13:46:18 +0000513logging.warning('Warning:config file %s not found', 'server.conf')
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000514logging.error('Error occurred')
515logging.critical('Critical error -- shutting down')
516\end{verbatim}
517
518This produces the following output:
519
520\begin{verbatim}
Andrew M. Kuchling37495072003-02-19 13:46:18 +0000521WARNING:root:Warning:config file server.conf not found
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000522ERROR:root:Error occurred
523CRITICAL:root:Critical error -- shutting down
524\end{verbatim}
525
526In the default configuration, informational and debugging messages are
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000527suppressed and the output is sent to standard error. You can enable
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000528the display of informational and debugging messages by calling the
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000529\method{setLevel()} method on the root logger.
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000530
Andrew M. Kuchling37495072003-02-19 13:46:18 +0000531Notice the \function{warning()} call's use of string formatting
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000532operators; all of the functions for logging messages take the
533arguments \code{(\var{msg}, \var{arg1}, \var{arg2}, ...)} and log the
534string resulting from \code{\var{msg} \% (\var{arg1}, \var{arg2},
535...)}.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000536
537There's also an \function{exception()} function that records the most
538recent traceback. Any of the other functions will also record the
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000539traceback if you specify a true value for the keyword argument
Fred Drakeaac8c582003-01-17 22:50:10 +0000540\var{exc_info}.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000541
542\begin{verbatim}
543def f():
544 try: 1/0
545 except: logging.exception('Problem recorded')
546
547f()
548\end{verbatim}
549
550This produces the following output:
551
552\begin{verbatim}
553ERROR:root:Problem recorded
554Traceback (most recent call last):
555 File "t.py", line 6, in f
556 1/0
557ZeroDivisionError: integer division or modulo by zero
558\end{verbatim}
559
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000560Slightly more advanced programs will use a logger other than the root
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000561logger. The \function{getLogger(\var{name})} function is used to get
562a particular log, creating it if it doesn't exist yet.
Andrew M. Kuchlingb1e4bf92002-12-03 13:35:17 +0000563\function{getLogger(None)} returns the root logger.
564
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000565
566\begin{verbatim}
567log = logging.getLogger('server')
568 ...
569log.info('Listening on port %i', port)
570 ...
571log.critical('Disk full')
572 ...
573\end{verbatim}
574
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000575Log records are usually propagated up the hierarchy, so a message
576logged to \samp{server.auth} is also seen by \samp{server} and
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +0000577\samp{root}, but a \class{Logger} can prevent this by setting its
Fred Drakeaac8c582003-01-17 22:50:10 +0000578\member{propagate} attribute to \constant{False}.
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000579
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000580There are more classes provided by the \module{logging} package that
581can be customized. When a \class{Logger} instance is told to log a
582message, it creates a \class{LogRecord} instance that is sent to any
583number of different \class{Handler} instances. Loggers and handlers
584can also have an attached list of filters, and each filter can cause
585the \class{LogRecord} to be ignored or can modify the record before
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +0000586passing it along. When they're finally output, \class{LogRecord}
587instances are converted to text by a \class{Formatter} class. All of
588these classes can be replaced by your own specially-written classes.
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000589
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000590With all of these features the \module{logging} package should provide
591enough flexibility for even the most complicated applications. This
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +0000592is only an incomplete overview of its features, so please see the
593\ulink{package's reference documentation}{../lib/module-logging.html}
594for all of the details. Reading \pep{282} will also be helpful.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000595
596
597\begin{seealso}
598
599\seepep{282}{A Logging System}{Written by Vinay Sajip and Trent Mick;
600implemented by Vinay Sajip.}
601
602\end{seealso}
603
604
605%======================================================================
Andrew M. Kuchling433307b2003-05-13 14:23:54 +0000606\section{PEP 285: A Boolean Type\label{section-bool}}
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000607
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000608A Boolean type was added to Python 2.3. Two new constants were added
609to the \module{__builtin__} module, \constant{True} and
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000610\constant{False}. (\constant{True} and
611\constant{False} constants were added to the built-ins
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000612in 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 +00006131 and 0 and aren't a different type.)
614
615The type object for this new type is named
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000616\class{bool}; the constructor for it takes any Python value and
617converts it to \constant{True} or \constant{False}.
618
619\begin{verbatim}
620>>> bool(1)
621True
622>>> bool(0)
623False
624>>> bool([])
625False
626>>> bool( (1,) )
627True
628\end{verbatim}
629
630Most of the standard library modules and built-in functions have been
631changed to return Booleans.
632
633\begin{verbatim}
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000634>>> obj = []
635>>> hasattr(obj, 'append')
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000636True
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000637>>> isinstance(obj, list)
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000638True
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000639>>> isinstance(obj, tuple)
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000640False
641\end{verbatim}
642
643Python's Booleans were added with the primary goal of making code
644clearer. For example, if you're reading a function and encounter the
Fred Drake5c4cf152002-11-13 14:59:06 +0000645statement \code{return 1}, you might wonder whether the \code{1}
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000646represents a Boolean truth value, an index, or a
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000647coefficient that multiplies some other quantity. If the statement is
648\code{return True}, however, the meaning of the return value is quite
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000649clear.
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000650
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000651Python's Booleans were \emph{not} added for the sake of strict
652type-checking. A very strict language such as Pascal would also
653prevent you performing arithmetic with Booleans, and would require
654that the expression in an \keyword{if} statement always evaluate to a
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000655Boolean result. Python is not this strict and never will be, as
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000656\pep{285} explicitly says. This means you can still use any
657expression in an \keyword{if} statement, even ones that evaluate to a
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000658list or tuple or some random object. The Boolean type is a
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000659subclass of the \class{int} class so that arithmetic using a Boolean
660still works.
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000661
662\begin{verbatim}
663>>> True + 1
6642
665>>> False + 1
6661
667>>> False * 75
6680
669>>> True * 75
67075
671\end{verbatim}
672
673To sum up \constant{True} and \constant{False} in a sentence: they're
674alternative ways to spell the integer values 1 and 0, with the single
675difference that \function{str()} and \function{repr()} return the
Fred Drake5c4cf152002-11-13 14:59:06 +0000676strings \code{'True'} and \code{'False'} instead of \code{'1'} and
677\code{'0'}.
Andrew M. Kuchling3a52ff62002-04-03 22:44:47 +0000678
679\begin{seealso}
680
681\seepep{285}{Adding a bool type}{Written and implemented by GvR.}
682
683\end{seealso}
684
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000685
Andrew M. Kuchling65b72822002-09-03 00:53:21 +0000686%======================================================================
687\section{PEP 293: Codec Error Handling Callbacks}
688
Martin v. Löwis20eae692002-10-07 19:01:07 +0000689When encoding a Unicode string into a byte string, unencodable
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000690characters may be encountered. So far, Python has allowed specifying
691the error processing as either ``strict'' (raising
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000692\exception{UnicodeError}), ``ignore'' (skipping the character), or
693``replace'' (using a question mark in the output string), with
694``strict'' being the default behavior. It may be desirable to specify
695alternative processing of such errors, such as inserting an XML
696character reference or HTML entity reference into the converted
697string.
Martin v. Löwis20eae692002-10-07 19:01:07 +0000698
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +0000699Python now has a flexible framework to add different processing
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000700strategies. New error handlers can be added with
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000701\function{codecs.register_error}, and codecs then can access the error
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000702handler with \function{codecs.lookup_error}. An equivalent C API has
703been added for codecs written in C. The error handler gets the
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000704necessary state information such as the string being converted, the
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000705position in the string where the error was detected, and the target
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000706encoding. The handler can then either raise an exception or return a
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000707replacement string.
Martin v. Löwis20eae692002-10-07 19:01:07 +0000708
709Two additional error handlers have been implemented using this
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000710framework: ``backslashreplace'' uses Python backslash quoting to
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +0000711represent unencodable characters and ``xmlcharrefreplace'' emits
Martin v. Löwis20eae692002-10-07 19:01:07 +0000712XML character references.
Andrew M. Kuchling65b72822002-09-03 00:53:21 +0000713
714\begin{seealso}
715
Fred Drake5c4cf152002-11-13 14:59:06 +0000716\seepep{293}{Codec Error Handling Callbacks}{Written and implemented by
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000717Walter D\"orwald.}
Andrew M. Kuchling65b72822002-09-03 00:53:21 +0000718
719\end{seealso}
720
721
722%======================================================================
Fred Drake693aea22003-02-07 14:52:18 +0000723\section{PEP 301: Package Index and Metadata for
724Distutils\label{section-pep301}}
Andrew M. Kuchling87cebbf2003-01-03 16:24:28 +0000725
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000726Support for the long-requested Python catalog makes its first
727appearance in 2.3.
728
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000729The heart of the catalog is the new Distutils \command{register} command.
Fred Drake693aea22003-02-07 14:52:18 +0000730Running \code{python setup.py register} will collect the metadata
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000731describing a package, such as its name, version, maintainer,
Andrew M. Kuchlingc61402b2003-02-26 19:00:52 +0000732description, \&c., and send it to a central catalog server. The
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000733resulting catalog is available from \url{http://www.python.org/pypi}.
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000734
735To make the catalog a bit more useful, a new optional
Fred Drake693aea22003-02-07 14:52:18 +0000736\var{classifiers} keyword argument has been added to the Distutils
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000737\function{setup()} function. A list of
Fred Drake693aea22003-02-07 14:52:18 +0000738\ulink{Trove}{http://catb.org/\textasciitilde esr/trove/}-style
739strings can be supplied to help classify the software.
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000740
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +0000741Here's an example \file{setup.py} with classifiers, written to be compatible
742with older versions of the Distutils:
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000743
744\begin{verbatim}
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +0000745from distutils import core
Fred Drake693aea22003-02-07 14:52:18 +0000746kw = {'name': "Quixote",
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +0000747 'version': "0.5.1",
748 'description': "A highly Pythonic Web application framework",
Fred Drake693aea22003-02-07 14:52:18 +0000749 # ...
750 }
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +0000751
Andrew M. Kuchlinga6b1c752003-04-09 17:26:38 +0000752if (hasattr(core, 'setup_keywords') and
753 'classifiers' in core.setup_keywords):
Fred Drake693aea22003-02-07 14:52:18 +0000754 kw['classifiers'] = \
755 ['Topic :: Internet :: WWW/HTTP :: Dynamic Content',
756 'Environment :: No Input/Output (Daemon)',
757 'Intended Audience :: Developers'],
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +0000758
Fred Drake693aea22003-02-07 14:52:18 +0000759core.setup(**kw)
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000760\end{verbatim}
761
762The full list of classifiers can be obtained by running
Andrew M. Kuchling0ceb9b12003-07-21 12:49:46 +0000763\verb|python setup.py register --list-classifiers|.
Andrew M. Kuchling87cebbf2003-01-03 16:24:28 +0000764
765\begin{seealso}
766
Fred Drake693aea22003-02-07 14:52:18 +0000767\seepep{301}{Package Index and Metadata for Distutils}{Written and
768implemented by Richard Jones.}
Andrew M. Kuchling87cebbf2003-01-03 16:24:28 +0000769
770\end{seealso}
771
772
773%======================================================================
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000774\section{PEP 302: New Import Hooks \label{section-pep302}}
775
776While it's been possible to write custom import hooks ever since the
777\module{ihooks} module was introduced in Python 1.3, no one has ever
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000778been really happy with it because writing new import hooks is
779difficult and messy. There have been various proposed alternatives
780such as the \module{imputil} and \module{iu} modules, but none of them
781has ever gained much acceptance, and none of them were easily usable
782from \C{} code.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000783
784\pep{302} borrows ideas from its predecessors, especially from
785Gordon McMillan's \module{iu} module. Three new items
786are added to the \module{sys} module:
787
788\begin{itemize}
Andrew M. Kuchlingd5ac8d02003-01-02 21:33:15 +0000789 \item \code{sys.path_hooks} is a list of callable objects; most
Fred Drakeaac8c582003-01-17 22:50:10 +0000790 often they'll be classes. Each callable takes a string containing a
791 path and either returns an importer object that will handle imports
792 from this path or raises an \exception{ImportError} exception if it
793 can't handle this path.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000794
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000795 \item \code{sys.path_importer_cache} caches importer objects for
Fred Drakeaac8c582003-01-17 22:50:10 +0000796 each path, so \code{sys.path_hooks} will only need to be traversed
797 once for each path.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000798
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000799 \item \code{sys.meta_path} is a list of importer objects that will
800 be traversed before \code{sys.path} is checked. This list is
801 initially empty, but user code can add objects to it. Additional
802 built-in and frozen modules can be imported by an object added to
803 this list.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000804
805\end{itemize}
806
807Importer objects must have a single method,
808\method{find_module(\var{fullname}, \var{path}=None)}. \var{fullname}
809will be a module or package name, e.g. \samp{string} or
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000810\samp{distutils.core}. \method{find_module()} must return a loader object
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000811that has a single method, \method{load_module(\var{fullname})}, that
812creates and returns the corresponding module object.
813
814Pseudo-code for Python's new import logic, therefore, looks something
815like this (simplified a bit; see \pep{302} for the full details):
816
817\begin{verbatim}
818for mp in sys.meta_path:
819 loader = mp(fullname)
820 if loader is not None:
Andrew M. Kuchlingd5ac8d02003-01-02 21:33:15 +0000821 <module> = loader.load_module(fullname)
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000822
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000823for path in sys.path:
824 for hook in sys.path_hooks:
Andrew M. Kuchlingd5ac8d02003-01-02 21:33:15 +0000825 try:
826 importer = hook(path)
827 except ImportError:
828 # ImportError, so try the other path hooks
829 pass
830 else:
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000831 loader = importer.find_module(fullname)
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000832 <module> = loader.load_module(fullname)
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000833
834# Not found!
835raise ImportError
836\end{verbatim}
837
838\begin{seealso}
839
840\seepep{302}{New Import Hooks}{Written by Just van~Rossum and Paul Moore.
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +0000841Implemented by Just van~Rossum.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000842}
843
844\end{seealso}
845
846
847%======================================================================
Andrew M. Kuchlinga978e102003-03-21 18:10:12 +0000848\section{PEP 305: Comma-separated Files \label{section-pep305}}
849
850Comma-separated files are a format frequently used for exporting data
851from databases and spreadsheets. Python 2.3 adds a parser for
852comma-separated files.
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000853
854Comma-separated format is deceptively simple at first glance:
Andrew M. Kuchlinga978e102003-03-21 18:10:12 +0000855
856\begin{verbatim}
857Costs,150,200,3.95
858\end{verbatim}
859
860Read a line and call \code{line.split(',')}: what could be simpler?
861But toss in string data that can contain commas, and things get more
862complicated:
863
864\begin{verbatim}
865"Costs",150,200,3.95,"Includes taxes, shipping, and sundry items"
866\end{verbatim}
867
868A big ugly regular expression can parse this, but using the new
869\module{csv} package is much simpler:
870
871\begin{verbatim}
Andrew M. Kuchlingba887bb2003-04-13 21:13:02 +0000872import csv
Andrew M. Kuchlinga978e102003-03-21 18:10:12 +0000873
874input = open('datafile', 'rb')
875reader = csv.reader(input)
876for line in reader:
877 print line
878\end{verbatim}
879
880The \function{reader} function takes a number of different options.
881The field separator isn't limited to the comma and can be changed to
882any character, and so can the quoting and line-ending characters.
883
884Different dialects of comma-separated files can be defined and
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000885registered; currently there are two dialects, both used by Microsoft Excel.
Andrew M. Kuchlinga978e102003-03-21 18:10:12 +0000886A separate \class{csv.writer} class will generate comma-separated files
887from a succession of tuples or lists, quoting strings that contain the
888delimiter.
889
890\begin{seealso}
891
892\seepep{305}{CSV File API}{Written and implemented
893by Kevin Altis, Dave Cole, Andrew McNamara, Skip Montanaro, Cliff Wells.
894}
895
896\end{seealso}
897
898%======================================================================
Andrew M. Kuchlinga092ba12003-03-21 18:32:43 +0000899\section{PEP 307: Pickle Enhancements \label{section-pep305}}
900
901The \module{pickle} and \module{cPickle} modules received some
902attention during the 2.3 development cycle. In 2.2, new-style classes
Andrew M. Kuchlinga6b1c752003-04-09 17:26:38 +0000903could be pickled without difficulty, but they weren't pickled very
Andrew M. Kuchlinga092ba12003-03-21 18:32:43 +0000904compactly; \pep{307} quotes a trivial example where a new-style class
905results in a pickled string three times longer than that for a classic
906class.
907
908The solution was to invent a new pickle protocol. The
909\function{pickle.dumps()} function has supported a text-or-binary flag
910for a long time. In 2.3, this flag is redefined from a Boolean to an
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000911integer: 0 is the old text-mode pickle format, 1 is the old binary
912format, and now 2 is a new 2.3-specific format. A new constant,
Andrew M. Kuchlinga092ba12003-03-21 18:32:43 +0000913\constant{pickle.HIGHEST_PROTOCOL}, can be used to select the fanciest
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000914protocol available.
Andrew M. Kuchlinga092ba12003-03-21 18:32:43 +0000915
916Unpickling is no longer considered a safe operation. 2.2's
917\module{pickle} provided hooks for trying to prevent unsafe classes
918from being unpickled (specifically, a
919\member{__safe_for_unpickling__} attribute), but none of this code
920was ever audited and therefore it's all been ripped out in 2.3. You
921should not unpickle untrusted data in any version of Python.
922
923To reduce the pickling overhead for new-style classes, a new interface
924for customizing pickling was added using three special methods:
925\method{__getstate__}, \method{__setstate__}, and
926\method{__getnewargs__}. Consult \pep{307} for the full semantics
927of these methods.
928
929As a way to compress pickles yet further, it's now possible to use
930integer codes instead of long strings to identify pickled classes.
931The Python Software Foundation will maintain a list of standardized
932codes; there's also a range of codes for private use. Currently no
933codes have been specified.
934
935\begin{seealso}
936
937\seepep{307}{Extensions to the pickle protocol}{Written and implemented
938by Guido van Rossum and Tim Peters.}
939
940\end{seealso}
941
942%======================================================================
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000943\section{Extended Slices\label{section-slices}}
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000944
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000945Ever since Python 1.4, the slicing syntax has supported an optional
946third ``step'' or ``stride'' argument. For example, these are all
947legal Python syntax: \code{L[1:10:2]}, \code{L[:-1:1]},
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000948\code{L[::-1]}. This was added to Python at the request of
949the developers of Numerical Python, which uses the third argument
950extensively. However, Python's built-in list, tuple, and string
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000951sequence types have never supported this feature, raising a
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000952\exception{TypeError} if you tried it. Michael Hudson contributed a
953patch to fix this shortcoming.
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000954
955For example, you can now easily extract the elements of a list that
956have even indexes:
Fred Drakedf872a22002-07-03 12:02:01 +0000957
958\begin{verbatim}
959>>> L = range(10)
960>>> L[::2]
961[0, 2, 4, 6, 8]
962\end{verbatim}
963
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000964Negative values also work to make a copy of the same list in reverse
965order:
Fred Drakedf872a22002-07-03 12:02:01 +0000966
967\begin{verbatim}
968>>> L[::-1]
969[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
970\end{verbatim}
Andrew M. Kuchling3a52ff62002-04-03 22:44:47 +0000971
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000972This also works for tuples, arrays, and strings:
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000973
974\begin{verbatim}
975>>> s='abcd'
976>>> s[::2]
977'ac'
978>>> s[::-1]
979'dcba'
980\end{verbatim}
981
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000982If you have a mutable sequence such as a list or an array you can
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000983assign to or delete an extended slice, but there are some differences
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000984between assignment to extended and regular slices. Assignment to a
985regular slice can be used to change the length of the sequence:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000986
987\begin{verbatim}
988>>> a = range(3)
989>>> a
990[0, 1, 2]
991>>> a[1:3] = [4, 5, 6]
992>>> a
993[0, 4, 5, 6]
994\end{verbatim}
995
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000996Extended slices aren't this flexible. When assigning to an extended
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000997slice, the list on the right hand side of the statement must contain
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000998the same number of items as the slice it is replacing:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000999
1000\begin{verbatim}
1001>>> a = range(4)
1002>>> a
1003[0, 1, 2, 3]
1004>>> a[::2]
1005[0, 2]
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001006>>> a[::2] = [0, -1]
Michael W. Hudson4da01ed2002-07-19 15:48:56 +00001007>>> a
1008[0, 1, -1, 3]
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001009>>> a[::2] = [0,1,2]
Michael W. Hudson4da01ed2002-07-19 15:48:56 +00001010Traceback (most recent call last):
1011 File "<stdin>", line 1, in ?
Raymond Hettingeree1bded2003-01-17 16:20:23 +00001012ValueError: attempt to assign sequence of size 3 to extended slice of size 2
Michael W. Hudson4da01ed2002-07-19 15:48:56 +00001013\end{verbatim}
1014
1015Deletion is more straightforward:
1016
1017\begin{verbatim}
1018>>> a = range(4)
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001019>>> a
1020[0, 1, 2, 3]
Michael W. Hudson4da01ed2002-07-19 15:48:56 +00001021>>> a[::2]
1022[0, 2]
1023>>> del a[::2]
1024>>> a
1025[1, 3]
1026\end{verbatim}
1027
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001028One can also now pass slice objects to the
1029\method{__getitem__} methods of the built-in sequences:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +00001030
1031\begin{verbatim}
1032>>> range(10).__getitem__(slice(0, 5, 2))
1033[0, 2, 4]
1034\end{verbatim}
1035
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001036Or use slice objects directly in subscripts:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +00001037
1038\begin{verbatim}
1039>>> range(10)[slice(0, 5, 2)]
1040[0, 2, 4]
1041\end{verbatim}
1042
Andrew M. Kuchlingb6f79592002-11-29 19:43:45 +00001043To simplify implementing sequences that support extended slicing,
1044slice objects now have a method \method{indices(\var{length})} which,
Fred Drakeaac8c582003-01-17 22:50:10 +00001045given the length of a sequence, returns a \code{(\var{start},
1046\var{stop}, \var{step})} tuple that can be passed directly to
1047\function{range()}.
Andrew M. Kuchlingb6f79592002-11-29 19:43:45 +00001048\method{indices()} handles omitted and out-of-bounds indices in a
1049manner consistent with regular slices (and this innocuous phrase hides
1050a welter of confusing details!). The method is intended to be used
1051like this:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +00001052
1053\begin{verbatim}
1054class FakeSeq:
1055 ...
1056 def calc_item(self, i):
1057 ...
1058 def __getitem__(self, item):
1059 if isinstance(item, slice):
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001060 indices = item.indices(len(self))
Andrew M. Kuchling68a32942003-07-30 11:55:06 +00001061 return FakeSeq([self.calc_item(i) for i in range(*indices)])
Fred Drake5c4cf152002-11-13 14:59:06 +00001062 else:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +00001063 return self.calc_item(i)
1064\end{verbatim}
1065
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001066From this example you can also see that the built-in \class{slice}
Andrew M. Kuchling90e9a792002-08-15 00:40:21 +00001067object is now the type object for the slice type, and is no longer a
1068function. This is consistent with Python 2.2, where \class{int},
1069\class{str}, etc., underwent the same change.
1070
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001071
Andrew M. Kuchling3a52ff62002-04-03 22:44:47 +00001072%======================================================================
Fred Drakedf872a22002-07-03 12:02:01 +00001073\section{Other Language Changes}
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001074
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001075Here are all of the changes that Python 2.3 makes to the core Python
1076language.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001077
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001078\begin{itemize}
1079\item The \keyword{yield} statement is now always a keyword, as
1080described in section~\ref{section-generators} of this document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001081
Fred Drake5c4cf152002-11-13 14:59:06 +00001082\item A new built-in function \function{enumerate()}
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001083was added, as described in section~\ref{section-enumerate} of this
1084document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001085
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001086\item Two new constants, \constant{True} and \constant{False} were
1087added along with the built-in \class{bool} type, as described in
1088section~\ref{section-bool} of this document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001089
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00001090\item The \function{int()} type constructor will now return a long
1091integer instead of raising an \exception{OverflowError} when a string
1092or floating-point number is too large to fit into an integer. This
1093can lead to the paradoxical result that
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001094\code{isinstance(int(\var{expression}), int)} is false, but that seems
1095unlikely to cause problems in practice.
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00001096
Fred Drake5c4cf152002-11-13 14:59:06 +00001097\item Built-in types now support the extended slicing syntax,
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001098as described in section~\ref{section-slices} of this document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001099
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001100\item A new built-in function, \function{sum(\var{iterable}, \var{start}=0)},
1101adds up the numeric items in the iterable object and returns their sum.
1102\function{sum()} only accepts numbers, meaning that you can't use it
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +00001103to concatenate a bunch of strings. (Contributed by Alex
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001104Martelli.)
1105
Andrew M. Kuchlingfcf6b3e2003-05-07 17:00:35 +00001106\item \code{list.insert(\var{pos}, \var{value})} used to
1107insert \var{value} at the front of the list when \var{pos} was
1108negative. The behaviour has now been changed to be consistent with
1109slice indexing, so when \var{pos} is -1 the value will be inserted
1110before the last element, and so forth.
1111
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +00001112\item \code{list.index(\var{value})}, which searches for \var{value}
1113within the list and returns its index, now takes optional
1114\var{start} and \var{stop} arguments to limit the search to
1115only part of the list.
1116
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +00001117\item Dictionaries have a new method, \method{pop(\var{key}\optional{,
1118\var{default}})}, that returns the value corresponding to \var{key}
1119and removes that key/value pair from the dictionary. If the requested
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001120key isn't present in the dictionary, \var{default} is returned if it's
1121specified and \exception{KeyError} raised if it isn't.
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001122
1123\begin{verbatim}
1124>>> d = {1:2}
1125>>> d
1126{1: 2}
1127>>> d.pop(4)
1128Traceback (most recent call last):
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +00001129 File "stdin", line 1, in ?
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001130KeyError: 4
1131>>> d.pop(1)
11322
1133>>> d.pop(1)
1134Traceback (most recent call last):
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +00001135 File "stdin", line 1, in ?
Raymond Hettingeree1bded2003-01-17 16:20:23 +00001136KeyError: 'pop(): dictionary is empty'
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001137>>> d
1138{}
1139>>>
1140\end{verbatim}
1141
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001142There's also a new class method,
1143\method{dict.fromkeys(\var{iterable}, \var{value})}, that
1144creates a dictionary with keys taken from the supplied iterator
1145\var{iterable} and all values set to \var{value}, defaulting to
1146\code{None}.
1147
1148(Patches contributed by Raymond Hettinger.)
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001149
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001150Also, the \function{dict()} constructor now accepts keyword arguments to
Raymond Hettinger45bda572002-12-14 20:20:45 +00001151simplify creating small dictionaries:
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001152
1153\begin{verbatim}
1154>>> dict(red=1, blue=2, green=3, black=4)
1155{'blue': 2, 'black': 4, 'green': 3, 'red': 1}
1156\end{verbatim}
1157
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +00001158(Contributed by Just van~Rossum.)
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001159
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +00001160\item The \keyword{assert} statement no longer checks the \code{__debug__}
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001161flag, so you can no longer disable assertions by assigning to \code{__debug__}.
Fred Drake5c4cf152002-11-13 14:59:06 +00001162Running Python with the \programopt{-O} switch will still generate
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001163code that doesn't execute any assertions.
1164
1165\item Most type objects are now callable, so you can use them
1166to create new objects such as functions, classes, and modules. (This
1167means that the \module{new} module can be deprecated in a future
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001168Python version, because you can now use the type objects available in
1169the \module{types} module.)
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001170% XXX should new.py use PendingDeprecationWarning?
1171For example, you can create a new module object with the following code:
1172
1173\begin{verbatim}
1174>>> import types
1175>>> m = types.ModuleType('abc','docstring')
1176>>> m
1177<module 'abc' (built-in)>
1178>>> m.__doc__
1179'docstring'
1180\end{verbatim}
1181
Fred Drake5c4cf152002-11-13 14:59:06 +00001182\item
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001183A new warning, \exception{PendingDeprecationWarning} was added to
1184indicate features which are in the process of being
1185deprecated. The warning will \emph{not} be printed by default. To
1186check for use of features that will be deprecated in the future,
1187supply \programopt{-Walways::PendingDeprecationWarning::} on the
1188command line or use \function{warnings.filterwarnings()}.
1189
Andrew M. Kuchlingc1dd1742003-01-13 13:59:22 +00001190\item The process of deprecating string-based exceptions, as
1191in \code{raise "Error occurred"}, has begun. Raising a string will
1192now trigger \exception{PendingDeprecationWarning}.
1193
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001194\item Using \code{None} as a variable name will now result in a
1195\exception{SyntaxWarning} warning. In a future version of Python,
1196\code{None} may finally become a keyword.
1197
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001198\item The \method{xreadlines()} method of file objects, introduced in
1199Python 2.1, is no longer necessary because files now behave as their
1200own iterator. \method{xreadlines()} was originally introduced as a
1201faster way to loop over all the lines in a file, but now you can
1202simply write \code{for line in file_obj}. File objects also have a
1203new read-only \member{encoding} attribute that gives the encoding used
1204by the file; Unicode strings written to the file will be automatically
1205converted to bytes using the given encoding.
1206
Andrew M. Kuchlingb60ea3f2002-11-15 14:37:10 +00001207\item The method resolution order used by new-style classes has
1208changed, though you'll only notice the difference if you have a really
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +00001209complicated inheritance hierarchy. Classic classes are unaffected by
1210this change. Python 2.2 originally used a topological sort of a
Andrew M. Kuchlingb60ea3f2002-11-15 14:37:10 +00001211class's ancestors, but 2.3 now uses the C3 algorithm as described in
Andrew M. Kuchling6f429c32002-11-19 13:09:00 +00001212the paper \ulink{``A Monotonic Superclass Linearization for
1213Dylan''}{http://www.webcom.com/haahr/dylan/linearization-oopsla96.html}.
Andrew M. Kuchlingc1dd1742003-01-13 13:59:22 +00001214To understand the motivation for this change,
1215read Michele Simionato's article
Fred Drake693aea22003-02-07 14:52:18 +00001216\ulink{``Python 2.3 Method Resolution Order''}
Andrew M. Kuchlingb8a39052003-02-07 20:22:33 +00001217 {http://www.python.org/2.3/mro.html}, or
Andrew M. Kuchlingc1dd1742003-01-13 13:59:22 +00001218read the thread on python-dev starting with the message at
Andrew M. Kuchlingb60ea3f2002-11-15 14:37:10 +00001219\url{http://mail.python.org/pipermail/python-dev/2002-October/029035.html}.
1220Samuele Pedroni first pointed out the problem and also implemented the
1221fix by coding the C3 algorithm.
1222
Andrew M. Kuchlingdcfd8252002-09-13 22:21:42 +00001223\item Python runs multithreaded programs by switching between threads
1224after executing N bytecodes. The default value for N has been
1225increased from 10 to 100 bytecodes, speeding up single-threaded
1226applications by reducing the switching overhead. Some multithreaded
1227applications may suffer slower response time, but that's easily fixed
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001228by setting the limit back to a lower number using
Andrew M. Kuchlingdcfd8252002-09-13 22:21:42 +00001229\function{sys.setcheckinterval(\var{N})}.
Andrew M. Kuchlingc760c6c2003-07-16 20:12:33 +00001230The limit can be retrieved with the new
1231\function{sys.getcheckinterval()} function.
Andrew M. Kuchlingdcfd8252002-09-13 22:21:42 +00001232
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001233\item One minor but far-reaching change is that the names of extension
1234types defined by the modules included with Python now contain the
Fred Drake5c4cf152002-11-13 14:59:06 +00001235module and a \character{.} in front of the type name. For example, in
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001236Python 2.2, if you created a socket and printed its
1237\member{__class__}, you'd get this output:
1238
1239\begin{verbatim}
1240>>> s = socket.socket()
1241>>> s.__class__
1242<type 'socket'>
1243\end{verbatim}
1244
1245In 2.3, you get this:
1246\begin{verbatim}
1247>>> s.__class__
1248<type '_socket.socket'>
1249\end{verbatim}
1250
Michael W. Hudson96bc3b42002-11-26 14:48:23 +00001251\item One of the noted incompatibilities between old- and new-style
1252 classes has been removed: you can now assign to the
1253 \member{__name__} and \member{__bases__} attributes of new-style
1254 classes. There are some restrictions on what can be assigned to
1255 \member{__bases__} along the lines of those relating to assigning to
1256 an instance's \member{__class__} attribute.
1257
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001258\end{itemize}
1259
1260
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001261%======================================================================
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001262\subsection{String Changes}
1263
1264\begin{itemize}
1265
Fred Drakeaac8c582003-01-17 22:50:10 +00001266\item The \keyword{in} operator now works differently for strings.
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001267Previously, when evaluating \code{\var{X} in \var{Y}} where \var{X}
1268and \var{Y} are strings, \var{X} could only be a single character.
1269That's now changed; \var{X} can be a string of any length, and
1270\code{\var{X} in \var{Y}} will return \constant{True} if \var{X} is a
1271substring of \var{Y}. If \var{X} is the empty string, the result is
1272always \constant{True}.
1273
1274\begin{verbatim}
1275>>> 'ab' in 'abcd'
1276True
1277>>> 'ad' in 'abcd'
1278False
1279>>> '' in 'abcd'
1280True
1281\end{verbatim}
1282
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001283Note that this doesn't tell you where the substring starts; if you
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +00001284need that information, use the \method{find()} string method.
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001285
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001286\item The \method{strip()}, \method{lstrip()}, and \method{rstrip()}
1287string methods now have an optional argument for specifying the
1288characters to strip. The default is still to remove all whitespace
1289characters:
1290
1291\begin{verbatim}
1292>>> ' abc '.strip()
1293'abc'
1294>>> '><><abc<><><>'.strip('<>')
1295'abc'
1296>>> '><><abc<><><>\n'.strip('<>')
1297'abc<><><>\n'
1298>>> u'\u4000\u4001abc\u4000'.strip(u'\u4000')
1299u'\u4001abc'
1300>>>
1301\end{verbatim}
1302
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001303(Suggested by Simon Brunning and implemented by Walter D\"orwald.)
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00001304
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001305\item The \method{startswith()} and \method{endswith()}
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001306string methods now accept negative numbers for the \var{start} and \var{end}
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001307parameters.
1308
1309\item Another new string method is \method{zfill()}, originally a
1310function in the \module{string} module. \method{zfill()} pads a
1311numeric string with zeros on the left until it's the specified width.
1312Note that the \code{\%} operator is still more flexible and powerful
1313than \method{zfill()}.
1314
1315\begin{verbatim}
1316>>> '45'.zfill(4)
1317'0045'
1318>>> '12345'.zfill(4)
1319'12345'
1320>>> 'goofy'.zfill(6)
1321'0goofy'
1322\end{verbatim}
1323
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00001324(Contributed by Walter D\"orwald.)
1325
Fred Drake5c4cf152002-11-13 14:59:06 +00001326\item A new type object, \class{basestring}, has been added.
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001327 Both 8-bit strings and Unicode strings inherit from this type, so
1328 \code{isinstance(obj, basestring)} will return \constant{True} for
1329 either kind of string. It's a completely abstract type, so you
1330 can't create \class{basestring} instances.
1331
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001332\item Interned strings are no longer immortal and will now be
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001333garbage-collected in the usual way when the only reference to them is
1334from the internal dictionary of interned strings. (Implemented by
1335Oren Tirosh.)
1336
1337\end{itemize}
1338
1339
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001340%======================================================================
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001341\subsection{Optimizations}
1342
1343\begin{itemize}
1344
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001345\item The creation of new-style class instances has been made much
1346faster; they're now faster than classic classes!
1347
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001348\item The \method{sort()} method of list objects has been extensively
1349rewritten by Tim Peters, and the implementation is significantly
1350faster.
1351
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001352\item Multiplication of large long integers is now much faster thanks
1353to an implementation of Karatsuba multiplication, an algorithm that
1354scales better than the O(n*n) required for the grade-school
1355multiplication algorithm. (Original patch by Christopher A. Craig,
1356and significantly reworked by Tim Peters.)
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001357
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001358\item The \code{SET_LINENO} opcode is now gone. This may provide a
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001359small speed increase, depending on your compiler's idiosyncrasies.
1360See section~\ref{section-other} for a longer explanation.
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001361(Removed by Michael Hudson.)
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001362
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001363\item \function{xrange()} objects now have their own iterator, making
1364\code{for i in xrange(n)} slightly faster than
1365\code{for i in range(n)}. (Patch by Raymond Hettinger.)
1366
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001367\item A number of small rearrangements have been made in various
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001368hotspots to improve performance, such as inlining a function or removing
1369some code. (Implemented mostly by GvR, but lots of people have
1370contributed single changes.)
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001371
1372\end{itemize}
Neal Norwitzd68f5172002-05-29 15:54:55 +00001373
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001374The net result of the 2.3 optimizations is that Python 2.3 runs the
1375pystone benchmark around 25\% faster than Python 2.2.
1376
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001377
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001378%======================================================================
Andrew M. Kuchlingef893fe2003-01-06 20:04:17 +00001379\section{New, Improved, and Deprecated Modules}
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00001380
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001381As usual, Python's standard library received a number of enhancements and
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001382bug fixes. Here's a partial list of the most notable changes, sorted
1383alphabetically by module name. Consult the
1384\file{Misc/NEWS} file in the source tree for a more
1385complete list of changes, or look through the CVS logs for all the
1386details.
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00001387
1388\begin{itemize}
1389
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001390\item The \module{array} module now supports arrays of Unicode
Fred Drake5c4cf152002-11-13 14:59:06 +00001391characters using the \character{u} format character. Arrays also now
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001392support using the \code{+=} assignment operator to add another array's
1393contents, and the \code{*=} assignment operator to repeat an array.
1394(Contributed by Jason Orendorff.)
1395
Gregory P. Smithe94040a2003-09-21 23:41:02 +00001396\item The \module{bsddb} module has been replaced by version 4.1.6
Andrew M. Kuchling669249e2002-11-19 13:05:33 +00001397of the \ulink{PyBSDDB}{http://pybsddb.sourceforge.net} package,
1398providing a more complete interface to the transactional features of
1399the BerkeleyDB library.
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001400
Andrew M. Kuchling669249e2002-11-19 13:05:33 +00001401The old version of the module has been renamed to
1402\module{bsddb185} and is no longer built automatically; you'll
1403have to edit \file{Modules/Setup} to enable it. Note that the new
1404\module{bsddb} package is intended to be compatible with the
1405old module, so be sure to file bugs if you discover any
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001406incompatibilities. When upgrading to Python 2.3, if the new interpreter is compiled
1407with a new version of
Skip Montanaro959c7722003-03-07 15:45:15 +00001408the underlying BerkeleyDB library, you will almost certainly have to
1409convert your database files to the new version. You can do this
1410fairly easily with the new scripts \file{db2pickle.py} and
1411\file{pickle2db.py} which you will find in the distribution's
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001412\file{Tools/scripts} directory. If you've already been using the PyBSDDB
Andrew M. Kuchlinge36b6902003-04-19 15:38:47 +00001413package and importing it as \module{bsddb3}, you will have to change your
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001414\code{import} statements to import it as \module{bsddb}.
Andrew M. Kuchlinge36b6902003-04-19 15:38:47 +00001415
1416\item The new \module{bz2} module is an interface to the bz2 data
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001417compression library. bz2-compressed data is usually smaller than
1418corresponding \module{zlib}-compressed data. (Contributed by Gustavo Niemeyer.)
Andrew M. Kuchling669249e2002-11-19 13:05:33 +00001419
Andrew M. Kuchling273069d2003-12-23 16:46:41 +00001420\item A set of standard date/time types has been added in the new \module{datetime}
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001421module. See the following section for more details.
1422
Fred Drake5c4cf152002-11-13 14:59:06 +00001423\item The Distutils \class{Extension} class now supports
1424an extra constructor argument named \var{depends} for listing
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001425additional source files that an extension depends on. This lets
1426Distutils recompile the module if any of the dependency files are
Fred Drake5c4cf152002-11-13 14:59:06 +00001427modified. For example, if \file{sampmodule.c} includes the header
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001428file \file{sample.h}, you would create the \class{Extension} object like
1429this:
1430
1431\begin{verbatim}
1432ext = Extension("samp",
1433 sources=["sampmodule.c"],
1434 depends=["sample.h"])
1435\end{verbatim}
1436
1437Modifying \file{sample.h} would then cause the module to be recompiled.
1438(Contributed by Jeremy Hylton.)
1439
Andrew M. Kuchlingdc3f7e12002-11-04 20:05:10 +00001440\item Other minor changes to Distutils:
1441it now checks for the \envvar{CC}, \envvar{CFLAGS}, \envvar{CPP},
1442\envvar{LDFLAGS}, and \envvar{CPPFLAGS} environment variables, using
1443them to override the settings in Python's configuration (contributed
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +00001444by Robert Weber).
Andrew M. Kuchlingdc3f7e12002-11-04 20:05:10 +00001445
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001446\item Previously the \module{doctest} module would only search the
1447docstrings of public methods and functions for test cases, but it now
1448also examines private ones as well. The \function{DocTestSuite(}
1449function creates a \class{unittest.TestSuite} object from a set of
1450\module{doctest} tests.
1451
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001452\item The new \function{gc.get_referents(\var{object})} function returns a
1453list of all the objects referenced by \var{object}.
1454
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001455\item The \module{getopt} module gained a new function,
1456\function{gnu_getopt()}, that supports the same arguments as the existing
Fred Drake5c4cf152002-11-13 14:59:06 +00001457\function{getopt()} function but uses GNU-style scanning mode.
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001458The existing \function{getopt()} stops processing options as soon as a
1459non-option argument is encountered, but in GNU-style mode processing
1460continues, meaning that options and arguments can be mixed. For
1461example:
1462
1463\begin{verbatim}
1464>>> getopt.getopt(['-f', 'filename', 'output', '-v'], 'f:v')
1465([('-f', 'filename')], ['output', '-v'])
1466>>> getopt.gnu_getopt(['-f', 'filename', 'output', '-v'], 'f:v')
1467([('-f', 'filename'), ('-v', '')], ['output'])
1468\end{verbatim}
1469
1470(Contributed by Peter \AA{strand}.)
1471
1472\item The \module{grp}, \module{pwd}, and \module{resource} modules
Fred Drake5c4cf152002-11-13 14:59:06 +00001473now return enhanced tuples:
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001474
1475\begin{verbatim}
1476>>> import grp
1477>>> g = grp.getgrnam('amk')
1478>>> g.gr_name, g.gr_gid
1479('amk', 500)
1480\end{verbatim}
1481
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001482\item The \module{gzip} module can now handle files exceeding 2~Gb.
1483
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001484\item The new \module{heapq} module contains an implementation of a
1485heap queue algorithm. A heap is an array-like data structure that
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001486keeps items in a partially sorted order such that, for every index
1487\var{k}, \code{heap[\var{k}] <= heap[2*\var{k}+1]} and
1488\code{heap[\var{k}] <= heap[2*\var{k}+2]}. This makes it quick to
1489remove the smallest item, and inserting a new item while maintaining
1490the heap property is O(lg~n). (See
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001491\url{http://www.nist.gov/dads/HTML/priorityque.html} for more
1492information about the priority queue data structure.)
1493
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001494The \module{heapq} module provides \function{heappush()} and
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001495\function{heappop()} functions for adding and removing items while
1496maintaining the heap property on top of some other mutable Python
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001497sequence type. Here's an example that uses a Python list:
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001498
1499\begin{verbatim}
1500>>> import heapq
1501>>> heap = []
1502>>> for item in [3, 7, 5, 11, 1]:
1503... heapq.heappush(heap, item)
1504...
1505>>> heap
1506[1, 3, 5, 11, 7]
1507>>> heapq.heappop(heap)
15081
1509>>> heapq.heappop(heap)
15103
1511>>> heap
1512[5, 7, 11]
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001513\end{verbatim}
1514
1515(Contributed by Kevin O'Connor.)
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001516
Andrew M. Kuchling6e73f9e2003-07-18 01:15:51 +00001517\item The IDLE integrated development environment has been updated
1518using the code from the IDLEfork project
1519(\url{http://idlefork.sf.net}). The most notable feature is that the
1520code being developed is now executed in a subprocess, meaning that
1521there's no longer any need for manual \code{reload()} operations.
1522IDLE's core code has been incorporated into the standard library as the
1523\module{idlelib} package.
1524
Andrew M. Kuchling87cebbf2003-01-03 16:24:28 +00001525\item The \module{imaplib} module now supports IMAP over SSL.
1526(Contributed by Piers Lauder and Tino Lange.)
1527
Andrew M. Kuchling41c3e002003-03-02 02:13:52 +00001528\item The \module{itertools} contains a number of useful functions for
1529use with iterators, inspired by various functions provided by the ML
1530and Haskell languages. For example,
1531\code{itertools.ifilter(predicate, iterator)} returns all elements in
1532the iterator for which the function \function{predicate()} returns
Andrew M. Kuchling563389f2003-03-02 02:31:58 +00001533\constant{True}, and \code{itertools.repeat(obj, \var{N})} returns
Andrew M. Kuchling41c3e002003-03-02 02:13:52 +00001534\code{obj} \var{N} times. There are a number of other functions in
1535the module; see the \ulink{package's reference
1536documentation}{../lib/module-itertools.html} for details.
Raymond Hettinger5284b442003-03-09 07:19:38 +00001537(Contributed by Raymond Hettinger.)
Fred Drakecade7132003-02-19 16:08:08 +00001538
Fred Drake5c4cf152002-11-13 14:59:06 +00001539\item Two new functions in the \module{math} module,
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001540\function{degrees(\var{rads})} and \function{radians(\var{degs})},
Fred Drake5c4cf152002-11-13 14:59:06 +00001541convert between radians and degrees. Other functions in the
Andrew M. Kuchling8e5b53b2002-12-15 20:17:38 +00001542\module{math} module such as \function{math.sin()} and
1543\function{math.cos()} have always required input values measured in
1544radians. Also, an optional \var{base} argument was added to
1545\function{math.log()} to make it easier to compute logarithms for
1546bases other than \code{e} and \code{10}. (Contributed by Raymond
1547Hettinger.)
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001548
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001549\item Several new POSIX functions (\function{getpgid()}, \function{killpg()},
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +00001550\function{lchown()}, \function{loadavg()}, \function{major()}, \function{makedev()},
1551\function{minor()}, and \function{mknod()}) were added to the
Andrew M. Kuchlingc309cca2002-10-10 16:04:08 +00001552\module{posix} module that underlies the \module{os} module.
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +00001553(Contributed by Gustavo Niemeyer, Geert Jansen, and Denis S. Otkidach.)
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001554
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001555\item In the \module{os} module, the \function{*stat()} family of
1556functions can now report fractions of a second in a timestamp. Such
1557time stamps are represented as floats, similar to
1558the value returned by \function{time.time()}.
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001559
1560During testing, it was found that some applications will break if time
1561stamps are floats. For compatibility, when using the tuple interface
1562of the \class{stat_result} time stamps will be represented as integers.
1563When using named fields (a feature first introduced in Python 2.2),
1564time stamps are still represented as integers, unless
1565\function{os.stat_float_times()} is invoked to enable float return
1566values:
1567
1568\begin{verbatim}
1569>>> os.stat("/tmp").st_mtime
15701034791200
1571>>> os.stat_float_times(True)
1572>>> os.stat("/tmp").st_mtime
15731034791200.6335014
1574\end{verbatim}
1575
1576In Python 2.4, the default will change to always returning floats.
1577
1578Application developers should enable this feature only if all their
1579libraries work properly when confronted with floating point time
1580stamps, or if they use the tuple API. If used, the feature should be
1581activated on an application level instead of trying to enable it on a
1582per-use basis.
1583
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001584\item The \module{optparse} module contains a new parser for command-line arguments
1585that can convert option values to a particular Python type
1586and will automatically generate a usage message. See the following section for
1587more details.
1588
Andrew M. Kuchling53262572002-12-01 14:00:21 +00001589\item The old and never-documented \module{linuxaudiodev} module has
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001590been deprecated, and a new version named \module{ossaudiodev} has been
1591added. The module was renamed because the OSS sound drivers can be
1592used on platforms other than Linux, and the interface has also been
1593tidied and brought up to date in various ways. (Contributed by Greg
Greg Wardaa1d3aa2003-01-03 18:03:21 +00001594Ward and Nicholas FitzRoy-Dale.)
Andrew M. Kuchling53262572002-12-01 14:00:21 +00001595
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001596\item The new \module{platform} module contains a number of functions
1597that try to determine various properties of the platform you're
1598running on. There are functions for getting the architecture, CPU
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001599type, the Windows OS version, and even the Linux distribution version.
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001600(Contributed by Marc-Andr\'e Lemburg.)
1601
Fred Drake5c4cf152002-11-13 14:59:06 +00001602\item The parser objects provided by the \module{pyexpat} module
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001603can now optionally buffer character data, resulting in fewer calls to
1604your character data handler and therefore faster performance. Setting
Fred Drake5c4cf152002-11-13 14:59:06 +00001605the parser object's \member{buffer_text} attribute to \constant{True}
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001606will enable buffering.
1607
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001608\item The \function{sample(\var{population}, \var{k})} function was
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001609added to the \module{random} module. \var{population} is a sequence or
1610\class{xrange} object containing the elements of a population, and
1611\function{sample()} chooses \var{k} elements from the population without
1612replacing chosen elements. \var{k} can be any value up to
1613\code{len(\var{population})}. For example:
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001614
1615\begin{verbatim}
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001616>>> days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'St', 'Sn']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001617>>> random.sample(days, 3) # Choose 3 elements
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001618['St', 'Sn', 'Th']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001619>>> random.sample(days, 7) # Choose 7 elements
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001620['Tu', 'Th', 'Mo', 'We', 'St', 'Fr', 'Sn']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001621>>> random.sample(days, 7) # Choose 7 again
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001622['We', 'Mo', 'Sn', 'Fr', 'Tu', 'St', 'Th']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001623>>> random.sample(days, 8) # Can't choose eight
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001624Traceback (most recent call last):
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +00001625 File "<stdin>", line 1, in ?
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001626 File "random.py", line 414, in sample
1627 raise ValueError, "sample larger than population"
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001628ValueError: sample larger than population
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001629>>> random.sample(xrange(1,10000,2), 10) # Choose ten odd nos. under 10000
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001630[3407, 3805, 1505, 7023, 2401, 2267, 9733, 3151, 8083, 9195]
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001631\end{verbatim}
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001632
1633The \module{random} module now uses a new algorithm, the Mersenne
1634Twister, implemented in C. It's faster and more extensively studied
1635than the previous algorithm.
1636
1637(All changes contributed by Raymond Hettinger.)
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001638
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001639\item The \module{readline} module also gained a number of new
1640functions: \function{get_history_item()},
1641\function{get_current_history_length()}, and \function{redisplay()}.
1642
Andrew M. Kuchlingef893fe2003-01-06 20:04:17 +00001643\item The \module{rexec} and \module{Bastion} modules have been
1644declared dead, and attempts to import them will fail with a
1645\exception{RuntimeError}. New-style classes provide new ways to break
1646out of the restricted execution environment provided by
1647\module{rexec}, and no one has interest in fixing them or time to do
1648so. If you have applications using \module{rexec}, rewrite them to
1649use something else.
1650
1651(Sticking with Python 2.2 or 2.1 will not make your applications any
Andrew M. Kuchling13b4c412003-04-24 13:23:43 +00001652safer because there are known bugs in the \module{rexec} module in
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001653those versions. To repeat: if you're using \module{rexec}, stop using
Andrew M. Kuchlingef893fe2003-01-06 20:04:17 +00001654it immediately.)
1655
Andrew M. Kuchling13b4c412003-04-24 13:23:43 +00001656\item The \module{rotor} module has been deprecated because the
1657 algorithm it uses for encryption is not believed to be secure. If
1658 you need encryption, use one of the several AES Python modules
1659 that are available separately.
1660
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001661\item The \module{shutil} module gained a \function{move(\var{src},
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001662\var{dest})} function that recursively moves a file or directory to a new
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001663location.
1664
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001665\item Support for more advanced POSIX signal handling was added
Michael W. Hudson43ed43b2003-03-13 13:56:53 +00001666to the \module{signal} but then removed again as it proved impossible
1667to make it work reliably across platforms.
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001668
1669\item The \module{socket} module now supports timeouts. You
1670can call the \method{settimeout(\var{t})} method on a socket object to
1671set a timeout of \var{t} seconds. Subsequent socket operations that
1672take longer than \var{t} seconds to complete will abort and raise a
Andrew M. Kuchlingc760c6c2003-07-16 20:12:33 +00001673\exception{socket.timeout} exception.
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001674
1675The original timeout implementation was by Tim O'Malley. Michael
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001676Gilfix integrated it into the Python \module{socket} module and
1677shepherded it through a lengthy review. After the code was checked
1678in, Guido van~Rossum rewrote parts of it. (This is a good example of
1679a collaborative development process in action.)
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001680
Mark Hammond8af50bc2002-12-03 06:13:35 +00001681\item On Windows, the \module{socket} module now ships with Secure
Michael W. Hudson065f5fa2003-02-10 19:24:50 +00001682Sockets Layer (SSL) support.
Mark Hammond8af50bc2002-12-03 06:13:35 +00001683
Andrew M. Kuchling563389f2003-03-02 02:31:58 +00001684\item The value of the C \constant{PYTHON_API_VERSION} macro is now
1685exposed at the Python level as \code{sys.api_version}. The current
1686exception can be cleared by calling the new \function{sys.exc_clear()}
1687function.
Andrew M. Kuchlingdcfd8252002-09-13 22:21:42 +00001688
Andrew M. Kuchling674b0bf2003-01-07 00:07:19 +00001689\item The new \module{tarfile} module
Neal Norwitz55d555f2003-01-08 05:27:42 +00001690allows reading from and writing to \program{tar}-format archive files.
Andrew M. Kuchling674b0bf2003-01-07 00:07:19 +00001691(Contributed by Lars Gust\"abel.)
1692
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001693\item The new \module{textwrap} module contains functions for wrapping
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001694strings containing paragraphs of text. The \function{wrap(\var{text},
1695\var{width})} function takes a string and returns a list containing
1696the text split into lines of no more than the chosen width. The
1697\function{fill(\var{text}, \var{width})} function returns a single
1698string, reformatted to fit into lines no longer than the chosen width.
1699(As you can guess, \function{fill()} is built on top of
1700\function{wrap()}. For example:
1701
1702\begin{verbatim}
1703>>> import textwrap
1704>>> paragraph = "Not a whit, we defy augury: ... more text ..."
1705>>> textwrap.wrap(paragraph, 60)
Fred Drake5c4cf152002-11-13 14:59:06 +00001706["Not a whit, we defy augury: there's a special providence in",
1707 "the fall of a sparrow. If it be now, 'tis not to come; if it",
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001708 ...]
1709>>> print textwrap.fill(paragraph, 35)
1710Not a whit, we defy augury: there's
1711a special providence in the fall of
1712a sparrow. If it be now, 'tis not
1713to come; if it be not to come, it
1714will be now; if it be not now, yet
1715it will come: the readiness is all.
Fred Drake5c4cf152002-11-13 14:59:06 +00001716>>>
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001717\end{verbatim}
1718
1719The module also contains a \class{TextWrapper} class that actually
Fred Drake5c4cf152002-11-13 14:59:06 +00001720implements the text wrapping strategy. Both the
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001721\class{TextWrapper} class and the \function{wrap()} and
1722\function{fill()} functions support a number of additional keyword
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +00001723arguments for fine-tuning the formatting; consult the \ulink{module's
1724documentation}{../lib/module-textwrap.html} for details.
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001725(Contributed by Greg Ward.)
1726
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001727\item The \module{thread} and \module{threading} modules now have
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001728companion modules, \module{dummy_thread} and \module{dummy_threading},
1729that provide a do-nothing implementation of the \module{thread}
1730module's interface for platforms where threads are not supported. The
1731intention is to simplify thread-aware modules (ones that \emph{don't}
1732rely on threads to run) by putting the following code at the top:
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001733
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001734\begin{verbatim}
1735try:
1736 import threading as _threading
1737except ImportError:
1738 import dummy_threading as _threading
1739\end{verbatim}
1740
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001741In this example, \module{_threading} is used as the module name to make
1742it clear that the module being used is not necessarily the actual
1743\module{threading} module. Code can call functions and use classes in
1744\module{_threading} whether or not threads are supported, avoiding an
1745\keyword{if} statement and making the code slightly clearer. This
1746module will not magically make multithreaded code run without threads;
1747code that waits for another thread to return or to do something will
1748simply hang forever.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001749
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001750\item The \module{time} module's \function{strptime()} function has
Fred Drake5c4cf152002-11-13 14:59:06 +00001751long been an annoyance because it uses the platform C library's
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001752\function{strptime()} implementation, and different platforms
1753sometimes have odd bugs. Brett Cannon contributed a portable
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001754implementation that's written in pure Python and should behave
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001755identically on all platforms.
1756
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +00001757\item The new \module{timeit} module helps measure how long snippets
1758of Python code take to execute. The \file{timeit.py} file can be run
1759directly from the command line, or the module's \class{Timer} class
1760can be imported and used directly. Here's a short example that
1761figures out whether it's faster to convert an 8-bit string to Unicode
1762by appending an empty Unicode string to it or by using the
1763\function{unicode()} function:
1764
1765\begin{verbatim}
1766import timeit
1767
1768timer1 = timeit.Timer('unicode("abc")')
1769timer2 = timeit.Timer('"abc" + u""')
1770
1771# Run three trials
1772print timer1.repeat(repeat=3, number=100000)
1773print timer2.repeat(repeat=3, number=100000)
1774
1775# On my laptop this outputs:
1776# [0.36831796169281006, 0.37441694736480713, 0.35304892063140869]
1777# [0.17574405670166016, 0.18193507194519043, 0.17565798759460449]
1778\end{verbatim}
1779
Raymond Hettinger8ccf4d72003-07-10 15:48:33 +00001780\item The \module{Tix} module has received various bug fixes and
Andrew M. Kuchlingef893fe2003-01-06 20:04:17 +00001781updates for the current version of the Tix package.
1782
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001783\item The \module{Tkinter} module now works with a thread-enabled
1784version of Tcl. Tcl's threading model requires that widgets only be
1785accessed from the thread in which they're created; accesses from
1786another thread can cause Tcl to panic. For certain Tcl interfaces,
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001787\module{Tkinter} will now automatically avoid this
1788when a widget is accessed from a different thread by marshalling a
1789command, passing it to the correct thread, and waiting for the
1790results. Other interfaces can't be handled automatically but
1791\module{Tkinter} will now raise an exception on such an access so that
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001792you can at least find out about the problem. See
Fred Drakeb876bcc2003-04-30 15:03:46 +00001793\url{http://mail.python.org/pipermail/python-dev/2002-December/031107.html} %
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001794for a more detailed explanation of this change. (Implemented by
Andrew M. Kuchlingfcf6b3e2003-05-07 17:00:35 +00001795Martin von~L\"owis.)
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001796
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001797\item Calling Tcl methods through \module{_tkinter} no longer
1798returns only strings. Instead, if Tcl returns other objects those
1799objects are converted to their Python equivalent, if one exists, or
1800wrapped with a \class{_tkinter.Tcl_Obj} object if no Python equivalent
Raymond Hettinger45bda572002-12-14 20:20:45 +00001801exists. This behavior can be controlled through the
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001802\method{wantobjects()} method of \class{tkapp} objects.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001803
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001804When using \module{_tkinter} through the \module{Tkinter} module (as
1805most Tkinter applications will), this feature is always activated. It
1806should not cause compatibility problems, since Tkinter would always
1807convert string results to Python types where possible.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001808
Raymond Hettinger45bda572002-12-14 20:20:45 +00001809If any incompatibilities are found, the old behavior can be restored
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001810by setting the \member{wantobjects} variable in the \module{Tkinter}
1811module to false before creating the first \class{tkapp} object.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001812
1813\begin{verbatim}
1814import Tkinter
Martin v. Löwis8c8aa5d2002-11-26 21:39:48 +00001815Tkinter.wantobjects = 0
Martin v. Löwis39b48522002-11-26 09:47:25 +00001816\end{verbatim}
1817
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001818Any breakage caused by this change should be reported as a bug.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001819
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001820\item The \module{UserDict} module has a new \class{DictMixin} class which
1821defines all dictionary methods for classes that already have a minimum
1822mapping interface. This greatly simplifies writing classes that need
1823to be substitutable for dictionaries, such as the classes in
1824the \module{shelve} module.
1825
1826Adding the mix-in as a superclass provides the full dictionary
1827interface whenever the class defines \method{__getitem__},
1828\method{__setitem__}, \method{__delitem__}, and \method{keys}.
1829For example:
1830
1831\begin{verbatim}
1832>>> import UserDict
1833>>> class SeqDict(UserDict.DictMixin):
1834... """Dictionary lookalike implemented with lists."""
1835... def __init__(self):
1836... self.keylist = []
1837... self.valuelist = []
1838... def __getitem__(self, key):
1839... try:
1840... i = self.keylist.index(key)
1841... except ValueError:
1842... raise KeyError
1843... return self.valuelist[i]
1844... def __setitem__(self, key, value):
1845... try:
1846... i = self.keylist.index(key)
1847... self.valuelist[i] = value
1848... except ValueError:
1849... self.keylist.append(key)
1850... self.valuelist.append(value)
1851... def __delitem__(self, key):
1852... try:
1853... i = self.keylist.index(key)
1854... except ValueError:
1855... raise KeyError
1856... self.keylist.pop(i)
1857... self.valuelist.pop(i)
1858... def keys(self):
1859... return list(self.keylist)
1860...
1861>>> s = SeqDict()
1862>>> dir(s) # See that other dictionary methods are implemented
1863['__cmp__', '__contains__', '__delitem__', '__doc__', '__getitem__',
1864 '__init__', '__iter__', '__len__', '__module__', '__repr__',
1865 '__setitem__', 'clear', 'get', 'has_key', 'items', 'iteritems',
1866 'iterkeys', 'itervalues', 'keylist', 'keys', 'pop', 'popitem',
1867 'setdefault', 'update', 'valuelist', 'values']
1868\end{verbatim}
1869
1870(Contributed by Raymond Hettinger.)
1871
Andrew M. Kuchlinge36b6902003-04-19 15:38:47 +00001872\item The DOM implementation
1873in \module{xml.dom.minidom} can now generate XML output in a
1874particular encoding by providing an optional encoding argument to
1875the \method{toxml()} and \method{toprettyxml()} methods of DOM nodes.
1876
Andrew M. Kuchling6e73f9e2003-07-18 01:15:51 +00001877\item The \module{xmlrpclib} module now supports an XML-RPC extension
1878for handling nil data values such as Python's \code{None}. Nil values
1879are always supported on unmarshalling an XML-RPC response. To
1880generate requests containing \code{None}, you must supply a true value
1881for the \var{allow_none} parameter when creating a \class{Marshaller}
1882instance.
1883
Andrew M. Kuchlinge36b6902003-04-19 15:38:47 +00001884\item The new \module{DocXMLRPCServer} module allows writing
1885self-documenting XML-RPC servers. Run it in demo mode (as a program)
1886to see it in action. Pointing the Web browser to the RPC server
1887produces pydoc-style documentation; pointing xmlrpclib to the
1888server allows invoking the actual methods.
1889(Contributed by Brian Quinlan.)
1890
Martin v. Löwis2548c732003-04-18 10:39:54 +00001891\item Support for internationalized domain names (RFCs 3454, 3490,
18923491, and 3492) has been added. The ``idna'' encoding can be used
1893to convert between a Unicode domain name and the ASCII-compatible
Andrew M. Kuchlinge36b6902003-04-19 15:38:47 +00001894encoding (ACE) of that name.
Martin v. Löwis2548c732003-04-18 10:39:54 +00001895
Martin v. Löwisfaf71ea2003-04-18 21:48:56 +00001896\begin{alltt}
Fred Drake15b3dba2003-07-16 04:00:14 +00001897>{}>{}> u"www.Alliancefran\c caise.nu".encode("idna")
Martin v. Löwis2548c732003-04-18 10:39:54 +00001898'www.xn--alliancefranaise-npb.nu'
Martin v. Löwisfaf71ea2003-04-18 21:48:56 +00001899\end{alltt}
Martin v. Löwis2548c732003-04-18 10:39:54 +00001900
Andrew M. Kuchlinge36b6902003-04-19 15:38:47 +00001901The \module{socket} module has also been extended to transparently
1902convert Unicode hostnames to the ACE version before passing them to
1903the C library. Modules that deal with hostnames such as
1904\module{httplib} and \module{ftplib}) also support Unicode host names;
1905\module{httplib} also sends HTTP \samp{Host} headers using the ACE
1906version of the domain name. \module{urllib} supports Unicode URLs
1907with non-ASCII host names as long as the \code{path} part of the URL
1908is ASCII only.
Martin v. Löwis2548c732003-04-18 10:39:54 +00001909
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001910To implement this change, the \module{stringprep} module, the
1911\code{mkstringprep} tool and the \code{punycode} encoding have been added.
Martin v. Löwis281b2c62003-04-18 21:04:39 +00001912
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00001913\end{itemize}
1914
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00001915
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001916%======================================================================
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001917\subsection{Date/Time Type}
1918
1919Date and time types suitable for expressing timestamps were added as
1920the \module{datetime} module. The types don't support different
1921calendars or many fancy features, and just stick to the basics of
1922representing time.
1923
1924The three primary types are: \class{date}, representing a day, month,
1925and year; \class{time}, consisting of hour, minute, and second; and
1926\class{datetime}, which contains all the attributes of both
Andrew M. Kuchlingc71bb972003-03-21 17:23:07 +00001927\class{date} and \class{time}. There's also a
1928\class{timedelta} class representing differences between two points
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001929in time, and time zone logic is implemented by classes inheriting from
1930the abstract \class{tzinfo} class.
1931
1932You can create instances of \class{date} and \class{time} by either
1933supplying keyword arguments to the appropriate constructor,
1934e.g. \code{datetime.date(year=1972, month=10, day=15)}, or by using
Andrew M. Kuchlingc71bb972003-03-21 17:23:07 +00001935one of a number of class methods. For example, the \method{date.today()}
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001936class method returns the current local date.
1937
1938Once created, instances of the date/time classes are all immutable.
1939There are a number of methods for producing formatted strings from
1940objects:
1941
1942\begin{verbatim}
1943>>> import datetime
1944>>> now = datetime.datetime.now()
1945>>> now.isoformat()
1946'2002-12-30T21:27:03.994956'
1947>>> now.ctime() # Only available on date, datetime
1948'Mon Dec 30 21:27:03 2002'
Raymond Hettingeree1bded2003-01-17 16:20:23 +00001949>>> now.strftime('%Y %d %b')
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001950'2002 30 Dec'
1951\end{verbatim}
1952
1953The \method{replace()} method allows modifying one or more fields
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001954of a \class{date} or \class{datetime} instance, returning a new instance:
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001955
1956\begin{verbatim}
1957>>> d = datetime.datetime.now()
1958>>> d
1959datetime.datetime(2002, 12, 30, 22, 15, 38, 827738)
1960>>> d.replace(year=2001, hour = 12)
1961datetime.datetime(2001, 12, 30, 12, 15, 38, 827738)
1962>>>
1963\end{verbatim}
1964
1965Instances can be compared, hashed, and converted to strings (the
1966result is the same as that of \method{isoformat()}). \class{date} and
1967\class{datetime} instances can be subtracted from each other, and
Andrew M. Kuchlingc71bb972003-03-21 17:23:07 +00001968added to \class{timedelta} instances. The largest missing feature is
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001969that there's no standard library support for parsing strings and getting back a
Andrew M. Kuchlingc71bb972003-03-21 17:23:07 +00001970\class{date} or \class{datetime}.
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001971
1972For more information, refer to the \ulink{module's reference
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +00001973documentation}{../lib/module-datetime.html}.
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001974(Contributed by Tim Peters.)
1975
1976
1977%======================================================================
Andrew M. Kuchling8d177092003-05-13 14:26:54 +00001978\subsection{The optparse Module}
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001979
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001980The \module{getopt} module provides simple parsing of command-line
1981arguments. The new \module{optparse} module (originally named Optik)
1982provides more elaborate command-line parsing that follows the Unix
1983conventions, automatically creates the output for \longprogramopt{help},
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001984and can perform different actions for different options.
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001985
1986You start by creating an instance of \class{OptionParser} and telling
1987it what your program's options are.
1988
1989\begin{verbatim}
Andrew M. Kuchling7ee9b512003-02-18 00:48:23 +00001990import sys
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001991from optparse import OptionParser
1992
1993op = OptionParser()
1994op.add_option('-i', '--input',
1995 action='store', type='string', dest='input',
1996 help='set input filename')
1997op.add_option('-l', '--length',
1998 action='store', type='int', dest='length',
1999 help='set maximum length of output')
2000\end{verbatim}
2001
2002Parsing a command line is then done by calling the \method{parse_args()}
2003method.
2004
2005\begin{verbatim}
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002006options, args = op.parse_args(sys.argv[1:])
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00002007print options
2008print args
2009\end{verbatim}
2010
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002011This returns an object containing all of the option values,
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00002012and a list of strings containing the remaining arguments.
2013
2014Invoking the script with the various arguments now works as you'd
2015expect it to. Note that the length argument is automatically
2016converted to an integer.
2017
2018\begin{verbatim}
2019$ ./python opt.py -i data arg1
2020<Values at 0x400cad4c: {'input': 'data', 'length': None}>
2021['arg1']
2022$ ./python opt.py --input=data --length=4
2023<Values at 0x400cad2c: {'input': 'data', 'length': 4}>
Andrew M. Kuchling7ee9b512003-02-18 00:48:23 +00002024[]
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00002025$
2026\end{verbatim}
2027
2028The help message is automatically generated for you:
2029
2030\begin{verbatim}
2031$ ./python opt.py --help
2032usage: opt.py [options]
2033
2034options:
2035 -h, --help show this help message and exit
2036 -iINPUT, --input=INPUT
2037 set input filename
2038 -lLENGTH, --length=LENGTH
2039 set maximum length of output
2040$
2041\end{verbatim}
Andrew M. Kuchling669249e2002-11-19 13:05:33 +00002042% $ prevent Emacs tex-mode from getting confused
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00002043
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +00002044See the \ulink{module's documentation}{../lib/module-optparse.html}
2045for more details.
2046
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00002047Optik was written by Greg Ward, with suggestions from the readers of
2048the Getopt SIG.
2049
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00002050
2051%======================================================================
Andrew M. Kuchling8d177092003-05-13 14:26:54 +00002052\section{Pymalloc: A Specialized Object Allocator\label{section-pymalloc}}
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002053
Andrew M. Kuchlingc71bb972003-03-21 17:23:07 +00002054Pymalloc, a specialized object allocator written by Vladimir
2055Marangozov, was a feature added to Python 2.1. Pymalloc is intended
2056to be faster than the system \cfunction{malloc()} and to have less
2057memory overhead for allocation patterns typical of Python programs.
2058The allocator uses C's \cfunction{malloc()} function to get large
2059pools of memory and then fulfills smaller memory requests from these
2060pools.
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002061
2062In 2.1 and 2.2, pymalloc was an experimental feature and wasn't
Andrew M. Kuchlingc71bb972003-03-21 17:23:07 +00002063enabled by default; you had to explicitly enable it when compiling
2064Python by providing the
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002065\longprogramopt{with-pymalloc} option to the \program{configure}
2066script. In 2.3, pymalloc has had further enhancements and is now
2067enabled by default; you'll have to supply
2068\longprogramopt{without-pymalloc} to disable it.
2069
2070This change is transparent to code written in Python; however,
2071pymalloc may expose bugs in C extensions. Authors of C extension
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002072modules should test their code with pymalloc enabled,
2073because some incorrect code may cause core dumps at runtime.
2074
2075There's one particularly common error that causes problems. There are
2076a number of memory allocation functions in Python's C API that have
2077previously just been aliases for the C library's \cfunction{malloc()}
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002078and \cfunction{free()}, meaning that if you accidentally called
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002079mismatched functions the error wouldn't be noticeable. When the
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002080object allocator is enabled, these functions aren't aliases of
2081\cfunction{malloc()} and \cfunction{free()} any more, and calling the
2082wrong function to free memory may get you a core dump. For example,
2083if memory was allocated using \cfunction{PyObject_Malloc()}, it has to
2084be freed using \cfunction{PyObject_Free()}, not \cfunction{free()}. A
2085few modules included with Python fell afoul of this and had to be
2086fixed; doubtless there are more third-party modules that will have the
2087same problem.
2088
2089As part of this change, the confusing multiple interfaces for
2090allocating memory have been consolidated down into two API families.
2091Memory allocated with one family must not be manipulated with
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002092functions from the other family. There is one family for allocating
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002093chunks of memory and another family of functions specifically for
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002094allocating Python objects.
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002095
2096\begin{itemize}
2097 \item To allocate and free an undistinguished chunk of memory use
2098 the ``raw memory'' family: \cfunction{PyMem_Malloc()},
2099 \cfunction{PyMem_Realloc()}, and \cfunction{PyMem_Free()}.
2100
2101 \item The ``object memory'' family is the interface to the pymalloc
2102 facility described above and is biased towards a large number of
2103 ``small'' allocations: \cfunction{PyObject_Malloc},
2104 \cfunction{PyObject_Realloc}, and \cfunction{PyObject_Free}.
2105
2106 \item To allocate and free Python objects, use the ``object'' family
2107 \cfunction{PyObject_New()}, \cfunction{PyObject_NewVar()}, and
2108 \cfunction{PyObject_Del()}.
2109\end{itemize}
2110
2111Thanks to lots of work by Tim Peters, pymalloc in 2.3 also provides
2112debugging features to catch memory overwrites and doubled frees in
2113both extension modules and in the interpreter itself. To enable this
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002114support, compile a debugging version of the Python interpreter by
2115running \program{configure} with \longprogramopt{with-pydebug}.
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002116
2117To aid extension writers, a header file \file{Misc/pymemcompat.h} is
2118distributed with the source to Python 2.3 that allows Python
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002119extensions to use the 2.3 interfaces to memory allocation while
2120compiling against any version of Python since 1.5.2. You would copy
2121the file from Python's source distribution and bundle it with the
2122source of your extension.
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002123
2124\begin{seealso}
2125
2126\seeurl{http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Objects/obmalloc.c}
2127{For the full details of the pymalloc implementation, see
2128the comments at the top of the file \file{Objects/obmalloc.c} in the
2129Python source code. The above link points to the file within the
2130SourceForge CVS browser.}
2131
2132\end{seealso}
2133
2134
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00002135% ======================================================================
2136\section{Build and C API Changes}
2137
Andrew M. Kuchling3c305d92002-07-22 18:50:11 +00002138Changes to Python's build process and to the C API include:
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00002139
2140\begin{itemize}
2141
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002142\item The cycle detection implementation used by the garbage collection
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002143has proven to be stable, so it's now been made mandatory. You can no
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002144longer compile Python without it, and the
2145\longprogramopt{with-cycle-gc} switch to \program{configure} has been removed.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00002146
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002147\item Python can now optionally be built as a shared library
2148(\file{libpython2.3.so}) by supplying \longprogramopt{enable-shared}
Fred Drake5c4cf152002-11-13 14:59:06 +00002149when running Python's \program{configure} script. (Contributed by Ondrej
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +00002150Palkovsky.)
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +00002151
Michael W. Hudsondd32a912002-08-15 14:59:02 +00002152\item The \csimplemacro{DL_EXPORT} and \csimplemacro{DL_IMPORT} macros
2153are now deprecated. Initialization functions for Python extension
2154modules should now be declared using the new macro
Andrew M. Kuchling3c305d92002-07-22 18:50:11 +00002155\csimplemacro{PyMODINIT_FUNC}, while the Python core will generally
2156use the \csimplemacro{PyAPI_FUNC} and \csimplemacro{PyAPI_DATA}
2157macros.
Neal Norwitzbba23a82002-07-22 13:18:59 +00002158
Fred Drake5c4cf152002-11-13 14:59:06 +00002159\item The interpreter can be compiled without any docstrings for
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00002160the built-in functions and modules by supplying
Fred Drake5c4cf152002-11-13 14:59:06 +00002161\longprogramopt{without-doc-strings} to the \program{configure} script.
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00002162This makes the Python executable about 10\% smaller, but will also
2163mean that you can't get help for Python's built-ins. (Contributed by
2164Gustavo Niemeyer.)
2165
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002166\item The \cfunction{PyArg_NoArgs()} macro is now deprecated, and code
Andrew M. Kuchling7845e7c2002-07-11 19:27:46 +00002167that uses it should be changed. For Python 2.2 and later, the method
2168definition table can specify the
Fred Drake5c4cf152002-11-13 14:59:06 +00002169\constant{METH_NOARGS} flag, signalling that there are no arguments, and
Andrew M. Kuchling7845e7c2002-07-11 19:27:46 +00002170the argument checking can then be removed. If compatibility with
2171pre-2.2 versions of Python is important, the code could use
Fred Drakeaac8c582003-01-17 22:50:10 +00002172\code{PyArg_ParseTuple(\var{args}, "")} instead, but this will be slower
Andrew M. Kuchling7845e7c2002-07-11 19:27:46 +00002173than using \constant{METH_NOARGS}.
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00002174
Andrew M. Kuchling50a25702003-10-23 18:08:03 +00002175\item \cfunction{PyArg_ParseTuple()} accepts new format characters for various sizes of unsigned integers: \samp{B} for \ctype{unsigned char},
2176\samp{H} for \ctype{unsigned short int},
2177\samp{I} for \ctype{unsigned int},
2178and \samp{K} for \ctype{unsigned long long}.
2179
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002180\item A new function, \cfunction{PyObject_DelItemString(\var{mapping},
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002181char *\var{key})} was added as shorthand for
Raymond Hettingera685f522003-07-12 04:42:30 +00002182\code{PyObject_DelItem(\var{mapping}, PyString_New(\var{key}))}.
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00002183
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002184\item File objects now manage their internal string buffer
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002185differently, increasing it exponentially when needed. This results in
2186the benchmark tests in \file{Lib/test/test_bufio.py} speeding up
2187considerably (from 57 seconds to 1.7 seconds, according to one
2188measurement).
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002189
Andrew M. Kuchling72b58e02002-05-29 17:30:34 +00002190\item It's now possible to define class and static methods for a C
2191extension type by setting either the \constant{METH_CLASS} or
2192\constant{METH_STATIC} flags in a method's \ctype{PyMethodDef}
2193structure.
Andrew M. Kuchling45afd542002-04-02 14:25:25 +00002194
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00002195\item Python now includes a copy of the Expat XML parser's source code,
2196removing any dependence on a system version or local installation of
Fred Drake5c4cf152002-11-13 14:59:06 +00002197Expat.
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00002198
Michael W. Hudson3e245d82003-02-11 14:19:56 +00002199\item If you dynamically allocate type objects in your extension, you
Neal Norwitzada859c2003-02-11 14:30:39 +00002200should be aware of a change in the rules relating to the
Michael W. Hudson3e245d82003-02-11 14:19:56 +00002201\member{__module__} and \member{__name__} attributes. In summary,
2202you will want to ensure the type's dictionary contains a
2203\code{'__module__'} key; making the module name the part of the type
2204name leading up to the final period will no longer have the desired
2205effect. For more detail, read the API reference documentation or the
2206source.
2207
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00002208\end{itemize}
2209
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00002210
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00002211%======================================================================
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00002212\subsection{Port-Specific Changes}
2213
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00002214Support for a port to IBM's OS/2 using the EMX runtime environment was
2215merged into the main Python source tree. EMX is a POSIX emulation
2216layer over the OS/2 system APIs. The Python port for EMX tries to
2217support all the POSIX-like capability exposed by the EMX runtime, and
2218mostly succeeds; \function{fork()} and \function{fcntl()} are
2219restricted by the limitations of the underlying emulation layer. The
2220standard OS/2 port, which uses IBM's Visual Age compiler, also gained
2221support for case-sensitive import semantics as part of the integration
2222of the EMX port into CVS. (Contributed by Andrew MacIntyre.)
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00002223
Andrew M. Kuchling72b58e02002-05-29 17:30:34 +00002224On MacOS, most toolbox modules have been weaklinked to improve
2225backward compatibility. This means that modules will no longer fail
Raymond Hettinger68804312005-01-01 00:28:46 +00002226to load if a single routine is missing on the current OS version.
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00002227Instead calling the missing routine will raise an exception.
2228(Contributed by Jack Jansen.)
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00002229
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00002230The RPM spec files, found in the \file{Misc/RPM/} directory in the
2231Python source distribution, were updated for 2.3. (Contributed by
2232Sean Reifschneider.)
Fred Drake03e10312002-03-26 19:17:43 +00002233
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002234Other new platforms now supported by Python include AtheOS
Fred Drake693aea22003-02-07 14:52:18 +00002235(\url{http://www.atheos.cx/}), GNU/Hurd, and OpenVMS.
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00002236
Fred Drake03e10312002-03-26 19:17:43 +00002237
2238%======================================================================
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002239\section{Other Changes and Fixes \label{section-other}}
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002240
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +00002241As usual, there were a bunch of other improvements and bugfixes
2242scattered throughout the source tree. A search through the CVS change
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +00002243logs finds there were 523 patches applied and 514 bugs fixed between
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +00002244Python 2.2 and 2.3. Both figures are likely to be underestimates.
2245
2246Some of the more notable changes are:
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002247
2248\begin{itemize}
2249
Andrew M. Kuchling6e73f9e2003-07-18 01:15:51 +00002250\item If the \envvar{PYTHONINSPECT} environment variable is set, the
2251Python interpreter will enter the interactive prompt after running a
2252Python program, as if Python had been invoked with the \programopt{-i}
2253option. The environment variable can be set before running the Python
2254interpreter, or it can be set by the Python program as part of its
2255execution.
2256
Fred Drake54fe3fd2002-11-26 22:07:35 +00002257\item The \file{regrtest.py} script now provides a way to allow ``all
2258resources except \var{foo}.'' A resource name passed to the
2259\programopt{-u} option can now be prefixed with a hyphen
2260(\character{-}) to mean ``remove this resource.'' For example, the
2261option `\code{\programopt{-u}all,-bsddb}' could be used to enable the
2262use of all resources except \code{bsddb}.
2263
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002264\item The tools used to build the documentation now work under Cygwin
2265as well as \UNIX.
2266
Michael W. Hudsondd32a912002-08-15 14:59:02 +00002267\item The \code{SET_LINENO} opcode has been removed. Back in the
2268mists of time, this opcode was needed to produce line numbers in
2269tracebacks and support trace functions (for, e.g., \module{pdb}).
2270Since Python 1.5, the line numbers in tracebacks have been computed
2271using a different mechanism that works with ``python -O''. For Python
22722.3 Michael Hudson implemented a similar scheme to determine when to
2273call the trace function, removing the need for \code{SET_LINENO}
2274entirely.
2275
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +00002276It would be difficult to detect any resulting difference from Python
2277code, apart from a slight speed up when Python is run without
Michael W. Hudsondd32a912002-08-15 14:59:02 +00002278\programopt{-O}.
2279
2280C extensions that access the \member{f_lineno} field of frame objects
2281should instead call \code{PyCode_Addr2Line(f->f_code, f->f_lasti)}.
2282This will have the added effect of making the code work as desired
2283under ``python -O'' in earlier versions of Python.
2284
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002285A nifty new feature is that trace functions can now assign to the
2286\member{f_lineno} attribute of frame objects, changing the line that
2287will be executed next. A \samp{jump} command has been added to the
2288\module{pdb} debugger taking advantage of this new feature.
2289(Implemented by Richie Hindle.)
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00002290
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002291\end{itemize}
2292
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00002293
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002294%======================================================================
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00002295\section{Porting to Python 2.3}
2296
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002297This section lists previously described changes that may require
2298changes to your code:
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002299
2300\begin{itemize}
2301
2302\item \keyword{yield} is now always a keyword; if it's used as a
2303variable name in your code, a different name must be chosen.
2304
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002305\item For strings \var{X} and \var{Y}, \code{\var{X} in \var{Y}} now works
2306if \var{X} is more than one character long.
2307
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00002308\item The \function{int()} type constructor will now return a long
2309integer instead of raising an \exception{OverflowError} when a string
2310or floating-point number is too large to fit into an integer.
2311
Andrew M. Kuchlingacddabc2003-02-18 00:43:24 +00002312\item If you have Unicode strings that contain 8-bit characters, you
2313must declare the file's encoding (UTF-8, Latin-1, or whatever) by
2314adding a comment to the top of the file. See
2315section~\ref{section-encodings} for more information.
2316
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00002317\item Calling Tcl methods through \module{_tkinter} no longer
2318returns only strings. Instead, if Tcl returns other objects those
2319objects are converted to their Python equivalent, if one exists, or
2320wrapped with a \class{_tkinter.Tcl_Obj} object if no Python equivalent
2321exists.
2322
Andrew M. Kuchling80fd7852003-02-06 15:14:04 +00002323\item Large octal and hex literals such as
Andrew M. Kuchling72df65a2003-02-10 15:08:16 +00002324\code{0xffffffff} now trigger a \exception{FutureWarning}. Currently
Andrew M. Kuchling80fd7852003-02-06 15:14:04 +00002325they're stored as 32-bit numbers and result in a negative value, but
Andrew M. Kuchling72df65a2003-02-10 15:08:16 +00002326in Python 2.4 they'll become positive long integers.
2327
Fred Drake2269d862004-11-11 06:14:05 +00002328% The empty groups below prevent conversion to guillemets.
Andrew M. Kuchling72df65a2003-02-10 15:08:16 +00002329There are a few ways to fix this warning. If you really need a
2330positive number, just add an \samp{L} to the end of the literal. If
2331you're trying to get a 32-bit integer with low bits set and have
Fred Drake2269d862004-11-11 06:14:05 +00002332previously used an expression such as \code{\textasciitilde(1 <{}< 31)},
2333it's probably
Andrew M. Kuchling72df65a2003-02-10 15:08:16 +00002334clearest to start with all bits set and clear the desired upper bits.
2335For example, to clear just the top bit (bit 31), you could write
Fred Drake2269d862004-11-11 06:14:05 +00002336\code{0xffffffffL {\&}{\textasciitilde}(1L<{}<31)}.
Andrew M. Kuchling80fd7852003-02-06 15:14:04 +00002337
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00002338\item You can no longer disable assertions by assigning to \code{__debug__}.
2339
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002340\item The Distutils \function{setup()} function has gained various new
Fred Drake5c4cf152002-11-13 14:59:06 +00002341keyword arguments such as \var{depends}. Old versions of the
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002342Distutils will abort if passed unknown keywords. A solution is to check
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002343for the presence of the new \function{get_distutil_options()} function
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002344in your \file{setup.py} and only uses the new keywords
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002345with a version of the Distutils that supports them:
2346
2347\begin{verbatim}
2348from distutils import core
2349
2350kw = {'sources': 'foo.c', ...}
2351if hasattr(core, 'get_distutil_options'):
2352 kw['depends'] = ['foo.h']
Fred Drake5c4cf152002-11-13 14:59:06 +00002353ext = Extension(**kw)
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002354\end{verbatim}
2355
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00002356\item Using \code{None} as a variable name will now result in a
2357\exception{SyntaxWarning} warning.
2358
2359\item Names of extension types defined by the modules included with
2360Python now contain the module and a \character{.} in front of the type
2361name.
2362
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002363\end{itemize}
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00002364
2365
2366%======================================================================
Fred Drake03e10312002-03-26 19:17:43 +00002367\section{Acknowledgements \label{acks}}
2368
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00002369The author would like to thank the following people for offering
2370suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +00002371article: Jeff Bauer, Simon Brunning, Brett Cannon, Michael Chermside,
Andrew M. Kuchling68a32942003-07-30 11:55:06 +00002372Andrew Dalke, Scott David Daniels, Fred~L. Drake, Jr., David Fraser,
2373Kelly Gerber,
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +00002374Raymond Hettinger, Michael Hudson, Chris Lambert, Detlef Lannert,
Andrew M. Kuchlingfcf6b3e2003-05-07 17:00:35 +00002375Martin von~L\"owis, Andrew MacIntyre, Lalo Martins, Chad Netzer,
2376Gustavo Niemeyer, Neal Norwitz, Hans Nowak, Chris Reedy, Francesco
2377Ricciardi, Vinay Sajip, Neil Schemenauer, Roman Suzi, Jason Tishler,
2378Just van~Rossum.
Fred Drake03e10312002-03-26 19:17:43 +00002379
2380\end{document}