blob: ebcdb3f229a9ed00c1dcd1c5f65c0db8bda74e05 [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. Kuchlingb34ba3f2003-07-29 12:06:32 +00006\release{1.00}
Fred Drakeaac8c582003-01-17 22:50:10 +00007\author{A.M.\ Kuchling}
Andrew M. Kuchlingbc5e3cc2002-11-05 00:26:33 +00008\authoraddress{\email{amk@amk.ca}}
Fred Drake03e10312002-03-26 19:17:43 +00009
10\begin{document}
11\maketitle
12\tableofcontents
13
Andrew M. Kuchlingb34ba3f2003-07-29 12:06:32 +000014This article explains the new features in Python 2.3. Python 2.3 was
15released on July 29, 2003.
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +000016
Andrew M. Kuchling95be8bd2003-07-18 02:12:16 +000017The main themes for Python 2.3 are polishing some of the features
18added in 2.2, adding various small but useful enhancements to the core
19language, and expanding the standard library. The new object model
20introduced in the previous version has benefited from 18 months of
21bugfixes and from optimization efforts that have improved the
22performance of new-style classes. A few new built-in functions have
23been added such as \function{sum()} and \function{enumerate()}. The
24\keyword{in} operator can now be used for substring searches (e.g.
25\code{"ab" in "abc"} returns \constant{True}).
26
27Some of the many new library features include Boolean, set, heap, and
28date/time data types, the ability to import modules from ZIP-format
29archives, metadata support for the long-awaited Python catalog, an
30updated version of IDLE, and modules for logging messages, wrapping
31text, parsing CSV files, processing command-line options, using BerkeleyDB
32databases... the list of new and enhanced modules is lengthy.
33
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +000034This article doesn't attempt to provide a complete specification of
35the new features, but instead provides a convenient overview. For
36full details, you should refer to the documentation for Python 2.3,
Fred Drake693aea22003-02-07 14:52:18 +000037such as the \citetitle[../lib/lib.html]{Python Library Reference} and
38the \citetitle[../ref/ref.html]{Python Reference Manual}. If you want
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +000039to understand the complete implementation and design rationale,
40refer to the PEP for a particular new feature.
Fred Drake03e10312002-03-26 19:17:43 +000041
42
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +000043%======================================================================
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000044\section{PEP 218: A Standard Set Datatype}
45
46The new \module{sets} module contains an implementation of a set
47datatype. The \class{Set} class is for mutable sets, sets that can
48have members added and removed. The \class{ImmutableSet} class is for
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +000049sets that can't be modified, and instances of \class{ImmutableSet} can
50therefore be used as dictionary keys. Sets are built on top of
51dictionaries, so the elements within a set must be hashable.
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000052
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +000053Here's a simple example:
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000054
55\begin{verbatim}
56>>> import sets
57>>> S = sets.Set([1,2,3])
58>>> S
59Set([1, 2, 3])
60>>> 1 in S
61True
62>>> 0 in S
63False
64>>> S.add(5)
65>>> S.remove(3)
66>>> S
67Set([1, 2, 5])
Fred Drake5c4cf152002-11-13 14:59:06 +000068>>>
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000069\end{verbatim}
70
71The union and intersection of sets can be computed with the
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +000072\method{union()} and \method{intersection()} methods; an alternative
73notation uses the bitwise operators \code{\&} and \code{|}.
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000074Mutable sets also have in-place versions of these methods,
75\method{union_update()} and \method{intersection_update()}.
76
77\begin{verbatim}
78>>> S1 = sets.Set([1,2,3])
79>>> S2 = sets.Set([4,5,6])
80>>> S1.union(S2)
81Set([1, 2, 3, 4, 5, 6])
82>>> S1 | S2 # Alternative notation
83Set([1, 2, 3, 4, 5, 6])
Fred Drake5c4cf152002-11-13 14:59:06 +000084>>> S1.intersection(S2)
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000085Set([])
86>>> S1 & S2 # Alternative notation
87Set([])
88>>> S1.union_update(S2)
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000089>>> S1
90Set([1, 2, 3, 4, 5, 6])
Fred Drake5c4cf152002-11-13 14:59:06 +000091>>>
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000092\end{verbatim}
93
94It's also possible to take the symmetric difference of two sets. This
95is the set of all elements in the union that aren't in the
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +000096intersection. Another way of putting it is that the symmetric
97difference contains all elements that are in exactly one
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +000098set. Again, there's an alternative notation (\code{\^}), and an
99in-place version with the ungainly name
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +0000100\method{symmetric_difference_update()}.
101
102\begin{verbatim}
103>>> S1 = sets.Set([1,2,3,4])
104>>> S2 = sets.Set([3,4,5,6])
105>>> S1.symmetric_difference(S2)
106Set([1, 2, 5, 6])
107>>> S1 ^ S2
108Set([1, 2, 5, 6])
109>>>
110\end{verbatim}
111
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000112There are also \method{issubset()} and \method{issuperset()} methods
Michael W. Hudson065f5fa2003-02-10 19:24:50 +0000113for checking whether one set is a subset or superset of another:
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +0000114
115\begin{verbatim}
116>>> S1 = sets.Set([1,2,3])
117>>> S2 = sets.Set([2,3])
118>>> S2.issubset(S1)
119True
120>>> S1.issubset(S2)
121False
122>>> S1.issuperset(S2)
123True
124>>>
125\end{verbatim}
126
127
128\begin{seealso}
129
130\seepep{218}{Adding a Built-In Set Object Type}{PEP written by Greg V. Wilson.
131Implemented by Greg V. Wilson, Alex Martelli, and GvR.}
132
133\end{seealso}
134
135
136
137%======================================================================
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000138\section{PEP 255: Simple Generators\label{section-generators}}
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000139
140In Python 2.2, generators were added as an optional feature, to be
141enabled by a \code{from __future__ import generators} directive. In
1422.3 generators no longer need to be specially enabled, and are now
143always present; this means that \keyword{yield} is now always a
144keyword. The rest of this section is a copy of the description of
145generators from the ``What's New in Python 2.2'' document; if you read
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000146it back when Python 2.2 came out, you can skip the rest of this section.
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000147
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000148You're doubtless familiar with how function calls work in Python or C.
149When you call a function, it gets a private namespace where its local
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000150variables are created. When the function reaches a \keyword{return}
151statement, the local variables are destroyed and the resulting value
152is returned to the caller. A later call to the same function will get
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000153a fresh new set of local variables. But, what if the local variables
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000154weren't thrown away on exiting a function? What if you could later
155resume the function where it left off? This is what generators
156provide; they can be thought of as resumable functions.
157
158Here's the simplest example of a generator function:
159
160\begin{verbatim}
161def generate_ints(N):
162 for i in range(N):
163 yield i
164\end{verbatim}
165
166A new keyword, \keyword{yield}, was introduced for generators. Any
167function containing a \keyword{yield} statement is a generator
168function; this is detected by Python's bytecode compiler which
Fred Drake5c4cf152002-11-13 14:59:06 +0000169compiles the function specially as a result.
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000170
171When you call a generator function, it doesn't return a single value;
172instead it returns a generator object that supports the iterator
173protocol. On executing the \keyword{yield} statement, the generator
174outputs the value of \code{i}, similar to a \keyword{return}
175statement. The big difference between \keyword{yield} and a
176\keyword{return} statement is that on reaching a \keyword{yield} the
177generator's state of execution is suspended and local variables are
178preserved. On the next call to the generator's \code{.next()} method,
179the function will resume executing immediately after the
180\keyword{yield} statement. (For complicated reasons, the
181\keyword{yield} statement isn't allowed inside the \keyword{try} block
Fred Drakeaac8c582003-01-17 22:50:10 +0000182of a \keyword{try}...\keyword{finally} statement; read \pep{255} for a full
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000183explanation of the interaction between \keyword{yield} and
184exceptions.)
185
Fred Drakeaac8c582003-01-17 22:50:10 +0000186Here's a sample usage of the \function{generate_ints()} generator:
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000187
188\begin{verbatim}
189>>> gen = generate_ints(3)
190>>> gen
191<generator object at 0x8117f90>
192>>> gen.next()
1930
194>>> gen.next()
1951
196>>> gen.next()
1972
198>>> gen.next()
199Traceback (most recent call last):
Andrew M. Kuchling9f6e1042002-06-17 13:40:04 +0000200 File "stdin", line 1, in ?
201 File "stdin", line 2, in generate_ints
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000202StopIteration
203\end{verbatim}
204
205You could equally write \code{for i in generate_ints(5)}, or
206\code{a,b,c = generate_ints(3)}.
207
208Inside a generator function, the \keyword{return} statement can only
209be used without a value, and signals the end of the procession of
210values; afterwards the generator cannot return any further values.
211\keyword{return} with a value, such as \code{return 5}, is a syntax
212error inside a generator function. The end of the generator's results
213can also be indicated by raising \exception{StopIteration} manually,
214or by just letting the flow of execution fall off the bottom of the
215function.
216
217You could achieve the effect of generators manually by writing your
218own class and storing all the local variables of the generator as
219instance variables. For example, returning a list of integers could
220be done by setting \code{self.count} to 0, and having the
221\method{next()} method increment \code{self.count} and return it.
222However, for a moderately complicated generator, writing a
223corresponding class would be much messier.
224\file{Lib/test/test_generators.py} contains a number of more
225interesting examples. The simplest one implements an in-order
226traversal of a tree using generators recursively.
227
228\begin{verbatim}
229# A recursive generator that generates Tree leaves in in-order.
230def inorder(t):
231 if t:
232 for x in inorder(t.left):
233 yield x
234 yield t.label
235 for x in inorder(t.right):
236 yield x
237\end{verbatim}
238
239Two other examples in \file{Lib/test/test_generators.py} produce
240solutions for the N-Queens problem (placing $N$ queens on an $NxN$
241chess board so that no queen threatens another) and the Knight's Tour
242(a route that takes a knight to every square of an $NxN$ chessboard
Fred Drake5c4cf152002-11-13 14:59:06 +0000243without visiting any square twice).
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000244
245The idea of generators comes from other programming languages,
246especially Icon (\url{http://www.cs.arizona.edu/icon/}), where the
247idea of generators is central. In Icon, every
248expression and function call behaves like a generator. One example
249from ``An Overview of the Icon Programming Language'' at
250\url{http://www.cs.arizona.edu/icon/docs/ipd266.htm} gives an idea of
251what this looks like:
252
253\begin{verbatim}
254sentence := "Store it in the neighboring harbor"
255if (i := find("or", sentence)) > 5 then write(i)
256\end{verbatim}
257
258In Icon the \function{find()} function returns the indexes at which the
259substring ``or'' is found: 3, 23, 33. In the \keyword{if} statement,
260\code{i} is first assigned a value of 3, but 3 is less than 5, so the
261comparison fails, and Icon retries it with the second value of 23. 23
262is greater than 5, so the comparison now succeeds, and the code prints
263the value 23 to the screen.
264
265Python doesn't go nearly as far as Icon in adopting generators as a
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000266central concept. Generators are considered part of the core
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000267Python language, but learning or using them isn't compulsory; if they
268don't solve any problems that you have, feel free to ignore them.
269One novel feature of Python's interface as compared to
270Icon's is that a generator's state is represented as a concrete object
271(the iterator) that can be passed around to other functions or stored
272in a data structure.
273
274\begin{seealso}
275
276\seepep{255}{Simple Generators}{Written by Neil Schemenauer, Tim
277Peters, Magnus Lie Hetland. Implemented mostly by Neil Schemenauer
278and Tim Peters, with other fixes from the Python Labs crew.}
279
280\end{seealso}
281
282
283%======================================================================
Fred Drake13090e12002-08-22 16:51:08 +0000284\section{PEP 263: Source Code Encodings \label{section-encodings}}
Andrew M. Kuchling950725f2002-08-06 01:40:48 +0000285
286Python source files can now be declared as being in different
287character set encodings. Encodings are declared by including a
288specially formatted comment in the first or second line of the source
289file. For example, a UTF-8 file can be declared with:
290
291\begin{verbatim}
292#!/usr/bin/env python
293# -*- coding: UTF-8 -*-
294\end{verbatim}
295
296Without such an encoding declaration, the default encoding used is
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +00002977-bit ASCII. Executing or importing modules that contain string
298literals with 8-bit characters and have no encoding declaration will result
Andrew M. Kuchlingacddabc2003-02-18 00:43:24 +0000299in a \exception{DeprecationWarning} being signalled by Python 2.3; in
3002.4 this will be a syntax error.
Andrew M. Kuchling950725f2002-08-06 01:40:48 +0000301
Andrew M. Kuchlingacddabc2003-02-18 00:43:24 +0000302The encoding declaration only affects Unicode string literals, which
303will be converted to Unicode using the specified encoding. Note that
304Python identifiers are still restricted to ASCII characters, so you
305can't have variable names that use characters outside of the usual
306alphanumerics.
Andrew M. Kuchling950725f2002-08-06 01:40:48 +0000307
308\begin{seealso}
309
310\seepep{263}{Defining Python Source Code Encodings}{Written by
Andrew M. Kuchlingfcf6b3e2003-05-07 17:00:35 +0000311Marc-Andr\'e Lemburg and Martin von~L\"owis; implemented by Suzuki
312Hisao and Martin von~L\"owis.}
Andrew M. Kuchling950725f2002-08-06 01:40:48 +0000313
314\end{seealso}
315
316
317%======================================================================
Andrew M. Kuchling95be8bd2003-07-18 02:12:16 +0000318\section{PEP 273: Importing Modules from Zip Archives}
319
320The new \module{zipimport} module adds support for importing
321modules from a ZIP-format archive. You don't need to import the
322module explicitly; it will be automatically imported if a ZIP
323archive's filename is added to \code{sys.path}. For example:
324
325\begin{verbatim}
326amk@nyman:~/src/python$ unzip -l /tmp/example.zip
327Archive: /tmp/example.zip
328 Length Date Time Name
329 -------- ---- ---- ----
330 8467 11-26-02 22:30 jwzthreading.py
331 -------- -------
332 8467 1 file
333amk@nyman:~/src/python$ ./python
334Python 2.3 (#1, Aug 1 2003, 19:54:32)
335>>> import sys
336>>> sys.path.insert(0, '/tmp/example.zip') # Add .zip file to front of path
337>>> import jwzthreading
338>>> jwzthreading.__file__
339'/tmp/example.zip/jwzthreading.py'
340>>>
341\end{verbatim}
342
343An entry in \code{sys.path} can now be the filename of a ZIP archive.
344The ZIP archive can contain any kind of files, but only files named
345\file{*.py}, \file{*.pyc}, or \file{*.pyo} can be imported. If an
346archive only contains \file{*.py} files, Python will not attempt to
347modify the archive by adding the corresponding \file{*.pyc} file, meaning
348that if a ZIP archive doesn't contain \file{*.pyc} files, importing may be
349rather slow.
350
351A path within the archive can also be specified to only import from a
352subdirectory; for example, the path \file{/tmp/example.zip/lib/}
353would only import from the \file{lib/} subdirectory within the
354archive.
355
356\begin{seealso}
357
358\seepep{273}{Import Modules from Zip Archives}{Written by James C. Ahlstrom,
359who also provided an implementation.
360Python 2.3 follows the specification in \pep{273},
361but uses an implementation written by Just van~Rossum
362that uses the import hooks described in \pep{302}.
363See section~\ref{section-pep302} for a description of the new import hooks.
364}
365
366\end{seealso}
367
368%======================================================================
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000369\section{PEP 277: Unicode file name support for Windows NT}
Andrew M. Kuchling0f345562002-10-04 22:34:11 +0000370
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000371On Windows NT, 2000, and XP, the system stores file names as Unicode
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000372strings. Traditionally, Python has represented file names as byte
373strings, which is inadequate because it renders some file names
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000374inaccessible.
375
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000376Python now allows using arbitrary Unicode strings (within the
377limitations of the file system) for all functions that expect file
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000378names, most notably the \function{open()} built-in function. If a Unicode
379string is passed to \function{os.listdir()}, Python now returns a list
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000380of Unicode strings. A new function, \function{os.getcwdu()}, returns
381the current directory as a Unicode string.
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000382
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000383Byte strings still work as file names, and on Windows Python will
384transparently convert them to Unicode using the \code{mbcs} encoding.
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000385
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000386Other systems also allow Unicode strings as file names but convert
387them to byte strings before passing them to the system, which can
388cause a \exception{UnicodeError} to be raised. Applications can test
389whether arbitrary Unicode strings are supported as file names by
Andrew M. Kuchlingb9ba4e62003-02-03 15:16:15 +0000390checking \member{os.path.supports_unicode_filenames}, a Boolean value.
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000391
Andrew M. Kuchling563389f2003-03-02 02:31:58 +0000392Under MacOS, \function{os.listdir()} may now return Unicode filenames.
393
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000394\begin{seealso}
395
396\seepep{277}{Unicode file name support for Windows NT}{Written by Neil
Andrew M. Kuchlingfcf6b3e2003-05-07 17:00:35 +0000397Hodgson; implemented by Neil Hodgson, Martin von~L\"owis, and Mark
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000398Hammond.}
399
400\end{seealso}
Andrew M. Kuchling0f345562002-10-04 22:34:11 +0000401
402
403%======================================================================
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000404\section{PEP 278: Universal Newline Support}
405
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000406The three major operating systems used today are Microsoft Windows,
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000407Apple's Macintosh OS, and the various \UNIX\ derivatives. A minor
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +0000408irritation of cross-platform work
409is that these three platforms all use different characters
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000410to mark the ends of lines in text files. \UNIX\ uses the linefeed
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +0000411(ASCII character 10), MacOS uses the carriage return (ASCII
412character 13), and Windows uses a two-character sequence of a
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000413carriage return plus a newline.
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000414
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000415Python's file objects can now support end of line conventions other
416than the one followed by the platform on which Python is running.
Fred Drake5c4cf152002-11-13 14:59:06 +0000417Opening a file with the mode \code{'U'} or \code{'rU'} will open a file
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000418for reading in universal newline mode. All three line ending
Fred Drake5c4cf152002-11-13 14:59:06 +0000419conventions will be translated to a \character{\e n} in the strings
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000420returned by the various file methods such as \method{read()} and
Fred Drake5c4cf152002-11-13 14:59:06 +0000421\method{readline()}.
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000422
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000423Universal newline support is also used when importing modules and when
424executing a file with the \function{execfile()} function. This means
425that Python modules can be shared between all three operating systems
426without needing to convert the line-endings.
427
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +0000428This feature can be disabled when compiling Python by specifying
429the \longprogramopt{without-universal-newlines} switch when running Python's
Fred Drake5c4cf152002-11-13 14:59:06 +0000430\program{configure} script.
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000431
432\begin{seealso}
433
Fred Drake5c4cf152002-11-13 14:59:06 +0000434\seepep{278}{Universal Newline Support}{Written
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000435and implemented by Jack Jansen.}
436
437\end{seealso}
438
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +0000439
440%======================================================================
Andrew M. Kuchling433307b2003-05-13 14:23:54 +0000441\section{PEP 279: enumerate()\label{section-enumerate}}
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +0000442
443A new built-in function, \function{enumerate()}, will make
444certain loops a bit clearer. \code{enumerate(thing)}, where
445\var{thing} is either an iterator or a sequence, returns a iterator
Fred Drake3605ae52003-07-16 03:26:31 +0000446that will return \code{(0, \var{thing}[0])}, \code{(1,
447\var{thing}[1])}, \code{(2, \var{thing}[2])}, and so forth.
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000448
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +0000449A common idiom to change every element of a list looks like this:
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +0000450
451\begin{verbatim}
452for i in range(len(L)):
453 item = L[i]
454 # ... compute some result based on item ...
455 L[i] = result
456\end{verbatim}
457
458This can be rewritten using \function{enumerate()} as:
459
460\begin{verbatim}
461for i, item in enumerate(L):
462 # ... compute some result based on item ...
463 L[i] = result
464\end{verbatim}
465
466
467\begin{seealso}
468
Fred Drake5c4cf152002-11-13 14:59:06 +0000469\seepep{279}{The enumerate() built-in function}{Written
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000470and implemented by Raymond D. Hettinger.}
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +0000471
472\end{seealso}
473
474
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000475%======================================================================
Andrew M. Kuchling433307b2003-05-13 14:23:54 +0000476\section{PEP 282: The logging Package}
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000477
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000478A standard package for writing logs, \module{logging}, has been added
479to Python 2.3. It provides a powerful and flexible mechanism for
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000480generating logging output which can then be filtered and processed in
481various ways. A configuration file written in a standard format can
482be used to control the logging behavior of a program. Python
483includes handlers that will write log records to
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000484standard error or to a file or socket, send them to the system log, or
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000485even e-mail them to a particular address; of course, it's also
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000486possible to write your own handler classes.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000487
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000488The \class{Logger} class is the primary class.
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000489Most application code will deal with one or more \class{Logger}
490objects, each one used by a particular subsystem of the application.
491Each \class{Logger} is identified by a name, and names are organized
492into a hierarchy using \samp{.} as the component separator. For
493example, you might have \class{Logger} instances named \samp{server},
494\samp{server.auth} and \samp{server.network}. The latter two
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000495instances are below \samp{server} in the hierarchy. This means that
496if you turn up the verbosity for \samp{server} or direct \samp{server}
497messages to a different handler, the changes will also apply to
498records logged to \samp{server.auth} and \samp{server.network}.
499There's also a root \class{Logger} that's the parent of all other
500loggers.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000501
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000502For simple uses, the \module{logging} package contains some
503convenience functions that always use the root log:
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000504
505\begin{verbatim}
506import logging
507
508logging.debug('Debugging information')
509logging.info('Informational message')
Andrew M. Kuchling37495072003-02-19 13:46:18 +0000510logging.warning('Warning:config file %s not found', 'server.conf')
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000511logging.error('Error occurred')
512logging.critical('Critical error -- shutting down')
513\end{verbatim}
514
515This produces the following output:
516
517\begin{verbatim}
Andrew M. Kuchling37495072003-02-19 13:46:18 +0000518WARNING:root:Warning:config file server.conf not found
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000519ERROR:root:Error occurred
520CRITICAL:root:Critical error -- shutting down
521\end{verbatim}
522
523In the default configuration, informational and debugging messages are
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000524suppressed and the output is sent to standard error. You can enable
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000525the display of informational and debugging messages by calling the
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000526\method{setLevel()} method on the root logger.
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000527
Andrew M. Kuchling37495072003-02-19 13:46:18 +0000528Notice the \function{warning()} call's use of string formatting
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000529operators; all of the functions for logging messages take the
530arguments \code{(\var{msg}, \var{arg1}, \var{arg2}, ...)} and log the
531string resulting from \code{\var{msg} \% (\var{arg1}, \var{arg2},
532...)}.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000533
534There's also an \function{exception()} function that records the most
535recent traceback. Any of the other functions will also record the
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000536traceback if you specify a true value for the keyword argument
Fred Drakeaac8c582003-01-17 22:50:10 +0000537\var{exc_info}.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000538
539\begin{verbatim}
540def f():
541 try: 1/0
542 except: logging.exception('Problem recorded')
543
544f()
545\end{verbatim}
546
547This produces the following output:
548
549\begin{verbatim}
550ERROR:root:Problem recorded
551Traceback (most recent call last):
552 File "t.py", line 6, in f
553 1/0
554ZeroDivisionError: integer division or modulo by zero
555\end{verbatim}
556
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000557Slightly more advanced programs will use a logger other than the root
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000558logger. The \function{getLogger(\var{name})} function is used to get
559a particular log, creating it if it doesn't exist yet.
Andrew M. Kuchlingb1e4bf92002-12-03 13:35:17 +0000560\function{getLogger(None)} returns the root logger.
561
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000562
563\begin{verbatim}
564log = logging.getLogger('server')
565 ...
566log.info('Listening on port %i', port)
567 ...
568log.critical('Disk full')
569 ...
570\end{verbatim}
571
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000572Log records are usually propagated up the hierarchy, so a message
573logged to \samp{server.auth} is also seen by \samp{server} and
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +0000574\samp{root}, but a \class{Logger} can prevent this by setting its
Fred Drakeaac8c582003-01-17 22:50:10 +0000575\member{propagate} attribute to \constant{False}.
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000576
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000577There are more classes provided by the \module{logging} package that
578can be customized. When a \class{Logger} instance is told to log a
579message, it creates a \class{LogRecord} instance that is sent to any
580number of different \class{Handler} instances. Loggers and handlers
581can also have an attached list of filters, and each filter can cause
582the \class{LogRecord} to be ignored or can modify the record before
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +0000583passing it along. When they're finally output, \class{LogRecord}
584instances are converted to text by a \class{Formatter} class. All of
585these classes can be replaced by your own specially-written classes.
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000586
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000587With all of these features the \module{logging} package should provide
588enough flexibility for even the most complicated applications. This
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +0000589is only an incomplete overview of its features, so please see the
590\ulink{package's reference documentation}{../lib/module-logging.html}
591for all of the details. Reading \pep{282} will also be helpful.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000592
593
594\begin{seealso}
595
596\seepep{282}{A Logging System}{Written by Vinay Sajip and Trent Mick;
597implemented by Vinay Sajip.}
598
599\end{seealso}
600
601
602%======================================================================
Andrew M. Kuchling433307b2003-05-13 14:23:54 +0000603\section{PEP 285: A Boolean Type\label{section-bool}}
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000604
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000605A Boolean type was added to Python 2.3. Two new constants were added
606to the \module{__builtin__} module, \constant{True} and
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000607\constant{False}. (\constant{True} and
608\constant{False} constants were added to the built-ins
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000609in 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 +00006101 and 0 and aren't a different type.)
611
612The type object for this new type is named
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000613\class{bool}; the constructor for it takes any Python value and
614converts it to \constant{True} or \constant{False}.
615
616\begin{verbatim}
617>>> bool(1)
618True
619>>> bool(0)
620False
621>>> bool([])
622False
623>>> bool( (1,) )
624True
625\end{verbatim}
626
627Most of the standard library modules and built-in functions have been
628changed to return Booleans.
629
630\begin{verbatim}
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000631>>> obj = []
632>>> hasattr(obj, 'append')
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000633True
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000634>>> isinstance(obj, list)
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000635True
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000636>>> isinstance(obj, tuple)
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000637False
638\end{verbatim}
639
640Python's Booleans were added with the primary goal of making code
641clearer. For example, if you're reading a function and encounter the
Fred Drake5c4cf152002-11-13 14:59:06 +0000642statement \code{return 1}, you might wonder whether the \code{1}
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000643represents a Boolean truth value, an index, or a
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000644coefficient that multiplies some other quantity. If the statement is
645\code{return True}, however, the meaning of the return value is quite
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000646clear.
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000647
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000648Python's Booleans were \emph{not} added for the sake of strict
649type-checking. A very strict language such as Pascal would also
650prevent you performing arithmetic with Booleans, and would require
651that the expression in an \keyword{if} statement always evaluate to a
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000652Boolean result. Python is not this strict and never will be, as
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000653\pep{285} explicitly says. This means you can still use any
654expression in an \keyword{if} statement, even ones that evaluate to a
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000655list or tuple or some random object. The Boolean type is a
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000656subclass of the \class{int} class so that arithmetic using a Boolean
657still works.
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000658
659\begin{verbatim}
660>>> True + 1
6612
662>>> False + 1
6631
664>>> False * 75
6650
666>>> True * 75
66775
668\end{verbatim}
669
670To sum up \constant{True} and \constant{False} in a sentence: they're
671alternative ways to spell the integer values 1 and 0, with the single
672difference that \function{str()} and \function{repr()} return the
Fred Drake5c4cf152002-11-13 14:59:06 +0000673strings \code{'True'} and \code{'False'} instead of \code{'1'} and
674\code{'0'}.
Andrew M. Kuchling3a52ff62002-04-03 22:44:47 +0000675
676\begin{seealso}
677
678\seepep{285}{Adding a bool type}{Written and implemented by GvR.}
679
680\end{seealso}
681
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000682
Andrew M. Kuchling65b72822002-09-03 00:53:21 +0000683%======================================================================
684\section{PEP 293: Codec Error Handling Callbacks}
685
Martin v. Löwis20eae692002-10-07 19:01:07 +0000686When encoding a Unicode string into a byte string, unencodable
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000687characters may be encountered. So far, Python has allowed specifying
688the error processing as either ``strict'' (raising
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000689\exception{UnicodeError}), ``ignore'' (skipping the character), or
690``replace'' (using a question mark in the output string), with
691``strict'' being the default behavior. It may be desirable to specify
692alternative processing of such errors, such as inserting an XML
693character reference or HTML entity reference into the converted
694string.
Martin v. Löwis20eae692002-10-07 19:01:07 +0000695
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +0000696Python now has a flexible framework to add different processing
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000697strategies. New error handlers can be added with
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000698\function{codecs.register_error}, and codecs then can access the error
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000699handler with \function{codecs.lookup_error}. An equivalent C API has
700been added for codecs written in C. The error handler gets the
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000701necessary state information such as the string being converted, the
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000702position in the string where the error was detected, and the target
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000703encoding. The handler can then either raise an exception or return a
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000704replacement string.
Martin v. Löwis20eae692002-10-07 19:01:07 +0000705
706Two additional error handlers have been implemented using this
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000707framework: ``backslashreplace'' uses Python backslash quoting to
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +0000708represent unencodable characters and ``xmlcharrefreplace'' emits
Martin v. Löwis20eae692002-10-07 19:01:07 +0000709XML character references.
Andrew M. Kuchling65b72822002-09-03 00:53:21 +0000710
711\begin{seealso}
712
Fred Drake5c4cf152002-11-13 14:59:06 +0000713\seepep{293}{Codec Error Handling Callbacks}{Written and implemented by
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000714Walter D\"orwald.}
Andrew M. Kuchling65b72822002-09-03 00:53:21 +0000715
716\end{seealso}
717
718
719%======================================================================
Fred Drake693aea22003-02-07 14:52:18 +0000720\section{PEP 301: Package Index and Metadata for
721Distutils\label{section-pep301}}
Andrew M. Kuchling87cebbf2003-01-03 16:24:28 +0000722
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000723Support for the long-requested Python catalog makes its first
724appearance in 2.3.
725
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000726The heart of the catalog is the new Distutils \command{register} command.
Fred Drake693aea22003-02-07 14:52:18 +0000727Running \code{python setup.py register} will collect the metadata
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000728describing a package, such as its name, version, maintainer,
Andrew M. Kuchlingc61402b2003-02-26 19:00:52 +0000729description, \&c., and send it to a central catalog server. The
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000730resulting catalog is available from \url{http://www.python.org/pypi}.
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000731
732To make the catalog a bit more useful, a new optional
Fred Drake693aea22003-02-07 14:52:18 +0000733\var{classifiers} keyword argument has been added to the Distutils
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000734\function{setup()} function. A list of
Fred Drake693aea22003-02-07 14:52:18 +0000735\ulink{Trove}{http://catb.org/\textasciitilde esr/trove/}-style
736strings can be supplied to help classify the software.
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000737
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +0000738Here's an example \file{setup.py} with classifiers, written to be compatible
739with older versions of the Distutils:
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000740
741\begin{verbatim}
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +0000742from distutils import core
Fred Drake693aea22003-02-07 14:52:18 +0000743kw = {'name': "Quixote",
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +0000744 'version': "0.5.1",
745 'description': "A highly Pythonic Web application framework",
Fred Drake693aea22003-02-07 14:52:18 +0000746 # ...
747 }
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +0000748
Andrew M. Kuchlinga6b1c752003-04-09 17:26:38 +0000749if (hasattr(core, 'setup_keywords') and
750 'classifiers' in core.setup_keywords):
Fred Drake693aea22003-02-07 14:52:18 +0000751 kw['classifiers'] = \
752 ['Topic :: Internet :: WWW/HTTP :: Dynamic Content',
753 'Environment :: No Input/Output (Daemon)',
754 'Intended Audience :: Developers'],
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +0000755
Fred Drake693aea22003-02-07 14:52:18 +0000756core.setup(**kw)
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000757\end{verbatim}
758
759The full list of classifiers can be obtained by running
Andrew M. Kuchling0ceb9b12003-07-21 12:49:46 +0000760\verb|python setup.py register --list-classifiers|.
Andrew M. Kuchling87cebbf2003-01-03 16:24:28 +0000761
762\begin{seealso}
763
Fred Drake693aea22003-02-07 14:52:18 +0000764\seepep{301}{Package Index and Metadata for Distutils}{Written and
765implemented by Richard Jones.}
Andrew M. Kuchling87cebbf2003-01-03 16:24:28 +0000766
767\end{seealso}
768
769
770%======================================================================
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000771\section{PEP 302: New Import Hooks \label{section-pep302}}
772
773While it's been possible to write custom import hooks ever since the
774\module{ihooks} module was introduced in Python 1.3, no one has ever
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000775been really happy with it because writing new import hooks is
776difficult and messy. There have been various proposed alternatives
777such as the \module{imputil} and \module{iu} modules, but none of them
778has ever gained much acceptance, and none of them were easily usable
779from \C{} code.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000780
781\pep{302} borrows ideas from its predecessors, especially from
782Gordon McMillan's \module{iu} module. Three new items
783are added to the \module{sys} module:
784
785\begin{itemize}
Andrew M. Kuchlingd5ac8d02003-01-02 21:33:15 +0000786 \item \code{sys.path_hooks} is a list of callable objects; most
Fred Drakeaac8c582003-01-17 22:50:10 +0000787 often they'll be classes. Each callable takes a string containing a
788 path and either returns an importer object that will handle imports
789 from this path or raises an \exception{ImportError} exception if it
790 can't handle this path.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000791
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000792 \item \code{sys.path_importer_cache} caches importer objects for
Fred Drakeaac8c582003-01-17 22:50:10 +0000793 each path, so \code{sys.path_hooks} will only need to be traversed
794 once for each path.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000795
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000796 \item \code{sys.meta_path} is a list of importer objects that will
797 be traversed before \code{sys.path} is checked. This list is
798 initially empty, but user code can add objects to it. Additional
799 built-in and frozen modules can be imported by an object added to
800 this list.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000801
802\end{itemize}
803
804Importer objects must have a single method,
805\method{find_module(\var{fullname}, \var{path}=None)}. \var{fullname}
806will be a module or package name, e.g. \samp{string} or
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000807\samp{distutils.core}. \method{find_module()} must return a loader object
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000808that has a single method, \method{load_module(\var{fullname})}, that
809creates and returns the corresponding module object.
810
811Pseudo-code for Python's new import logic, therefore, looks something
812like this (simplified a bit; see \pep{302} for the full details):
813
814\begin{verbatim}
815for mp in sys.meta_path:
816 loader = mp(fullname)
817 if loader is not None:
Andrew M. Kuchlingd5ac8d02003-01-02 21:33:15 +0000818 <module> = loader.load_module(fullname)
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000819
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000820for path in sys.path:
821 for hook in sys.path_hooks:
Andrew M. Kuchlingd5ac8d02003-01-02 21:33:15 +0000822 try:
823 importer = hook(path)
824 except ImportError:
825 # ImportError, so try the other path hooks
826 pass
827 else:
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000828 loader = importer.find_module(fullname)
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000829 <module> = loader.load_module(fullname)
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000830
831# Not found!
832raise ImportError
833\end{verbatim}
834
835\begin{seealso}
836
837\seepep{302}{New Import Hooks}{Written by Just van~Rossum and Paul Moore.
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +0000838Implemented by Just van~Rossum.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000839}
840
841\end{seealso}
842
843
844%======================================================================
Andrew M. Kuchlinga978e102003-03-21 18:10:12 +0000845\section{PEP 305: Comma-separated Files \label{section-pep305}}
846
847Comma-separated files are a format frequently used for exporting data
848from databases and spreadsheets. Python 2.3 adds a parser for
849comma-separated files.
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000850
851Comma-separated format is deceptively simple at first glance:
Andrew M. Kuchlinga978e102003-03-21 18:10:12 +0000852
853\begin{verbatim}
854Costs,150,200,3.95
855\end{verbatim}
856
857Read a line and call \code{line.split(',')}: what could be simpler?
858But toss in string data that can contain commas, and things get more
859complicated:
860
861\begin{verbatim}
862"Costs",150,200,3.95,"Includes taxes, shipping, and sundry items"
863\end{verbatim}
864
865A big ugly regular expression can parse this, but using the new
866\module{csv} package is much simpler:
867
868\begin{verbatim}
Andrew M. Kuchlingba887bb2003-04-13 21:13:02 +0000869import csv
Andrew M. Kuchlinga978e102003-03-21 18:10:12 +0000870
871input = open('datafile', 'rb')
872reader = csv.reader(input)
873for line in reader:
874 print line
875\end{verbatim}
876
877The \function{reader} function takes a number of different options.
878The field separator isn't limited to the comma and can be changed to
879any character, and so can the quoting and line-ending characters.
880
881Different dialects of comma-separated files can be defined and
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000882registered; currently there are two dialects, both used by Microsoft Excel.
Andrew M. Kuchlinga978e102003-03-21 18:10:12 +0000883A separate \class{csv.writer} class will generate comma-separated files
884from a succession of tuples or lists, quoting strings that contain the
885delimiter.
886
887\begin{seealso}
888
889\seepep{305}{CSV File API}{Written and implemented
890by Kevin Altis, Dave Cole, Andrew McNamara, Skip Montanaro, Cliff Wells.
891}
892
893\end{seealso}
894
895%======================================================================
Andrew M. Kuchlinga092ba12003-03-21 18:32:43 +0000896\section{PEP 307: Pickle Enhancements \label{section-pep305}}
897
898The \module{pickle} and \module{cPickle} modules received some
899attention during the 2.3 development cycle. In 2.2, new-style classes
Andrew M. Kuchlinga6b1c752003-04-09 17:26:38 +0000900could be pickled without difficulty, but they weren't pickled very
Andrew M. Kuchlinga092ba12003-03-21 18:32:43 +0000901compactly; \pep{307} quotes a trivial example where a new-style class
902results in a pickled string three times longer than that for a classic
903class.
904
905The solution was to invent a new pickle protocol. The
906\function{pickle.dumps()} function has supported a text-or-binary flag
907for a long time. In 2.3, this flag is redefined from a Boolean to an
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000908integer: 0 is the old text-mode pickle format, 1 is the old binary
909format, and now 2 is a new 2.3-specific format. A new constant,
Andrew M. Kuchlinga092ba12003-03-21 18:32:43 +0000910\constant{pickle.HIGHEST_PROTOCOL}, can be used to select the fanciest
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000911protocol available.
Andrew M. Kuchlinga092ba12003-03-21 18:32:43 +0000912
913Unpickling is no longer considered a safe operation. 2.2's
914\module{pickle} provided hooks for trying to prevent unsafe classes
915from being unpickled (specifically, a
916\member{__safe_for_unpickling__} attribute), but none of this code
917was ever audited and therefore it's all been ripped out in 2.3. You
918should not unpickle untrusted data in any version of Python.
919
920To reduce the pickling overhead for new-style classes, a new interface
921for customizing pickling was added using three special methods:
922\method{__getstate__}, \method{__setstate__}, and
923\method{__getnewargs__}. Consult \pep{307} for the full semantics
924of these methods.
925
926As a way to compress pickles yet further, it's now possible to use
927integer codes instead of long strings to identify pickled classes.
928The Python Software Foundation will maintain a list of standardized
929codes; there's also a range of codes for private use. Currently no
930codes have been specified.
931
932\begin{seealso}
933
934\seepep{307}{Extensions to the pickle protocol}{Written and implemented
935by Guido van Rossum and Tim Peters.}
936
937\end{seealso}
938
939%======================================================================
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000940\section{Extended Slices\label{section-slices}}
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000941
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000942Ever since Python 1.4, the slicing syntax has supported an optional
943third ``step'' or ``stride'' argument. For example, these are all
944legal Python syntax: \code{L[1:10:2]}, \code{L[:-1:1]},
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000945\code{L[::-1]}. This was added to Python at the request of
946the developers of Numerical Python, which uses the third argument
947extensively. However, Python's built-in list, tuple, and string
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000948sequence types have never supported this feature, raising a
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000949\exception{TypeError} if you tried it. Michael Hudson contributed a
950patch to fix this shortcoming.
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000951
952For example, you can now easily extract the elements of a list that
953have even indexes:
Fred Drakedf872a22002-07-03 12:02:01 +0000954
955\begin{verbatim}
956>>> L = range(10)
957>>> L[::2]
958[0, 2, 4, 6, 8]
959\end{verbatim}
960
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000961Negative values also work to make a copy of the same list in reverse
962order:
Fred Drakedf872a22002-07-03 12:02:01 +0000963
964\begin{verbatim}
965>>> L[::-1]
966[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
967\end{verbatim}
Andrew M. Kuchling3a52ff62002-04-03 22:44:47 +0000968
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000969This also works for tuples, arrays, and strings:
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000970
971\begin{verbatim}
972>>> s='abcd'
973>>> s[::2]
974'ac'
975>>> s[::-1]
976'dcba'
977\end{verbatim}
978
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000979If you have a mutable sequence such as a list or an array you can
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000980assign to or delete an extended slice, but there are some differences
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000981between assignment to extended and regular slices. Assignment to a
982regular slice can be used to change the length of the sequence:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000983
984\begin{verbatim}
985>>> a = range(3)
986>>> a
987[0, 1, 2]
988>>> a[1:3] = [4, 5, 6]
989>>> a
990[0, 4, 5, 6]
991\end{verbatim}
992
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000993Extended slices aren't this flexible. When assigning to an extended
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +0000994slice, the list on the right hand side of the statement must contain
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000995the same number of items as the slice it is replacing:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000996
997\begin{verbatim}
998>>> a = range(4)
999>>> a
1000[0, 1, 2, 3]
1001>>> a[::2]
1002[0, 2]
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001003>>> a[::2] = [0, -1]
Michael W. Hudson4da01ed2002-07-19 15:48:56 +00001004>>> a
1005[0, 1, -1, 3]
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001006>>> a[::2] = [0,1,2]
Michael W. Hudson4da01ed2002-07-19 15:48:56 +00001007Traceback (most recent call last):
1008 File "<stdin>", line 1, in ?
Raymond Hettingeree1bded2003-01-17 16:20:23 +00001009ValueError: attempt to assign sequence of size 3 to extended slice of size 2
Michael W. Hudson4da01ed2002-07-19 15:48:56 +00001010\end{verbatim}
1011
1012Deletion is more straightforward:
1013
1014\begin{verbatim}
1015>>> a = range(4)
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001016>>> a
1017[0, 1, 2, 3]
Michael W. Hudson4da01ed2002-07-19 15:48:56 +00001018>>> a[::2]
1019[0, 2]
1020>>> del a[::2]
1021>>> a
1022[1, 3]
1023\end{verbatim}
1024
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001025One can also now pass slice objects to the
1026\method{__getitem__} methods of the built-in sequences:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +00001027
1028\begin{verbatim}
1029>>> range(10).__getitem__(slice(0, 5, 2))
1030[0, 2, 4]
1031\end{verbatim}
1032
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001033Or use slice objects directly in subscripts:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +00001034
1035\begin{verbatim}
1036>>> range(10)[slice(0, 5, 2)]
1037[0, 2, 4]
1038\end{verbatim}
1039
Andrew M. Kuchlingb6f79592002-11-29 19:43:45 +00001040To simplify implementing sequences that support extended slicing,
1041slice objects now have a method \method{indices(\var{length})} which,
Fred Drakeaac8c582003-01-17 22:50:10 +00001042given the length of a sequence, returns a \code{(\var{start},
1043\var{stop}, \var{step})} tuple that can be passed directly to
1044\function{range()}.
Andrew M. Kuchlingb6f79592002-11-29 19:43:45 +00001045\method{indices()} handles omitted and out-of-bounds indices in a
1046manner consistent with regular slices (and this innocuous phrase hides
1047a welter of confusing details!). The method is intended to be used
1048like this:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +00001049
1050\begin{verbatim}
1051class FakeSeq:
1052 ...
1053 def calc_item(self, i):
1054 ...
1055 def __getitem__(self, item):
1056 if isinstance(item, slice):
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001057 indices = item.indices(len(self))
Andrew M. Kuchling68a32942003-07-30 11:55:06 +00001058 return FakeSeq([self.calc_item(i) for i in range(*indices)])
Fred Drake5c4cf152002-11-13 14:59:06 +00001059 else:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +00001060 return self.calc_item(i)
1061\end{verbatim}
1062
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001063From this example you can also see that the built-in \class{slice}
Andrew M. Kuchling90e9a792002-08-15 00:40:21 +00001064object is now the type object for the slice type, and is no longer a
1065function. This is consistent with Python 2.2, where \class{int},
1066\class{str}, etc., underwent the same change.
1067
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001068
Andrew M. Kuchling3a52ff62002-04-03 22:44:47 +00001069%======================================================================
Fred Drakedf872a22002-07-03 12:02:01 +00001070\section{Other Language Changes}
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001071
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001072Here are all of the changes that Python 2.3 makes to the core Python
1073language.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001074
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001075\begin{itemize}
1076\item The \keyword{yield} statement is now always a keyword, as
1077described in section~\ref{section-generators} of this document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001078
Fred Drake5c4cf152002-11-13 14:59:06 +00001079\item A new built-in function \function{enumerate()}
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001080was added, as described in section~\ref{section-enumerate} of this
1081document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001082
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001083\item Two new constants, \constant{True} and \constant{False} were
1084added along with the built-in \class{bool} type, as described in
1085section~\ref{section-bool} of this document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001086
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00001087\item The \function{int()} type constructor will now return a long
1088integer instead of raising an \exception{OverflowError} when a string
1089or floating-point number is too large to fit into an integer. This
1090can lead to the paradoxical result that
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001091\code{isinstance(int(\var{expression}), int)} is false, but that seems
1092unlikely to cause problems in practice.
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00001093
Fred Drake5c4cf152002-11-13 14:59:06 +00001094\item Built-in types now support the extended slicing syntax,
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001095as described in section~\ref{section-slices} of this document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001096
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001097\item A new built-in function, \function{sum(\var{iterable}, \var{start}=0)},
1098adds up the numeric items in the iterable object and returns their sum.
1099\function{sum()} only accepts numbers, meaning that you can't use it
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +00001100to concatenate a bunch of strings. (Contributed by Alex
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001101Martelli.)
1102
Andrew M. Kuchlingfcf6b3e2003-05-07 17:00:35 +00001103\item \code{list.insert(\var{pos}, \var{value})} used to
1104insert \var{value} at the front of the list when \var{pos} was
1105negative. The behaviour has now been changed to be consistent with
1106slice indexing, so when \var{pos} is -1 the value will be inserted
1107before the last element, and so forth.
1108
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +00001109\item \code{list.index(\var{value})}, which searches for \var{value}
1110within the list and returns its index, now takes optional
1111\var{start} and \var{stop} arguments to limit the search to
1112only part of the list.
1113
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +00001114\item Dictionaries have a new method, \method{pop(\var{key}\optional{,
1115\var{default}})}, that returns the value corresponding to \var{key}
1116and removes that key/value pair from the dictionary. If the requested
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001117key isn't present in the dictionary, \var{default} is returned if it's
1118specified and \exception{KeyError} raised if it isn't.
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001119
1120\begin{verbatim}
1121>>> d = {1:2}
1122>>> d
1123{1: 2}
1124>>> d.pop(4)
1125Traceback (most recent call last):
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +00001126 File "stdin", line 1, in ?
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001127KeyError: 4
1128>>> d.pop(1)
11292
1130>>> d.pop(1)
1131Traceback (most recent call last):
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +00001132 File "stdin", line 1, in ?
Raymond Hettingeree1bded2003-01-17 16:20:23 +00001133KeyError: 'pop(): dictionary is empty'
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001134>>> d
1135{}
1136>>>
1137\end{verbatim}
1138
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001139There's also a new class method,
1140\method{dict.fromkeys(\var{iterable}, \var{value})}, that
1141creates a dictionary with keys taken from the supplied iterator
1142\var{iterable} and all values set to \var{value}, defaulting to
1143\code{None}.
1144
1145(Patches contributed by Raymond Hettinger.)
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001146
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001147Also, the \function{dict()} constructor now accepts keyword arguments to
Raymond Hettinger45bda572002-12-14 20:20:45 +00001148simplify creating small dictionaries:
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001149
1150\begin{verbatim}
1151>>> dict(red=1, blue=2, green=3, black=4)
1152{'blue': 2, 'black': 4, 'green': 3, 'red': 1}
1153\end{verbatim}
1154
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +00001155(Contributed by Just van~Rossum.)
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001156
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +00001157\item The \keyword{assert} statement no longer checks the \code{__debug__}
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001158flag, so you can no longer disable assertions by assigning to \code{__debug__}.
Fred Drake5c4cf152002-11-13 14:59:06 +00001159Running Python with the \programopt{-O} switch will still generate
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001160code that doesn't execute any assertions.
1161
1162\item Most type objects are now callable, so you can use them
1163to create new objects such as functions, classes, and modules. (This
1164means that the \module{new} module can be deprecated in a future
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001165Python version, because you can now use the type objects available in
1166the \module{types} module.)
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001167% XXX should new.py use PendingDeprecationWarning?
1168For example, you can create a new module object with the following code:
1169
1170\begin{verbatim}
1171>>> import types
1172>>> m = types.ModuleType('abc','docstring')
1173>>> m
1174<module 'abc' (built-in)>
1175>>> m.__doc__
1176'docstring'
1177\end{verbatim}
1178
Fred Drake5c4cf152002-11-13 14:59:06 +00001179\item
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001180A new warning, \exception{PendingDeprecationWarning} was added to
1181indicate features which are in the process of being
1182deprecated. The warning will \emph{not} be printed by default. To
1183check for use of features that will be deprecated in the future,
1184supply \programopt{-Walways::PendingDeprecationWarning::} on the
1185command line or use \function{warnings.filterwarnings()}.
1186
Andrew M. Kuchlingc1dd1742003-01-13 13:59:22 +00001187\item The process of deprecating string-based exceptions, as
1188in \code{raise "Error occurred"}, has begun. Raising a string will
1189now trigger \exception{PendingDeprecationWarning}.
1190
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001191\item Using \code{None} as a variable name will now result in a
1192\exception{SyntaxWarning} warning. In a future version of Python,
1193\code{None} may finally become a keyword.
1194
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001195\item The \method{xreadlines()} method of file objects, introduced in
1196Python 2.1, is no longer necessary because files now behave as their
1197own iterator. \method{xreadlines()} was originally introduced as a
1198faster way to loop over all the lines in a file, but now you can
1199simply write \code{for line in file_obj}. File objects also have a
1200new read-only \member{encoding} attribute that gives the encoding used
1201by the file; Unicode strings written to the file will be automatically
1202converted to bytes using the given encoding.
1203
Andrew M. Kuchlingb60ea3f2002-11-15 14:37:10 +00001204\item The method resolution order used by new-style classes has
1205changed, though you'll only notice the difference if you have a really
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +00001206complicated inheritance hierarchy. Classic classes are unaffected by
1207this change. Python 2.2 originally used a topological sort of a
Andrew M. Kuchlingb60ea3f2002-11-15 14:37:10 +00001208class's ancestors, but 2.3 now uses the C3 algorithm as described in
Andrew M. Kuchling6f429c32002-11-19 13:09:00 +00001209the paper \ulink{``A Monotonic Superclass Linearization for
1210Dylan''}{http://www.webcom.com/haahr/dylan/linearization-oopsla96.html}.
Andrew M. Kuchlingc1dd1742003-01-13 13:59:22 +00001211To understand the motivation for this change,
1212read Michele Simionato's article
Fred Drake693aea22003-02-07 14:52:18 +00001213\ulink{``Python 2.3 Method Resolution Order''}
Andrew M. Kuchlingb8a39052003-02-07 20:22:33 +00001214 {http://www.python.org/2.3/mro.html}, or
Andrew M. Kuchlingc1dd1742003-01-13 13:59:22 +00001215read the thread on python-dev starting with the message at
Andrew M. Kuchlingb60ea3f2002-11-15 14:37:10 +00001216\url{http://mail.python.org/pipermail/python-dev/2002-October/029035.html}.
1217Samuele Pedroni first pointed out the problem and also implemented the
1218fix by coding the C3 algorithm.
1219
Andrew M. Kuchlingdcfd8252002-09-13 22:21:42 +00001220\item Python runs multithreaded programs by switching between threads
1221after executing N bytecodes. The default value for N has been
1222increased from 10 to 100 bytecodes, speeding up single-threaded
1223applications by reducing the switching overhead. Some multithreaded
1224applications may suffer slower response time, but that's easily fixed
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001225by setting the limit back to a lower number using
Andrew M. Kuchlingdcfd8252002-09-13 22:21:42 +00001226\function{sys.setcheckinterval(\var{N})}.
Andrew M. Kuchlingc760c6c2003-07-16 20:12:33 +00001227The limit can be retrieved with the new
1228\function{sys.getcheckinterval()} function.
Andrew M. Kuchlingdcfd8252002-09-13 22:21:42 +00001229
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001230\item One minor but far-reaching change is that the names of extension
1231types defined by the modules included with Python now contain the
Fred Drake5c4cf152002-11-13 14:59:06 +00001232module and a \character{.} in front of the type name. For example, in
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001233Python 2.2, if you created a socket and printed its
1234\member{__class__}, you'd get this output:
1235
1236\begin{verbatim}
1237>>> s = socket.socket()
1238>>> s.__class__
1239<type 'socket'>
1240\end{verbatim}
1241
1242In 2.3, you get this:
1243\begin{verbatim}
1244>>> s.__class__
1245<type '_socket.socket'>
1246\end{verbatim}
1247
Michael W. Hudson96bc3b42002-11-26 14:48:23 +00001248\item One of the noted incompatibilities between old- and new-style
1249 classes has been removed: you can now assign to the
1250 \member{__name__} and \member{__bases__} attributes of new-style
1251 classes. There are some restrictions on what can be assigned to
1252 \member{__bases__} along the lines of those relating to assigning to
1253 an instance's \member{__class__} attribute.
1254
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001255\end{itemize}
1256
1257
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001258%======================================================================
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001259\subsection{String Changes}
1260
1261\begin{itemize}
1262
Fred Drakeaac8c582003-01-17 22:50:10 +00001263\item The \keyword{in} operator now works differently for strings.
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001264Previously, when evaluating \code{\var{X} in \var{Y}} where \var{X}
1265and \var{Y} are strings, \var{X} could only be a single character.
1266That's now changed; \var{X} can be a string of any length, and
1267\code{\var{X} in \var{Y}} will return \constant{True} if \var{X} is a
1268substring of \var{Y}. If \var{X} is the empty string, the result is
1269always \constant{True}.
1270
1271\begin{verbatim}
1272>>> 'ab' in 'abcd'
1273True
1274>>> 'ad' in 'abcd'
1275False
1276>>> '' in 'abcd'
1277True
1278\end{verbatim}
1279
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001280Note that this doesn't tell you where the substring starts; if you
Andrew M. Kuchlingaa9b39f2003-07-16 20:37:26 +00001281need that information, use the \method{find()} string method.
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001282
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001283\item The \method{strip()}, \method{lstrip()}, and \method{rstrip()}
1284string methods now have an optional argument for specifying the
1285characters to strip. The default is still to remove all whitespace
1286characters:
1287
1288\begin{verbatim}
1289>>> ' abc '.strip()
1290'abc'
1291>>> '><><abc<><><>'.strip('<>')
1292'abc'
1293>>> '><><abc<><><>\n'.strip('<>')
1294'abc<><><>\n'
1295>>> u'\u4000\u4001abc\u4000'.strip(u'\u4000')
1296u'\u4001abc'
1297>>>
1298\end{verbatim}
1299
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001300(Suggested by Simon Brunning and implemented by Walter D\"orwald.)
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00001301
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001302\item The \method{startswith()} and \method{endswith()}
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001303string methods now accept negative numbers for the \var{start} and \var{end}
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001304parameters.
1305
1306\item Another new string method is \method{zfill()}, originally a
1307function in the \module{string} module. \method{zfill()} pads a
1308numeric string with zeros on the left until it's the specified width.
1309Note that the \code{\%} operator is still more flexible and powerful
1310than \method{zfill()}.
1311
1312\begin{verbatim}
1313>>> '45'.zfill(4)
1314'0045'
1315>>> '12345'.zfill(4)
1316'12345'
1317>>> 'goofy'.zfill(6)
1318'0goofy'
1319\end{verbatim}
1320
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00001321(Contributed by Walter D\"orwald.)
1322
Fred Drake5c4cf152002-11-13 14:59:06 +00001323\item A new type object, \class{basestring}, has been added.
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001324 Both 8-bit strings and Unicode strings inherit from this type, so
1325 \code{isinstance(obj, basestring)} will return \constant{True} for
1326 either kind of string. It's a completely abstract type, so you
1327 can't create \class{basestring} instances.
1328
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001329\item Interned strings are no longer immortal and will now be
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001330garbage-collected in the usual way when the only reference to them is
1331from the internal dictionary of interned strings. (Implemented by
1332Oren Tirosh.)
1333
1334\end{itemize}
1335
1336
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001337%======================================================================
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001338\subsection{Optimizations}
1339
1340\begin{itemize}
1341
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001342\item The creation of new-style class instances has been made much
1343faster; they're now faster than classic classes!
1344
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001345\item The \method{sort()} method of list objects has been extensively
1346rewritten by Tim Peters, and the implementation is significantly
1347faster.
1348
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001349\item Multiplication of large long integers is now much faster thanks
1350to an implementation of Karatsuba multiplication, an algorithm that
1351scales better than the O(n*n) required for the grade-school
1352multiplication algorithm. (Original patch by Christopher A. Craig,
1353and significantly reworked by Tim Peters.)
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001354
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001355\item The \code{SET_LINENO} opcode is now gone. This may provide a
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001356small speed increase, depending on your compiler's idiosyncrasies.
1357See section~\ref{section-other} for a longer explanation.
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001358(Removed by Michael Hudson.)
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001359
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001360\item \function{xrange()} objects now have their own iterator, making
1361\code{for i in xrange(n)} slightly faster than
1362\code{for i in range(n)}. (Patch by Raymond Hettinger.)
1363
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001364\item A number of small rearrangements have been made in various
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001365hotspots to improve performance, such as inlining a function or removing
1366some code. (Implemented mostly by GvR, but lots of people have
1367contributed single changes.)
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001368
1369\end{itemize}
Neal Norwitzd68f5172002-05-29 15:54:55 +00001370
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001371The net result of the 2.3 optimizations is that Python 2.3 runs the
1372pystone benchmark around 25\% faster than Python 2.2.
1373
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001374
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001375%======================================================================
Andrew M. Kuchlingef893fe2003-01-06 20:04:17 +00001376\section{New, Improved, and Deprecated Modules}
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00001377
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001378As usual, Python's standard library received a number of enhancements and
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001379bug fixes. Here's a partial list of the most notable changes, sorted
1380alphabetically by module name. Consult the
1381\file{Misc/NEWS} file in the source tree for a more
1382complete list of changes, or look through the CVS logs for all the
1383details.
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00001384
1385\begin{itemize}
1386
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001387\item The \module{array} module now supports arrays of Unicode
Fred Drake5c4cf152002-11-13 14:59:06 +00001388characters using the \character{u} format character. Arrays also now
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001389support using the \code{+=} assignment operator to add another array's
1390contents, and the \code{*=} assignment operator to repeat an array.
1391(Contributed by Jason Orendorff.)
1392
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001393\item The \module{bsddb} module has been replaced by version 4.1.1
Andrew M. Kuchling669249e2002-11-19 13:05:33 +00001394of the \ulink{PyBSDDB}{http://pybsddb.sourceforge.net} package,
1395providing a more complete interface to the transactional features of
1396the BerkeleyDB library.
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001397
Andrew M. Kuchling669249e2002-11-19 13:05:33 +00001398The old version of the module has been renamed to
1399\module{bsddb185} and is no longer built automatically; you'll
1400have to edit \file{Modules/Setup} to enable it. Note that the new
1401\module{bsddb} package is intended to be compatible with the
1402old module, so be sure to file bugs if you discover any
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001403incompatibilities. When upgrading to Python 2.3, if the new interpreter is compiled
1404with a new version of
Skip Montanaro959c7722003-03-07 15:45:15 +00001405the underlying BerkeleyDB library, you will almost certainly have to
1406convert your database files to the new version. You can do this
1407fairly easily with the new scripts \file{db2pickle.py} and
1408\file{pickle2db.py} which you will find in the distribution's
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001409\file{Tools/scripts} directory. If you've already been using the PyBSDDB
Andrew M. Kuchlinge36b6902003-04-19 15:38:47 +00001410package and importing it as \module{bsddb3}, you will have to change your
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001411\code{import} statements to import it as \module{bsddb}.
Andrew M. Kuchlinge36b6902003-04-19 15:38:47 +00001412
1413\item The new \module{bz2} module is an interface to the bz2 data
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001414compression library. bz2-compressed data is usually smaller than
1415corresponding \module{zlib}-compressed data. (Contributed by Gustavo Niemeyer.)
Andrew M. Kuchling669249e2002-11-19 13:05:33 +00001416
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001417\item A set of standard date/type types has been added in the new \module{datetime}
1418module. See the following section for more details.
1419
Fred Drake5c4cf152002-11-13 14:59:06 +00001420\item The Distutils \class{Extension} class now supports
1421an extra constructor argument named \var{depends} for listing
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001422additional source files that an extension depends on. This lets
1423Distutils recompile the module if any of the dependency files are
Fred Drake5c4cf152002-11-13 14:59:06 +00001424modified. For example, if \file{sampmodule.c} includes the header
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001425file \file{sample.h}, you would create the \class{Extension} object like
1426this:
1427
1428\begin{verbatim}
1429ext = Extension("samp",
1430 sources=["sampmodule.c"],
1431 depends=["sample.h"])
1432\end{verbatim}
1433
1434Modifying \file{sample.h} would then cause the module to be recompiled.
1435(Contributed by Jeremy Hylton.)
1436
Andrew M. Kuchlingdc3f7e12002-11-04 20:05:10 +00001437\item Other minor changes to Distutils:
1438it now checks for the \envvar{CC}, \envvar{CFLAGS}, \envvar{CPP},
1439\envvar{LDFLAGS}, and \envvar{CPPFLAGS} environment variables, using
1440them to override the settings in Python's configuration (contributed
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +00001441by Robert Weber).
Andrew M. Kuchlingdc3f7e12002-11-04 20:05:10 +00001442
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001443\item Previously the \module{doctest} module would only search the
1444docstrings of public methods and functions for test cases, but it now
1445also examines private ones as well. The \function{DocTestSuite(}
1446function creates a \class{unittest.TestSuite} object from a set of
1447\module{doctest} tests.
1448
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001449\item The new \function{gc.get_referents(\var{object})} function returns a
1450list of all the objects referenced by \var{object}.
1451
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001452\item The \module{getopt} module gained a new function,
1453\function{gnu_getopt()}, that supports the same arguments as the existing
Fred Drake5c4cf152002-11-13 14:59:06 +00001454\function{getopt()} function but uses GNU-style scanning mode.
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001455The existing \function{getopt()} stops processing options as soon as a
1456non-option argument is encountered, but in GNU-style mode processing
1457continues, meaning that options and arguments can be mixed. For
1458example:
1459
1460\begin{verbatim}
1461>>> getopt.getopt(['-f', 'filename', 'output', '-v'], 'f:v')
1462([('-f', 'filename')], ['output', '-v'])
1463>>> getopt.gnu_getopt(['-f', 'filename', 'output', '-v'], 'f:v')
1464([('-f', 'filename'), ('-v', '')], ['output'])
1465\end{verbatim}
1466
1467(Contributed by Peter \AA{strand}.)
1468
1469\item The \module{grp}, \module{pwd}, and \module{resource} modules
Fred Drake5c4cf152002-11-13 14:59:06 +00001470now return enhanced tuples:
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001471
1472\begin{verbatim}
1473>>> import grp
1474>>> g = grp.getgrnam('amk')
1475>>> g.gr_name, g.gr_gid
1476('amk', 500)
1477\end{verbatim}
1478
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001479\item The \module{gzip} module can now handle files exceeding 2~Gb.
1480
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001481\item The new \module{heapq} module contains an implementation of a
1482heap queue algorithm. A heap is an array-like data structure that
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001483keeps items in a partially sorted order such that, for every index
1484\var{k}, \code{heap[\var{k}] <= heap[2*\var{k}+1]} and
1485\code{heap[\var{k}] <= heap[2*\var{k}+2]}. This makes it quick to
1486remove the smallest item, and inserting a new item while maintaining
1487the heap property is O(lg~n). (See
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001488\url{http://www.nist.gov/dads/HTML/priorityque.html} for more
1489information about the priority queue data structure.)
1490
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001491The \module{heapq} module provides \function{heappush()} and
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001492\function{heappop()} functions for adding and removing items while
1493maintaining the heap property on top of some other mutable Python
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001494sequence type. Here's an example that uses a Python list:
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001495
1496\begin{verbatim}
1497>>> import heapq
1498>>> heap = []
1499>>> for item in [3, 7, 5, 11, 1]:
1500... heapq.heappush(heap, item)
1501...
1502>>> heap
1503[1, 3, 5, 11, 7]
1504>>> heapq.heappop(heap)
15051
1506>>> heapq.heappop(heap)
15073
1508>>> heap
1509[5, 7, 11]
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001510\end{verbatim}
1511
1512(Contributed by Kevin O'Connor.)
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001513
Andrew M. Kuchling6e73f9e2003-07-18 01:15:51 +00001514\item The IDLE integrated development environment has been updated
1515using the code from the IDLEfork project
1516(\url{http://idlefork.sf.net}). The most notable feature is that the
1517code being developed is now executed in a subprocess, meaning that
1518there's no longer any need for manual \code{reload()} operations.
1519IDLE's core code has been incorporated into the standard library as the
1520\module{idlelib} package.
1521
Andrew M. Kuchling87cebbf2003-01-03 16:24:28 +00001522\item The \module{imaplib} module now supports IMAP over SSL.
1523(Contributed by Piers Lauder and Tino Lange.)
1524
Andrew M. Kuchling41c3e002003-03-02 02:13:52 +00001525\item The \module{itertools} contains a number of useful functions for
1526use with iterators, inspired by various functions provided by the ML
1527and Haskell languages. For example,
1528\code{itertools.ifilter(predicate, iterator)} returns all elements in
1529the iterator for which the function \function{predicate()} returns
Andrew M. Kuchling563389f2003-03-02 02:31:58 +00001530\constant{True}, and \code{itertools.repeat(obj, \var{N})} returns
Andrew M. Kuchling41c3e002003-03-02 02:13:52 +00001531\code{obj} \var{N} times. There are a number of other functions in
1532the module; see the \ulink{package's reference
1533documentation}{../lib/module-itertools.html} for details.
Raymond Hettinger5284b442003-03-09 07:19:38 +00001534(Contributed by Raymond Hettinger.)
Fred Drakecade7132003-02-19 16:08:08 +00001535
Fred Drake5c4cf152002-11-13 14:59:06 +00001536\item Two new functions in the \module{math} module,
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001537\function{degrees(\var{rads})} and \function{radians(\var{degs})},
Fred Drake5c4cf152002-11-13 14:59:06 +00001538convert between radians and degrees. Other functions in the
Andrew M. Kuchling8e5b53b2002-12-15 20:17:38 +00001539\module{math} module such as \function{math.sin()} and
1540\function{math.cos()} have always required input values measured in
1541radians. Also, an optional \var{base} argument was added to
1542\function{math.log()} to make it easier to compute logarithms for
1543bases other than \code{e} and \code{10}. (Contributed by Raymond
1544Hettinger.)
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001545
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001546\item Several new POSIX functions (\function{getpgid()}, \function{killpg()},
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +00001547\function{lchown()}, \function{loadavg()}, \function{major()}, \function{makedev()},
1548\function{minor()}, and \function{mknod()}) were added to the
Andrew M. Kuchlingc309cca2002-10-10 16:04:08 +00001549\module{posix} module that underlies the \module{os} module.
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +00001550(Contributed by Gustavo Niemeyer, Geert Jansen, and Denis S. Otkidach.)
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001551
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001552\item In the \module{os} module, the \function{*stat()} family of
1553functions can now report fractions of a second in a timestamp. Such
1554time stamps are represented as floats, similar to
1555the value returned by \function{time.time()}.
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001556
1557During testing, it was found that some applications will break if time
1558stamps are floats. For compatibility, when using the tuple interface
1559of the \class{stat_result} time stamps will be represented as integers.
1560When using named fields (a feature first introduced in Python 2.2),
1561time stamps are still represented as integers, unless
1562\function{os.stat_float_times()} is invoked to enable float return
1563values:
1564
1565\begin{verbatim}
1566>>> os.stat("/tmp").st_mtime
15671034791200
1568>>> os.stat_float_times(True)
1569>>> os.stat("/tmp").st_mtime
15701034791200.6335014
1571\end{verbatim}
1572
1573In Python 2.4, the default will change to always returning floats.
1574
1575Application developers should enable this feature only if all their
1576libraries work properly when confronted with floating point time
1577stamps, or if they use the tuple API. If used, the feature should be
1578activated on an application level instead of trying to enable it on a
1579per-use basis.
1580
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001581\item The \module{optparse} module contains a new parser for command-line arguments
1582that can convert option values to a particular Python type
1583and will automatically generate a usage message. See the following section for
1584more details.
1585
Andrew M. Kuchling53262572002-12-01 14:00:21 +00001586\item The old and never-documented \module{linuxaudiodev} module has
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001587been deprecated, and a new version named \module{ossaudiodev} has been
1588added. The module was renamed because the OSS sound drivers can be
1589used on platforms other than Linux, and the interface has also been
1590tidied and brought up to date in various ways. (Contributed by Greg
Greg Wardaa1d3aa2003-01-03 18:03:21 +00001591Ward and Nicholas FitzRoy-Dale.)
Andrew M. Kuchling53262572002-12-01 14:00:21 +00001592
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001593\item The new \module{platform} module contains a number of functions
1594that try to determine various properties of the platform you're
1595running on. There are functions for getting the architecture, CPU
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001596type, the Windows OS version, and even the Linux distribution version.
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001597(Contributed by Marc-Andr\'e Lemburg.)
1598
Fred Drake5c4cf152002-11-13 14:59:06 +00001599\item The parser objects provided by the \module{pyexpat} module
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001600can now optionally buffer character data, resulting in fewer calls to
1601your character data handler and therefore faster performance. Setting
Fred Drake5c4cf152002-11-13 14:59:06 +00001602the parser object's \member{buffer_text} attribute to \constant{True}
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001603will enable buffering.
1604
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001605\item The \function{sample(\var{population}, \var{k})} function was
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001606added to the \module{random} module. \var{population} is a sequence or
1607\class{xrange} object containing the elements of a population, and
1608\function{sample()} chooses \var{k} elements from the population without
1609replacing chosen elements. \var{k} can be any value up to
1610\code{len(\var{population})}. For example:
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001611
1612\begin{verbatim}
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001613>>> days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'St', 'Sn']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001614>>> random.sample(days, 3) # Choose 3 elements
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001615['St', 'Sn', 'Th']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001616>>> random.sample(days, 7) # Choose 7 elements
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001617['Tu', 'Th', 'Mo', 'We', 'St', 'Fr', 'Sn']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001618>>> random.sample(days, 7) # Choose 7 again
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001619['We', 'Mo', 'Sn', 'Fr', 'Tu', 'St', 'Th']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001620>>> random.sample(days, 8) # Can't choose eight
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001621Traceback (most recent call last):
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +00001622 File "<stdin>", line 1, in ?
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001623 File "random.py", line 414, in sample
1624 raise ValueError, "sample larger than population"
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001625ValueError: sample larger than population
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001626>>> random.sample(xrange(1,10000,2), 10) # Choose ten odd nos. under 10000
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001627[3407, 3805, 1505, 7023, 2401, 2267, 9733, 3151, 8083, 9195]
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001628\end{verbatim}
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001629
1630The \module{random} module now uses a new algorithm, the Mersenne
1631Twister, implemented in C. It's faster and more extensively studied
1632than the previous algorithm.
1633
1634(All changes contributed by Raymond Hettinger.)
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001635
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001636\item The \module{readline} module also gained a number of new
1637functions: \function{get_history_item()},
1638\function{get_current_history_length()}, and \function{redisplay()}.
1639
Andrew M. Kuchlingef893fe2003-01-06 20:04:17 +00001640\item The \module{rexec} and \module{Bastion} modules have been
1641declared dead, and attempts to import them will fail with a
1642\exception{RuntimeError}. New-style classes provide new ways to break
1643out of the restricted execution environment provided by
1644\module{rexec}, and no one has interest in fixing them or time to do
1645so. If you have applications using \module{rexec}, rewrite them to
1646use something else.
1647
1648(Sticking with Python 2.2 or 2.1 will not make your applications any
Andrew M. Kuchling13b4c412003-04-24 13:23:43 +00001649safer because there are known bugs in the \module{rexec} module in
Andrew M. Kuchling035272b2003-04-24 16:38:20 +00001650those versions. To repeat: if you're using \module{rexec}, stop using
Andrew M. Kuchlingef893fe2003-01-06 20:04:17 +00001651it immediately.)
1652
Andrew M. Kuchling13b4c412003-04-24 13:23:43 +00001653\item The \module{rotor} module has been deprecated because the
1654 algorithm it uses for encryption is not believed to be secure. If
1655 you need encryption, use one of the several AES Python modules
1656 that are available separately.
1657
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001658\item The \module{shutil} module gained a \function{move(\var{src},
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001659\var{dest})} function that recursively moves a file or directory to a new
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001660location.
1661
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001662\item Support for more advanced POSIX signal handling was added
Michael W. Hudson43ed43b2003-03-13 13:56:53 +00001663to the \module{signal} but then removed again as it proved impossible
1664to make it work reliably across platforms.
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001665
1666\item The \module{socket} module now supports timeouts. You
1667can call the \method{settimeout(\var{t})} method on a socket object to
1668set a timeout of \var{t} seconds. Subsequent socket operations that
1669take longer than \var{t} seconds to complete will abort and raise a
Andrew M. Kuchlingc760c6c2003-07-16 20:12:33 +00001670\exception{socket.timeout} exception.
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001671
1672The original timeout implementation was by Tim O'Malley. Michael
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001673Gilfix integrated it into the Python \module{socket} module and
1674shepherded it through a lengthy review. After the code was checked
1675in, Guido van~Rossum rewrote parts of it. (This is a good example of
1676a collaborative development process in action.)
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001677
Mark Hammond8af50bc2002-12-03 06:13:35 +00001678\item On Windows, the \module{socket} module now ships with Secure
Michael W. Hudson065f5fa2003-02-10 19:24:50 +00001679Sockets Layer (SSL) support.
Mark Hammond8af50bc2002-12-03 06:13:35 +00001680
Andrew M. Kuchling563389f2003-03-02 02:31:58 +00001681\item The value of the C \constant{PYTHON_API_VERSION} macro is now
1682exposed at the Python level as \code{sys.api_version}. The current
1683exception can be cleared by calling the new \function{sys.exc_clear()}
1684function.
Andrew M. Kuchlingdcfd8252002-09-13 22:21:42 +00001685
Andrew M. Kuchling674b0bf2003-01-07 00:07:19 +00001686\item The new \module{tarfile} module
Neal Norwitz55d555f2003-01-08 05:27:42 +00001687allows reading from and writing to \program{tar}-format archive files.
Andrew M. Kuchling674b0bf2003-01-07 00:07:19 +00001688(Contributed by Lars Gust\"abel.)
1689
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001690\item The new \module{textwrap} module contains functions for wrapping
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001691strings containing paragraphs of text. The \function{wrap(\var{text},
1692\var{width})} function takes a string and returns a list containing
1693the text split into lines of no more than the chosen width. The
1694\function{fill(\var{text}, \var{width})} function returns a single
1695string, reformatted to fit into lines no longer than the chosen width.
1696(As you can guess, \function{fill()} is built on top of
1697\function{wrap()}. For example:
1698
1699\begin{verbatim}
1700>>> import textwrap
1701>>> paragraph = "Not a whit, we defy augury: ... more text ..."
1702>>> textwrap.wrap(paragraph, 60)
Fred Drake5c4cf152002-11-13 14:59:06 +00001703["Not a whit, we defy augury: there's a special providence in",
1704 "the fall of a sparrow. If it be now, 'tis not to come; if it",
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001705 ...]
1706>>> print textwrap.fill(paragraph, 35)
1707Not a whit, we defy augury: there's
1708a special providence in the fall of
1709a sparrow. If it be now, 'tis not
1710to come; if it be not to come, it
1711will be now; if it be not now, yet
1712it will come: the readiness is all.
Fred Drake5c4cf152002-11-13 14:59:06 +00001713>>>
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001714\end{verbatim}
1715
1716The module also contains a \class{TextWrapper} class that actually
Fred Drake5c4cf152002-11-13 14:59:06 +00001717implements the text wrapping strategy. Both the
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001718\class{TextWrapper} class and the \function{wrap()} and
1719\function{fill()} functions support a number of additional keyword
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +00001720arguments for fine-tuning the formatting; consult the \ulink{module's
1721documentation}{../lib/module-textwrap.html} for details.
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001722(Contributed by Greg Ward.)
1723
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001724\item The \module{thread} and \module{threading} modules now have
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001725companion modules, \module{dummy_thread} and \module{dummy_threading},
1726that provide a do-nothing implementation of the \module{thread}
1727module's interface for platforms where threads are not supported. The
1728intention is to simplify thread-aware modules (ones that \emph{don't}
1729rely on threads to run) by putting the following code at the top:
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001730
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001731\begin{verbatim}
1732try:
1733 import threading as _threading
1734except ImportError:
1735 import dummy_threading as _threading
1736\end{verbatim}
1737
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001738In this example, \module{_threading} is used as the module name to make
1739it clear that the module being used is not necessarily the actual
1740\module{threading} module. Code can call functions and use classes in
1741\module{_threading} whether or not threads are supported, avoiding an
1742\keyword{if} statement and making the code slightly clearer. This
1743module will not magically make multithreaded code run without threads;
1744code that waits for another thread to return or to do something will
1745simply hang forever.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001746
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001747\item The \module{time} module's \function{strptime()} function has
Fred Drake5c4cf152002-11-13 14:59:06 +00001748long been an annoyance because it uses the platform C library's
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001749\function{strptime()} implementation, and different platforms
1750sometimes have odd bugs. Brett Cannon contributed a portable
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001751implementation that's written in pure Python and should behave
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001752identically on all platforms.
1753
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +00001754\item The new \module{timeit} module helps measure how long snippets
1755of Python code take to execute. The \file{timeit.py} file can be run
1756directly from the command line, or the module's \class{Timer} class
1757can be imported and used directly. Here's a short example that
1758figures out whether it's faster to convert an 8-bit string to Unicode
1759by appending an empty Unicode string to it or by using the
1760\function{unicode()} function:
1761
1762\begin{verbatim}
1763import timeit
1764
1765timer1 = timeit.Timer('unicode("abc")')
1766timer2 = timeit.Timer('"abc" + u""')
1767
1768# Run three trials
1769print timer1.repeat(repeat=3, number=100000)
1770print timer2.repeat(repeat=3, number=100000)
1771
1772# On my laptop this outputs:
1773# [0.36831796169281006, 0.37441694736480713, 0.35304892063140869]
1774# [0.17574405670166016, 0.18193507194519043, 0.17565798759460449]
1775\end{verbatim}
1776
Raymond Hettinger8ccf4d72003-07-10 15:48:33 +00001777\item The \module{Tix} module has received various bug fixes and
Andrew M. Kuchlingef893fe2003-01-06 20:04:17 +00001778updates for the current version of the Tix package.
1779
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001780\item The \module{Tkinter} module now works with a thread-enabled
1781version of Tcl. Tcl's threading model requires that widgets only be
1782accessed from the thread in which they're created; accesses from
1783another thread can cause Tcl to panic. For certain Tcl interfaces,
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001784\module{Tkinter} will now automatically avoid this
1785when a widget is accessed from a different thread by marshalling a
1786command, passing it to the correct thread, and waiting for the
1787results. Other interfaces can't be handled automatically but
1788\module{Tkinter} will now raise an exception on such an access so that
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001789you can at least find out about the problem. See
Fred Drakeb876bcc2003-04-30 15:03:46 +00001790\url{http://mail.python.org/pipermail/python-dev/2002-December/031107.html} %
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001791for a more detailed explanation of this change. (Implemented by
Andrew M. Kuchlingfcf6b3e2003-05-07 17:00:35 +00001792Martin von~L\"owis.)
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001793
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001794\item Calling Tcl methods through \module{_tkinter} no longer
1795returns only strings. Instead, if Tcl returns other objects those
1796objects are converted to their Python equivalent, if one exists, or
1797wrapped with a \class{_tkinter.Tcl_Obj} object if no Python equivalent
Raymond Hettinger45bda572002-12-14 20:20:45 +00001798exists. This behavior can be controlled through the
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001799\method{wantobjects()} method of \class{tkapp} objects.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001800
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001801When using \module{_tkinter} through the \module{Tkinter} module (as
1802most Tkinter applications will), this feature is always activated. It
1803should not cause compatibility problems, since Tkinter would always
1804convert string results to Python types where possible.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001805
Raymond Hettinger45bda572002-12-14 20:20:45 +00001806If any incompatibilities are found, the old behavior can be restored
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001807by setting the \member{wantobjects} variable in the \module{Tkinter}
1808module to false before creating the first \class{tkapp} object.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001809
1810\begin{verbatim}
1811import Tkinter
Martin v. Löwis8c8aa5d2002-11-26 21:39:48 +00001812Tkinter.wantobjects = 0
Martin v. Löwis39b48522002-11-26 09:47:25 +00001813\end{verbatim}
1814
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001815Any breakage caused by this change should be reported as a bug.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001816
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001817\item The \module{UserDict} module has a new \class{DictMixin} class which
1818defines all dictionary methods for classes that already have a minimum
1819mapping interface. This greatly simplifies writing classes that need
1820to be substitutable for dictionaries, such as the classes in
1821the \module{shelve} module.
1822
1823Adding the mix-in as a superclass provides the full dictionary
1824interface whenever the class defines \method{__getitem__},
1825\method{__setitem__}, \method{__delitem__}, and \method{keys}.
1826For example:
1827
1828\begin{verbatim}
1829>>> import UserDict
1830>>> class SeqDict(UserDict.DictMixin):
1831... """Dictionary lookalike implemented with lists."""
1832... def __init__(self):
1833... self.keylist = []
1834... self.valuelist = []
1835... def __getitem__(self, key):
1836... try:
1837... i = self.keylist.index(key)
1838... except ValueError:
1839... raise KeyError
1840... return self.valuelist[i]
1841... def __setitem__(self, key, value):
1842... try:
1843... i = self.keylist.index(key)
1844... self.valuelist[i] = value
1845... except ValueError:
1846... self.keylist.append(key)
1847... self.valuelist.append(value)
1848... def __delitem__(self, key):
1849... try:
1850... i = self.keylist.index(key)
1851... except ValueError:
1852... raise KeyError
1853... self.keylist.pop(i)
1854... self.valuelist.pop(i)
1855... def keys(self):
1856... return list(self.keylist)
1857...
1858>>> s = SeqDict()
1859>>> dir(s) # See that other dictionary methods are implemented
1860['__cmp__', '__contains__', '__delitem__', '__doc__', '__getitem__',
1861 '__init__', '__iter__', '__len__', '__module__', '__repr__',
1862 '__setitem__', 'clear', 'get', 'has_key', 'items', 'iteritems',
1863 'iterkeys', 'itervalues', 'keylist', 'keys', 'pop', 'popitem',
1864 'setdefault', 'update', 'valuelist', 'values']
1865\end{verbatim}
1866
1867(Contributed by Raymond Hettinger.)
1868
Andrew M. Kuchlinge36b6902003-04-19 15:38:47 +00001869\item The DOM implementation
1870in \module{xml.dom.minidom} can now generate XML output in a
1871particular encoding by providing an optional encoding argument to
1872the \method{toxml()} and \method{toprettyxml()} methods of DOM nodes.
1873
Andrew M. Kuchling6e73f9e2003-07-18 01:15:51 +00001874\item The \module{xmlrpclib} module now supports an XML-RPC extension
1875for handling nil data values such as Python's \code{None}. Nil values
1876are always supported on unmarshalling an XML-RPC response. To
1877generate requests containing \code{None}, you must supply a true value
1878for the \var{allow_none} parameter when creating a \class{Marshaller}
1879instance.
1880
Andrew M. Kuchlinge36b6902003-04-19 15:38:47 +00001881\item The new \module{DocXMLRPCServer} module allows writing
1882self-documenting XML-RPC servers. Run it in demo mode (as a program)
1883to see it in action. Pointing the Web browser to the RPC server
1884produces pydoc-style documentation; pointing xmlrpclib to the
1885server allows invoking the actual methods.
1886(Contributed by Brian Quinlan.)
1887
Martin v. Löwis2548c732003-04-18 10:39:54 +00001888\item Support for internationalized domain names (RFCs 3454, 3490,
18893491, and 3492) has been added. The ``idna'' encoding can be used
1890to convert between a Unicode domain name and the ASCII-compatible
Andrew M. Kuchlinge36b6902003-04-19 15:38:47 +00001891encoding (ACE) of that name.
Martin v. Löwis2548c732003-04-18 10:39:54 +00001892
Martin v. Löwisfaf71ea2003-04-18 21:48:56 +00001893\begin{alltt}
Fred Drake15b3dba2003-07-16 04:00:14 +00001894>{}>{}> u"www.Alliancefran\c caise.nu".encode("idna")
Martin v. Löwis2548c732003-04-18 10:39:54 +00001895'www.xn--alliancefranaise-npb.nu'
Martin v. Löwisfaf71ea2003-04-18 21:48:56 +00001896\end{alltt}
Martin v. Löwis2548c732003-04-18 10:39:54 +00001897
Andrew M. Kuchlinge36b6902003-04-19 15:38:47 +00001898The \module{socket} module has also been extended to transparently
1899convert Unicode hostnames to the ACE version before passing them to
1900the C library. Modules that deal with hostnames such as
1901\module{httplib} and \module{ftplib}) also support Unicode host names;
1902\module{httplib} also sends HTTP \samp{Host} headers using the ACE
1903version of the domain name. \module{urllib} supports Unicode URLs
1904with non-ASCII host names as long as the \code{path} part of the URL
1905is ASCII only.
Martin v. Löwis2548c732003-04-18 10:39:54 +00001906
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001907To implement this change, the \module{stringprep} module, the
1908\code{mkstringprep} tool and the \code{punycode} encoding have been added.
Martin v. Löwis281b2c62003-04-18 21:04:39 +00001909
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00001910\end{itemize}
1911
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00001912
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001913%======================================================================
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001914\subsection{Date/Time Type}
1915
1916Date and time types suitable for expressing timestamps were added as
1917the \module{datetime} module. The types don't support different
1918calendars or many fancy features, and just stick to the basics of
1919representing time.
1920
1921The three primary types are: \class{date}, representing a day, month,
1922and year; \class{time}, consisting of hour, minute, and second; and
1923\class{datetime}, which contains all the attributes of both
Andrew M. Kuchlingc71bb972003-03-21 17:23:07 +00001924\class{date} and \class{time}. There's also a
1925\class{timedelta} class representing differences between two points
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001926in time, and time zone logic is implemented by classes inheriting from
1927the abstract \class{tzinfo} class.
1928
1929You can create instances of \class{date} and \class{time} by either
1930supplying keyword arguments to the appropriate constructor,
1931e.g. \code{datetime.date(year=1972, month=10, day=15)}, or by using
Andrew M. Kuchlingc71bb972003-03-21 17:23:07 +00001932one of a number of class methods. For example, the \method{date.today()}
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001933class method returns the current local date.
1934
1935Once created, instances of the date/time classes are all immutable.
1936There are a number of methods for producing formatted strings from
1937objects:
1938
1939\begin{verbatim}
1940>>> import datetime
1941>>> now = datetime.datetime.now()
1942>>> now.isoformat()
1943'2002-12-30T21:27:03.994956'
1944>>> now.ctime() # Only available on date, datetime
1945'Mon Dec 30 21:27:03 2002'
Raymond Hettingeree1bded2003-01-17 16:20:23 +00001946>>> now.strftime('%Y %d %b')
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001947'2002 30 Dec'
1948\end{verbatim}
1949
1950The \method{replace()} method allows modifying one or more fields
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001951of a \class{date} or \class{datetime} instance, returning a new instance:
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001952
1953\begin{verbatim}
1954>>> d = datetime.datetime.now()
1955>>> d
1956datetime.datetime(2002, 12, 30, 22, 15, 38, 827738)
1957>>> d.replace(year=2001, hour = 12)
1958datetime.datetime(2001, 12, 30, 12, 15, 38, 827738)
1959>>>
1960\end{verbatim}
1961
1962Instances can be compared, hashed, and converted to strings (the
1963result is the same as that of \method{isoformat()}). \class{date} and
1964\class{datetime} instances can be subtracted from each other, and
Andrew M. Kuchlingc71bb972003-03-21 17:23:07 +00001965added to \class{timedelta} instances. The largest missing feature is
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00001966that there's no standard library support for parsing strings and getting back a
Andrew M. Kuchlingc71bb972003-03-21 17:23:07 +00001967\class{date} or \class{datetime}.
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001968
1969For more information, refer to the \ulink{module's reference
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +00001970documentation}{../lib/module-datetime.html}.
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001971(Contributed by Tim Peters.)
1972
1973
1974%======================================================================
Andrew M. Kuchling8d177092003-05-13 14:26:54 +00001975\subsection{The optparse Module}
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001976
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001977The \module{getopt} module provides simple parsing of command-line
1978arguments. The new \module{optparse} module (originally named Optik)
1979provides more elaborate command-line parsing that follows the Unix
1980conventions, automatically creates the output for \longprogramopt{help},
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001981and can perform different actions for different options.
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001982
1983You start by creating an instance of \class{OptionParser} and telling
1984it what your program's options are.
1985
1986\begin{verbatim}
Andrew M. Kuchling7ee9b512003-02-18 00:48:23 +00001987import sys
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001988from optparse import OptionParser
1989
1990op = OptionParser()
1991op.add_option('-i', '--input',
1992 action='store', type='string', dest='input',
1993 help='set input filename')
1994op.add_option('-l', '--length',
1995 action='store', type='int', dest='length',
1996 help='set maximum length of output')
1997\end{verbatim}
1998
1999Parsing a command line is then done by calling the \method{parse_args()}
2000method.
2001
2002\begin{verbatim}
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002003options, args = op.parse_args(sys.argv[1:])
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00002004print options
2005print args
2006\end{verbatim}
2007
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002008This returns an object containing all of the option values,
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00002009and a list of strings containing the remaining arguments.
2010
2011Invoking the script with the various arguments now works as you'd
2012expect it to. Note that the length argument is automatically
2013converted to an integer.
2014
2015\begin{verbatim}
2016$ ./python opt.py -i data arg1
2017<Values at 0x400cad4c: {'input': 'data', 'length': None}>
2018['arg1']
2019$ ./python opt.py --input=data --length=4
2020<Values at 0x400cad2c: {'input': 'data', 'length': 4}>
Andrew M. Kuchling7ee9b512003-02-18 00:48:23 +00002021[]
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00002022$
2023\end{verbatim}
2024
2025The help message is automatically generated for you:
2026
2027\begin{verbatim}
2028$ ./python opt.py --help
2029usage: opt.py [options]
2030
2031options:
2032 -h, --help show this help message and exit
2033 -iINPUT, --input=INPUT
2034 set input filename
2035 -lLENGTH, --length=LENGTH
2036 set maximum length of output
2037$
2038\end{verbatim}
Andrew M. Kuchling669249e2002-11-19 13:05:33 +00002039% $ prevent Emacs tex-mode from getting confused
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00002040
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +00002041See the \ulink{module's documentation}{../lib/module-optparse.html}
2042for more details.
2043
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00002044Optik was written by Greg Ward, with suggestions from the readers of
2045the Getopt SIG.
2046
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00002047
2048%======================================================================
Andrew M. Kuchling8d177092003-05-13 14:26:54 +00002049\section{Pymalloc: A Specialized Object Allocator\label{section-pymalloc}}
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002050
Andrew M. Kuchlingc71bb972003-03-21 17:23:07 +00002051Pymalloc, a specialized object allocator written by Vladimir
2052Marangozov, was a feature added to Python 2.1. Pymalloc is intended
2053to be faster than the system \cfunction{malloc()} and to have less
2054memory overhead for allocation patterns typical of Python programs.
2055The allocator uses C's \cfunction{malloc()} function to get large
2056pools of memory and then fulfills smaller memory requests from these
2057pools.
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002058
2059In 2.1 and 2.2, pymalloc was an experimental feature and wasn't
Andrew M. Kuchlingc71bb972003-03-21 17:23:07 +00002060enabled by default; you had to explicitly enable it when compiling
2061Python by providing the
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002062\longprogramopt{with-pymalloc} option to the \program{configure}
2063script. In 2.3, pymalloc has had further enhancements and is now
2064enabled by default; you'll have to supply
2065\longprogramopt{without-pymalloc} to disable it.
2066
2067This change is transparent to code written in Python; however,
2068pymalloc may expose bugs in C extensions. Authors of C extension
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002069modules should test their code with pymalloc enabled,
2070because some incorrect code may cause core dumps at runtime.
2071
2072There's one particularly common error that causes problems. There are
2073a number of memory allocation functions in Python's C API that have
2074previously just been aliases for the C library's \cfunction{malloc()}
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002075and \cfunction{free()}, meaning that if you accidentally called
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002076mismatched functions the error wouldn't be noticeable. When the
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002077object allocator is enabled, these functions aren't aliases of
2078\cfunction{malloc()} and \cfunction{free()} any more, and calling the
2079wrong function to free memory may get you a core dump. For example,
2080if memory was allocated using \cfunction{PyObject_Malloc()}, it has to
2081be freed using \cfunction{PyObject_Free()}, not \cfunction{free()}. A
2082few modules included with Python fell afoul of this and had to be
2083fixed; doubtless there are more third-party modules that will have the
2084same problem.
2085
2086As part of this change, the confusing multiple interfaces for
2087allocating memory have been consolidated down into two API families.
2088Memory allocated with one family must not be manipulated with
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002089functions from the other family. There is one family for allocating
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002090chunks of memory and another family of functions specifically for
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002091allocating Python objects.
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002092
2093\begin{itemize}
2094 \item To allocate and free an undistinguished chunk of memory use
2095 the ``raw memory'' family: \cfunction{PyMem_Malloc()},
2096 \cfunction{PyMem_Realloc()}, and \cfunction{PyMem_Free()}.
2097
2098 \item The ``object memory'' family is the interface to the pymalloc
2099 facility described above and is biased towards a large number of
2100 ``small'' allocations: \cfunction{PyObject_Malloc},
2101 \cfunction{PyObject_Realloc}, and \cfunction{PyObject_Free}.
2102
2103 \item To allocate and free Python objects, use the ``object'' family
2104 \cfunction{PyObject_New()}, \cfunction{PyObject_NewVar()}, and
2105 \cfunction{PyObject_Del()}.
2106\end{itemize}
2107
2108Thanks to lots of work by Tim Peters, pymalloc in 2.3 also provides
2109debugging features to catch memory overwrites and doubled frees in
2110both extension modules and in the interpreter itself. To enable this
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002111support, compile a debugging version of the Python interpreter by
2112running \program{configure} with \longprogramopt{with-pydebug}.
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002113
2114To aid extension writers, a header file \file{Misc/pymemcompat.h} is
2115distributed with the source to Python 2.3 that allows Python
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002116extensions to use the 2.3 interfaces to memory allocation while
2117compiling against any version of Python since 1.5.2. You would copy
2118the file from Python's source distribution and bundle it with the
2119source of your extension.
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002120
2121\begin{seealso}
2122
2123\seeurl{http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Objects/obmalloc.c}
2124{For the full details of the pymalloc implementation, see
2125the comments at the top of the file \file{Objects/obmalloc.c} in the
2126Python source code. The above link points to the file within the
2127SourceForge CVS browser.}
2128
2129\end{seealso}
2130
2131
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00002132% ======================================================================
2133\section{Build and C API Changes}
2134
Andrew M. Kuchling3c305d92002-07-22 18:50:11 +00002135Changes to Python's build process and to the C API include:
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00002136
2137\begin{itemize}
2138
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002139\item The C-level interface to the garbage collector has been changed
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002140to make it easier to write extension types that support garbage
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002141collection and to debug misuses of the functions.
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00002142Various functions have slightly different semantics, so a bunch of
2143functions had to be renamed. Extensions that use the old API will
2144still compile but will \emph{not} participate in garbage collection,
2145so updating them for 2.3 should be considered fairly high priority.
2146
2147To upgrade an extension module to the new API, perform the following
2148steps:
2149
2150\begin{itemize}
2151
2152\item Rename \cfunction{Py_TPFLAGS_GC} to \cfunction{PyTPFLAGS_HAVE_GC}.
2153
2154\item Use \cfunction{PyObject_GC_New} or \cfunction{PyObject_GC_NewVar} to
2155allocate objects, and \cfunction{PyObject_GC_Del} to deallocate them.
2156
2157\item Rename \cfunction{PyObject_GC_Init} to \cfunction{PyObject_GC_Track} and
2158\cfunction{PyObject_GC_Fini} to \cfunction{PyObject_GC_UnTrack}.
2159
2160\item Remove \cfunction{PyGC_HEAD_SIZE} from object size calculations.
2161
2162\item Remove calls to \cfunction{PyObject_AS_GC} and \cfunction{PyObject_FROM_GC}.
2163
2164\end{itemize}
2165
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002166\item The cycle detection implementation used by the garbage collection
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002167has proven to be stable, so it's now been made mandatory. You can no
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002168longer compile Python without it, and the
2169\longprogramopt{with-cycle-gc} switch to \program{configure} has been removed.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00002170
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002171\item Python can now optionally be built as a shared library
2172(\file{libpython2.3.so}) by supplying \longprogramopt{enable-shared}
Fred Drake5c4cf152002-11-13 14:59:06 +00002173when running Python's \program{configure} script. (Contributed by Ondrej
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +00002174Palkovsky.)
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +00002175
Michael W. Hudsondd32a912002-08-15 14:59:02 +00002176\item The \csimplemacro{DL_EXPORT} and \csimplemacro{DL_IMPORT} macros
2177are now deprecated. Initialization functions for Python extension
2178modules should now be declared using the new macro
Andrew M. Kuchling3c305d92002-07-22 18:50:11 +00002179\csimplemacro{PyMODINIT_FUNC}, while the Python core will generally
2180use the \csimplemacro{PyAPI_FUNC} and \csimplemacro{PyAPI_DATA}
2181macros.
Neal Norwitzbba23a82002-07-22 13:18:59 +00002182
Fred Drake5c4cf152002-11-13 14:59:06 +00002183\item The interpreter can be compiled without any docstrings for
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00002184the built-in functions and modules by supplying
Fred Drake5c4cf152002-11-13 14:59:06 +00002185\longprogramopt{without-doc-strings} to the \program{configure} script.
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00002186This makes the Python executable about 10\% smaller, but will also
2187mean that you can't get help for Python's built-ins. (Contributed by
2188Gustavo Niemeyer.)
2189
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002190\item The \cfunction{PyArg_NoArgs()} macro is now deprecated, and code
Andrew M. Kuchling7845e7c2002-07-11 19:27:46 +00002191that uses it should be changed. For Python 2.2 and later, the method
2192definition table can specify the
Fred Drake5c4cf152002-11-13 14:59:06 +00002193\constant{METH_NOARGS} flag, signalling that there are no arguments, and
Andrew M. Kuchling7845e7c2002-07-11 19:27:46 +00002194the argument checking can then be removed. If compatibility with
2195pre-2.2 versions of Python is important, the code could use
Fred Drakeaac8c582003-01-17 22:50:10 +00002196\code{PyArg_ParseTuple(\var{args}, "")} instead, but this will be slower
Andrew M. Kuchling7845e7c2002-07-11 19:27:46 +00002197than using \constant{METH_NOARGS}.
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00002198
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002199\item A new function, \cfunction{PyObject_DelItemString(\var{mapping},
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002200char *\var{key})} was added as shorthand for
Raymond Hettingera685f522003-07-12 04:42:30 +00002201\code{PyObject_DelItem(\var{mapping}, PyString_New(\var{key}))}.
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00002202
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002203\item File objects now manage their internal string buffer
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002204differently, increasing it exponentially when needed. This results in
2205the benchmark tests in \file{Lib/test/test_bufio.py} speeding up
2206considerably (from 57 seconds to 1.7 seconds, according to one
2207measurement).
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002208
Andrew M. Kuchling72b58e02002-05-29 17:30:34 +00002209\item It's now possible to define class and static methods for a C
2210extension type by setting either the \constant{METH_CLASS} or
2211\constant{METH_STATIC} flags in a method's \ctype{PyMethodDef}
2212structure.
Andrew M. Kuchling45afd542002-04-02 14:25:25 +00002213
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00002214\item Python now includes a copy of the Expat XML parser's source code,
2215removing any dependence on a system version or local installation of
Fred Drake5c4cf152002-11-13 14:59:06 +00002216Expat.
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00002217
Michael W. Hudson3e245d82003-02-11 14:19:56 +00002218\item If you dynamically allocate type objects in your extension, you
Neal Norwitzada859c2003-02-11 14:30:39 +00002219should be aware of a change in the rules relating to the
Michael W. Hudson3e245d82003-02-11 14:19:56 +00002220\member{__module__} and \member{__name__} attributes. In summary,
2221you will want to ensure the type's dictionary contains a
2222\code{'__module__'} key; making the module name the part of the type
2223name leading up to the final period will no longer have the desired
2224effect. For more detail, read the API reference documentation or the
2225source.
2226
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00002227\end{itemize}
2228
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00002229
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00002230%======================================================================
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00002231\subsection{Port-Specific Changes}
2232
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00002233Support for a port to IBM's OS/2 using the EMX runtime environment was
2234merged into the main Python source tree. EMX is a POSIX emulation
2235layer over the OS/2 system APIs. The Python port for EMX tries to
2236support all the POSIX-like capability exposed by the EMX runtime, and
2237mostly succeeds; \function{fork()} and \function{fcntl()} are
2238restricted by the limitations of the underlying emulation layer. The
2239standard OS/2 port, which uses IBM's Visual Age compiler, also gained
2240support for case-sensitive import semantics as part of the integration
2241of the EMX port into CVS. (Contributed by Andrew MacIntyre.)
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00002242
Andrew M. Kuchling72b58e02002-05-29 17:30:34 +00002243On MacOS, most toolbox modules have been weaklinked to improve
2244backward compatibility. This means that modules will no longer fail
2245to load if a single routine is missing on the curent OS version.
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00002246Instead calling the missing routine will raise an exception.
2247(Contributed by Jack Jansen.)
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00002248
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00002249The RPM spec files, found in the \file{Misc/RPM/} directory in the
2250Python source distribution, were updated for 2.3. (Contributed by
2251Sean Reifschneider.)
Fred Drake03e10312002-03-26 19:17:43 +00002252
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002253Other new platforms now supported by Python include AtheOS
Fred Drake693aea22003-02-07 14:52:18 +00002254(\url{http://www.atheos.cx/}), GNU/Hurd, and OpenVMS.
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00002255
Fred Drake03e10312002-03-26 19:17:43 +00002256
2257%======================================================================
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002258\section{Other Changes and Fixes \label{section-other}}
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002259
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +00002260As usual, there were a bunch of other improvements and bugfixes
2261scattered throughout the source tree. A search through the CVS change
Andrew M. Kuchling2cd77312003-07-16 14:44:12 +00002262logs finds there were 523 patches applied and 514 bugs fixed between
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +00002263Python 2.2 and 2.3. Both figures are likely to be underestimates.
2264
2265Some of the more notable changes are:
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002266
2267\begin{itemize}
2268
Andrew M. Kuchling6e73f9e2003-07-18 01:15:51 +00002269\item If the \envvar{PYTHONINSPECT} environment variable is set, the
2270Python interpreter will enter the interactive prompt after running a
2271Python program, as if Python had been invoked with the \programopt{-i}
2272option. The environment variable can be set before running the Python
2273interpreter, or it can be set by the Python program as part of its
2274execution.
2275
Fred Drake54fe3fd2002-11-26 22:07:35 +00002276\item The \file{regrtest.py} script now provides a way to allow ``all
2277resources except \var{foo}.'' A resource name passed to the
2278\programopt{-u} option can now be prefixed with a hyphen
2279(\character{-}) to mean ``remove this resource.'' For example, the
2280option `\code{\programopt{-u}all,-bsddb}' could be used to enable the
2281use of all resources except \code{bsddb}.
2282
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002283\item The tools used to build the documentation now work under Cygwin
2284as well as \UNIX.
2285
Michael W. Hudsondd32a912002-08-15 14:59:02 +00002286\item The \code{SET_LINENO} opcode has been removed. Back in the
2287mists of time, this opcode was needed to produce line numbers in
2288tracebacks and support trace functions (for, e.g., \module{pdb}).
2289Since Python 1.5, the line numbers in tracebacks have been computed
2290using a different mechanism that works with ``python -O''. For Python
22912.3 Michael Hudson implemented a similar scheme to determine when to
2292call the trace function, removing the need for \code{SET_LINENO}
2293entirely.
2294
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +00002295It would be difficult to detect any resulting difference from Python
2296code, apart from a slight speed up when Python is run without
Michael W. Hudsondd32a912002-08-15 14:59:02 +00002297\programopt{-O}.
2298
2299C extensions that access the \member{f_lineno} field of frame objects
2300should instead call \code{PyCode_Addr2Line(f->f_code, f->f_lasti)}.
2301This will have the added effect of making the code work as desired
2302under ``python -O'' in earlier versions of Python.
2303
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002304A nifty new feature is that trace functions can now assign to the
2305\member{f_lineno} attribute of frame objects, changing the line that
2306will be executed next. A \samp{jump} command has been added to the
2307\module{pdb} debugger taking advantage of this new feature.
2308(Implemented by Richie Hindle.)
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00002309
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002310\end{itemize}
2311
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00002312
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002313%======================================================================
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00002314\section{Porting to Python 2.3}
2315
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002316This section lists previously described changes that may require
2317changes to your code:
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002318
2319\begin{itemize}
2320
2321\item \keyword{yield} is now always a keyword; if it's used as a
2322variable name in your code, a different name must be chosen.
2323
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002324\item For strings \var{X} and \var{Y}, \code{\var{X} in \var{Y}} now works
2325if \var{X} is more than one character long.
2326
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00002327\item The \function{int()} type constructor will now return a long
2328integer instead of raising an \exception{OverflowError} when a string
2329or floating-point number is too large to fit into an integer.
2330
Andrew M. Kuchlingacddabc2003-02-18 00:43:24 +00002331\item If you have Unicode strings that contain 8-bit characters, you
2332must declare the file's encoding (UTF-8, Latin-1, or whatever) by
2333adding a comment to the top of the file. See
2334section~\ref{section-encodings} for more information.
2335
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00002336\item Calling Tcl methods through \module{_tkinter} no longer
2337returns only strings. Instead, if Tcl returns other objects those
2338objects are converted to their Python equivalent, if one exists, or
2339wrapped with a \class{_tkinter.Tcl_Obj} object if no Python equivalent
2340exists.
2341
Andrew M. Kuchling80fd7852003-02-06 15:14:04 +00002342\item Large octal and hex literals such as
Andrew M. Kuchling72df65a2003-02-10 15:08:16 +00002343\code{0xffffffff} now trigger a \exception{FutureWarning}. Currently
Andrew M. Kuchling80fd7852003-02-06 15:14:04 +00002344they're stored as 32-bit numbers and result in a negative value, but
Andrew M. Kuchling72df65a2003-02-10 15:08:16 +00002345in Python 2.4 they'll become positive long integers.
2346
2347There are a few ways to fix this warning. If you really need a
2348positive number, just add an \samp{L} to the end of the literal. If
2349you're trying to get a 32-bit integer with low bits set and have
2350previously used an expression such as \code{~(1 << 31)}, it's probably
2351clearest to start with all bits set and clear the desired upper bits.
2352For example, to clear just the top bit (bit 31), you could write
2353\code{0xffffffffL {\&}{\textasciitilde}(1L<<31)}.
Andrew M. Kuchling80fd7852003-02-06 15:14:04 +00002354
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00002355\item You can no longer disable assertions by assigning to \code{__debug__}.
2356
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002357\item The Distutils \function{setup()} function has gained various new
Fred Drake5c4cf152002-11-13 14:59:06 +00002358keyword arguments such as \var{depends}. Old versions of the
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002359Distutils will abort if passed unknown keywords. A solution is to check
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002360for the presence of the new \function{get_distutil_options()} function
Andrew M. Kuchling8744f122003-07-17 23:56:58 +00002361in your \file{setup.py} and only uses the new keywords
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002362with a version of the Distutils that supports them:
2363
2364\begin{verbatim}
2365from distutils import core
2366
2367kw = {'sources': 'foo.c', ...}
2368if hasattr(core, 'get_distutil_options'):
2369 kw['depends'] = ['foo.h']
Fred Drake5c4cf152002-11-13 14:59:06 +00002370ext = Extension(**kw)
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002371\end{verbatim}
2372
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00002373\item Using \code{None} as a variable name will now result in a
2374\exception{SyntaxWarning} warning.
2375
2376\item Names of extension types defined by the modules included with
2377Python now contain the module and a \character{.} in front of the type
2378name.
2379
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002380\end{itemize}
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00002381
2382
2383%======================================================================
Fred Drake03e10312002-03-26 19:17:43 +00002384\section{Acknowledgements \label{acks}}
2385
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00002386The author would like to thank the following people for offering
2387suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +00002388article: Jeff Bauer, Simon Brunning, Brett Cannon, Michael Chermside,
Andrew M. Kuchling68a32942003-07-30 11:55:06 +00002389Andrew Dalke, Scott David Daniels, Fred~L. Drake, Jr., David Fraser,
2390Kelly Gerber,
Andrew M. Kuchlingd39078b2003-04-13 21:44:28 +00002391Raymond Hettinger, Michael Hudson, Chris Lambert, Detlef Lannert,
Andrew M. Kuchlingfcf6b3e2003-05-07 17:00:35 +00002392Martin von~L\"owis, Andrew MacIntyre, Lalo Martins, Chad Netzer,
2393Gustavo Niemeyer, Neal Norwitz, Hans Nowak, Chris Reedy, Francesco
2394Ricciardi, Vinay Sajip, Neil Schemenauer, Roman Suzi, Jason Tishler,
2395Just van~Rossum.
Fred Drake03e10312002-03-26 19:17:43 +00002396
2397\end{document}