blob: 3e5d0a2807a7023935c317ef978743049a0799af [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. Kuchling5095a472002-12-31 02:48:59 +00005\release{0.06}
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. Kuchling20e5abc2002-07-11 20:50:34 +000022release date of Python 2.3 is currently scheduled for some undefined
23time before the end of 2002.
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +000024
25This article doesn't attempt to provide a complete specification of
26the new features, but instead provides a convenient overview. For
27full details, you should refer to the documentation for Python 2.3,
28such as the
29\citetitle[http://www.python.org/doc/2.3/lib/lib.html]{Python Library
30Reference} and the
31\citetitle[http://www.python.org/doc/2.3/ref/ref.html]{Python
32Reference Manual}. If you want to understand the complete
33implementation and design rationale for a change, refer to the PEP for
34a particular new feature.
Fred Drake03e10312002-03-26 19:17:43 +000035
36
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +000037%======================================================================
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000038\section{PEP 218: A Standard Set Datatype}
39
40The new \module{sets} module contains an implementation of a set
41datatype. The \class{Set} class is for mutable sets, sets that can
42have members added and removed. The \class{ImmutableSet} class is for
43sets that can't be modified, and can be used as dictionary keys. Sets
44are built on top of dictionaries, so the elements within a set must be
45hashable.
46
Fred Drake5c4cf152002-11-13 14:59:06 +000047As a simple example,
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000048
49\begin{verbatim}
50>>> import sets
51>>> S = sets.Set([1,2,3])
52>>> S
53Set([1, 2, 3])
54>>> 1 in S
55True
56>>> 0 in S
57False
58>>> S.add(5)
59>>> S.remove(3)
60>>> S
61Set([1, 2, 5])
Fred Drake5c4cf152002-11-13 14:59:06 +000062>>>
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000063\end{verbatim}
64
65The union and intersection of sets can be computed with the
66\method{union()} and \method{intersection()} methods, or,
Fred Drake5c4cf152002-11-13 14:59:06 +000067alternatively, using the bitwise operators \code{\&} and \code{|}.
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000068Mutable sets also have in-place versions of these methods,
69\method{union_update()} and \method{intersection_update()}.
70
71\begin{verbatim}
72>>> S1 = sets.Set([1,2,3])
73>>> S2 = sets.Set([4,5,6])
74>>> S1.union(S2)
75Set([1, 2, 3, 4, 5, 6])
76>>> S1 | S2 # Alternative notation
77Set([1, 2, 3, 4, 5, 6])
Fred Drake5c4cf152002-11-13 14:59:06 +000078>>> S1.intersection(S2)
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000079Set([])
80>>> S1 & S2 # Alternative notation
81Set([])
82>>> S1.union_update(S2)
83Set([1, 2, 3, 4, 5, 6])
84>>> S1
85Set([1, 2, 3, 4, 5, 6])
Fred Drake5c4cf152002-11-13 14:59:06 +000086>>>
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000087\end{verbatim}
88
89It's also possible to take the symmetric difference of two sets. This
90is the set of all elements in the union that aren't in the
91intersection. An alternative way of expressing the symmetric
92difference is that it contains all elements that are in exactly one
93set. Again, there's an in-place version, with the ungainly name
94\method{symmetric_difference_update()}.
95
96\begin{verbatim}
97>>> S1 = sets.Set([1,2,3,4])
98>>> S2 = sets.Set([3,4,5,6])
99>>> S1.symmetric_difference(S2)
100Set([1, 2, 5, 6])
101>>> S1 ^ S2
102Set([1, 2, 5, 6])
103>>>
104\end{verbatim}
105
106There are also methods, \method{issubset()} and \method{issuperset()},
107for checking whether one set is a strict subset or superset of
108another:
109
110\begin{verbatim}
111>>> S1 = sets.Set([1,2,3])
112>>> S2 = sets.Set([2,3])
113>>> S2.issubset(S1)
114True
115>>> S1.issubset(S2)
116False
117>>> S1.issuperset(S2)
118True
119>>>
120\end{verbatim}
121
122
123\begin{seealso}
124
125\seepep{218}{Adding a Built-In Set Object Type}{PEP written by Greg V. Wilson.
126Implemented by Greg V. Wilson, Alex Martelli, and GvR.}
127
128\end{seealso}
129
130
131
132%======================================================================
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000133\section{PEP 255: Simple Generators\label{section-generators}}
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000134
135In Python 2.2, generators were added as an optional feature, to be
136enabled by a \code{from __future__ import generators} directive. In
1372.3 generators no longer need to be specially enabled, and are now
138always present; this means that \keyword{yield} is now always a
139keyword. The rest of this section is a copy of the description of
140generators from the ``What's New in Python 2.2'' document; if you read
141it when 2.2 came out, you can skip the rest of this section.
142
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000143You're doubtless familiar with how function calls work in Python or C.
144When you call a function, it gets a private namespace where its local
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000145variables are created. When the function reaches a \keyword{return}
146statement, the local variables are destroyed and the resulting value
147is returned to the caller. A later call to the same function will get
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000148a fresh new set of local variables. But, what if the local variables
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000149weren't thrown away on exiting a function? What if you could later
150resume the function where it left off? This is what generators
151provide; they can be thought of as resumable functions.
152
153Here's the simplest example of a generator function:
154
155\begin{verbatim}
156def generate_ints(N):
157 for i in range(N):
158 yield i
159\end{verbatim}
160
161A new keyword, \keyword{yield}, was introduced for generators. Any
162function containing a \keyword{yield} statement is a generator
163function; this is detected by Python's bytecode compiler which
Fred Drake5c4cf152002-11-13 14:59:06 +0000164compiles the function specially as a result.
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000165
166When you call a generator function, it doesn't return a single value;
167instead it returns a generator object that supports the iterator
168protocol. On executing the \keyword{yield} statement, the generator
169outputs the value of \code{i}, similar to a \keyword{return}
170statement. The big difference between \keyword{yield} and a
171\keyword{return} statement is that on reaching a \keyword{yield} the
172generator's state of execution is suspended and local variables are
173preserved. On the next call to the generator's \code{.next()} method,
174the function will resume executing immediately after the
175\keyword{yield} statement. (For complicated reasons, the
176\keyword{yield} statement isn't allowed inside the \keyword{try} block
177of a \code{try...finally} statement; read \pep{255} for a full
178explanation of the interaction between \keyword{yield} and
179exceptions.)
180
181Here's a sample usage of the \function{generate_ints} generator:
182
183\begin{verbatim}
184>>> gen = generate_ints(3)
185>>> gen
186<generator object at 0x8117f90>
187>>> gen.next()
1880
189>>> gen.next()
1901
191>>> gen.next()
1922
193>>> gen.next()
194Traceback (most recent call last):
Andrew M. Kuchling9f6e1042002-06-17 13:40:04 +0000195 File "stdin", line 1, in ?
196 File "stdin", line 2, in generate_ints
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000197StopIteration
198\end{verbatim}
199
200You could equally write \code{for i in generate_ints(5)}, or
201\code{a,b,c = generate_ints(3)}.
202
203Inside a generator function, the \keyword{return} statement can only
204be used without a value, and signals the end of the procession of
205values; afterwards the generator cannot return any further values.
206\keyword{return} with a value, such as \code{return 5}, is a syntax
207error inside a generator function. The end of the generator's results
208can also be indicated by raising \exception{StopIteration} manually,
209or by just letting the flow of execution fall off the bottom of the
210function.
211
212You could achieve the effect of generators manually by writing your
213own class and storing all the local variables of the generator as
214instance variables. For example, returning a list of integers could
215be done by setting \code{self.count} to 0, and having the
216\method{next()} method increment \code{self.count} and return it.
217However, for a moderately complicated generator, writing a
218corresponding class would be much messier.
219\file{Lib/test/test_generators.py} contains a number of more
220interesting examples. The simplest one implements an in-order
221traversal of a tree using generators recursively.
222
223\begin{verbatim}
224# A recursive generator that generates Tree leaves in in-order.
225def inorder(t):
226 if t:
227 for x in inorder(t.left):
228 yield x
229 yield t.label
230 for x in inorder(t.right):
231 yield x
232\end{verbatim}
233
234Two other examples in \file{Lib/test/test_generators.py} produce
235solutions for the N-Queens problem (placing $N$ queens on an $NxN$
236chess board so that no queen threatens another) and the Knight's Tour
237(a route that takes a knight to every square of an $NxN$ chessboard
Fred Drake5c4cf152002-11-13 14:59:06 +0000238without visiting any square twice).
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000239
240The idea of generators comes from other programming languages,
241especially Icon (\url{http://www.cs.arizona.edu/icon/}), where the
242idea of generators is central. In Icon, every
243expression and function call behaves like a generator. One example
244from ``An Overview of the Icon Programming Language'' at
245\url{http://www.cs.arizona.edu/icon/docs/ipd266.htm} gives an idea of
246what this looks like:
247
248\begin{verbatim}
249sentence := "Store it in the neighboring harbor"
250if (i := find("or", sentence)) > 5 then write(i)
251\end{verbatim}
252
253In Icon the \function{find()} function returns the indexes at which the
254substring ``or'' is found: 3, 23, 33. In the \keyword{if} statement,
255\code{i} is first assigned a value of 3, but 3 is less than 5, so the
256comparison fails, and Icon retries it with the second value of 23. 23
257is greater than 5, so the comparison now succeeds, and the code prints
258the value 23 to the screen.
259
260Python doesn't go nearly as far as Icon in adopting generators as a
261central concept. Generators are considered a new part of the core
262Python language, but learning or using them isn't compulsory; if they
263don't solve any problems that you have, feel free to ignore them.
264One novel feature of Python's interface as compared to
265Icon's is that a generator's state is represented as a concrete object
266(the iterator) that can be passed around to other functions or stored
267in a data structure.
268
269\begin{seealso}
270
271\seepep{255}{Simple Generators}{Written by Neil Schemenauer, Tim
272Peters, Magnus Lie Hetland. Implemented mostly by Neil Schemenauer
273and Tim Peters, with other fixes from the Python Labs crew.}
274
275\end{seealso}
276
277
278%======================================================================
Fred Drake13090e12002-08-22 16:51:08 +0000279\section{PEP 263: Source Code Encodings \label{section-encodings}}
Andrew M. Kuchling950725f2002-08-06 01:40:48 +0000280
281Python source files can now be declared as being in different
282character set encodings. Encodings are declared by including a
283specially formatted comment in the first or second line of the source
284file. For example, a UTF-8 file can be declared with:
285
286\begin{verbatim}
287#!/usr/bin/env python
288# -*- coding: UTF-8 -*-
289\end{verbatim}
290
291Without such an encoding declaration, the default encoding used is
Fred Drake5c4cf152002-11-13 14:59:06 +0000292ISO-8859-1, also known as Latin1.
Andrew M. Kuchling950725f2002-08-06 01:40:48 +0000293
294The encoding declaration only affects Unicode string literals; the
295text in the source code will be converted to Unicode using the
296specified encoding. Note that Python identifiers are still restricted
297to ASCII characters, so you can't have variable names that use
298characters outside of the usual alphanumerics.
299
300\begin{seealso}
301
302\seepep{263}{Defining Python Source Code Encodings}{Written by
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000303Marc-Andr\'e Lemburg and Martin von L\"owis; implemented by SUZUKI
304Hisao and Martin von L\"owis.}
Andrew M. Kuchling950725f2002-08-06 01:40:48 +0000305
306\end{seealso}
307
308
309%======================================================================
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000310\section{PEP 277: Unicode file name support for Windows NT}
Andrew M. Kuchling0f345562002-10-04 22:34:11 +0000311
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000312On Windows NT, 2000, and XP, the system stores file names as Unicode
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000313strings. Traditionally, Python has represented file names as byte
314strings, which is inadequate because it renders some file names
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000315inaccessible.
316
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000317Python now allows using arbitrary Unicode strings (within the
318limitations of the file system) for all functions that expect file
319names, in particular the \function{open()} built-in. If a Unicode
320string is passed to \function{os.listdir}, Python now returns a list
321of Unicode strings. A new function, \function{os.getcwdu()}, returns
322the current directory as a Unicode string.
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000323
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000324Byte strings still work as file names, and Python will transparently
325convert them to Unicode using the \code{mbcs} encoding.
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000326
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000327Other systems also allow Unicode strings as file names, but convert
328them to byte strings before passing them to the system which may cause
329a \exception{UnicodeError} to be raised. Applications can test whether
330arbitrary Unicode strings are supported as file names by checking
331\member{os.path.unicode_file_names}, a Boolean value.
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000332
333\begin{seealso}
334
335\seepep{277}{Unicode file name support for Windows NT}{Written by Neil
336Hodgson; implemented by Neil Hodgson, Martin von L\"owis, and Mark
337Hammond.}
338
339\end{seealso}
Andrew M. Kuchling0f345562002-10-04 22:34:11 +0000340
341
342%======================================================================
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000343\section{PEP 278: Universal Newline Support}
344
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000345The three major operating systems used today are Microsoft Windows,
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000346Apple's Macintosh OS, and the various \UNIX\ derivatives. A minor
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000347irritation is that these three platforms all use different characters
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000348to mark the ends of lines in text files. \UNIX\ uses character 10,
349the ASCII linefeed, while MacOS uses character 13, the ASCII carriage
350return, and Windows uses a two-character sequence of a carriage return
351plus a newline.
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000352
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000353Python's file objects can now support end of line conventions other
354than the one followed by the platform on which Python is running.
Fred Drake5c4cf152002-11-13 14:59:06 +0000355Opening a file with the mode \code{'U'} or \code{'rU'} will open a file
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000356for reading in universal newline mode. All three line ending
Fred Drake5c4cf152002-11-13 14:59:06 +0000357conventions will be translated to a \character{\e n} in the strings
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000358returned by the various file methods such as \method{read()} and
Fred Drake5c4cf152002-11-13 14:59:06 +0000359\method{readline()}.
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000360
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000361Universal newline support is also used when importing modules and when
362executing a file with the \function{execfile()} function. This means
363that Python modules can be shared between all three operating systems
364without needing to convert the line-endings.
365
Fred Drake5c4cf152002-11-13 14:59:06 +0000366This feature can be disabled at compile-time by specifying
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000367\longprogramopt{without-universal-newlines} when running Python's
Fred Drake5c4cf152002-11-13 14:59:06 +0000368\program{configure} script.
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000369
370\begin{seealso}
371
Fred Drake5c4cf152002-11-13 14:59:06 +0000372\seepep{278}{Universal Newline Support}{Written
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000373and implemented by Jack Jansen.}
374
375\end{seealso}
376
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +0000377
378%======================================================================
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000379\section{PEP 279: The \function{enumerate()} Built-in Function\label{section-enumerate}}
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +0000380
381A new built-in function, \function{enumerate()}, will make
382certain loops a bit clearer. \code{enumerate(thing)}, where
383\var{thing} is either an iterator or a sequence, returns a iterator
384that will return \code{(0, \var{thing[0]})}, \code{(1,
385\var{thing[1]})}, \code{(2, \var{thing[2]})}, and so forth. Fairly
386often you'll see code to change every element of a list that looks
387like this:
388
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. Kuchlingfad2f592002-05-10 21:00:05 +0000408by Raymond D. Hettinger.}
409
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. Kuchling366c10c2002-11-14 23:07:57 +0000416A standard package for writing logs called \module{logging} has been
417added to Python 2.3. It provides a powerful and flexible way for
418components to generate logging output which can then be filtered and
419processed in various ways. A standard configuration file format can
Raymond Hettinger45bda572002-12-14 20:20:45 +0000420be used to control the logging behavior of a program. Python comes
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000421with handlers that will write log records to standard error or to a
422file or socket, send them to the system log, or even e-mail them to a
423particular address, and of course it's also possible to write your own
424handler classes.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000425
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000426Most application code will deal with one or more \class{Logger}
427objects, each one used by a particular subsystem of the application.
428Each \class{Logger} is identified by a name, and names are organized
429into a hierarchy using \samp{.} as the component separator. For
430example, you might have \class{Logger} instances named \samp{server},
431\samp{server.auth} and \samp{server.network}. The latter two
432instances fall under the \samp{server} \class{Logger} in the
433hierarchy. This means that if you turn up the verbosity for
434\samp{server} or direct \samp{server} messages to a different handler,
435the changes will also apply to records logged to \samp{server.auth}
Andrew M. Kuchlingb1e4bf92002-12-03 13:35:17 +0000436and \samp{server.network}. There's also a root \class{Logger} that's
437the parent of all other loggers.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000438
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000439For simple uses, the \module{logging} package contains some
440convenience functions that always use the root log:
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000441
442\begin{verbatim}
443import logging
444
445logging.debug('Debugging information')
446logging.info('Informational message')
Andrew M. Kuchlingb1e4bf92002-12-03 13:35:17 +0000447logging.warn('Warning:config file %s not found', 'server.conf')
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000448logging.error('Error occurred')
449logging.critical('Critical error -- shutting down')
450\end{verbatim}
451
452This produces the following output:
453
454\begin{verbatim}
Andrew M. Kuchlingb1e4bf92002-12-03 13:35:17 +0000455WARN:root:Warning:config file server.conf not found
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000456ERROR:root:Error occurred
457CRITICAL:root:Critical error -- shutting down
458\end{verbatim}
459
460In the default configuration, informational and debugging messages are
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000461suppressed and the output is sent to standard error; you can change
462this by calling the \method{setLevel()} method on the root logger.
463
464Notice the \function{warn()} call's use of string formatting
465operators; all of the functions for logging messages take the
466arguments \code{(\var{msg}, \var{arg1}, \var{arg2}, ...)} and log the
467string resulting from \code{\var{msg} \% (\var{arg1}, \var{arg2},
468...)}.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000469
470There's also an \function{exception()} function that records the most
471recent traceback. Any of the other functions will also record the
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000472traceback if you specify a true value for the keyword argument
473\code{exc_info}.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000474
475\begin{verbatim}
476def f():
477 try: 1/0
478 except: logging.exception('Problem recorded')
479
480f()
481\end{verbatim}
482
483This produces the following output:
484
485\begin{verbatim}
486ERROR:root:Problem recorded
487Traceback (most recent call last):
488 File "t.py", line 6, in f
489 1/0
490ZeroDivisionError: integer division or modulo by zero
491\end{verbatim}
492
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000493Slightly more advanced programs will use a logger other than the root
494logger. The \function{getLogger(\var{name})} is used to get a
Andrew M. Kuchlingb1e4bf92002-12-03 13:35:17 +0000495particular log, creating it if it doesn't exist yet;
496\function{getLogger(None)} returns the root logger.
497
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000498
499\begin{verbatim}
500log = logging.getLogger('server')
501 ...
502log.info('Listening on port %i', port)
503 ...
504log.critical('Disk full')
505 ...
506\end{verbatim}
507
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000508There are more classes that can be customized. When a \class{Logger}
509instance is told to log a message, it creates a \class{LogRecord}
510instance that is sent to any number of different \class{Handler}
511instances. Loggers and handlers can also have an attached list of
512filters, and each filter can cause the \class{LogRecord} to be ignored
513or can modify the record before passing it along. \class{LogRecord}
514instances are converted to text by a \class{Formatter} class.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000515
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000516Log records are usually propagated up the hierarchy, so a message
517logged to \samp{server.auth} is also seen by \samp{server} and
518\samp{root}, but a handler can prevent this by setting its
Andrew M. Kuchlingb6f79592002-11-29 19:43:45 +0000519\member{propagate} attribute to \code{False}.
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000520
521With all of these features the \module{logging} package should provide
522enough flexibility for even the most complicated applications. This
523is only a partial overview of the \module{logging} package's features,
524so please see the
Andrew M. Kuchling9e7453d2002-11-25 16:02:13 +0000525\ulink{package's reference documentation}{http://www.python.org/dev/doc/devel/lib/module-logging.html}
526for all of the details. Reading \pep{282} will also be helpful.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000527
528
529\begin{seealso}
530
531\seepep{282}{A Logging System}{Written by Vinay Sajip and Trent Mick;
532implemented by Vinay Sajip.}
533
534\end{seealso}
535
536
537%======================================================================
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000538\section{PEP 285: The \class{bool} Type\label{section-bool}}
539
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000540A Boolean type was added to Python 2.3. Two new constants were added
541to the \module{__builtin__} module, \constant{True} and
542\constant{False}. The type object for this new type is named
543\class{bool}; the constructor for it takes any Python value and
544converts it to \constant{True} or \constant{False}.
545
546\begin{verbatim}
547>>> bool(1)
548True
549>>> bool(0)
550False
551>>> bool([])
552False
553>>> bool( (1,) )
554True
555\end{verbatim}
556
557Most of the standard library modules and built-in functions have been
558changed to return Booleans.
559
560\begin{verbatim}
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000561>>> obj = []
562>>> hasattr(obj, 'append')
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000563True
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000564>>> isinstance(obj, list)
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000565True
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000566>>> isinstance(obj, tuple)
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000567False
568\end{verbatim}
569
570Python's Booleans were added with the primary goal of making code
571clearer. For example, if you're reading a function and encounter the
Fred Drake5c4cf152002-11-13 14:59:06 +0000572statement \code{return 1}, you might wonder whether the \code{1}
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000573represents a truth value, or whether it's an index, or whether it's a
574coefficient that multiplies some other quantity. If the statement is
575\code{return True}, however, the meaning of the return value is quite
576clearly a truth value.
577
578Python's Booleans were not added for the sake of strict type-checking.
Andrew M. Kuchlinga2a206b2002-05-24 21:08:58 +0000579A very strict language such as Pascal would also prevent you
580performing arithmetic with Booleans, and would require that the
581expression in an \keyword{if} statement always evaluate to a Boolean.
582Python is not this strict, and it never will be. (\pep{285}
583explicitly says so.) So you can still use any expression in an
584\keyword{if}, even ones that evaluate to a list or tuple or some
585random object, and the Boolean type is a subclass of the
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000586\class{int} class, so arithmetic using a Boolean still works.
587
588\begin{verbatim}
589>>> True + 1
5902
591>>> False + 1
5921
593>>> False * 75
5940
595>>> True * 75
59675
597\end{verbatim}
598
599To sum up \constant{True} and \constant{False} in a sentence: they're
600alternative ways to spell the integer values 1 and 0, with the single
601difference that \function{str()} and \function{repr()} return the
Fred Drake5c4cf152002-11-13 14:59:06 +0000602strings \code{'True'} and \code{'False'} instead of \code{'1'} and
603\code{'0'}.
Andrew M. Kuchling3a52ff62002-04-03 22:44:47 +0000604
605\begin{seealso}
606
607\seepep{285}{Adding a bool type}{Written and implemented by GvR.}
608
609\end{seealso}
610
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000611
Andrew M. Kuchling65b72822002-09-03 00:53:21 +0000612%======================================================================
613\section{PEP 293: Codec Error Handling Callbacks}
614
Martin v. Löwis20eae692002-10-07 19:01:07 +0000615When encoding a Unicode string into a byte string, unencodable
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000616characters may be encountered. So far, Python has allowed specifying
617the error processing as either ``strict'' (raising
618\exception{UnicodeError}), ``ignore'' (skip the character), or
619``replace'' (with question mark), defaulting to ``strict''. It may be
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +0000620desirable to specify an alternative processing of the error, such as
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000621inserting an XML character reference or HTML entity reference into the
622converted string.
Martin v. Löwis20eae692002-10-07 19:01:07 +0000623
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +0000624Python now has a flexible framework to add different processing
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000625strategies. New error handlers can be added with
Martin v. Löwis20eae692002-10-07 19:01:07 +0000626\function{codecs.register_error}. Codecs then can access the error
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000627handler with \function{codecs.lookup_error}. An equivalent C API has
628been added for codecs written in C. The error handler gets the
629necessary state information, such as the string being converted, the
630position in the string where the error was detected, and the target
631encoding. The handler can then either raise an exception, or return a
632replacement string.
Martin v. Löwis20eae692002-10-07 19:01:07 +0000633
634Two additional error handlers have been implemented using this
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000635framework: ``backslashreplace'' uses Python backslash quoting to
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +0000636represent unencodable characters and ``xmlcharrefreplace'' emits
Martin v. Löwis20eae692002-10-07 19:01:07 +0000637XML character references.
Andrew M. Kuchling65b72822002-09-03 00:53:21 +0000638
639\begin{seealso}
640
Fred Drake5c4cf152002-11-13 14:59:06 +0000641\seepep{293}{Codec Error Handling Callbacks}{Written and implemented by
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000642Walter D\"orwald.}
Andrew M. Kuchling65b72822002-09-03 00:53:21 +0000643
644\end{seealso}
645
646
647%======================================================================
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000648\section{PEP 273: Importing Modules from Zip Archives}
649
650The new \module{zipimport} module adds support for importing
651modules from a ZIP-format archive. You shouldn't need to import the
652module explicitly; it will be automatically imported if a ZIP
653archive's filename is added to \code{sys.path}. For example:
654
655\begin{verbatim}
656amk@nyman:~/src/python$ unzip -l /tmp/example.zip
657Archive: /tmp/example.zip
658 Length Date Time Name
659 -------- ---- ---- ----
660 8467 11-26-02 22:30 jwzthreading.py
661 -------- -------
662 8467 1 file
663amk@nyman:~/src/python$ ./python
664Python 2.3a0 (#1, Dec 30 2002, 19:54:32)
665[GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-113)] on linux2
666Type "help", "copyright", "credits" or "license" for more information.
667>>> import sys
668>>> sys.path.insert(0, '/tmp/example.zip') # Add .zip file to front of path
669>>> import jwzthreading
670>>> jwzthreading.__file__
671'/tmp/example.zip/jwzthreading.py'
672>>>
673\end{verbatim}
674
675An entry in \code{sys.path} can now be the filename of a ZIP archive.
676The ZIP archive can contain any kind of files, but only files named
677\code{*.py}, \code{*.pyc}, or \code{*.pyo} can be imported. If an
678archive only contains \code{*.py} files, Python will not attempt to
679modify the archive by adding the corresponding {*.pyc} file.
680Therefore, if a ZIP archive doesn't contain {*.pyc} files, importing
681may be rather slow.
682
683A path within the archive can also be specified to only import from a
684subdirectory; for example, the path \file{/tmp/example.zip/lib/}
685would only import from the \file{lib/} subdirectory within the
686archive.
687
688This new feature is implemented using the new import hooks from
689\pep{302}; see section~\ref{section-pep302} for a description.
690
691\begin{seealso}
692
693\seepep{273}{Import Modules from Zip Archives}{Written by James C. Ahlstrom,
694who also provided an implementation.
695Python 2.3 follows the specification in \pep{273},
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +0000696but uses an implementation written by Just van~Rossum
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000697that uses the import hooks described in \pep{302}.}
698
699\end{seealso}
700
701%======================================================================
702\section{PEP 302: New Import Hooks \label{section-pep302}}
703
704While it's been possible to write custom import hooks ever since the
705\module{ihooks} module was introduced in Python 1.3, no one has ever
706been really happy with it, because writing new import hooks is
707difficult and messy. There have been various alternative interfaces
708proposed, such as the \module{imputil} and \module{iu} modules, but
709none has ever gained much acceptance, and none was easily usable from
710\C{} code.
711
712\pep{302} borrows ideas from its predecessors, especially from
713Gordon McMillan's \module{iu} module. Three new items
714are added to the \module{sys} module:
715
716\begin{itemize}
717 \item[\code{sys.path_hooks}] is a list of functions. Each function
718takes a string containing a path and returns either \code{None} or an
719importer object that will handle imports from this path.
720
721 \item[\code{sys.path_importer_cache}] caches importer objects for
722each path, so \code{sys.path_hooks} will only need to be traversed
723once for each path.
724
725 \item[\code{sys.meta_path}] is a list of importer objects
726that will be traversed before \code{sys.path} is checked at all.
727This list is initially empty, but can be extended. Additional built-in
728and frozen modules can be imported by an object added to this list.
729
730\end{itemize}
731
732Importer objects must have a single method,
733\method{find_module(\var{fullname}, \var{path}=None)}. \var{fullname}
734will be a module or package name, e.g. \samp{string} or
735\samp{spam.ham}. \method{find_module()} must return a loader object
736that has a single method, \method{load_module(\var{fullname})}, that
737creates and returns the corresponding module object.
738
739Pseudo-code for Python's new import logic, therefore, looks something
740like this (simplified a bit; see \pep{302} for the full details):
741
742\begin{verbatim}
743for mp in sys.meta_path:
744 loader = mp(fullname)
745 if loader is not None:
746 <module> = loader(fullname)
747
748for path in sys.path:
749 for hook in sys.path_hooks:
750 importer = hook(path)
751 if importer is not None:
752 loader = importer.find_module(fullname)
753 return loader.load_module(fullname)
754
755# Not found!
756raise ImportError
757\end{verbatim}
758
759\begin{seealso}
760
761\seepep{302}{New Import Hooks}{Written by Just van~Rossum and Paul Moore.
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +0000762Implemented by Just van~Rossum.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000763}
764
765\end{seealso}
766
767
768%======================================================================
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000769\section{Extended Slices\label{section-slices}}
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000770
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000771Ever since Python 1.4, the slicing syntax has supported an optional
772third ``step'' or ``stride'' argument. For example, these are all
773legal Python syntax: \code{L[1:10:2]}, \code{L[:-1:1]},
774\code{L[::-1]}. This was added to Python included at the request of
775the developers of Numerical Python. However, the built-in sequence
776types of lists, tuples, and strings have never supported this feature,
777and you got a \exception{TypeError} if you tried it. Michael Hudson
Fred Drake5c4cf152002-11-13 14:59:06 +0000778contributed a patch that was applied to Python 2.3 and fixed this
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000779shortcoming.
780
781For example, you can now easily extract the elements of a list that
782have even indexes:
Fred Drakedf872a22002-07-03 12:02:01 +0000783
784\begin{verbatim}
785>>> L = range(10)
786>>> L[::2]
787[0, 2, 4, 6, 8]
788\end{verbatim}
789
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000790Negative values also work, so you can make a copy of the same list in
791reverse order:
Fred Drakedf872a22002-07-03 12:02:01 +0000792
793\begin{verbatim}
794>>> L[::-1]
795[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
796\end{verbatim}
Andrew M. Kuchling3a52ff62002-04-03 22:44:47 +0000797
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000798This also works for strings:
799
800\begin{verbatim}
801>>> s='abcd'
802>>> s[::2]
803'ac'
804>>> s[::-1]
805'dcba'
806\end{verbatim}
807
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000808as well as tuples and arrays.
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000809
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000810If you have a mutable sequence (i.e. a list or an array) you can
811assign to or delete an extended slice, but there are some differences
812in assignment to extended and regular slices. Assignment to a regular
813slice can be used to change the length of the sequence:
814
815\begin{verbatim}
816>>> a = range(3)
817>>> a
818[0, 1, 2]
819>>> a[1:3] = [4, 5, 6]
820>>> a
821[0, 4, 5, 6]
822\end{verbatim}
823
824but when assigning to an extended slice the list on the right hand
825side of the statement must contain the same number of items as the
826slice it is replacing:
827
828\begin{verbatim}
829>>> a = range(4)
830>>> a
831[0, 1, 2, 3]
832>>> a[::2]
833[0, 2]
834>>> a[::2] = range(0, -2, -1)
835>>> a
836[0, 1, -1, 3]
837>>> a[::2] = range(3)
838Traceback (most recent call last):
839 File "<stdin>", line 1, in ?
840ValueError: attempt to assign list of size 3 to extended slice of size 2
841\end{verbatim}
842
843Deletion is more straightforward:
844
845\begin{verbatim}
846>>> a = range(4)
847>>> a[::2]
848[0, 2]
849>>> del a[::2]
850>>> a
851[1, 3]
852\end{verbatim}
853
854One can also now pass slice objects to builtin sequences
855\method{__getitem__} methods:
856
857\begin{verbatim}
858>>> range(10).__getitem__(slice(0, 5, 2))
859[0, 2, 4]
860\end{verbatim}
861
862or use them directly in subscripts:
863
864\begin{verbatim}
865>>> range(10)[slice(0, 5, 2)]
866[0, 2, 4]
867\end{verbatim}
868
Andrew M. Kuchlingb6f79592002-11-29 19:43:45 +0000869To simplify implementing sequences that support extended slicing,
870slice objects now have a method \method{indices(\var{length})} which,
871given the length of a sequence, returns a \code{(start, stop, step)}
872tuple that can be passed directly to \function{range()}.
873\method{indices()} handles omitted and out-of-bounds indices in a
874manner consistent with regular slices (and this innocuous phrase hides
875a welter of confusing details!). The method is intended to be used
876like this:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000877
878\begin{verbatim}
879class FakeSeq:
880 ...
881 def calc_item(self, i):
882 ...
883 def __getitem__(self, item):
884 if isinstance(item, slice):
Fred Drake5c4cf152002-11-13 14:59:06 +0000885 return FakeSeq([self.calc_item(i)
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000886 in range(*item.indices(len(self)))])
Fred Drake5c4cf152002-11-13 14:59:06 +0000887 else:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000888 return self.calc_item(i)
889\end{verbatim}
890
Andrew M. Kuchling90e9a792002-08-15 00:40:21 +0000891From this example you can also see that the builtin ``\class{slice}''
892object is now the type object for the slice type, and is no longer a
893function. This is consistent with Python 2.2, where \class{int},
894\class{str}, etc., underwent the same change.
895
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000896
Andrew M. Kuchling3a52ff62002-04-03 22:44:47 +0000897%======================================================================
Fred Drakedf872a22002-07-03 12:02:01 +0000898\section{Other Language Changes}
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000899
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000900Here are all of the changes that Python 2.3 makes to the core Python
901language.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000902
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000903\begin{itemize}
904\item The \keyword{yield} statement is now always a keyword, as
905described in section~\ref{section-generators} of this document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000906
Fred Drake5c4cf152002-11-13 14:59:06 +0000907\item A new built-in function \function{enumerate()}
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000908was added, as described in section~\ref{section-enumerate} of this
909document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000910
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000911\item Two new constants, \constant{True} and \constant{False} were
912added along with the built-in \class{bool} type, as described in
913section~\ref{section-bool} of this document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000914
Andrew M. Kuchling495172c2002-11-20 13:50:15 +0000915\item The \function{int()} type constructor will now return a long
916integer instead of raising an \exception{OverflowError} when a string
917or floating-point number is too large to fit into an integer. This
918can lead to the paradoxical result that
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000919\code{isinstance(int(\var{expression}), int)} is false, but that seems
920unlikely to cause problems in practice.
Andrew M. Kuchling495172c2002-11-20 13:50:15 +0000921
Fred Drake5c4cf152002-11-13 14:59:06 +0000922\item Built-in types now support the extended slicing syntax,
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000923as described in section~\ref{section-slices} of this document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000924
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000925\item Dictionaries have a new method, \method{pop(\var{key})}, that
926returns the value corresponding to \var{key} and removes that
927key/value pair from the dictionary. \method{pop()} will raise a
928\exception{KeyError} if the requested key isn't present in the
929dictionary:
930
931\begin{verbatim}
932>>> d = {1:2}
933>>> d
934{1: 2}
935>>> d.pop(4)
936Traceback (most recent call last):
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000937 File "stdin", line 1, in ?
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000938KeyError: 4
939>>> d.pop(1)
9402
941>>> d.pop(1)
942Traceback (most recent call last):
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000943 File "stdin", line 1, in ?
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000944KeyError: pop(): dictionary is empty
945>>> d
946{}
947>>>
948\end{verbatim}
949
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +0000950There's also a new class method,
951\method{dict.fromkeys(\var{iterable}, \var{value})}, that
952creates a dictionary with keys taken from the supplied iterator
953\var{iterable} and all values set to \var{value}, defaulting to
954\code{None}.
955
956(Patches contributed by Raymond Hettinger.)
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000957
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000958Also, the \function{dict()} constructor now accepts keyword arguments to
Raymond Hettinger45bda572002-12-14 20:20:45 +0000959simplify creating small dictionaries:
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +0000960
961\begin{verbatim}
962>>> dict(red=1, blue=2, green=3, black=4)
963{'blue': 2, 'black': 4, 'green': 3, 'red': 1}
964\end{verbatim}
965
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +0000966(Contributed by Just van~Rossum.)
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +0000967
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +0000968\item The \keyword{assert} statement no longer checks the \code{__debug__}
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +0000969flag, so you can no longer disable assertions by assigning to \code{__debug__}.
Fred Drake5c4cf152002-11-13 14:59:06 +0000970Running Python with the \programopt{-O} switch will still generate
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +0000971code that doesn't execute any assertions.
972
973\item Most type objects are now callable, so you can use them
974to create new objects such as functions, classes, and modules. (This
975means that the \module{new} module can be deprecated in a future
976Python version, because you can now use the type objects available
977in the \module{types} module.)
978% XXX should new.py use PendingDeprecationWarning?
979For example, you can create a new module object with the following code:
980
981\begin{verbatim}
982>>> import types
983>>> m = types.ModuleType('abc','docstring')
984>>> m
985<module 'abc' (built-in)>
986>>> m.__doc__
987'docstring'
988\end{verbatim}
989
Fred Drake5c4cf152002-11-13 14:59:06 +0000990\item
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +0000991A new warning, \exception{PendingDeprecationWarning} was added to
992indicate features which are in the process of being
993deprecated. The warning will \emph{not} be printed by default. To
994check for use of features that will be deprecated in the future,
995supply \programopt{-Walways::PendingDeprecationWarning::} on the
996command line or use \function{warnings.filterwarnings()}.
997
998\item Using \code{None} as a variable name will now result in a
999\exception{SyntaxWarning} warning. In a future version of Python,
1000\code{None} may finally become a keyword.
1001
Andrew M. Kuchlingb60ea3f2002-11-15 14:37:10 +00001002\item The method resolution order used by new-style classes has
1003changed, though you'll only notice the difference if you have a really
1004complicated inheritance hierarchy. (Classic classes are unaffected by
1005this change.) Python 2.2 originally used a topological sort of a
1006class's ancestors, but 2.3 now uses the C3 algorithm as described in
Andrew M. Kuchling6f429c32002-11-19 13:09:00 +00001007the paper \ulink{``A Monotonic Superclass Linearization for
1008Dylan''}{http://www.webcom.com/haahr/dylan/linearization-oopsla96.html}.
1009To understand the motivation for this change, read the thread on
1010python-dev starting with the message at
Andrew M. Kuchlingb60ea3f2002-11-15 14:37:10 +00001011\url{http://mail.python.org/pipermail/python-dev/2002-October/029035.html}.
1012Samuele Pedroni first pointed out the problem and also implemented the
1013fix by coding the C3 algorithm.
1014
Andrew M. Kuchlingdcfd8252002-09-13 22:21:42 +00001015\item Python runs multithreaded programs by switching between threads
1016after executing N bytecodes. The default value for N has been
1017increased from 10 to 100 bytecodes, speeding up single-threaded
1018applications by reducing the switching overhead. Some multithreaded
1019applications may suffer slower response time, but that's easily fixed
1020by setting the limit back to a lower number by calling
1021\function{sys.setcheckinterval(\var{N})}.
1022
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001023\item One minor but far-reaching change is that the names of extension
1024types defined by the modules included with Python now contain the
Fred Drake5c4cf152002-11-13 14:59:06 +00001025module and a \character{.} in front of the type name. For example, in
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001026Python 2.2, if you created a socket and printed its
1027\member{__class__}, you'd get this output:
1028
1029\begin{verbatim}
1030>>> s = socket.socket()
1031>>> s.__class__
1032<type 'socket'>
1033\end{verbatim}
1034
1035In 2.3, you get this:
1036\begin{verbatim}
1037>>> s.__class__
1038<type '_socket.socket'>
1039\end{verbatim}
1040
Michael W. Hudson96bc3b42002-11-26 14:48:23 +00001041\item One of the noted incompatibilities between old- and new-style
1042 classes has been removed: you can now assign to the
1043 \member{__name__} and \member{__bases__} attributes of new-style
1044 classes. There are some restrictions on what can be assigned to
1045 \member{__bases__} along the lines of those relating to assigning to
1046 an instance's \member{__class__} attribute.
1047
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001048\end{itemize}
1049
1050
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001051%======================================================================
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001052\subsection{String Changes}
1053
1054\begin{itemize}
1055
1056\item The \code{in} operator now works differently for strings.
1057Previously, when evaluating \code{\var{X} in \var{Y}} where \var{X}
1058and \var{Y} are strings, \var{X} could only be a single character.
1059That's now changed; \var{X} can be a string of any length, and
1060\code{\var{X} in \var{Y}} will return \constant{True} if \var{X} is a
1061substring of \var{Y}. If \var{X} is the empty string, the result is
1062always \constant{True}.
1063
1064\begin{verbatim}
1065>>> 'ab' in 'abcd'
1066True
1067>>> 'ad' in 'abcd'
1068False
1069>>> '' in 'abcd'
1070True
1071\end{verbatim}
1072
1073Note that this doesn't tell you where the substring starts; the
1074\method{find()} method is still necessary to figure that out.
1075
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001076\item The \method{strip()}, \method{lstrip()}, and \method{rstrip()}
1077string methods now have an optional argument for specifying the
1078characters to strip. The default is still to remove all whitespace
1079characters:
1080
1081\begin{verbatim}
1082>>> ' abc '.strip()
1083'abc'
1084>>> '><><abc<><><>'.strip('<>')
1085'abc'
1086>>> '><><abc<><><>\n'.strip('<>')
1087'abc<><><>\n'
1088>>> u'\u4000\u4001abc\u4000'.strip(u'\u4000')
1089u'\u4001abc'
1090>>>
1091\end{verbatim}
1092
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +00001093(Suggested by Simon Brunning, and implemented by Walter D\"orwald.)
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00001094
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001095\item The \method{startswith()} and \method{endswith()}
1096string methods now accept negative numbers for the start and end
1097parameters.
1098
1099\item Another new string method is \method{zfill()}, originally a
1100function in the \module{string} module. \method{zfill()} pads a
1101numeric string with zeros on the left until it's the specified width.
1102Note that the \code{\%} operator is still more flexible and powerful
1103than \method{zfill()}.
1104
1105\begin{verbatim}
1106>>> '45'.zfill(4)
1107'0045'
1108>>> '12345'.zfill(4)
1109'12345'
1110>>> 'goofy'.zfill(6)
1111'0goofy'
1112\end{verbatim}
1113
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00001114(Contributed by Walter D\"orwald.)
1115
Fred Drake5c4cf152002-11-13 14:59:06 +00001116\item A new type object, \class{basestring}, has been added.
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001117 Both 8-bit strings and Unicode strings inherit from this type, so
1118 \code{isinstance(obj, basestring)} will return \constant{True} for
1119 either kind of string. It's a completely abstract type, so you
1120 can't create \class{basestring} instances.
1121
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001122\item Interned strings are no longer immortal. Interned will now be
1123garbage-collected in the usual way when the only reference to them is
1124from the internal dictionary of interned strings. (Implemented by
1125Oren Tirosh.)
1126
1127\end{itemize}
1128
1129
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001130%======================================================================
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001131\subsection{Optimizations}
1132
1133\begin{itemize}
1134
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001135\item The creation of new-style class instances has been made much
1136faster; they're now faster than classic classes!
1137
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001138\item The \method{sort()} method of list objects has been extensively
1139rewritten by Tim Peters, and the implementation is significantly
1140faster.
1141
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001142\item Multiplication of large long integers is now much faster thanks
1143to an implementation of Karatsuba multiplication, an algorithm that
1144scales better than the O(n*n) required for the grade-school
1145multiplication algorithm. (Original patch by Christopher A. Craig,
1146and significantly reworked by Tim Peters.)
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001147
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001148\item The \code{SET_LINENO} opcode is now gone. This may provide a
1149small speed increase, subject to your compiler's idiosyncrasies.
1150(Removed by Michael Hudson.)
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001151
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001152\item \function{xrange()} objects now have their own iterator, making
1153\code{for i in xrange(n)} slightly faster than
1154\code{for i in range(n)}. (Patch by Raymond Hettinger.)
1155
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001156\item A number of small rearrangements have been made in various
1157hotspots to improve performance, inlining a function here, removing
1158some code there. (Implemented mostly by GvR, but lots of people have
1159contributed to one change or another.)
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001160
1161\end{itemize}
Neal Norwitzd68f5172002-05-29 15:54:55 +00001162
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001163
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001164%======================================================================
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00001165\section{New and Improved Modules}
1166
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00001167As usual, Python's standard modules had a number of enhancements and
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001168bug fixes. Here's a partial list of the most notable changes, sorted
1169alphabetically by module name. Consult the
1170\file{Misc/NEWS} file in the source tree for a more
1171complete list of changes, or look through the CVS logs for all the
1172details.
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00001173
1174\begin{itemize}
1175
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001176\item The \module{array} module now supports arrays of Unicode
Fred Drake5c4cf152002-11-13 14:59:06 +00001177characters using the \character{u} format character. Arrays also now
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001178support using the \code{+=} assignment operator to add another array's
1179contents, and the \code{*=} assignment operator to repeat an array.
1180(Contributed by Jason Orendorff.)
1181
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001182\item The \module{bsddb} module has been updated to version 4.1.1
Andrew M. Kuchling669249e2002-11-19 13:05:33 +00001183of the \ulink{PyBSDDB}{http://pybsddb.sourceforge.net} package,
1184providing a more complete interface to the transactional features of
1185the BerkeleyDB library.
1186The old version of the module has been renamed to
1187\module{bsddb185} and is no longer built automatically; you'll
1188have to edit \file{Modules/Setup} to enable it. Note that the new
1189\module{bsddb} package is intended to be compatible with the
1190old module, so be sure to file bugs if you discover any
1191incompatibilities.
1192
Fred Drake5c4cf152002-11-13 14:59:06 +00001193\item The Distutils \class{Extension} class now supports
1194an extra constructor argument named \var{depends} for listing
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001195additional source files that an extension depends on. This lets
1196Distutils recompile the module if any of the dependency files are
Fred Drake5c4cf152002-11-13 14:59:06 +00001197modified. For example, if \file{sampmodule.c} includes the header
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001198file \file{sample.h}, you would create the \class{Extension} object like
1199this:
1200
1201\begin{verbatim}
1202ext = Extension("samp",
1203 sources=["sampmodule.c"],
1204 depends=["sample.h"])
1205\end{verbatim}
1206
1207Modifying \file{sample.h} would then cause the module to be recompiled.
1208(Contributed by Jeremy Hylton.)
1209
Andrew M. Kuchlingdc3f7e12002-11-04 20:05:10 +00001210\item Other minor changes to Distutils:
1211it now checks for the \envvar{CC}, \envvar{CFLAGS}, \envvar{CPP},
1212\envvar{LDFLAGS}, and \envvar{CPPFLAGS} environment variables, using
1213them to override the settings in Python's configuration (contributed
Andrew M. Kuchling53262572002-12-01 14:00:21 +00001214by Robert Weber); the \function{get_distutils_options()} method lists
Andrew M. Kuchlingdc3f7e12002-11-04 20:05:10 +00001215recently-added extensions to Distutils.
1216
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001217\item The \module{getopt} module gained a new function,
1218\function{gnu_getopt()}, that supports the same arguments as the existing
Fred Drake5c4cf152002-11-13 14:59:06 +00001219\function{getopt()} function but uses GNU-style scanning mode.
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001220The existing \function{getopt()} stops processing options as soon as a
1221non-option argument is encountered, but in GNU-style mode processing
1222continues, meaning that options and arguments can be mixed. For
1223example:
1224
1225\begin{verbatim}
1226>>> getopt.getopt(['-f', 'filename', 'output', '-v'], 'f:v')
1227([('-f', 'filename')], ['output', '-v'])
1228>>> getopt.gnu_getopt(['-f', 'filename', 'output', '-v'], 'f:v')
1229([('-f', 'filename'), ('-v', '')], ['output'])
1230\end{verbatim}
1231
1232(Contributed by Peter \AA{strand}.)
1233
1234\item The \module{grp}, \module{pwd}, and \module{resource} modules
Fred Drake5c4cf152002-11-13 14:59:06 +00001235now return enhanced tuples:
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001236
1237\begin{verbatim}
1238>>> import grp
1239>>> g = grp.getgrnam('amk')
1240>>> g.gr_name, g.gr_gid
1241('amk', 500)
1242\end{verbatim}
1243
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001244\item The \module{gzip} module can now handle files exceeding 2~Gb.
1245
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001246\item The new \module{heapq} module contains an implementation of a
1247heap queue algorithm. A heap is an array-like data structure that
Tim Peters85f7f832002-12-10 21:04:25 +00001248keeps items in a partially sorted order such that,
1249for every index k, heap[k] <= heap[2*k+1] and heap[k] <= heap[2*k+2].
1250This makes it quick to remove
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001251the smallest item, and inserting a new item while maintaining the heap
1252property is O(lg~n). (See
1253\url{http://www.nist.gov/dads/HTML/priorityque.html} for more
1254information about the priority queue data structure.)
1255
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001256The \module{heapq} module provides \function{heappush()} and
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001257\function{heappop()} functions for adding and removing items while
1258maintaining the heap property on top of some other mutable Python
1259sequence type. For example:
1260
1261\begin{verbatim}
1262>>> import heapq
1263>>> heap = []
1264>>> for item in [3, 7, 5, 11, 1]:
1265... heapq.heappush(heap, item)
1266...
1267>>> heap
1268[1, 3, 5, 11, 7]
1269>>> heapq.heappop(heap)
12701
1271>>> heapq.heappop(heap)
12723
1273>>> heap
1274[5, 7, 11]
1275>>>
1276>>> heapq.heappush(heap, 5)
1277>>> heap = []
1278>>> for item in [3, 7, 5, 11, 1]:
1279... heapq.heappush(heap, item)
1280...
1281>>> heap
1282[1, 3, 5, 11, 7]
1283>>> heapq.heappop(heap)
12841
1285>>> heapq.heappop(heap)
12863
1287>>> heap
1288[5, 7, 11]
1289>>>
1290\end{verbatim}
1291
1292(Contributed by Kevin O'Connor.)
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001293
Fred Drake5c4cf152002-11-13 14:59:06 +00001294\item Two new functions in the \module{math} module,
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001295\function{degrees(\var{rads})} and \function{radians(\var{degs})},
Fred Drake5c4cf152002-11-13 14:59:06 +00001296convert between radians and degrees. Other functions in the
Andrew M. Kuchling8e5b53b2002-12-15 20:17:38 +00001297\module{math} module such as \function{math.sin()} and
1298\function{math.cos()} have always required input values measured in
1299radians. Also, an optional \var{base} argument was added to
1300\function{math.log()} to make it easier to compute logarithms for
1301bases other than \code{e} and \code{10}. (Contributed by Raymond
1302Hettinger.)
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001303
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +00001304\item Several new functions (\function{getpgid()}, \function{killpg()},
1305\function{lchown()}, \function{loadavg()}, \function{major()}, \function{makedev()},
1306\function{minor()}, and \function{mknod()}) were added to the
Andrew M. Kuchlingc309cca2002-10-10 16:04:08 +00001307\module{posix} module that underlies the \module{os} module.
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +00001308(Contributed by Gustavo Niemeyer, Geert Jansen, and Denis S. Otkidach.)
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001309
Andrew M. Kuchling53262572002-12-01 14:00:21 +00001310\item The old and never-documented \module{linuxaudiodev} module has
1311been renamed to \module{ossaudiodev}, because the OSS sound drivers
1312can be used on platforms other than Linux. The interface has also
1313been tidied and brought up to date in various ways. (Contributed by
1314Greg Ward.)
1315
Fred Drake5c4cf152002-11-13 14:59:06 +00001316\item The parser objects provided by the \module{pyexpat} module
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001317can now optionally buffer character data, resulting in fewer calls to
1318your character data handler and therefore faster performance. Setting
Fred Drake5c4cf152002-11-13 14:59:06 +00001319the parser object's \member{buffer_text} attribute to \constant{True}
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001320will enable buffering.
1321
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001322\item The \function{sample(\var{population}, \var{k})} function was
1323added to the \module{random} module. \var{population} is a sequence
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001324or \code{xrange} object containing the elements of a population, and \function{sample()}
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001325chooses \var{k} elements from the population without replacing chosen
1326elements. \var{k} can be any value up to \code{len(\var{population})}.
1327For example:
1328
1329\begin{verbatim}
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001330>>> days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'St', 'Sn']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001331>>> random.sample(days, 3) # Choose 3 elements
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001332['St', 'Sn', 'Th']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001333>>> random.sample(days, 7) # Choose 7 elements
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001334['Tu', 'Th', 'Mo', 'We', 'St', 'Fr', 'Sn']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001335>>> random.sample(days, 7) # Choose 7 again
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001336['We', 'Mo', 'Sn', 'Fr', 'Tu', 'St', 'Th']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001337>>> random.sample(days, 8) # Can't choose eight
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001338Traceback (most recent call last):
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +00001339 File "<stdin>", line 1, in ?
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001340 File "random.py", line 414, in sample
1341 raise ValueError, "sample larger than population"
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001342ValueError: sample larger than population
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001343>>> random.sample(xrange(1,10000,2), 10) # Choose ten odds under 10000
1344[3407, 3805, 1505, 7023, 2401, 2267, 9733, 3151, 8083, 9195]
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001345\end{verbatim}
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001346
1347The \module{random} module now uses a new algorithm, the Mersenne
1348Twister, implemented in C. It's faster and more extensively studied
1349than the previous algorithm.
1350
1351(All changes contributed by Raymond Hettinger.)
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001352
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001353\item The \module{readline} module also gained a number of new
1354functions: \function{get_history_item()},
1355\function{get_current_history_length()}, and \function{redisplay()}.
1356
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001357\item The \module{shutil} module gained a \function{move(\var{src},
1358\var{dest})} that recursively moves a file or directory to a new
1359location.
1360
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001361\item Support for more advanced POSIX signal handling was added
1362to the \module{signal} module by adding the \function{sigpending},
1363\function{sigprocmask} and \function{sigsuspend} functions, where supported
1364by the platform. These functions make it possible to avoid some previously
1365unavoidable race conditions.
1366
1367\item The \module{socket} module now supports timeouts. You
1368can call the \method{settimeout(\var{t})} method on a socket object to
1369set a timeout of \var{t} seconds. Subsequent socket operations that
1370take longer than \var{t} seconds to complete will abort and raise a
Fred Drake5c4cf152002-11-13 14:59:06 +00001371\exception{socket.error} exception.
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001372
1373The original timeout implementation was by Tim O'Malley. Michael
1374Gilfix integrated it into the Python \module{socket} module, after the
1375patch had undergone a lengthy review. After it was checked in, Guido
1376van~Rossum rewrote parts of it. This is a good example of the free
1377software development process in action.
1378
Mark Hammond8af50bc2002-12-03 06:13:35 +00001379\item On Windows, the \module{socket} module now ships with Secure
1380Sockets Library (SSL) support.
1381
Fred Drake5c4cf152002-11-13 14:59:06 +00001382\item The value of the C \constant{PYTHON_API_VERSION} macro is now exposed
Fred Drake583db0d2002-09-14 02:03:25 +00001383at the Python level as \code{sys.api_version}.
Andrew M. Kuchlingdcfd8252002-09-13 22:21:42 +00001384
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001385\item The new \module{textwrap} module contains functions for wrapping
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001386strings containing paragraphs of text. The \function{wrap(\var{text},
1387\var{width})} function takes a string and returns a list containing
1388the text split into lines of no more than the chosen width. The
1389\function{fill(\var{text}, \var{width})} function returns a single
1390string, reformatted to fit into lines no longer than the chosen width.
1391(As you can guess, \function{fill()} is built on top of
1392\function{wrap()}. For example:
1393
1394\begin{verbatim}
1395>>> import textwrap
1396>>> paragraph = "Not a whit, we defy augury: ... more text ..."
1397>>> textwrap.wrap(paragraph, 60)
Fred Drake5c4cf152002-11-13 14:59:06 +00001398["Not a whit, we defy augury: there's a special providence in",
1399 "the fall of a sparrow. If it be now, 'tis not to come; if it",
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001400 ...]
1401>>> print textwrap.fill(paragraph, 35)
1402Not a whit, we defy augury: there's
1403a special providence in the fall of
1404a sparrow. If it be now, 'tis not
1405to come; if it be not to come, it
1406will be now; if it be not now, yet
1407it will come: the readiness is all.
Fred Drake5c4cf152002-11-13 14:59:06 +00001408>>>
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001409\end{verbatim}
1410
1411The module also contains a \class{TextWrapper} class that actually
Fred Drake5c4cf152002-11-13 14:59:06 +00001412implements the text wrapping strategy. Both the
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001413\class{TextWrapper} class and the \function{wrap()} and
1414\function{fill()} functions support a number of additional keyword
1415arguments for fine-tuning the formatting; consult the module's
Fred Drake5c4cf152002-11-13 14:59:06 +00001416documentation for details.
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001417%XXX add a link to the module docs?
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001418(Contributed by Greg Ward.)
1419
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001420\item The \module{thread} and \module{threading} modules now have
1421companion, \module{dummy_thread} and \module{dummy_threading}, that
1422provide a do-nothing implementation of the \module{thread} module's
1423interface, even if threads are not supported. The intention is to
1424simplify thread-aware modules (that \emph{don't} rely on threads to
1425run) by putting the following code at the top:
1426
1427% XXX why as _threading?
1428\begin{verbatim}
1429try:
1430 import threading as _threading
1431except ImportError:
1432 import dummy_threading as _threading
1433\end{verbatim}
1434
1435Code can then call functions and use classes in \module{_threading}
1436whether or not threads are supported, avoiding an \keyword{if}
1437statement and making the code slightly clearer. This module will not
1438magically make multithreaded code run without threads; code that waits
1439for another thread to return or to do something will simply hang
1440forever.
1441
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001442\item The \module{time} module's \function{strptime()} function has
Fred Drake5c4cf152002-11-13 14:59:06 +00001443long been an annoyance because it uses the platform C library's
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001444\function{strptime()} implementation, and different platforms
1445sometimes have odd bugs. Brett Cannon contributed a portable
1446implementation that's written in pure Python, which should behave
1447identically on all platforms.
1448
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001449\item The \module{UserDict} module has a new \class{DictMixin} class which
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001450defines all dictionary methods for classes that already have a minimum
1451mapping interface. This greatly simplifies writing classes that need
1452to be substitutable for dictionaries, such as the classes in
1453the \module{shelve} module.
1454
1455Adding the mixin as a superclass provides the full dictionary
1456interface whenever the class defines \method{__getitem__},
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001457\method{__setitem__}, \method{__delitem__}, and \method{keys}.
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001458For example:
1459
1460\begin{verbatim}
1461>>> import UserDict
1462>>> class SeqDict(UserDict.DictMixin):
1463 """Dictionary lookalike implemented with lists."""
1464 def __init__(self):
1465 self.keylist = []
1466 self.valuelist = []
1467 def __getitem__(self, key):
1468 try:
1469 i = self.keylist.index(key)
1470 except ValueError:
1471 raise KeyError
1472 return self.valuelist[i]
1473 def __setitem__(self, key, value):
1474 try:
1475 i = self.keylist.index(key)
1476 self.valuelist[i] = value
1477 except ValueError:
1478 self.keylist.append(key)
1479 self.valuelist.append(value)
1480 def __delitem__(self, key):
1481 try:
1482 i = self.keylist.index(key)
1483 except ValueError:
1484 raise KeyError
1485 self.keylist.pop(i)
1486 self.valuelist.pop(i)
1487 def keys(self):
1488 return list(self.keylist)
1489
1490>>> s = SeqDict()
1491>>> dir(s) # See that other dictionary methods are implemented
1492['__cmp__', '__contains__', '__delitem__', '__doc__', '__getitem__',
1493 '__init__', '__iter__', '__len__', '__module__', '__repr__',
1494 '__setitem__', 'clear', 'get', 'has_key', 'items', 'iteritems',
1495 'iterkeys', 'itervalues', 'keylist', 'keys', 'pop', 'popitem',
1496 'setdefault', 'update', 'valuelist', 'values']
Neal Norwitzc7d8c682002-12-24 14:51:43 +00001497\end{verbatim}
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001498
1499(Contributed by Raymond Hettinger.)
1500
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001501\item The DOM implementation
1502in \module{xml.dom.minidom} can now generate XML output in a
1503particular encoding, by specifying an optional encoding argument to
1504the \method{toxml()} and \method{toprettyxml()} methods of DOM nodes.
1505
Andrew M. Kuchlingbc5e3cc2002-11-05 00:26:33 +00001506\item The \function{*stat()} family of functions can now report
1507fractions of a second in a timestamp. Such time stamps are
1508represented as floats, similar to \function{time.time()}.
Martin v. Löwisf607bda2002-10-16 18:27:39 +00001509
Andrew M. Kuchlingbc5e3cc2002-11-05 00:26:33 +00001510During testing, it was found that some applications will break if time
1511stamps are floats. For compatibility, when using the tuple interface
Martin v. Löwisf607bda2002-10-16 18:27:39 +00001512of the \class{stat_result}, time stamps are represented as integers.
Andrew M. Kuchlingbc5e3cc2002-11-05 00:26:33 +00001513When using named fields (a feature first introduced in Python 2.2),
1514time stamps are still represented as ints, unless
1515\function{os.stat_float_times()} is invoked to enable float return
1516values:
Martin v. Löwisf607bda2002-10-16 18:27:39 +00001517
1518\begin{verbatim}
Andrew M. Kuchlingbc5e3cc2002-11-05 00:26:33 +00001519>>> os.stat("/tmp").st_mtime
15201034791200
Martin v. Löwisf607bda2002-10-16 18:27:39 +00001521>>> os.stat_float_times(True)
1522>>> os.stat("/tmp").st_mtime
15231034791200.6335014
1524\end{verbatim}
1525
Andrew M. Kuchlingbc5e3cc2002-11-05 00:26:33 +00001526In Python 2.4, the default will change to always returning floats.
Martin v. Löwisf607bda2002-10-16 18:27:39 +00001527
1528Application developers should use this feature only if all their
1529libraries work properly when confronted with floating point time
Andrew M. Kuchlingbc5e3cc2002-11-05 00:26:33 +00001530stamps, or if they use the tuple API. If used, the feature should be
1531activated on an application level instead of trying to enable it on a
Martin v. Löwisf607bda2002-10-16 18:27:39 +00001532per-use basis.
1533
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001534\item The \module{Tkinter} module now works with a thread-enabled
1535version of Tcl. Tcl's threading model requires that widgets only be
1536accessed from the thread in which they're created; accesses from
1537another thread can cause Tcl to panic. For certain Tcl interfaces,
1538\module{Tkinter} will now automatically avoid this by marshalling a
1539command, passing it to the correct thread, and waiting for the results
1540when a widget is accessed from a different thread. Other interfaces
1541can't be handled automatically but \module{Tkinter} will now raise an
1542exception on such an access so that you can at least find out about
1543the problem. See
1544\url{http://mail.python.org/pipermail/python-dev/2002-December/031107.html}
1545for a more detailed explanation of this change. (Implemented by
1546Martin von L\"owis.)
1547
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001548\item Calling Tcl methods through \module{_tkinter} no longer
1549returns only strings. Instead, if Tcl returns other objects those
1550objects are converted to their Python equivalent, if one exists, or
1551wrapped with a \class{_tkinter.Tcl_Obj} object if no Python equivalent
Raymond Hettinger45bda572002-12-14 20:20:45 +00001552exists. This behavior can be controlled through the
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001553\method{wantobjects()} method of \class{tkapp} objects.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001554
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001555When using \module{_tkinter} through the \module{Tkinter} module (as
1556most Tkinter applications will), this feature is always activated. It
1557should not cause compatibility problems, since Tkinter would always
1558convert string results to Python types where possible.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001559
Raymond Hettinger45bda572002-12-14 20:20:45 +00001560If any incompatibilities are found, the old behavior can be restored
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001561by setting the \member{wantobjects} variable in the \module{Tkinter}
1562module to false before creating the first \class{tkapp} object.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001563
1564\begin{verbatim}
1565import Tkinter
Martin v. Löwis8c8aa5d2002-11-26 21:39:48 +00001566Tkinter.wantobjects = 0
Martin v. Löwis39b48522002-11-26 09:47:25 +00001567\end{verbatim}
1568
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001569Any breakage caused by this change should be reported as a bug.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001570
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00001571\end{itemize}
1572
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00001573
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001574%======================================================================
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001575\subsection{The \module{optparse} Module}
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001576
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001577The \module{getopt} module provides simple parsing of command-line
1578arguments. The new \module{optparse} module (originally named Optik)
1579provides more elaborate command-line parsing that follows the Unix
1580conventions, automatically creates the output for \longprogramopt{help},
1581and can perform different actions
1582
1583You start by creating an instance of \class{OptionParser} and telling
1584it what your program's options are.
1585
1586\begin{verbatim}
1587from optparse import OptionParser
1588
1589op = OptionParser()
1590op.add_option('-i', '--input',
1591 action='store', type='string', dest='input',
1592 help='set input filename')
1593op.add_option('-l', '--length',
1594 action='store', type='int', dest='length',
1595 help='set maximum length of output')
1596\end{verbatim}
1597
1598Parsing a command line is then done by calling the \method{parse_args()}
1599method.
1600
1601\begin{verbatim}
1602options, args = op.parse_args(sys.argv[1:])
1603print options
1604print args
1605\end{verbatim}
1606
1607This returns an object containing all of the option values,
1608and a list of strings containing the remaining arguments.
1609
1610Invoking the script with the various arguments now works as you'd
1611expect it to. Note that the length argument is automatically
1612converted to an integer.
1613
1614\begin{verbatim}
1615$ ./python opt.py -i data arg1
1616<Values at 0x400cad4c: {'input': 'data', 'length': None}>
1617['arg1']
1618$ ./python opt.py --input=data --length=4
1619<Values at 0x400cad2c: {'input': 'data', 'length': 4}>
1620['arg1']
1621$
1622\end{verbatim}
1623
1624The help message is automatically generated for you:
1625
1626\begin{verbatim}
1627$ ./python opt.py --help
1628usage: opt.py [options]
1629
1630options:
1631 -h, --help show this help message and exit
1632 -iINPUT, --input=INPUT
1633 set input filename
1634 -lLENGTH, --length=LENGTH
1635 set maximum length of output
1636$
1637\end{verbatim}
Andrew M. Kuchling669249e2002-11-19 13:05:33 +00001638% $ prevent Emacs tex-mode from getting confused
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001639
1640Optik was written by Greg Ward, with suggestions from the readers of
1641the Getopt SIG.
1642
1643\begin{seealso}
1644\seeurl{http://optik.sourceforge.net}
1645{The Optik site has tutorial and reference documentation for
1646\module{optparse}.
1647% XXX change to point to Python docs, when those docs get written.
1648}
1649\end{seealso}
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001650
1651
1652%======================================================================
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001653\section{Specialized Object Allocator (pymalloc)\label{section-pymalloc}}
1654
1655An experimental feature added to Python 2.1 was a specialized object
1656allocator called pymalloc, written by Vladimir Marangozov. Pymalloc
1657was intended to be faster than the system \cfunction{malloc()} and have
1658less memory overhead for typical allocation patterns of Python
1659programs. The allocator uses C's \cfunction{malloc()} function to get
1660large pools of memory, and then fulfills smaller memory requests from
1661these pools.
1662
1663In 2.1 and 2.2, pymalloc was an experimental feature and wasn't
1664enabled by default; you had to explicitly turn it on by providing the
1665\longprogramopt{with-pymalloc} option to the \program{configure}
1666script. In 2.3, pymalloc has had further enhancements and is now
1667enabled by default; you'll have to supply
1668\longprogramopt{without-pymalloc} to disable it.
1669
1670This change is transparent to code written in Python; however,
1671pymalloc may expose bugs in C extensions. Authors of C extension
1672modules should test their code with the object allocator enabled,
1673because some incorrect code may cause core dumps at runtime. There
1674are a bunch of memory allocation functions in Python's C API that have
1675previously been just aliases for the C library's \cfunction{malloc()}
1676and \cfunction{free()}, meaning that if you accidentally called
1677mismatched functions, the error wouldn't be noticeable. When the
1678object 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
1690functions from the other family.
1691
1692There is another family of functions specifically for allocating
1693Python \emph{objects} (as opposed to memory).
1694
1695\begin{itemize}
1696 \item To allocate and free an undistinguished chunk of memory use
1697 the ``raw memory'' family: \cfunction{PyMem_Malloc()},
1698 \cfunction{PyMem_Realloc()}, and \cfunction{PyMem_Free()}.
1699
1700 \item The ``object memory'' family is the interface to the pymalloc
1701 facility described above and is biased towards a large number of
1702 ``small'' allocations: \cfunction{PyObject_Malloc},
1703 \cfunction{PyObject_Realloc}, and \cfunction{PyObject_Free}.
1704
1705 \item To allocate and free Python objects, use the ``object'' family
1706 \cfunction{PyObject_New()}, \cfunction{PyObject_NewVar()}, and
1707 \cfunction{PyObject_Del()}.
1708\end{itemize}
1709
1710Thanks to lots of work by Tim Peters, pymalloc in 2.3 also provides
1711debugging features to catch memory overwrites and doubled frees in
1712both extension modules and in the interpreter itself. To enable this
1713support, turn on the Python interpreter's debugging code by running
Fred Drake5c4cf152002-11-13 14:59:06 +00001714\program{configure} with \longprogramopt{with-pydebug}.
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001715
1716To aid extension writers, a header file \file{Misc/pymemcompat.h} is
1717distributed with the source to Python 2.3 that allows Python
1718extensions to use the 2.3 interfaces to memory allocation and compile
1719against any version of Python since 1.5.2. You would copy the file
1720from Python's source distribution and bundle it with the source of
1721your extension.
1722
1723\begin{seealso}
1724
1725\seeurl{http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Objects/obmalloc.c}
1726{For the full details of the pymalloc implementation, see
1727the comments at the top of the file \file{Objects/obmalloc.c} in the
1728Python source code. The above link points to the file within the
1729SourceForge CVS browser.}
1730
1731\end{seealso}
1732
1733
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00001734% ======================================================================
1735\section{Build and C API Changes}
1736
Andrew M. Kuchling3c305d92002-07-22 18:50:11 +00001737Changes to Python's build process and to the C API include:
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00001738
1739\begin{itemize}
1740
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001741\item The C-level interface to the garbage collector has been changed,
1742to make it easier to write extension types that support garbage
1743collection, and to make it easier to debug misuses of the functions.
1744Various functions have slightly different semantics, so a bunch of
1745functions had to be renamed. Extensions that use the old API will
1746still compile but will \emph{not} participate in garbage collection,
1747so updating them for 2.3 should be considered fairly high priority.
1748
1749To upgrade an extension module to the new API, perform the following
1750steps:
1751
1752\begin{itemize}
1753
1754\item Rename \cfunction{Py_TPFLAGS_GC} to \cfunction{PyTPFLAGS_HAVE_GC}.
1755
1756\item Use \cfunction{PyObject_GC_New} or \cfunction{PyObject_GC_NewVar} to
1757allocate objects, and \cfunction{PyObject_GC_Del} to deallocate them.
1758
1759\item Rename \cfunction{PyObject_GC_Init} to \cfunction{PyObject_GC_Track} and
1760\cfunction{PyObject_GC_Fini} to \cfunction{PyObject_GC_UnTrack}.
1761
1762\item Remove \cfunction{PyGC_HEAD_SIZE} from object size calculations.
1763
1764\item Remove calls to \cfunction{PyObject_AS_GC} and \cfunction{PyObject_FROM_GC}.
1765
1766\end{itemize}
1767
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001768It's also no longer possible to build Python without the garbage collector.
1769
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001770\item Python can now optionally be built as a shared library
1771(\file{libpython2.3.so}) by supplying \longprogramopt{enable-shared}
Fred Drake5c4cf152002-11-13 14:59:06 +00001772when running Python's \program{configure} script. (Contributed by Ondrej
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +00001773Palkovsky.)
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +00001774
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001775\item The \csimplemacro{DL_EXPORT} and \csimplemacro{DL_IMPORT} macros
1776are now deprecated. Initialization functions for Python extension
1777modules should now be declared using the new macro
Andrew M. Kuchling3c305d92002-07-22 18:50:11 +00001778\csimplemacro{PyMODINIT_FUNC}, while the Python core will generally
1779use the \csimplemacro{PyAPI_FUNC} and \csimplemacro{PyAPI_DATA}
1780macros.
Neal Norwitzbba23a82002-07-22 13:18:59 +00001781
Fred Drake5c4cf152002-11-13 14:59:06 +00001782\item The interpreter can be compiled without any docstrings for
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001783the built-in functions and modules by supplying
Fred Drake5c4cf152002-11-13 14:59:06 +00001784\longprogramopt{without-doc-strings} to the \program{configure} script.
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001785This makes the Python executable about 10\% smaller, but will also
1786mean that you can't get help for Python's built-ins. (Contributed by
1787Gustavo Niemeyer.)
1788
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001789\item The cycle detection implementation used by the garbage collection
1790has proven to be stable, so it's now being made mandatory; you can no
1791longer compile Python without it, and the
Fred Drake5c4cf152002-11-13 14:59:06 +00001792\longprogramopt{with-cycle-gc} switch to \program{configure} has been removed.
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001793
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001794\item The \cfunction{PyArg_NoArgs()} macro is now deprecated, and code
Andrew M. Kuchling7845e7c2002-07-11 19:27:46 +00001795that uses it should be changed. For Python 2.2 and later, the method
1796definition table can specify the
Fred Drake5c4cf152002-11-13 14:59:06 +00001797\constant{METH_NOARGS} flag, signalling that there are no arguments, and
Andrew M. Kuchling7845e7c2002-07-11 19:27:46 +00001798the argument checking can then be removed. If compatibility with
1799pre-2.2 versions of Python is important, the code could use
Fred Drake5c4cf152002-11-13 14:59:06 +00001800\code{PyArg_ParseTuple(args, "")} instead, but this will be slower
Andrew M. Kuchling7845e7c2002-07-11 19:27:46 +00001801than using \constant{METH_NOARGS}.
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00001802
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001803\item A new function, \cfunction{PyObject_DelItemString(\var{mapping},
1804char *\var{key})} was added
Fred Drake5c4cf152002-11-13 14:59:06 +00001805as shorthand for
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001806\code{PyObject_DelItem(\var{mapping}, PyString_New(\var{key})}.
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00001807
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001808\item The \method{xreadlines()} method of file objects, introduced in
1809Python 2.1, is no longer necessary because files now behave as their
1810own iterator. \method{xreadlines()} was originally introduced as a
1811faster way to loop over all the lines in a file, but now you can
1812simply write \code{for line in file_obj}.
1813
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001814\item File objects now manage their internal string buffer
Fred Drake5c4cf152002-11-13 14:59:06 +00001815differently by increasing it exponentially when needed.
1816This results in the benchmark tests in \file{Lib/test/test_bufio.py}
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001817speeding up from 57 seconds to 1.7 seconds, according to one
1818measurement.
1819
Andrew M. Kuchling72b58e02002-05-29 17:30:34 +00001820\item It's now possible to define class and static methods for a C
1821extension type by setting either the \constant{METH_CLASS} or
1822\constant{METH_STATIC} flags in a method's \ctype{PyMethodDef}
1823structure.
Andrew M. Kuchling45afd542002-04-02 14:25:25 +00001824
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00001825\item Python now includes a copy of the Expat XML parser's source code,
1826removing any dependence on a system version or local installation of
Fred Drake5c4cf152002-11-13 14:59:06 +00001827Expat.
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00001828
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00001829\end{itemize}
1830
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001831
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001832%======================================================================
1833\subsection{Date/Time Type}
1834
1835Date and time types suitable for expressing timestamps were added as
1836the \module{datetime} module. The types don't support different
Andrew M. Kuchling5095a472002-12-31 02:48:59 +00001837calendars or many fancy features, and just stick to the basics of
1838representing time.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001839
1840The three primary types are: \class{date}, representing a day, month,
1841and year; \class{time}, consisting of hour, minute, and second value;
Andrew M. Kuchling5095a472002-12-31 02:48:59 +00001842and \class{datetime}, which contains both a date and a time. These
1843basic types don't understand time zones, but there are subclasses
1844named \class{timetz} and \class{datetimetz} that do. There's also a
1845\class{timedelta} class representing a difference between two points
1846in time, and time zone logic is implemented by classes inheriting from
1847the abstract \class{tzinfo} class.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001848
Andrew M. Kuchling5095a472002-12-31 02:48:59 +00001849You can create instances of \class{date} and \class{time} by either
1850supplying keyword arguments to the constructor,
1851e.g. \code{datetime.date(year=1972, month=10, day=15)}, or by using
1852one of a number of class methods. For example, the \method{today()}
1853class method returns the current local date:
1854\code{datetime.date.today()}.
1855
1856Once created, instances of the date/time classes are all immutable.
1857There are a number of methods for producing formatted strings from
1858objects,
1859
1860\begin{verbatim}
1861>>> import datetime
1862>>> now = datetime.datetime.now()
1863>>> now.isoformat()
1864'2002-12-30T21:27:03.994956'
1865>>> now.ctime() # Only available on date, datetime
1866'Mon Dec 30 21:27:03 2002'
1867>>> now.strftime('%Y %d %h')
1868'2002 30 Dec'
1869\end{verbatim}
1870
1871The \method{replace()} method allows modifying one or more fields
1872of a \class{date} or \class{datetime} instance:
1873
1874\begin{verbatim}
1875>>> d = datetime.datetime.now()
1876>>> d
1877datetime.datetime(2002, 12, 30, 22, 15, 38, 827738)
1878>>> d.replace(year=2001, hour = 12)
1879datetime.datetime(2001, 12, 30, 12, 15, 38, 827738)
1880>>>
1881\end{verbatim}
1882
1883Instances can be compared, hashed, and converted to strings (the
1884result is the same as that of \method{isoformat()}). \class{date} and
1885\class{datetime} instances can be subtracted from each other, and
1886added to \class{timedelta} instances.
1887
1888For more information, refer to the \ulink{module's reference
1889documentation}{http://www.python.org/dev/doc/devel/lib/module-datetime.html}.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001890
1891
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001892%======================================================================
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00001893\subsection{Port-Specific Changes}
1894
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00001895Support for a port to IBM's OS/2 using the EMX runtime environment was
1896merged into the main Python source tree. EMX is a POSIX emulation
1897layer over the OS/2 system APIs. The Python port for EMX tries to
1898support all the POSIX-like capability exposed by the EMX runtime, and
1899mostly succeeds; \function{fork()} and \function{fcntl()} are
1900restricted by the limitations of the underlying emulation layer. The
1901standard OS/2 port, which uses IBM's Visual Age compiler, also gained
1902support for case-sensitive import semantics as part of the integration
1903of the EMX port into CVS. (Contributed by Andrew MacIntyre.)
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00001904
Andrew M. Kuchling72b58e02002-05-29 17:30:34 +00001905On MacOS, most toolbox modules have been weaklinked to improve
1906backward compatibility. This means that modules will no longer fail
1907to load if a single routine is missing on the curent OS version.
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00001908Instead calling the missing routine will raise an exception.
1909(Contributed by Jack Jansen.)
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00001910
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00001911The RPM spec files, found in the \file{Misc/RPM/} directory in the
1912Python source distribution, were updated for 2.3. (Contributed by
1913Sean Reifschneider.)
Fred Drake03e10312002-03-26 19:17:43 +00001914
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001915Python now supports AtheOS (\url{http://www.atheos.cx}), GNU/Hurd,
1916OpenVMS, and OS/2 with EMX.
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001917
Fred Drake03e10312002-03-26 19:17:43 +00001918
1919%======================================================================
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001920\section{Other Changes and Fixes}
1921
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +00001922As usual, there were a bunch of other improvements and bugfixes
1923scattered throughout the source tree. A search through the CVS change
1924logs finds there were 289 patches applied and 323 bugs fixed between
1925Python 2.2 and 2.3. Both figures are likely to be underestimates.
1926
1927Some of the more notable changes are:
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001928
1929\begin{itemize}
1930
Fred Drake54fe3fd2002-11-26 22:07:35 +00001931\item The \file{regrtest.py} script now provides a way to allow ``all
1932resources except \var{foo}.'' A resource name passed to the
1933\programopt{-u} option can now be prefixed with a hyphen
1934(\character{-}) to mean ``remove this resource.'' For example, the
1935option `\code{\programopt{-u}all,-bsddb}' could be used to enable the
1936use of all resources except \code{bsddb}.
1937
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001938\item The tools used to build the documentation now work under Cygwin
1939as well as \UNIX.
1940
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001941\item The \code{SET_LINENO} opcode has been removed. Back in the
1942mists of time, this opcode was needed to produce line numbers in
1943tracebacks and support trace functions (for, e.g., \module{pdb}).
1944Since Python 1.5, the line numbers in tracebacks have been computed
1945using a different mechanism that works with ``python -O''. For Python
19462.3 Michael Hudson implemented a similar scheme to determine when to
1947call the trace function, removing the need for \code{SET_LINENO}
1948entirely.
1949
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +00001950It would be difficult to detect any resulting difference from Python
1951code, apart from a slight speed up when Python is run without
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001952\programopt{-O}.
1953
1954C extensions that access the \member{f_lineno} field of frame objects
1955should instead call \code{PyCode_Addr2Line(f->f_code, f->f_lasti)}.
1956This will have the added effect of making the code work as desired
1957under ``python -O'' in earlier versions of Python.
1958
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001959A nifty new feature is that trace functions can now the
1960\member{f_lineno} attribute of frame objects can now be assigned to,
1961changing the line that will be executed next. A \samp{jump} command
1962has been added to the \module{pdb} debugger taking advantage of this
1963new feature. (Implemented by Richie Hindle.)
1964
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001965\end{itemize}
1966
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00001967
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001968%======================================================================
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001969\section{Porting to Python 2.3}
1970
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001971This section lists changes that may actually require changes to your code:
1972
1973\begin{itemize}
1974
1975\item \keyword{yield} is now always a keyword; if it's used as a
1976variable name in your code, a different name must be chosen.
1977
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001978\item For strings \var{X} and \var{Y}, \code{\var{X} in \var{Y}} now works
1979if \var{X} is more than one character long.
1980
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00001981\item The \function{int()} type constructor will now return a long
1982integer instead of raising an \exception{OverflowError} when a string
1983or floating-point number is too large to fit into an integer.
1984
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001985\item Calling Tcl methods through \module{_tkinter} no longer
1986returns only strings. Instead, if Tcl returns other objects those
1987objects are converted to their Python equivalent, if one exists, or
1988wrapped with a \class{_tkinter.Tcl_Obj} object if no Python equivalent
1989exists.
1990
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00001991\item You can no longer disable assertions by assigning to \code{__debug__}.
1992
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001993\item The Distutils \function{setup()} function has gained various new
Fred Drake5c4cf152002-11-13 14:59:06 +00001994keyword arguments such as \var{depends}. Old versions of the
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001995Distutils will abort if passed unknown keywords. The fix is to check
1996for the presence of the new \function{get_distutil_options()} function
1997in your \file{setup.py} if you want to only support the new keywords
1998with a version of the Distutils that supports them:
1999
2000\begin{verbatim}
2001from distutils import core
2002
2003kw = {'sources': 'foo.c', ...}
2004if hasattr(core, 'get_distutil_options'):
2005 kw['depends'] = ['foo.h']
Fred Drake5c4cf152002-11-13 14:59:06 +00002006ext = Extension(**kw)
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002007\end{verbatim}
2008
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00002009\item Using \code{None} as a variable name will now result in a
2010\exception{SyntaxWarning} warning.
2011
2012\item Names of extension types defined by the modules included with
2013Python now contain the module and a \character{.} in front of the type
2014name.
2015
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002016\end{itemize}
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00002017
2018
2019%======================================================================
Fred Drake03e10312002-03-26 19:17:43 +00002020\section{Acknowledgements \label{acks}}
2021
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00002022The author would like to thank the following people for offering
2023suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00002024article: Simon Brunning, Michael Chermside, Scott David Daniels,
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00002025Fred~L. Drake, Jr., Raymond Hettinger, Michael Hudson, Detlef Lannert,
2026Martin von L\"owis, Andrew MacIntyre, Lalo Martins, Gustavo Niemeyer,
2027Neal Norwitz, Chris Reedy, Vinay Sajip, Neil Schemenauer, Jason
2028Tishler.
Fred Drake03e10312002-03-26 19:17:43 +00002029
2030\end{document}