blob: 2523e3c55882eb4b777b970bb38a73be484c9ec8 [file] [log] [blame]
Fred Drake03e10312002-03-26 19:17:43 +00001\documentclass{howto}
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00002% $Id$
3
4\title{What's New in Python 2.3}
Andrew M. Kuchlingd5ac8d02003-01-02 21:33:15 +00005\release{0.07}
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00006\author{A.M. Kuchling}
Andrew M. Kuchlingbc5e3cc2002-11-05 00:26:33 +00007\authoraddress{\email{amk@amk.ca}}
Fred Drake03e10312002-03-26 19:17:43 +00008
9\begin{document}
10\maketitle
11\tableofcontents
12
Andrew M. Kuchlingc61ec522002-08-04 01:20:05 +000013% MacOS framework-related changes (section of its own, probably)
Andrew M. Kuchlingf70a0a82002-06-10 13:22:46 +000014
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +000015%\section{Introduction \label{intro}}
16
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +000017{\large This article is a draft, and is currently up to date for
18Python 2.3alpha1. Please send any additions, comments or errata to
19the author.}
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +000020
21This article explains the new features in Python 2.3. The tentative
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +000022release date of Python 2.3 is currently scheduled for mid-2003.
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +000023
24This article doesn't attempt to provide a complete specification of
25the new features, but instead provides a convenient overview. For
26full details, you should refer to the documentation for Python 2.3,
27such as the
28\citetitle[http://www.python.org/doc/2.3/lib/lib.html]{Python Library
29Reference} and the
30\citetitle[http://www.python.org/doc/2.3/ref/ref.html]{Python
31Reference Manual}. If you want to understand the complete
32implementation and design rationale for a change, refer to the PEP for
33a particular new feature.
Fred Drake03e10312002-03-26 19:17:43 +000034
35
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +000036%======================================================================
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000037\section{PEP 218: A Standard Set Datatype}
38
39The new \module{sets} module contains an implementation of a set
40datatype. The \class{Set} class is for mutable sets, sets that can
41have members added and removed. The \class{ImmutableSet} class is for
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +000042sets that can't be modified, and instances of \class{ImmutableSet} can
43therefore be used as dictionary keys. Sets are built on top of
44dictionaries, so the elements within a set must be hashable.
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000045
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +000046Here's a simple example:
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000047
48\begin{verbatim}
49>>> import sets
50>>> S = sets.Set([1,2,3])
51>>> S
52Set([1, 2, 3])
53>>> 1 in S
54True
55>>> 0 in S
56False
57>>> S.add(5)
58>>> S.remove(3)
59>>> S
60Set([1, 2, 5])
Fred Drake5c4cf152002-11-13 14:59:06 +000061>>>
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000062\end{verbatim}
63
64The union and intersection of sets can be computed with the
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +000065\method{union()} and \method{intersection()} methods or
66alternatively using the bitwise operators \code{\&} and \code{|}.
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000067Mutable sets also have in-place versions of these methods,
68\method{union_update()} and \method{intersection_update()}.
69
70\begin{verbatim}
71>>> S1 = sets.Set([1,2,3])
72>>> S2 = sets.Set([4,5,6])
73>>> S1.union(S2)
74Set([1, 2, 3, 4, 5, 6])
75>>> S1 | S2 # Alternative notation
76Set([1, 2, 3, 4, 5, 6])
Fred Drake5c4cf152002-11-13 14:59:06 +000077>>> S1.intersection(S2)
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000078Set([])
79>>> S1 & S2 # Alternative notation
80Set([])
81>>> S1.union_update(S2)
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000082>>> S1
83Set([1, 2, 3, 4, 5, 6])
Fred Drake5c4cf152002-11-13 14:59:06 +000084>>>
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000085\end{verbatim}
86
87It's also possible to take the symmetric difference of two sets. This
88is the set of all elements in the union that aren't in the
89intersection. An alternative way of expressing the symmetric
90difference is that it contains all elements that are in exactly one
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +000091set. Again, there's an alternative notation (\code{\^}), and an
92in-place version with the ungainly name
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000093\method{symmetric_difference_update()}.
94
95\begin{verbatim}
96>>> S1 = sets.Set([1,2,3,4])
97>>> S2 = sets.Set([3,4,5,6])
98>>> S1.symmetric_difference(S2)
99Set([1, 2, 5, 6])
100>>> S1 ^ S2
101Set([1, 2, 5, 6])
102>>>
103\end{verbatim}
104
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000105There are also \method{issubset()} and \method{issuperset()} methods
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +0000106for checking whether one set is a strict subset or superset of
107another:
108
109\begin{verbatim}
110>>> S1 = sets.Set([1,2,3])
111>>> S2 = sets.Set([2,3])
112>>> S2.issubset(S1)
113True
114>>> S1.issubset(S2)
115False
116>>> S1.issuperset(S2)
117True
118>>>
119\end{verbatim}
120
121
122\begin{seealso}
123
124\seepep{218}{Adding a Built-In Set Object Type}{PEP written by Greg V. Wilson.
125Implemented by Greg V. Wilson, Alex Martelli, and GvR.}
126
127\end{seealso}
128
129
130
131%======================================================================
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000132\section{PEP 255: Simple Generators\label{section-generators}}
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000133
134In Python 2.2, generators were added as an optional feature, to be
135enabled by a \code{from __future__ import generators} directive. In
1362.3 generators no longer need to be specially enabled, and are now
137always present; this means that \keyword{yield} is now always a
138keyword. The rest of this section is a copy of the description of
139generators from the ``What's New in Python 2.2'' document; if you read
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000140it back when Python 2.2 came out, you can skip the rest of this section.
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000141
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000142You're doubtless familiar with how function calls work in Python or C.
143When you call a function, it gets a private namespace where its local
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000144variables are created. When the function reaches a \keyword{return}
145statement, the local variables are destroyed and the resulting value
146is returned to the caller. A later call to the same function will get
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000147a fresh new set of local variables. But, what if the local variables
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000148weren't thrown away on exiting a function? What if you could later
149resume the function where it left off? This is what generators
150provide; they can be thought of as resumable functions.
151
152Here's the simplest example of a generator function:
153
154\begin{verbatim}
155def generate_ints(N):
156 for i in range(N):
157 yield i
158\end{verbatim}
159
160A new keyword, \keyword{yield}, was introduced for generators. Any
161function containing a \keyword{yield} statement is a generator
162function; this is detected by Python's bytecode compiler which
Fred Drake5c4cf152002-11-13 14:59:06 +0000163compiles the function specially as a result.
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000164
165When you call a generator function, it doesn't return a single value;
166instead it returns a generator object that supports the iterator
167protocol. On executing the \keyword{yield} statement, the generator
168outputs the value of \code{i}, similar to a \keyword{return}
169statement. The big difference between \keyword{yield} and a
170\keyword{return} statement is that on reaching a \keyword{yield} the
171generator's state of execution is suspended and local variables are
172preserved. On the next call to the generator's \code{.next()} method,
173the function will resume executing immediately after the
174\keyword{yield} statement. (For complicated reasons, the
175\keyword{yield} statement isn't allowed inside the \keyword{try} block
176of a \code{try...finally} statement; read \pep{255} for a full
177explanation of the interaction between \keyword{yield} and
178exceptions.)
179
180Here's a sample usage of the \function{generate_ints} generator:
181
182\begin{verbatim}
183>>> gen = generate_ints(3)
184>>> gen
185<generator object at 0x8117f90>
186>>> gen.next()
1870
188>>> gen.next()
1891
190>>> gen.next()
1912
192>>> gen.next()
193Traceback (most recent call last):
Andrew M. Kuchling9f6e1042002-06-17 13:40:04 +0000194 File "stdin", line 1, in ?
195 File "stdin", line 2, in generate_ints
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000196StopIteration
197\end{verbatim}
198
199You could equally write \code{for i in generate_ints(5)}, or
200\code{a,b,c = generate_ints(3)}.
201
202Inside a generator function, the \keyword{return} statement can only
203be used without a value, and signals the end of the procession of
204values; afterwards the generator cannot return any further values.
205\keyword{return} with a value, such as \code{return 5}, is a syntax
206error inside a generator function. The end of the generator's results
207can also be indicated by raising \exception{StopIteration} manually,
208or by just letting the flow of execution fall off the bottom of the
209function.
210
211You could achieve the effect of generators manually by writing your
212own class and storing all the local variables of the generator as
213instance variables. For example, returning a list of integers could
214be done by setting \code{self.count} to 0, and having the
215\method{next()} method increment \code{self.count} and return it.
216However, for a moderately complicated generator, writing a
217corresponding class would be much messier.
218\file{Lib/test/test_generators.py} contains a number of more
219interesting examples. The simplest one implements an in-order
220traversal of a tree using generators recursively.
221
222\begin{verbatim}
223# A recursive generator that generates Tree leaves in in-order.
224def inorder(t):
225 if t:
226 for x in inorder(t.left):
227 yield x
228 yield t.label
229 for x in inorder(t.right):
230 yield x
231\end{verbatim}
232
233Two other examples in \file{Lib/test/test_generators.py} produce
234solutions for the N-Queens problem (placing $N$ queens on an $NxN$
235chess board so that no queen threatens another) and the Knight's Tour
236(a route that takes a knight to every square of an $NxN$ chessboard
Fred Drake5c4cf152002-11-13 14:59:06 +0000237without visiting any square twice).
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000238
239The idea of generators comes from other programming languages,
240especially Icon (\url{http://www.cs.arizona.edu/icon/}), where the
241idea of generators is central. In Icon, every
242expression and function call behaves like a generator. One example
243from ``An Overview of the Icon Programming Language'' at
244\url{http://www.cs.arizona.edu/icon/docs/ipd266.htm} gives an idea of
245what this looks like:
246
247\begin{verbatim}
248sentence := "Store it in the neighboring harbor"
249if (i := find("or", sentence)) > 5 then write(i)
250\end{verbatim}
251
252In Icon the \function{find()} function returns the indexes at which the
253substring ``or'' is found: 3, 23, 33. In the \keyword{if} statement,
254\code{i} is first assigned a value of 3, but 3 is less than 5, so the
255comparison fails, and Icon retries it with the second value of 23. 23
256is greater than 5, so the comparison now succeeds, and the code prints
257the value 23 to the screen.
258
259Python doesn't go nearly as far as Icon in adopting generators as a
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000260central concept. Generators are considered part of the core
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000261Python language, but learning or using them isn't compulsory; if they
262don't solve any problems that you have, feel free to ignore them.
263One novel feature of Python's interface as compared to
264Icon's is that a generator's state is represented as a concrete object
265(the iterator) that can be passed around to other functions or stored
266in a data structure.
267
268\begin{seealso}
269
270\seepep{255}{Simple Generators}{Written by Neil Schemenauer, Tim
271Peters, Magnus Lie Hetland. Implemented mostly by Neil Schemenauer
272and Tim Peters, with other fixes from the Python Labs crew.}
273
274\end{seealso}
275
276
277%======================================================================
Fred Drake13090e12002-08-22 16:51:08 +0000278\section{PEP 263: Source Code Encodings \label{section-encodings}}
Andrew M. Kuchling950725f2002-08-06 01:40:48 +0000279
280Python source files can now be declared as being in different
281character set encodings. Encodings are declared by including a
282specially formatted comment in the first or second line of the source
283file. For example, a UTF-8 file can be declared with:
284
285\begin{verbatim}
286#!/usr/bin/env python
287# -*- coding: UTF-8 -*-
288\end{verbatim}
289
290Without such an encoding declaration, the default encoding used is
Fred Drake5c4cf152002-11-13 14:59:06 +0000291ISO-8859-1, also known as Latin1.
Andrew M. Kuchling950725f2002-08-06 01:40:48 +0000292
293The encoding declaration only affects Unicode string literals; the
294text in the source code will be converted to Unicode using the
295specified encoding. Note that Python identifiers are still restricted
296to ASCII characters, so you can't have variable names that use
297characters outside of the usual alphanumerics.
298
299\begin{seealso}
300
301\seepep{263}{Defining Python Source Code Encodings}{Written by
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000302Marc-Andr\'e Lemburg and Martin von L\"owis; implemented by SUZUKI
303Hisao and Martin von L\"owis.}
Andrew M. Kuchling950725f2002-08-06 01:40:48 +0000304
305\end{seealso}
306
307
308%======================================================================
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000309\section{PEP 277: Unicode file name support for Windows NT}
Andrew M. Kuchling0f345562002-10-04 22:34:11 +0000310
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000311On Windows NT, 2000, and XP, the system stores file names as Unicode
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000312strings. Traditionally, Python has represented file names as byte
313strings, which is inadequate because it renders some file names
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000314inaccessible.
315
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000316Python now allows using arbitrary Unicode strings (within the
317limitations of the file system) for all functions that expect file
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000318names, most notably the \function{open()} built-in function. If a Unicode
319string is passed to \function{os.listdir()}, Python now returns a list
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000320of Unicode strings. A new function, \function{os.getcwdu()}, returns
321the current directory as a Unicode string.
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000322
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000323Byte strings still work as file names, and on Windows Python will
324transparently convert them to Unicode using the \code{mbcs} encoding.
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000325
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000326Other systems also allow Unicode strings as file names but convert
327them to byte strings before passing them to the system, which can
328cause a \exception{UnicodeError} to be raised. Applications can test
329whether arbitrary Unicode strings are supported as file names by
330checking \member{os.path.unicode_file_names}, a Boolean value.
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000331
332\begin{seealso}
333
334\seepep{277}{Unicode file name support for Windows NT}{Written by Neil
335Hodgson; implemented by Neil Hodgson, Martin von L\"owis, and Mark
336Hammond.}
337
338\end{seealso}
Andrew M. Kuchling0f345562002-10-04 22:34:11 +0000339
340
341%======================================================================
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000342\section{PEP 278: Universal Newline Support}
343
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000344The three major operating systems used today are Microsoft Windows,
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000345Apple's Macintosh OS, and the various \UNIX\ derivatives. A minor
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000346irritation is that these three platforms all use different characters
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000347to mark the ends of lines in text files. \UNIX\ uses the linefeed
348(ASCII character 10), while MacOS uses the carriage return (ASCII
349character 13), and Windows uses a two-character sequence containing a
350carriage return plus a newline.
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000351
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000352Python's file objects can now support end of line conventions other
353than the one followed by the platform on which Python is running.
Fred Drake5c4cf152002-11-13 14:59:06 +0000354Opening a file with the mode \code{'U'} or \code{'rU'} will open a file
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000355for reading in universal newline mode. All three line ending
Fred Drake5c4cf152002-11-13 14:59:06 +0000356conventions will be translated to a \character{\e n} in the strings
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000357returned by the various file methods such as \method{read()} and
Fred Drake5c4cf152002-11-13 14:59:06 +0000358\method{readline()}.
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000359
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000360Universal newline support is also used when importing modules and when
361executing a file with the \function{execfile()} function. This means
362that Python modules can be shared between all three operating systems
363without needing to convert the line-endings.
364
Fred Drake5c4cf152002-11-13 14:59:06 +0000365This feature can be disabled at compile-time by specifying
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000366\longprogramopt{without-universal-newlines} when running Python's
Fred Drake5c4cf152002-11-13 14:59:06 +0000367\program{configure} script.
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000368
369\begin{seealso}
370
Fred Drake5c4cf152002-11-13 14:59:06 +0000371\seepep{278}{Universal Newline Support}{Written
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000372and implemented by Jack Jansen.}
373
374\end{seealso}
375
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +0000376
377%======================================================================
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000378\section{PEP 279: The \function{enumerate()} Built-in Function\label{section-enumerate}}
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +0000379
380A new built-in function, \function{enumerate()}, will make
381certain loops a bit clearer. \code{enumerate(thing)}, where
382\var{thing} is either an iterator or a sequence, returns a iterator
383that will return \code{(0, \var{thing[0]})}, \code{(1,
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000384\var{thing[1]})}, \code{(2, \var{thing[2]})}, and so forth.
385
386Fairly often you'll see code to change every element of a list that
387looks like this:
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +0000388
389\begin{verbatim}
390for i in range(len(L)):
391 item = L[i]
392 # ... compute some result based on item ...
393 L[i] = result
394\end{verbatim}
395
396This can be rewritten using \function{enumerate()} as:
397
398\begin{verbatim}
399for i, item in enumerate(L):
400 # ... compute some result based on item ...
401 L[i] = result
402\end{verbatim}
403
404
405\begin{seealso}
406
Fred Drake5c4cf152002-11-13 14:59:06 +0000407\seepep{279}{The enumerate() built-in function}{Written
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000408and implemented by Raymond D. Hettinger.}
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +0000409
410\end{seealso}
411
412
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000413%======================================================================
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000414\section{PEP 282: The \module{logging} Package}
415
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000416A standard package for writing logs, \module{logging}, has been added
417to Python 2.3. It provides a powerful and flexible mechanism for
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000418components to generate logging output which can then be filtered and
419processed in various ways. A standard configuration file format can
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000420be used to control the logging behavior of a program. Python's
421standard library includes handlers that will write log records to
422standard error or to a file or socket, send them to the system log, or
423even e-mail them to a particular address, and of course it's also
424possible to write your own handler classes.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000425
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000426The \class{Logger} class is the primary class.
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000427Most application code will deal with one or more \class{Logger}
428objects, each one used by a particular subsystem of the application.
429Each \class{Logger} is identified by a name, and names are organized
430into a hierarchy using \samp{.} as the component separator. For
431example, you might have \class{Logger} instances named \samp{server},
432\samp{server.auth} and \samp{server.network}. The latter two
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000433instances are below \samp{server} in the hierarchy. This means that
434if you turn up the verbosity for \samp{server} or direct \samp{server}
435messages to a different handler, the changes will also apply to
436records logged to \samp{server.auth} and \samp{server.network}.
437There's also a root \class{Logger} that's the parent of all other
438loggers.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000439
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000440For simple uses, the \module{logging} package contains some
441convenience functions that always use the root log:
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000442
443\begin{verbatim}
444import logging
445
446logging.debug('Debugging information')
447logging.info('Informational message')
Andrew M. Kuchlingb1e4bf92002-12-03 13:35:17 +0000448logging.warn('Warning:config file %s not found', 'server.conf')
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000449logging.error('Error occurred')
450logging.critical('Critical error -- shutting down')
451\end{verbatim}
452
453This produces the following output:
454
455\begin{verbatim}
Andrew M. Kuchlingb1e4bf92002-12-03 13:35:17 +0000456WARN:root:Warning:config file server.conf not found
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000457ERROR:root:Error occurred
458CRITICAL:root:Critical error -- shutting down
459\end{verbatim}
460
461In the default configuration, informational and debugging messages are
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000462suppressed and the output is sent to standard error. You can enable
463the display of information and debugging messages by calling the
464\method{setLevel()} method on the root logger.
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000465
466Notice the \function{warn()} call's use of string formatting
467operators; all of the functions for logging messages take the
468arguments \code{(\var{msg}, \var{arg1}, \var{arg2}, ...)} and log the
469string resulting from \code{\var{msg} \% (\var{arg1}, \var{arg2},
470...)}.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000471
472There's also an \function{exception()} function that records the most
473recent traceback. Any of the other functions will also record the
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000474traceback if you specify a true value for the keyword argument
475\code{exc_info}.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000476
477\begin{verbatim}
478def f():
479 try: 1/0
480 except: logging.exception('Problem recorded')
481
482f()
483\end{verbatim}
484
485This produces the following output:
486
487\begin{verbatim}
488ERROR:root:Problem recorded
489Traceback (most recent call last):
490 File "t.py", line 6, in f
491 1/0
492ZeroDivisionError: integer division or modulo by zero
493\end{verbatim}
494
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000495Slightly more advanced programs will use a logger other than the root
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000496logger. The \function{getLogger(\var{name})} function is used to get
497a particular log, creating it if it doesn't exist yet.
Andrew M. Kuchlingb1e4bf92002-12-03 13:35:17 +0000498\function{getLogger(None)} returns the root logger.
499
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000500
501\begin{verbatim}
502log = logging.getLogger('server')
503 ...
504log.info('Listening on port %i', port)
505 ...
506log.critical('Disk full')
507 ...
508\end{verbatim}
509
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000510Log records are usually propagated up the hierarchy, so a message
511logged to \samp{server.auth} is also seen by \samp{server} and
512\samp{root}, but a handler can prevent this by setting its
Andrew M. Kuchlingb6f79592002-11-29 19:43:45 +0000513\member{propagate} attribute to \code{False}.
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000514
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000515There are more classes provided by the \module{logging} package that
516can be customized. When a \class{Logger} instance is told to log a
517message, it creates a \class{LogRecord} instance that is sent to any
518number of different \class{Handler} instances. Loggers and handlers
519can also have an attached list of filters, and each filter can cause
520the \class{LogRecord} to be ignored or can modify the record before
521passing it along. \class{LogRecord} instances are converted to text
522for output by a \class{Formatter} class. All of these classes can be
523replaced by your own specially-written classes.
524
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000525With all of these features the \module{logging} package should provide
526enough flexibility for even the most complicated applications. This
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000527is only a partial overview of the \module{logging} package, so please
528see the \ulink{package's reference
529documentation}{http://www.python.org/dev/doc/devel/lib/module-logging.html}
Andrew M. Kuchling9e7453d2002-11-25 16:02:13 +0000530for all of the details. Reading \pep{282} will also be helpful.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000531
532
533\begin{seealso}
534
535\seepep{282}{A Logging System}{Written by Vinay Sajip and Trent Mick;
536implemented by Vinay Sajip.}
537
538\end{seealso}
539
540
541%======================================================================
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000542\section{PEP 285: The \class{bool} Type\label{section-bool}}
543
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000544A Boolean type was added to Python 2.3. Two new constants were added
545to the \module{__builtin__} module, \constant{True} and
546\constant{False}. The type object for this new type is named
547\class{bool}; the constructor for it takes any Python value and
548converts it to \constant{True} or \constant{False}.
549
550\begin{verbatim}
551>>> bool(1)
552True
553>>> bool(0)
554False
555>>> bool([])
556False
557>>> bool( (1,) )
558True
559\end{verbatim}
560
561Most of the standard library modules and built-in functions have been
562changed to return Booleans.
563
564\begin{verbatim}
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000565>>> obj = []
566>>> hasattr(obj, 'append')
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000567True
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000568>>> isinstance(obj, list)
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000569True
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000570>>> isinstance(obj, tuple)
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000571False
572\end{verbatim}
573
574Python's Booleans were added with the primary goal of making code
575clearer. For example, if you're reading a function and encounter the
Fred Drake5c4cf152002-11-13 14:59:06 +0000576statement \code{return 1}, you might wonder whether the \code{1}
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000577represents a Boolean truth value, an index, or a
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000578coefficient that multiplies some other quantity. If the statement is
579\code{return True}, however, the meaning of the return value is quite
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000580clear.
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000581
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000582Python's Booleans were \emph{not} added for the sake of strict
583type-checking. A very strict language such as Pascal would also
584prevent you performing arithmetic with Booleans, and would require
585that the expression in an \keyword{if} statement always evaluate to a
586Boolean. Python is not this strict, and it never will be, as
587\pep{285} explicitly says. This means you can still use any
588expression in an \keyword{if} statement, even ones that evaluate to a
589list or tuple or some random object, and the Boolean type is a
590subclass of the \class{int} class so that arithmetic using a Boolean
591still works.
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000592
593\begin{verbatim}
594>>> True + 1
5952
596>>> False + 1
5971
598>>> False * 75
5990
600>>> True * 75
60175
602\end{verbatim}
603
604To sum up \constant{True} and \constant{False} in a sentence: they're
605alternative ways to spell the integer values 1 and 0, with the single
606difference that \function{str()} and \function{repr()} return the
Fred Drake5c4cf152002-11-13 14:59:06 +0000607strings \code{'True'} and \code{'False'} instead of \code{'1'} and
608\code{'0'}.
Andrew M. Kuchling3a52ff62002-04-03 22:44:47 +0000609
610\begin{seealso}
611
612\seepep{285}{Adding a bool type}{Written and implemented by GvR.}
613
614\end{seealso}
615
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000616
Andrew M. Kuchling65b72822002-09-03 00:53:21 +0000617%======================================================================
618\section{PEP 293: Codec Error Handling Callbacks}
619
Martin v. Löwis20eae692002-10-07 19:01:07 +0000620When encoding a Unicode string into a byte string, unencodable
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000621characters may be encountered. So far, Python has allowed specifying
622the error processing as either ``strict'' (raising
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000623\exception{UnicodeError}), ``ignore'' (skipping the character), or
624``replace'' (using a question mark in the output string), with
625``strict'' being the default behavior. It may be desirable to specify
626alternative processing of such errors, such as inserting an XML
627character reference or HTML entity reference into the converted
628string.
Martin v. Löwis20eae692002-10-07 19:01:07 +0000629
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +0000630Python now has a flexible framework to add different processing
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000631strategies. New error handlers can be added with
Martin v. Löwis20eae692002-10-07 19:01:07 +0000632\function{codecs.register_error}. Codecs then can access the error
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000633handler with \function{codecs.lookup_error}. An equivalent C API has
634been added for codecs written in C. The error handler gets the
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000635necessary state information such as the string being converted, the
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000636position in the string where the error was detected, and the target
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000637encoding. The handler can then either raise an exception or return a
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000638replacement string.
Martin v. Löwis20eae692002-10-07 19:01:07 +0000639
640Two additional error handlers have been implemented using this
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000641framework: ``backslashreplace'' uses Python backslash quoting to
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +0000642represent unencodable characters and ``xmlcharrefreplace'' emits
Martin v. Löwis20eae692002-10-07 19:01:07 +0000643XML character references.
Andrew M. Kuchling65b72822002-09-03 00:53:21 +0000644
645\begin{seealso}
646
Fred Drake5c4cf152002-11-13 14:59:06 +0000647\seepep{293}{Codec Error Handling Callbacks}{Written and implemented by
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000648Walter D\"orwald.}
Andrew M. Kuchling65b72822002-09-03 00:53:21 +0000649
650\end{seealso}
651
652
653%======================================================================
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000654\section{PEP 273: Importing Modules from Zip Archives}
655
656The new \module{zipimport} module adds support for importing
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000657modules from a ZIP-format archive. You don't need to import the
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000658module explicitly; it will be automatically imported if a ZIP
659archive's filename is added to \code{sys.path}. For example:
660
661\begin{verbatim}
662amk@nyman:~/src/python$ unzip -l /tmp/example.zip
663Archive: /tmp/example.zip
664 Length Date Time Name
665 -------- ---- ---- ----
666 8467 11-26-02 22:30 jwzthreading.py
667 -------- -------
668 8467 1 file
669amk@nyman:~/src/python$ ./python
670Python 2.3a0 (#1, Dec 30 2002, 19:54:32)
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000671>>> import sys
672>>> sys.path.insert(0, '/tmp/example.zip') # Add .zip file to front of path
673>>> import jwzthreading
674>>> jwzthreading.__file__
675'/tmp/example.zip/jwzthreading.py'
676>>>
677\end{verbatim}
678
679An entry in \code{sys.path} can now be the filename of a ZIP archive.
680The ZIP archive can contain any kind of files, but only files named
681\code{*.py}, \code{*.pyc}, or \code{*.pyo} can be imported. If an
682archive only contains \code{*.py} files, Python will not attempt to
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000683modify the archive by adding the corresponding \code{*.pyc} file, meaning
684that if a ZIP archive doesn't contain \code{*.pyc} files, importing may be
685rather slow.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000686
687A path within the archive can also be specified to only import from a
688subdirectory; for example, the path \file{/tmp/example.zip/lib/}
689would only import from the \file{lib/} subdirectory within the
690archive.
691
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000692\begin{seealso}
693
694\seepep{273}{Import Modules from Zip Archives}{Written by James C. Ahlstrom,
695who also provided an implementation.
696Python 2.3 follows the specification in \pep{273},
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +0000697but uses an implementation written by Just van~Rossum
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000698that uses the import hooks described in \pep{302}.
699See section~\ref{section-pep302} for a description of the new import hooks.
700}
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000701
702\end{seealso}
703
704%======================================================================
705\section{PEP 302: New Import Hooks \label{section-pep302}}
706
707While it's been possible to write custom import hooks ever since the
708\module{ihooks} module was introduced in Python 1.3, no one has ever
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000709been really happy with it because writing new import hooks is
710difficult and messy. There have been various proposed alternatives
711such as the \module{imputil} and \module{iu} modules, but none of them
712has ever gained much acceptance, and none of them were easily usable
713from \C{} code.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000714
715\pep{302} borrows ideas from its predecessors, especially from
716Gordon McMillan's \module{iu} module. Three new items
717are added to the \module{sys} module:
718
719\begin{itemize}
Andrew M. Kuchlingd5ac8d02003-01-02 21:33:15 +0000720 \item \code{sys.path_hooks} is a list of callable objects; most
721often they'll be classes. Each callable takes a string containing
722a path and either returns an importer object that will handle imports
723from this path or raises an \exception{ImportError} exception if it
724can't handle this path.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000725
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000726 \item \code{sys.path_importer_cache} caches importer objects for
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000727each path, so \code{sys.path_hooks} will only need to be traversed
728once for each path.
729
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000730 \item \code{sys.meta_path} is a list of importer objects that will
731 be traversed before \code{sys.path} is checked. This list is
732 initially empty, but user code can add objects to it. Additional
733 built-in and frozen modules can be imported by an object added to
734 this list.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000735
736\end{itemize}
737
738Importer objects must have a single method,
739\method{find_module(\var{fullname}, \var{path}=None)}. \var{fullname}
740will be a module or package name, e.g. \samp{string} or
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000741\samp{distutils.core}. \method{find_module()} must return a loader object
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000742that has a single method, \method{load_module(\var{fullname})}, that
743creates and returns the corresponding module object.
744
745Pseudo-code for Python's new import logic, therefore, looks something
746like this (simplified a bit; see \pep{302} for the full details):
747
748\begin{verbatim}
749for mp in sys.meta_path:
750 loader = mp(fullname)
751 if loader is not None:
Andrew M. Kuchlingd5ac8d02003-01-02 21:33:15 +0000752 <module> = loader.load_module(fullname)
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000753
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000754for path in sys.path:
755 for hook in sys.path_hooks:
Andrew M. Kuchlingd5ac8d02003-01-02 21:33:15 +0000756 try:
757 importer = hook(path)
758 except ImportError:
759 # ImportError, so try the other path hooks
760 pass
761 else:
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000762 loader = importer.find_module(fullname)
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000763 <module> = loader.load_module(fullname)
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000764
765# Not found!
766raise ImportError
767\end{verbatim}
768
769\begin{seealso}
770
771\seepep{302}{New Import Hooks}{Written by Just van~Rossum and Paul Moore.
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +0000772Implemented by Just van~Rossum.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000773}
774
775\end{seealso}
776
777
778%======================================================================
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000779\section{Extended Slices\label{section-slices}}
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000780
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000781Ever since Python 1.4, the slicing syntax has supported an optional
782third ``step'' or ``stride'' argument. For example, these are all
783legal Python syntax: \code{L[1:10:2]}, \code{L[:-1:1]},
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000784\code{L[::-1]}. This was added to Python at the request of
785the developers of Numerical Python, which uses the third argument
786extensively. However, Python's built-in list, tuple, and string
787sequence types have never supported this feature, and you got a
788\exception{TypeError} if you tried it. Michael Hudson contributed a
789patch to fix this shortcoming.
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000790
791For example, you can now easily extract the elements of a list that
792have even indexes:
Fred Drakedf872a22002-07-03 12:02:01 +0000793
794\begin{verbatim}
795>>> L = range(10)
796>>> L[::2]
797[0, 2, 4, 6, 8]
798\end{verbatim}
799
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000800Negative values also work to make a copy of the same list in reverse
801order:
Fred Drakedf872a22002-07-03 12:02:01 +0000802
803\begin{verbatim}
804>>> L[::-1]
805[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
806\end{verbatim}
Andrew M. Kuchling3a52ff62002-04-03 22:44:47 +0000807
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000808This also works for tuples, arrays, and strings:
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000809
810\begin{verbatim}
811>>> s='abcd'
812>>> s[::2]
813'ac'
814>>> s[::-1]
815'dcba'
816\end{verbatim}
817
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000818If you have a mutable sequence such as a list or an array you can
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000819assign to or delete an extended slice, but there are some differences
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000820between assignment to extended and regular slices. Assignment to a
821regular slice can be used to change the length of the sequence:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000822
823\begin{verbatim}
824>>> a = range(3)
825>>> a
826[0, 1, 2]
827>>> a[1:3] = [4, 5, 6]
828>>> a
829[0, 4, 5, 6]
830\end{verbatim}
831
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000832Extended slices aren't this flexible. When assigning to an extended
833slice the list on the right hand side of the statement must contain
834the same number of items as the slice it is replacing:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000835
836\begin{verbatim}
837>>> a = range(4)
838>>> a
839[0, 1, 2, 3]
840>>> a[::2]
841[0, 2]
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000842>>> a[::2] = [0, -1]
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000843>>> a
844[0, 1, -1, 3]
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000845>>> a[::2] = [0,1,2]
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000846Traceback (most recent call last):
847 File "<stdin>", line 1, in ?
848ValueError: attempt to assign list of size 3 to extended slice of size 2
849\end{verbatim}
850
851Deletion is more straightforward:
852
853\begin{verbatim}
854>>> a = range(4)
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000855>>> a
856[0, 1, 2, 3]
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000857>>> a[::2]
858[0, 2]
859>>> del a[::2]
860>>> a
861[1, 3]
862\end{verbatim}
863
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000864One can also now pass slice objects to the
865\method{__getitem__} methods of the built-in sequences:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000866
867\begin{verbatim}
868>>> range(10).__getitem__(slice(0, 5, 2))
869[0, 2, 4]
870\end{verbatim}
871
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000872Or use slice objects directly in subscripts:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000873
874\begin{verbatim}
875>>> range(10)[slice(0, 5, 2)]
876[0, 2, 4]
877\end{verbatim}
878
Andrew M. Kuchlingb6f79592002-11-29 19:43:45 +0000879To simplify implementing sequences that support extended slicing,
880slice objects now have a method \method{indices(\var{length})} which,
881given the length of a sequence, returns a \code{(start, stop, step)}
882tuple that can be passed directly to \function{range()}.
883\method{indices()} handles omitted and out-of-bounds indices in a
884manner consistent with regular slices (and this innocuous phrase hides
885a welter of confusing details!). The method is intended to be used
886like this:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000887
888\begin{verbatim}
889class FakeSeq:
890 ...
891 def calc_item(self, i):
892 ...
893 def __getitem__(self, item):
894 if isinstance(item, slice):
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000895 indices = item.indices(len(self))
896 return FakeSeq([self.calc_item(i) in range(*indices)])
Fred Drake5c4cf152002-11-13 14:59:06 +0000897 else:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000898 return self.calc_item(i)
899\end{verbatim}
900
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000901From this example you can also see that the built-in \class{slice}
Andrew M. Kuchling90e9a792002-08-15 00:40:21 +0000902object is now the type object for the slice type, and is no longer a
903function. This is consistent with Python 2.2, where \class{int},
904\class{str}, etc., underwent the same change.
905
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000906
Andrew M. Kuchling3a52ff62002-04-03 22:44:47 +0000907%======================================================================
Fred Drakedf872a22002-07-03 12:02:01 +0000908\section{Other Language Changes}
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000909
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000910Here are all of the changes that Python 2.3 makes to the core Python
911language.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000912
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000913\begin{itemize}
914\item The \keyword{yield} statement is now always a keyword, as
915described in section~\ref{section-generators} of this document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000916
Fred Drake5c4cf152002-11-13 14:59:06 +0000917\item A new built-in function \function{enumerate()}
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000918was added, as described in section~\ref{section-enumerate} of this
919document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000920
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000921\item Two new constants, \constant{True} and \constant{False} were
922added along with the built-in \class{bool} type, as described in
923section~\ref{section-bool} of this document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000924
Andrew M. Kuchling495172c2002-11-20 13:50:15 +0000925\item The \function{int()} type constructor will now return a long
926integer instead of raising an \exception{OverflowError} when a string
927or floating-point number is too large to fit into an integer. This
928can lead to the paradoxical result that
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000929\code{isinstance(int(\var{expression}), int)} is false, but that seems
930unlikely to cause problems in practice.
Andrew M. Kuchling495172c2002-11-20 13:50:15 +0000931
Fred Drake5c4cf152002-11-13 14:59:06 +0000932\item Built-in types now support the extended slicing syntax,
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000933as described in section~\ref{section-slices} of this document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000934
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000935\item Dictionaries have a new method, \method{pop(\var{key})}, that
936returns the value corresponding to \var{key} and removes that
937key/value pair from the dictionary. \method{pop()} will raise a
938\exception{KeyError} if the requested key isn't present in the
939dictionary:
940
941\begin{verbatim}
942>>> d = {1:2}
943>>> d
944{1: 2}
945>>> d.pop(4)
946Traceback (most recent call last):
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000947 File "stdin", line 1, in ?
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000948KeyError: 4
949>>> d.pop(1)
9502
951>>> d.pop(1)
952Traceback (most recent call last):
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000953 File "stdin", line 1, in ?
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000954KeyError: pop(): dictionary is empty
955>>> d
956{}
957>>>
958\end{verbatim}
959
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +0000960There's also a new class method,
961\method{dict.fromkeys(\var{iterable}, \var{value})}, that
962creates a dictionary with keys taken from the supplied iterator
963\var{iterable} and all values set to \var{value}, defaulting to
964\code{None}.
965
966(Patches contributed by Raymond Hettinger.)
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000967
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000968Also, the \function{dict()} constructor now accepts keyword arguments to
Raymond Hettinger45bda572002-12-14 20:20:45 +0000969simplify creating small dictionaries:
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +0000970
971\begin{verbatim}
972>>> dict(red=1, blue=2, green=3, black=4)
973{'blue': 2, 'black': 4, 'green': 3, 'red': 1}
974\end{verbatim}
975
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +0000976(Contributed by Just van~Rossum.)
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +0000977
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +0000978\item The \keyword{assert} statement no longer checks the \code{__debug__}
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +0000979flag, so you can no longer disable assertions by assigning to \code{__debug__}.
Fred Drake5c4cf152002-11-13 14:59:06 +0000980Running Python with the \programopt{-O} switch will still generate
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +0000981code that doesn't execute any assertions.
982
983\item Most type objects are now callable, so you can use them
984to create new objects such as functions, classes, and modules. (This
985means that the \module{new} module can be deprecated in a future
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000986Python version, because you can now use the type objects available in
987the \module{types} module.)
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +0000988% XXX should new.py use PendingDeprecationWarning?
989For example, you can create a new module object with the following code:
990
991\begin{verbatim}
992>>> import types
993>>> m = types.ModuleType('abc','docstring')
994>>> m
995<module 'abc' (built-in)>
996>>> m.__doc__
997'docstring'
998\end{verbatim}
999
Fred Drake5c4cf152002-11-13 14:59:06 +00001000\item
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001001A new warning, \exception{PendingDeprecationWarning} was added to
1002indicate features which are in the process of being
1003deprecated. The warning will \emph{not} be printed by default. To
1004check for use of features that will be deprecated in the future,
1005supply \programopt{-Walways::PendingDeprecationWarning::} on the
1006command line or use \function{warnings.filterwarnings()}.
1007
1008\item Using \code{None} as a variable name will now result in a
1009\exception{SyntaxWarning} warning. In a future version of Python,
1010\code{None} may finally become a keyword.
1011
Andrew M. Kuchlingb60ea3f2002-11-15 14:37:10 +00001012\item The method resolution order used by new-style classes has
1013changed, though you'll only notice the difference if you have a really
1014complicated inheritance hierarchy. (Classic classes are unaffected by
1015this change.) Python 2.2 originally used a topological sort of a
1016class's ancestors, but 2.3 now uses the C3 algorithm as described in
Andrew M. Kuchling6f429c32002-11-19 13:09:00 +00001017the paper \ulink{``A Monotonic Superclass Linearization for
1018Dylan''}{http://www.webcom.com/haahr/dylan/linearization-oopsla96.html}.
1019To understand the motivation for this change, read the thread on
1020python-dev starting with the message at
Andrew M. Kuchlingb60ea3f2002-11-15 14:37:10 +00001021\url{http://mail.python.org/pipermail/python-dev/2002-October/029035.html}.
1022Samuele Pedroni first pointed out the problem and also implemented the
1023fix by coding the C3 algorithm.
1024
Andrew M. Kuchlingdcfd8252002-09-13 22:21:42 +00001025\item Python runs multithreaded programs by switching between threads
1026after executing N bytecodes. The default value for N has been
1027increased from 10 to 100 bytecodes, speeding up single-threaded
1028applications by reducing the switching overhead. Some multithreaded
1029applications may suffer slower response time, but that's easily fixed
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001030by setting the limit back to a lower number using
Andrew M. Kuchlingdcfd8252002-09-13 22:21:42 +00001031\function{sys.setcheckinterval(\var{N})}.
1032
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001033\item One minor but far-reaching change is that the names of extension
1034types defined by the modules included with Python now contain the
Fred Drake5c4cf152002-11-13 14:59:06 +00001035module and a \character{.} in front of the type name. For example, in
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001036Python 2.2, if you created a socket and printed its
1037\member{__class__}, you'd get this output:
1038
1039\begin{verbatim}
1040>>> s = socket.socket()
1041>>> s.__class__
1042<type 'socket'>
1043\end{verbatim}
1044
1045In 2.3, you get this:
1046\begin{verbatim}
1047>>> s.__class__
1048<type '_socket.socket'>
1049\end{verbatim}
1050
Michael W. Hudson96bc3b42002-11-26 14:48:23 +00001051\item One of the noted incompatibilities between old- and new-style
1052 classes has been removed: you can now assign to the
1053 \member{__name__} and \member{__bases__} attributes of new-style
1054 classes. There are some restrictions on what can be assigned to
1055 \member{__bases__} along the lines of those relating to assigning to
1056 an instance's \member{__class__} attribute.
1057
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001058\end{itemize}
1059
1060
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001061%======================================================================
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001062\subsection{String Changes}
1063
1064\begin{itemize}
1065
1066\item The \code{in} operator now works differently for strings.
1067Previously, when evaluating \code{\var{X} in \var{Y}} where \var{X}
1068and \var{Y} are strings, \var{X} could only be a single character.
1069That's now changed; \var{X} can be a string of any length, and
1070\code{\var{X} in \var{Y}} will return \constant{True} if \var{X} is a
1071substring of \var{Y}. If \var{X} is the empty string, the result is
1072always \constant{True}.
1073
1074\begin{verbatim}
1075>>> 'ab' in 'abcd'
1076True
1077>>> 'ad' in 'abcd'
1078False
1079>>> '' in 'abcd'
1080True
1081\end{verbatim}
1082
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001083Note that this doesn't tell you where the substring starts; if you
1084need that information, you must use the \method{find()} method
1085instead.
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001086
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001087\item The \method{strip()}, \method{lstrip()}, and \method{rstrip()}
1088string methods now have an optional argument for specifying the
1089characters to strip. The default is still to remove all whitespace
1090characters:
1091
1092\begin{verbatim}
1093>>> ' abc '.strip()
1094'abc'
1095>>> '><><abc<><><>'.strip('<>')
1096'abc'
1097>>> '><><abc<><><>\n'.strip('<>')
1098'abc<><><>\n'
1099>>> u'\u4000\u4001abc\u4000'.strip(u'\u4000')
1100u'\u4001abc'
1101>>>
1102\end{verbatim}
1103
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001104(Suggested by Simon Brunning and implemented by Walter D\"orwald.)
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00001105
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001106\item The \method{startswith()} and \method{endswith()}
1107string methods now accept negative numbers for the start and end
1108parameters.
1109
1110\item Another new string method is \method{zfill()}, originally a
1111function in the \module{string} module. \method{zfill()} pads a
1112numeric string with zeros on the left until it's the specified width.
1113Note that the \code{\%} operator is still more flexible and powerful
1114than \method{zfill()}.
1115
1116\begin{verbatim}
1117>>> '45'.zfill(4)
1118'0045'
1119>>> '12345'.zfill(4)
1120'12345'
1121>>> 'goofy'.zfill(6)
1122'0goofy'
1123\end{verbatim}
1124
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00001125(Contributed by Walter D\"orwald.)
1126
Fred Drake5c4cf152002-11-13 14:59:06 +00001127\item A new type object, \class{basestring}, has been added.
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001128 Both 8-bit strings and Unicode strings inherit from this type, so
1129 \code{isinstance(obj, basestring)} will return \constant{True} for
1130 either kind of string. It's a completely abstract type, so you
1131 can't create \class{basestring} instances.
1132
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001133\item Interned strings are no longer immortal, and will now be
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001134garbage-collected in the usual way when the only reference to them is
1135from the internal dictionary of interned strings. (Implemented by
1136Oren Tirosh.)
1137
1138\end{itemize}
1139
1140
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001141%======================================================================
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001142\subsection{Optimizations}
1143
1144\begin{itemize}
1145
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001146\item The creation of new-style class instances has been made much
1147faster; they're now faster than classic classes!
1148
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001149\item The \method{sort()} method of list objects has been extensively
1150rewritten by Tim Peters, and the implementation is significantly
1151faster.
1152
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001153\item Multiplication of large long integers is now much faster thanks
1154to an implementation of Karatsuba multiplication, an algorithm that
1155scales better than the O(n*n) required for the grade-school
1156multiplication algorithm. (Original patch by Christopher A. Craig,
1157and significantly reworked by Tim Peters.)
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001158
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001159\item The \code{SET_LINENO} opcode is now gone. This may provide a
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001160small speed increase, depending on your compiler's idiosyncrasies.
1161See section~\ref{section-other} for a longer explanation.
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001162(Removed by Michael Hudson.)
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001163
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001164\item \function{xrange()} objects now have their own iterator, making
1165\code{for i in xrange(n)} slightly faster than
1166\code{for i in range(n)}. (Patch by Raymond Hettinger.)
1167
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001168\item A number of small rearrangements have been made in various
1169hotspots to improve performance, inlining a function here, removing
1170some code there. (Implemented mostly by GvR, but lots of people have
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001171contributed single changes.)
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001172
1173\end{itemize}
Neal Norwitzd68f5172002-05-29 15:54:55 +00001174
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001175
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001176%======================================================================
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00001177\section{New and Improved Modules}
1178
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001179As usual, Python's standard library received a number of enhancements and
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001180bug fixes. Here's a partial list of the most notable changes, sorted
1181alphabetically by module name. Consult the
1182\file{Misc/NEWS} file in the source tree for a more
1183complete list of changes, or look through the CVS logs for all the
1184details.
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00001185
1186\begin{itemize}
1187
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001188\item The \module{array} module now supports arrays of Unicode
Fred Drake5c4cf152002-11-13 14:59:06 +00001189characters using the \character{u} format character. Arrays also now
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001190support using the \code{+=} assignment operator to add another array's
1191contents, and the \code{*=} assignment operator to repeat an array.
1192(Contributed by Jason Orendorff.)
1193
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001194\item The \module{bsddb} module has been replaced by version 4.1.1
Andrew M. Kuchling669249e2002-11-19 13:05:33 +00001195of the \ulink{PyBSDDB}{http://pybsddb.sourceforge.net} package,
1196providing a more complete interface to the transactional features of
1197the BerkeleyDB library.
1198The old version of the module has been renamed to
1199\module{bsddb185} and is no longer built automatically; you'll
1200have to edit \file{Modules/Setup} to enable it. Note that the new
1201\module{bsddb} package is intended to be compatible with the
1202old module, so be sure to file bugs if you discover any
1203incompatibilities.
1204
Fred Drake5c4cf152002-11-13 14:59:06 +00001205\item The Distutils \class{Extension} class now supports
1206an extra constructor argument named \var{depends} for listing
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001207additional source files that an extension depends on. This lets
1208Distutils recompile the module if any of the dependency files are
Fred Drake5c4cf152002-11-13 14:59:06 +00001209modified. For example, if \file{sampmodule.c} includes the header
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001210file \file{sample.h}, you would create the \class{Extension} object like
1211this:
1212
1213\begin{verbatim}
1214ext = Extension("samp",
1215 sources=["sampmodule.c"],
1216 depends=["sample.h"])
1217\end{verbatim}
1218
1219Modifying \file{sample.h} would then cause the module to be recompiled.
1220(Contributed by Jeremy Hylton.)
1221
Andrew M. Kuchlingdc3f7e12002-11-04 20:05:10 +00001222\item Other minor changes to Distutils:
1223it now checks for the \envvar{CC}, \envvar{CFLAGS}, \envvar{CPP},
1224\envvar{LDFLAGS}, and \envvar{CPPFLAGS} environment variables, using
1225them to override the settings in Python's configuration (contributed
Andrew M. Kuchling53262572002-12-01 14:00:21 +00001226by Robert Weber); the \function{get_distutils_options()} method lists
Andrew M. Kuchlingdc3f7e12002-11-04 20:05:10 +00001227recently-added extensions to Distutils.
1228
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001229\item The \module{getopt} module gained a new function,
1230\function{gnu_getopt()}, that supports the same arguments as the existing
Fred Drake5c4cf152002-11-13 14:59:06 +00001231\function{getopt()} function but uses GNU-style scanning mode.
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001232The existing \function{getopt()} stops processing options as soon as a
1233non-option argument is encountered, but in GNU-style mode processing
1234continues, meaning that options and arguments can be mixed. For
1235example:
1236
1237\begin{verbatim}
1238>>> getopt.getopt(['-f', 'filename', 'output', '-v'], 'f:v')
1239([('-f', 'filename')], ['output', '-v'])
1240>>> getopt.gnu_getopt(['-f', 'filename', 'output', '-v'], 'f:v')
1241([('-f', 'filename'), ('-v', '')], ['output'])
1242\end{verbatim}
1243
1244(Contributed by Peter \AA{strand}.)
1245
1246\item The \module{grp}, \module{pwd}, and \module{resource} modules
Fred Drake5c4cf152002-11-13 14:59:06 +00001247now return enhanced tuples:
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001248
1249\begin{verbatim}
1250>>> import grp
1251>>> g = grp.getgrnam('amk')
1252>>> g.gr_name, g.gr_gid
1253('amk', 500)
1254\end{verbatim}
1255
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001256\item The \module{gzip} module can now handle files exceeding 2~Gb.
1257
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001258\item The new \module{heapq} module contains an implementation of a
1259heap queue algorithm. A heap is an array-like data structure that
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001260keeps items in a partially sorted order such that, for every index
1261\var{k}, \code{heap[\var{k}] <= heap[2*\var{k}+1]} and
1262\code{heap[\var{k}] <= heap[2*\var{k}+2]}. This makes it quick to
1263remove the smallest item, and inserting a new item while maintaining
1264the heap property is O(lg~n). (See
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001265\url{http://www.nist.gov/dads/HTML/priorityque.html} for more
1266information about the priority queue data structure.)
1267
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001268The \module{heapq} module provides \function{heappush()} and
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001269\function{heappop()} functions for adding and removing items while
1270maintaining the heap property on top of some other mutable Python
1271sequence type. For example:
1272
1273\begin{verbatim}
1274>>> import heapq
1275>>> heap = []
1276>>> for item in [3, 7, 5, 11, 1]:
1277... heapq.heappush(heap, item)
1278...
1279>>> heap
1280[1, 3, 5, 11, 7]
1281>>> heapq.heappop(heap)
12821
1283>>> heapq.heappop(heap)
12843
1285>>> heap
1286[5, 7, 11]
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001287\end{verbatim}
1288
1289(Contributed by Kevin O'Connor.)
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001290
Fred Drake5c4cf152002-11-13 14:59:06 +00001291\item Two new functions in the \module{math} module,
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001292\function{degrees(\var{rads})} and \function{radians(\var{degs})},
Fred Drake5c4cf152002-11-13 14:59:06 +00001293convert between radians and degrees. Other functions in the
Andrew M. Kuchling8e5b53b2002-12-15 20:17:38 +00001294\module{math} module such as \function{math.sin()} and
1295\function{math.cos()} have always required input values measured in
1296radians. Also, an optional \var{base} argument was added to
1297\function{math.log()} to make it easier to compute logarithms for
1298bases other than \code{e} and \code{10}. (Contributed by Raymond
1299Hettinger.)
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001300
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +00001301\item Several new functions (\function{getpgid()}, \function{killpg()},
1302\function{lchown()}, \function{loadavg()}, \function{major()}, \function{makedev()},
1303\function{minor()}, and \function{mknod()}) were added to the
Andrew M. Kuchlingc309cca2002-10-10 16:04:08 +00001304\module{posix} module that underlies the \module{os} module.
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +00001305(Contributed by Gustavo Niemeyer, Geert Jansen, and Denis S. Otkidach.)
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001306
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001307\item In the \module{os} module, the \function{*stat()} family of functions can now report
1308fractions of a second in a timestamp. Such time stamps are
1309represented as floats, similar to \function{time.time()}.
1310
1311During testing, it was found that some applications will break if time
1312stamps are floats. For compatibility, when using the tuple interface
1313of the \class{stat_result} time stamps will be represented as integers.
1314When using named fields (a feature first introduced in Python 2.2),
1315time stamps are still represented as integers, unless
1316\function{os.stat_float_times()} is invoked to enable float return
1317values:
1318
1319\begin{verbatim}
1320>>> os.stat("/tmp").st_mtime
13211034791200
1322>>> os.stat_float_times(True)
1323>>> os.stat("/tmp").st_mtime
13241034791200.6335014
1325\end{verbatim}
1326
1327In Python 2.4, the default will change to always returning floats.
1328
1329Application developers should enable this feature only if all their
1330libraries work properly when confronted with floating point time
1331stamps, or if they use the tuple API. If used, the feature should be
1332activated on an application level instead of trying to enable it on a
1333per-use basis.
1334
Andrew M. Kuchling53262572002-12-01 14:00:21 +00001335\item The old and never-documented \module{linuxaudiodev} module has
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001336been deprecated, and a new version named \module{ossaudiodev} has been
1337added. The module was renamed because the OSS sound drivers can be
1338used on platforms other than Linux, and the interface has also been
1339tidied and brought up to date in various ways. (Contributed by Greg
1340Ward.)
Andrew M. Kuchling53262572002-12-01 14:00:21 +00001341
Fred Drake5c4cf152002-11-13 14:59:06 +00001342\item The parser objects provided by the \module{pyexpat} module
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001343can now optionally buffer character data, resulting in fewer calls to
1344your character data handler and therefore faster performance. Setting
Fred Drake5c4cf152002-11-13 14:59:06 +00001345the parser object's \member{buffer_text} attribute to \constant{True}
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001346will enable buffering.
1347
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001348\item The \function{sample(\var{population}, \var{k})} function was
1349added to the \module{random} module. \var{population} is a sequence
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001350or \code{xrange} object containing the elements of a population, and \function{sample()}
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001351chooses \var{k} elements from the population without replacing chosen
1352elements. \var{k} can be any value up to \code{len(\var{population})}.
1353For example:
1354
1355\begin{verbatim}
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001356>>> days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'St', 'Sn']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001357>>> random.sample(days, 3) # Choose 3 elements
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001358['St', 'Sn', 'Th']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001359>>> random.sample(days, 7) # Choose 7 elements
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001360['Tu', 'Th', 'Mo', 'We', 'St', 'Fr', 'Sn']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001361>>> random.sample(days, 7) # Choose 7 again
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001362['We', 'Mo', 'Sn', 'Fr', 'Tu', 'St', 'Th']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001363>>> random.sample(days, 8) # Can't choose eight
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001364Traceback (most recent call last):
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +00001365 File "<stdin>", line 1, in ?
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001366 File "random.py", line 414, in sample
1367 raise ValueError, "sample larger than population"
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001368ValueError: sample larger than population
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001369>>> random.sample(xrange(1,10000,2), 10) # Choose ten odd nos. under 10000
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001370[3407, 3805, 1505, 7023, 2401, 2267, 9733, 3151, 8083, 9195]
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001371\end{verbatim}
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001372
1373The \module{random} module now uses a new algorithm, the Mersenne
1374Twister, implemented in C. It's faster and more extensively studied
1375than the previous algorithm.
1376
1377(All changes contributed by Raymond Hettinger.)
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001378
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001379\item The \module{readline} module also gained a number of new
1380functions: \function{get_history_item()},
1381\function{get_current_history_length()}, and \function{redisplay()}.
1382
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001383\item The \module{shutil} module gained a \function{move(\var{src},
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001384\var{dest})} function that recursively moves a file or directory to a new
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001385location.
1386
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001387\item Support for more advanced POSIX signal handling was added
1388to the \module{signal} module by adding the \function{sigpending},
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001389\function{sigprocmask} and \function{sigsuspend} functions where supported
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001390by the platform. These functions make it possible to avoid some previously
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001391unavoidable race conditions with signal handling.
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001392
1393\item The \module{socket} module now supports timeouts. You
1394can call the \method{settimeout(\var{t})} method on a socket object to
1395set a timeout of \var{t} seconds. Subsequent socket operations that
1396take longer than \var{t} seconds to complete will abort and raise a
Fred Drake5c4cf152002-11-13 14:59:06 +00001397\exception{socket.error} exception.
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001398
1399The original timeout implementation was by Tim O'Malley. Michael
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001400Gilfix integrated it into the Python \module{socket} module and
1401shepherded it through a lengthy review. After the code was checked
1402in, Guido van~Rossum rewrote parts of it. (This is a good example of
1403a collaborative development process in action.)
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001404
Mark Hammond8af50bc2002-12-03 06:13:35 +00001405\item On Windows, the \module{socket} module now ships with Secure
1406Sockets Library (SSL) support.
1407
Fred Drake5c4cf152002-11-13 14:59:06 +00001408\item The value of the C \constant{PYTHON_API_VERSION} macro is now exposed
Fred Drake583db0d2002-09-14 02:03:25 +00001409at the Python level as \code{sys.api_version}.
Andrew M. Kuchlingdcfd8252002-09-13 22:21:42 +00001410
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001411\item The new \module{textwrap} module contains functions for wrapping
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001412strings containing paragraphs of text. The \function{wrap(\var{text},
1413\var{width})} function takes a string and returns a list containing
1414the text split into lines of no more than the chosen width. The
1415\function{fill(\var{text}, \var{width})} function returns a single
1416string, reformatted to fit into lines no longer than the chosen width.
1417(As you can guess, \function{fill()} is built on top of
1418\function{wrap()}. For example:
1419
1420\begin{verbatim}
1421>>> import textwrap
1422>>> paragraph = "Not a whit, we defy augury: ... more text ..."
1423>>> textwrap.wrap(paragraph, 60)
Fred Drake5c4cf152002-11-13 14:59:06 +00001424["Not a whit, we defy augury: there's a special providence in",
1425 "the fall of a sparrow. If it be now, 'tis not to come; if it",
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001426 ...]
1427>>> print textwrap.fill(paragraph, 35)
1428Not a whit, we defy augury: there's
1429a special providence in the fall of
1430a sparrow. If it be now, 'tis not
1431to come; if it be not to come, it
1432will be now; if it be not now, yet
1433it will come: the readiness is all.
Fred Drake5c4cf152002-11-13 14:59:06 +00001434>>>
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001435\end{verbatim}
1436
1437The module also contains a \class{TextWrapper} class that actually
Fred Drake5c4cf152002-11-13 14:59:06 +00001438implements the text wrapping strategy. Both the
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001439\class{TextWrapper} class and the \function{wrap()} and
1440\function{fill()} functions support a number of additional keyword
1441arguments for fine-tuning the formatting; consult the module's
Fred Drake5c4cf152002-11-13 14:59:06 +00001442documentation for details.
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001443%XXX add a link to the module docs?
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001444(Contributed by Greg Ward.)
1445
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001446\item The \module{thread} and \module{threading} modules now have
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001447companion modules, \module{dummy_thread} and \module{dummy_threading},
1448that provide a do-nothing implementation of the \module{thread}
1449module's interface for platforms where threads are not supported. The
1450intention is to simplify thread-aware modules (ones that \emph{don't}
1451rely on threads to run) by putting the following code at the top:
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001452
1453% XXX why as _threading?
1454\begin{verbatim}
1455try:
1456 import threading as _threading
1457except ImportError:
1458 import dummy_threading as _threading
1459\end{verbatim}
1460
1461Code can then call functions and use classes in \module{_threading}
1462whether or not threads are supported, avoiding an \keyword{if}
1463statement and making the code slightly clearer. This module will not
1464magically make multithreaded code run without threads; code that waits
1465for another thread to return or to do something will simply hang
1466forever.
1467
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001468\item The \module{time} module's \function{strptime()} function has
Fred Drake5c4cf152002-11-13 14:59:06 +00001469long been an annoyance because it uses the platform C library's
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001470\function{strptime()} implementation, and different platforms
1471sometimes have odd bugs. Brett Cannon contributed a portable
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001472implementation that's written in pure Python and should behave
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001473identically on all platforms.
1474
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001475\item The \module{UserDict} module has a new \class{DictMixin} class which
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001476defines all dictionary methods for classes that already have a minimum
1477mapping interface. This greatly simplifies writing classes that need
1478to be substitutable for dictionaries, such as the classes in
1479the \module{shelve} module.
1480
1481Adding the mixin as a superclass provides the full dictionary
1482interface whenever the class defines \method{__getitem__},
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001483\method{__setitem__}, \method{__delitem__}, and \method{keys}.
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001484For example:
1485
1486\begin{verbatim}
1487>>> import UserDict
1488>>> class SeqDict(UserDict.DictMixin):
1489 """Dictionary lookalike implemented with lists."""
1490 def __init__(self):
1491 self.keylist = []
1492 self.valuelist = []
1493 def __getitem__(self, key):
1494 try:
1495 i = self.keylist.index(key)
1496 except ValueError:
1497 raise KeyError
1498 return self.valuelist[i]
1499 def __setitem__(self, key, value):
1500 try:
1501 i = self.keylist.index(key)
1502 self.valuelist[i] = value
1503 except ValueError:
1504 self.keylist.append(key)
1505 self.valuelist.append(value)
1506 def __delitem__(self, key):
1507 try:
1508 i = self.keylist.index(key)
1509 except ValueError:
1510 raise KeyError
1511 self.keylist.pop(i)
1512 self.valuelist.pop(i)
1513 def keys(self):
1514 return list(self.keylist)
1515
1516>>> s = SeqDict()
1517>>> dir(s) # See that other dictionary methods are implemented
1518['__cmp__', '__contains__', '__delitem__', '__doc__', '__getitem__',
1519 '__init__', '__iter__', '__len__', '__module__', '__repr__',
1520 '__setitem__', 'clear', 'get', 'has_key', 'items', 'iteritems',
1521 'iterkeys', 'itervalues', 'keylist', 'keys', 'pop', 'popitem',
1522 'setdefault', 'update', 'valuelist', 'values']
Neal Norwitzc7d8c682002-12-24 14:51:43 +00001523\end{verbatim}
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001524
1525(Contributed by Raymond Hettinger.)
1526
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001527\item The DOM implementation
1528in \module{xml.dom.minidom} can now generate XML output in a
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001529particular encoding by providing an optional encoding argument to
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001530the \method{toxml()} and \method{toprettyxml()} methods of DOM nodes.
1531
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001532\item The \module{Tkinter} module now works with a thread-enabled
1533version of Tcl. Tcl's threading model requires that widgets only be
1534accessed from the thread in which they're created; accesses from
1535another thread can cause Tcl to panic. For certain Tcl interfaces,
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001536\module{Tkinter} will now automatically avoid this
1537when a widget is accessed from a different thread by marshalling a
1538command, passing it to the correct thread, and waiting for the
1539results. Other interfaces can't be handled automatically but
1540\module{Tkinter} will now raise an exception on such an access so that
1541at least you can find out about the problem. See
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001542\url{http://mail.python.org/pipermail/python-dev/2002-December/031107.html}
1543for a more detailed explanation of this change. (Implemented by
1544Martin von L\"owis.)
1545
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001546\item Calling Tcl methods through \module{_tkinter} no longer
1547returns only strings. Instead, if Tcl returns other objects those
1548objects are converted to their Python equivalent, if one exists, or
1549wrapped with a \class{_tkinter.Tcl_Obj} object if no Python equivalent
Raymond Hettinger45bda572002-12-14 20:20:45 +00001550exists. This behavior can be controlled through the
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001551\method{wantobjects()} method of \class{tkapp} objects.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001552
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001553When using \module{_tkinter} through the \module{Tkinter} module (as
1554most Tkinter applications will), this feature is always activated. It
1555should not cause compatibility problems, since Tkinter would always
1556convert string results to Python types where possible.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001557
Raymond Hettinger45bda572002-12-14 20:20:45 +00001558If any incompatibilities are found, the old behavior can be restored
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001559by setting the \member{wantobjects} variable in the \module{Tkinter}
1560module to false before creating the first \class{tkapp} object.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001561
1562\begin{verbatim}
1563import Tkinter
Martin v. Löwis8c8aa5d2002-11-26 21:39:48 +00001564Tkinter.wantobjects = 0
Martin v. Löwis39b48522002-11-26 09:47:25 +00001565\end{verbatim}
1566
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001567Any breakage caused by this change should be reported as a bug.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001568
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00001569\end{itemize}
1570
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00001571
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001572%======================================================================
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001573\subsection{The \module{optparse} Module}
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001574
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001575The \module{getopt} module provides simple parsing of command-line
1576arguments. The new \module{optparse} module (originally named Optik)
1577provides more elaborate command-line parsing that follows the Unix
1578conventions, automatically creates the output for \longprogramopt{help},
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001579and can perform different actions for different options.
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001580
1581You start by creating an instance of \class{OptionParser} and telling
1582it what your program's options are.
1583
1584\begin{verbatim}
1585from optparse import OptionParser
1586
1587op = OptionParser()
1588op.add_option('-i', '--input',
1589 action='store', type='string', dest='input',
1590 help='set input filename')
1591op.add_option('-l', '--length',
1592 action='store', type='int', dest='length',
1593 help='set maximum length of output')
1594\end{verbatim}
1595
1596Parsing a command line is then done by calling the \method{parse_args()}
1597method.
1598
1599\begin{verbatim}
1600options, args = op.parse_args(sys.argv[1:])
1601print options
1602print args
1603\end{verbatim}
1604
1605This returns an object containing all of the option values,
1606and a list of strings containing the remaining arguments.
1607
1608Invoking the script with the various arguments now works as you'd
1609expect it to. Note that the length argument is automatically
1610converted to an integer.
1611
1612\begin{verbatim}
1613$ ./python opt.py -i data arg1
1614<Values at 0x400cad4c: {'input': 'data', 'length': None}>
1615['arg1']
1616$ ./python opt.py --input=data --length=4
1617<Values at 0x400cad2c: {'input': 'data', 'length': 4}>
1618['arg1']
1619$
1620\end{verbatim}
1621
1622The help message is automatically generated for you:
1623
1624\begin{verbatim}
1625$ ./python opt.py --help
1626usage: opt.py [options]
1627
1628options:
1629 -h, --help show this help message and exit
1630 -iINPUT, --input=INPUT
1631 set input filename
1632 -lLENGTH, --length=LENGTH
1633 set maximum length of output
1634$
1635\end{verbatim}
Andrew M. Kuchling669249e2002-11-19 13:05:33 +00001636% $ prevent Emacs tex-mode from getting confused
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001637
1638Optik was written by Greg Ward, with suggestions from the readers of
1639the Getopt SIG.
1640
1641\begin{seealso}
1642\seeurl{http://optik.sourceforge.net}
1643{The Optik site has tutorial and reference documentation for
1644\module{optparse}.
1645% XXX change to point to Python docs, when those docs get written.
1646}
1647\end{seealso}
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001648
1649
1650%======================================================================
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001651\section{Specialized Object Allocator (pymalloc)\label{section-pymalloc}}
1652
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001653An experimental feature added to Python 2.1 was pymalloc, a
1654specialized object allocator written by Vladimir Marangozov. Pymalloc
1655is intended to be faster than the system \cfunction{malloc()} and
1656to have less memory overhead for allocation patterns typical of Python
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001657programs. The allocator uses C's \cfunction{malloc()} function to get
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001658large pools of memory and then fulfills smaller memory requests from
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001659these pools.
1660
1661In 2.1 and 2.2, pymalloc was an experimental feature and wasn't
1662enabled by default; you had to explicitly turn it on by providing the
1663\longprogramopt{with-pymalloc} option to the \program{configure}
1664script. In 2.3, pymalloc has had further enhancements and is now
1665enabled by default; you'll have to supply
1666\longprogramopt{without-pymalloc} to disable it.
1667
1668This change is transparent to code written in Python; however,
1669pymalloc may expose bugs in C extensions. Authors of C extension
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001670modules should test their code with pymalloc enabled,
1671because some incorrect code may cause core dumps at runtime.
1672
1673There's one particularly common error that causes problems. There are
1674a number of memory allocation functions in Python's C API that have
1675previously just been aliases for the C library's \cfunction{malloc()}
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001676and \cfunction{free()}, meaning that if you accidentally called
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001677mismatched functions the error wouldn't be noticeable. When the
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001678object allocator is enabled, these functions aren't aliases of
1679\cfunction{malloc()} and \cfunction{free()} any more, and calling the
1680wrong function to free memory may get you a core dump. For example,
1681if memory was allocated using \cfunction{PyObject_Malloc()}, it has to
1682be freed using \cfunction{PyObject_Free()}, not \cfunction{free()}. A
1683few modules included with Python fell afoul of this and had to be
1684fixed; doubtless there are more third-party modules that will have the
1685same problem.
1686
1687As part of this change, the confusing multiple interfaces for
1688allocating memory have been consolidated down into two API families.
1689Memory allocated with one family must not be manipulated with
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001690functions from the other family. There is one family for allocating
1691chunks of memory, and another family of functions specifically for
1692allocating Python objects.
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001693
1694\begin{itemize}
1695 \item To allocate and free an undistinguished chunk of memory use
1696 the ``raw memory'' family: \cfunction{PyMem_Malloc()},
1697 \cfunction{PyMem_Realloc()}, and \cfunction{PyMem_Free()}.
1698
1699 \item The ``object memory'' family is the interface to the pymalloc
1700 facility described above and is biased towards a large number of
1701 ``small'' allocations: \cfunction{PyObject_Malloc},
1702 \cfunction{PyObject_Realloc}, and \cfunction{PyObject_Free}.
1703
1704 \item To allocate and free Python objects, use the ``object'' family
1705 \cfunction{PyObject_New()}, \cfunction{PyObject_NewVar()}, and
1706 \cfunction{PyObject_Del()}.
1707\end{itemize}
1708
1709Thanks to lots of work by Tim Peters, pymalloc in 2.3 also provides
1710debugging features to catch memory overwrites and doubled frees in
1711both extension modules and in the interpreter itself. To enable this
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001712support, compile a debugging version of the Python interpreter by
1713running \program{configure} with \longprogramopt{with-pydebug}.
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001714
1715To aid extension writers, a header file \file{Misc/pymemcompat.h} is
1716distributed with the source to Python 2.3 that allows Python
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001717extensions to use the 2.3 interfaces to memory allocation while
1718compiling against any version of Python since 1.5.2. You would copy
1719the file from Python's source distribution and bundle it with the
1720source of your extension.
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001721
1722\begin{seealso}
1723
1724\seeurl{http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Objects/obmalloc.c}
1725{For the full details of the pymalloc implementation, see
1726the comments at the top of the file \file{Objects/obmalloc.c} in the
1727Python source code. The above link points to the file within the
1728SourceForge CVS browser.}
1729
1730\end{seealso}
1731
1732
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00001733% ======================================================================
1734\section{Build and C API Changes}
1735
Andrew M. Kuchling3c305d92002-07-22 18:50:11 +00001736Changes to Python's build process and to the C API include:
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00001737
1738\begin{itemize}
1739
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001740\item The C-level interface to the garbage collector has been changed,
1741to make it easier to write extension types that support garbage
1742collection, and to make it easier to debug misuses of the functions.
1743Various functions have slightly different semantics, so a bunch of
1744functions had to be renamed. Extensions that use the old API will
1745still compile but will \emph{not} participate in garbage collection,
1746so updating them for 2.3 should be considered fairly high priority.
1747
1748To upgrade an extension module to the new API, perform the following
1749steps:
1750
1751\begin{itemize}
1752
1753\item Rename \cfunction{Py_TPFLAGS_GC} to \cfunction{PyTPFLAGS_HAVE_GC}.
1754
1755\item Use \cfunction{PyObject_GC_New} or \cfunction{PyObject_GC_NewVar} to
1756allocate objects, and \cfunction{PyObject_GC_Del} to deallocate them.
1757
1758\item Rename \cfunction{PyObject_GC_Init} to \cfunction{PyObject_GC_Track} and
1759\cfunction{PyObject_GC_Fini} to \cfunction{PyObject_GC_UnTrack}.
1760
1761\item Remove \cfunction{PyGC_HEAD_SIZE} from object size calculations.
1762
1763\item Remove calls to \cfunction{PyObject_AS_GC} and \cfunction{PyObject_FROM_GC}.
1764
1765\end{itemize}
1766
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001767\item The cycle detection implementation used by the garbage collection
1768has proven to be stable, so it's now being made mandatory; you can no
1769longer compile Python without it, and the
1770\longprogramopt{with-cycle-gc} switch to \program{configure} has been removed.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001771
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001772\item Python can now optionally be built as a shared library
1773(\file{libpython2.3.so}) by supplying \longprogramopt{enable-shared}
Fred Drake5c4cf152002-11-13 14:59:06 +00001774when running Python's \program{configure} script. (Contributed by Ondrej
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +00001775Palkovsky.)
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +00001776
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001777\item The \csimplemacro{DL_EXPORT} and \csimplemacro{DL_IMPORT} macros
1778are now deprecated. Initialization functions for Python extension
1779modules should now be declared using the new macro
Andrew M. Kuchling3c305d92002-07-22 18:50:11 +00001780\csimplemacro{PyMODINIT_FUNC}, while the Python core will generally
1781use the \csimplemacro{PyAPI_FUNC} and \csimplemacro{PyAPI_DATA}
1782macros.
Neal Norwitzbba23a82002-07-22 13:18:59 +00001783
Fred Drake5c4cf152002-11-13 14:59:06 +00001784\item The interpreter can be compiled without any docstrings for
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001785the built-in functions and modules by supplying
Fred Drake5c4cf152002-11-13 14:59:06 +00001786\longprogramopt{without-doc-strings} to the \program{configure} script.
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001787This makes the Python executable about 10\% smaller, but will also
1788mean that you can't get help for Python's built-ins. (Contributed by
1789Gustavo Niemeyer.)
1790
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001791\item The \cfunction{PyArg_NoArgs()} macro is now deprecated, and code
Andrew M. Kuchling7845e7c2002-07-11 19:27:46 +00001792that uses it should be changed. For Python 2.2 and later, the method
1793definition table can specify the
Fred Drake5c4cf152002-11-13 14:59:06 +00001794\constant{METH_NOARGS} flag, signalling that there are no arguments, and
Andrew M. Kuchling7845e7c2002-07-11 19:27:46 +00001795the argument checking can then be removed. If compatibility with
1796pre-2.2 versions of Python is important, the code could use
Fred Drake5c4cf152002-11-13 14:59:06 +00001797\code{PyArg_ParseTuple(args, "")} instead, but this will be slower
Andrew M. Kuchling7845e7c2002-07-11 19:27:46 +00001798than using \constant{METH_NOARGS}.
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00001799
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001800\item A new function, \cfunction{PyObject_DelItemString(\var{mapping},
1801char *\var{key})} was added
Fred Drake5c4cf152002-11-13 14:59:06 +00001802as shorthand for
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001803\code{PyObject_DelItem(\var{mapping}, PyString_New(\var{key})}.
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00001804
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001805\item The \method{xreadlines()} method of file objects, introduced in
1806Python 2.1, is no longer necessary because files now behave as their
1807own iterator. \method{xreadlines()} was originally introduced as a
1808faster way to loop over all the lines in a file, but now you can
1809simply write \code{for line in file_obj}.
1810
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001811\item File objects now manage their internal string buffer
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001812differently, increasing it exponentially when needed. This results in
1813the benchmark tests in \file{Lib/test/test_bufio.py} speeding up
1814considerably (from 57 seconds to 1.7 seconds, according to one
1815measurement).
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001816
Andrew M. Kuchling72b58e02002-05-29 17:30:34 +00001817\item It's now possible to define class and static methods for a C
1818extension type by setting either the \constant{METH_CLASS} or
1819\constant{METH_STATIC} flags in a method's \ctype{PyMethodDef}
1820structure.
Andrew M. Kuchling45afd542002-04-02 14:25:25 +00001821
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00001822\item Python now includes a copy of the Expat XML parser's source code,
1823removing any dependence on a system version or local installation of
Fred Drake5c4cf152002-11-13 14:59:06 +00001824Expat.
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00001825
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00001826\end{itemize}
1827
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001828
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001829%======================================================================
1830\subsection{Date/Time Type}
1831
1832Date and time types suitable for expressing timestamps were added as
1833the \module{datetime} module. The types don't support different
Andrew M. Kuchling5095a472002-12-31 02:48:59 +00001834calendars or many fancy features, and just stick to the basics of
1835representing time.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001836
1837The three primary types are: \class{date}, representing a day, month,
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001838and year; \class{time}, consisting of hour, minute, and second; and
1839\class{datetime}, which contains all the attributes of both
1840\class{date} and \class{time}. These basic types don't understand
1841time zones, but there are subclasses named \class{timetz} and
1842\class{datetimetz} that do. There's also a
Andrew M. Kuchling5095a472002-12-31 02:48:59 +00001843\class{timedelta} class representing a difference between two points
1844in time, and time zone logic is implemented by classes inheriting from
1845the abstract \class{tzinfo} class.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001846
Andrew M. Kuchling5095a472002-12-31 02:48:59 +00001847You can create instances of \class{date} and \class{time} by either
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001848supplying keyword arguments to the appropriate constructor,
Andrew M. Kuchling5095a472002-12-31 02:48:59 +00001849e.g. \code{datetime.date(year=1972, month=10, day=15)}, or by using
1850one of a number of class methods. For example, the \method{today()}
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001851class method returns the current local date.
Andrew M. Kuchling5095a472002-12-31 02:48:59 +00001852
1853Once created, instances of the date/time classes are all immutable.
1854There are a number of methods for producing formatted strings from
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001855objects:
Andrew M. Kuchling5095a472002-12-31 02:48:59 +00001856
1857\begin{verbatim}
1858>>> import datetime
1859>>> now = datetime.datetime.now()
1860>>> now.isoformat()
1861'2002-12-30T21:27:03.994956'
1862>>> now.ctime() # Only available on date, datetime
1863'Mon Dec 30 21:27:03 2002'
1864>>> now.strftime('%Y %d %h')
1865'2002 30 Dec'
1866\end{verbatim}
1867
1868The \method{replace()} method allows modifying one or more fields
1869of a \class{date} or \class{datetime} instance:
1870
1871\begin{verbatim}
1872>>> d = datetime.datetime.now()
1873>>> d
1874datetime.datetime(2002, 12, 30, 22, 15, 38, 827738)
1875>>> d.replace(year=2001, hour = 12)
1876datetime.datetime(2001, 12, 30, 12, 15, 38, 827738)
1877>>>
1878\end{verbatim}
1879
1880Instances can be compared, hashed, and converted to strings (the
1881result is the same as that of \method{isoformat()}). \class{date} and
1882\class{datetime} instances can be subtracted from each other, and
1883added to \class{timedelta} instances.
1884
1885For more information, refer to the \ulink{module's reference
1886documentation}{http://www.python.org/dev/doc/devel/lib/module-datetime.html}.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001887
1888
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001889%======================================================================
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00001890\subsection{Port-Specific Changes}
1891
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00001892Support for a port to IBM's OS/2 using the EMX runtime environment was
1893merged into the main Python source tree. EMX is a POSIX emulation
1894layer over the OS/2 system APIs. The Python port for EMX tries to
1895support all the POSIX-like capability exposed by the EMX runtime, and
1896mostly succeeds; \function{fork()} and \function{fcntl()} are
1897restricted by the limitations of the underlying emulation layer. The
1898standard OS/2 port, which uses IBM's Visual Age compiler, also gained
1899support for case-sensitive import semantics as part of the integration
1900of the EMX port into CVS. (Contributed by Andrew MacIntyre.)
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00001901
Andrew M. Kuchling72b58e02002-05-29 17:30:34 +00001902On MacOS, most toolbox modules have been weaklinked to improve
1903backward compatibility. This means that modules will no longer fail
1904to load if a single routine is missing on the curent OS version.
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00001905Instead calling the missing routine will raise an exception.
1906(Contributed by Jack Jansen.)
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00001907
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00001908The RPM spec files, found in the \file{Misc/RPM/} directory in the
1909Python source distribution, were updated for 2.3. (Contributed by
1910Sean Reifschneider.)
Fred Drake03e10312002-03-26 19:17:43 +00001911
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001912Other new platforms now supported by Python include AtheOS
1913(\url{http://www.atheos.cx}), GNU/Hurd, and OpenVMS.
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001914
Fred Drake03e10312002-03-26 19:17:43 +00001915
1916%======================================================================
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001917\section{Other Changes and Fixes \label{section-other}}
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001918
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +00001919As usual, there were a bunch of other improvements and bugfixes
1920scattered throughout the source tree. A search through the CVS change
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001921logs finds there were 121 patches applied and 103 bugs fixed between
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +00001922Python 2.2 and 2.3. Both figures are likely to be underestimates.
1923
1924Some of the more notable changes are:
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001925
1926\begin{itemize}
1927
Fred Drake54fe3fd2002-11-26 22:07:35 +00001928\item The \file{regrtest.py} script now provides a way to allow ``all
1929resources except \var{foo}.'' A resource name passed to the
1930\programopt{-u} option can now be prefixed with a hyphen
1931(\character{-}) to mean ``remove this resource.'' For example, the
1932option `\code{\programopt{-u}all,-bsddb}' could be used to enable the
1933use of all resources except \code{bsddb}.
1934
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001935\item The tools used to build the documentation now work under Cygwin
1936as well as \UNIX.
1937
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001938\item The \code{SET_LINENO} opcode has been removed. Back in the
1939mists of time, this opcode was needed to produce line numbers in
1940tracebacks and support trace functions (for, e.g., \module{pdb}).
1941Since Python 1.5, the line numbers in tracebacks have been computed
1942using a different mechanism that works with ``python -O''. For Python
19432.3 Michael Hudson implemented a similar scheme to determine when to
1944call the trace function, removing the need for \code{SET_LINENO}
1945entirely.
1946
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +00001947It would be difficult to detect any resulting difference from Python
1948code, apart from a slight speed up when Python is run without
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001949\programopt{-O}.
1950
1951C extensions that access the \member{f_lineno} field of frame objects
1952should instead call \code{PyCode_Addr2Line(f->f_code, f->f_lasti)}.
1953This will have the added effect of making the code work as desired
1954under ``python -O'' in earlier versions of Python.
1955
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001956A nifty new feature is that trace functions can now assign to the
1957\member{f_lineno} attribute of frame objects, changing the line that
1958will be executed next. A \samp{jump} command has been added to the
1959\module{pdb} debugger taking advantage of this new feature.
1960(Implemented by Richie Hindle.)
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001961
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001962\end{itemize}
1963
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00001964
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001965%======================================================================
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001966\section{Porting to Python 2.3}
1967
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001968This section lists previously described changes that may require
1969changes to your code:
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001970
1971\begin{itemize}
1972
1973\item \keyword{yield} is now always a keyword; if it's used as a
1974variable name in your code, a different name must be chosen.
1975
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001976\item For strings \var{X} and \var{Y}, \code{\var{X} in \var{Y}} now works
1977if \var{X} is more than one character long.
1978
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00001979\item The \function{int()} type constructor will now return a long
1980integer instead of raising an \exception{OverflowError} when a string
1981or floating-point number is too large to fit into an integer.
1982
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001983\item Calling Tcl methods through \module{_tkinter} no longer
1984returns only strings. Instead, if Tcl returns other objects those
1985objects are converted to their Python equivalent, if one exists, or
1986wrapped with a \class{_tkinter.Tcl_Obj} object if no Python equivalent
1987exists.
1988
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00001989\item You can no longer disable assertions by assigning to \code{__debug__}.
1990
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001991\item The Distutils \function{setup()} function has gained various new
Fred Drake5c4cf152002-11-13 14:59:06 +00001992keyword arguments such as \var{depends}. Old versions of the
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001993Distutils will abort if passed unknown keywords. The fix is to check
1994for the presence of the new \function{get_distutil_options()} function
1995in your \file{setup.py} if you want to only support the new keywords
1996with a version of the Distutils that supports them:
1997
1998\begin{verbatim}
1999from distutils import core
2000
2001kw = {'sources': 'foo.c', ...}
2002if hasattr(core, 'get_distutil_options'):
2003 kw['depends'] = ['foo.h']
Fred Drake5c4cf152002-11-13 14:59:06 +00002004ext = Extension(**kw)
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002005\end{verbatim}
2006
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00002007\item Using \code{None} as a variable name will now result in a
2008\exception{SyntaxWarning} warning.
2009
2010\item Names of extension types defined by the modules included with
2011Python now contain the module and a \character{.} in front of the type
2012name.
2013
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002014\end{itemize}
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00002015
2016
2017%======================================================================
Fred Drake03e10312002-03-26 19:17:43 +00002018\section{Acknowledgements \label{acks}}
2019
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00002020The author would like to thank the following people for offering
2021suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00002022article: Simon Brunning, Michael Chermside, Scott David Daniels,
Andrew M. Kuchlingd5ac8d02003-01-02 21:33:15 +00002023Fred~L. Drake, Jr., Kelly Gerber, Raymond Hettinger, Michael Hudson,
2024Detlef Lannert, Martin von L\"owis, Andrew MacIntyre, Lalo Martins,
2025Gustavo Niemeyer, Neal Norwitz, Hans Nowak, Chris Reedy, Vinay Sajip,
2026Neil Schemenauer, Jason Tishler, Just van~Rossum.
Fred Drake03e10312002-03-26 19:17:43 +00002027
2028\end{document}