blob: 446ce43020801da17a0978a8d48eacc25eac65bf [file] [log] [blame]
Fred Drake03e10312002-03-26 19:17:43 +00001\documentclass{howto}
Fred Drake693aea22003-02-07 14:52:18 +00002\usepackage{distutils}
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00003% $Id$
4
5\title{What's New in Python 2.3}
Andrew M. Kuchlingd97b01c2003-01-08 02:09:40 +00006\release{0.08}
Fred Drakeaac8c582003-01-17 22:50:10 +00007\author{A.M.\ Kuchling}
Andrew M. Kuchlingbc5e3cc2002-11-05 00:26:33 +00008\authoraddress{\email{amk@amk.ca}}
Fred Drake03e10312002-03-26 19:17:43 +00009
10\begin{document}
11\maketitle
12\tableofcontents
13
Andrew M. Kuchlingc61ec522002-08-04 01:20:05 +000014% MacOS framework-related changes (section of its own, probably)
Andrew M. Kuchlingf70a0a82002-06-10 13:22:46 +000015
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +000016%\section{Introduction \label{intro}}
17
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +000018{\large This article is a draft, and is currently up to date for
19Python 2.3alpha1. Please send any additions, comments or errata to
20the author.}
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +000021
22This article explains the new features in Python 2.3. The tentative
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +000023release date of Python 2.3 is currently scheduled for mid-2003.
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,
Fred Drake693aea22003-02-07 14:52:18 +000028such as the \citetitle[../lib/lib.html]{Python Library Reference} and
29the \citetitle[../ref/ref.html]{Python Reference Manual}. If you want
30to understand the complete implementation and design rationale for a
31change, refer to the PEP for a particular new feature.
Fred Drake03e10312002-03-26 19:17:43 +000032
33
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +000034%======================================================================
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000035\section{PEP 218: A Standard Set Datatype}
36
37The new \module{sets} module contains an implementation of a set
38datatype. The \class{Set} class is for mutable sets, sets that can
39have members added and removed. The \class{ImmutableSet} class is for
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +000040sets that can't be modified, and instances of \class{ImmutableSet} can
41therefore be used as dictionary keys. Sets are built on top of
42dictionaries, so the elements within a set must be hashable.
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000043
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +000044Here's a simple example:
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000045
46\begin{verbatim}
47>>> import sets
48>>> S = sets.Set([1,2,3])
49>>> S
50Set([1, 2, 3])
51>>> 1 in S
52True
53>>> 0 in S
54False
55>>> S.add(5)
56>>> S.remove(3)
57>>> S
58Set([1, 2, 5])
Fred Drake5c4cf152002-11-13 14:59:06 +000059>>>
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000060\end{verbatim}
61
62The union and intersection of sets can be computed with the
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +000063\method{union()} and \method{intersection()} methods or
64alternatively using the bitwise operators \code{\&} and \code{|}.
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000065Mutable sets also have in-place versions of these methods,
66\method{union_update()} and \method{intersection_update()}.
67
68\begin{verbatim}
69>>> S1 = sets.Set([1,2,3])
70>>> S2 = sets.Set([4,5,6])
71>>> S1.union(S2)
72Set([1, 2, 3, 4, 5, 6])
73>>> S1 | S2 # Alternative notation
74Set([1, 2, 3, 4, 5, 6])
Fred Drake5c4cf152002-11-13 14:59:06 +000075>>> S1.intersection(S2)
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000076Set([])
77>>> S1 & S2 # Alternative notation
78Set([])
79>>> S1.union_update(S2)
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000080>>> S1
81Set([1, 2, 3, 4, 5, 6])
Fred Drake5c4cf152002-11-13 14:59:06 +000082>>>
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000083\end{verbatim}
84
85It's also possible to take the symmetric difference of two sets. This
86is the set of all elements in the union that aren't in the
87intersection. An alternative way of expressing the symmetric
88difference is that it contains all elements that are in exactly one
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +000089set. Again, there's an alternative notation (\code{\^}), and an
90in-place version with the ungainly name
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +000091\method{symmetric_difference_update()}.
92
93\begin{verbatim}
94>>> S1 = sets.Set([1,2,3,4])
95>>> S2 = sets.Set([3,4,5,6])
96>>> S1.symmetric_difference(S2)
97Set([1, 2, 5, 6])
98>>> S1 ^ S2
99Set([1, 2, 5, 6])
100>>>
101\end{verbatim}
102
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000103There are also \method{issubset()} and \method{issuperset()} methods
Michael W. Hudson065f5fa2003-02-10 19:24:50 +0000104for checking whether one set is a subset or superset of another:
Andrew M. Kuchlingbc465102002-08-20 01:34:06 +0000105
106\begin{verbatim}
107>>> S1 = sets.Set([1,2,3])
108>>> S2 = sets.Set([2,3])
109>>> S2.issubset(S1)
110True
111>>> S1.issubset(S2)
112False
113>>> S1.issuperset(S2)
114True
115>>>
116\end{verbatim}
117
118
119\begin{seealso}
120
121\seepep{218}{Adding a Built-In Set Object Type}{PEP written by Greg V. Wilson.
122Implemented by Greg V. Wilson, Alex Martelli, and GvR.}
123
124\end{seealso}
125
126
127
128%======================================================================
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000129\section{PEP 255: Simple Generators\label{section-generators}}
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000130
131In Python 2.2, generators were added as an optional feature, to be
132enabled by a \code{from __future__ import generators} directive. In
1332.3 generators no longer need to be specially enabled, and are now
134always present; this means that \keyword{yield} is now always a
135keyword. The rest of this section is a copy of the description of
136generators from the ``What's New in Python 2.2'' document; if you read
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000137it back when Python 2.2 came out, you can skip the rest of this section.
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000138
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000139You're doubtless familiar with how function calls work in Python or C.
140When you call a function, it gets a private namespace where its local
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000141variables are created. When the function reaches a \keyword{return}
142statement, the local variables are destroyed and the resulting value
143is returned to the caller. A later call to the same function will get
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000144a fresh new set of local variables. But, what if the local variables
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000145weren't thrown away on exiting a function? What if you could later
146resume the function where it left off? This is what generators
147provide; they can be thought of as resumable functions.
148
149Here's the simplest example of a generator function:
150
151\begin{verbatim}
152def generate_ints(N):
153 for i in range(N):
154 yield i
155\end{verbatim}
156
157A new keyword, \keyword{yield}, was introduced for generators. Any
158function containing a \keyword{yield} statement is a generator
159function; this is detected by Python's bytecode compiler which
Fred Drake5c4cf152002-11-13 14:59:06 +0000160compiles the function specially as a result.
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000161
162When you call a generator function, it doesn't return a single value;
163instead it returns a generator object that supports the iterator
164protocol. On executing the \keyword{yield} statement, the generator
165outputs the value of \code{i}, similar to a \keyword{return}
166statement. The big difference between \keyword{yield} and a
167\keyword{return} statement is that on reaching a \keyword{yield} the
168generator's state of execution is suspended and local variables are
169preserved. On the next call to the generator's \code{.next()} method,
170the function will resume executing immediately after the
171\keyword{yield} statement. (For complicated reasons, the
172\keyword{yield} statement isn't allowed inside the \keyword{try} block
Fred Drakeaac8c582003-01-17 22:50:10 +0000173of a \keyword{try}...\keyword{finally} statement; read \pep{255} for a full
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000174explanation of the interaction between \keyword{yield} and
175exceptions.)
176
Fred Drakeaac8c582003-01-17 22:50:10 +0000177Here's a sample usage of the \function{generate_ints()} generator:
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000178
179\begin{verbatim}
180>>> gen = generate_ints(3)
181>>> gen
182<generator object at 0x8117f90>
183>>> gen.next()
1840
185>>> gen.next()
1861
187>>> gen.next()
1882
189>>> gen.next()
190Traceback (most recent call last):
Andrew M. Kuchling9f6e1042002-06-17 13:40:04 +0000191 File "stdin", line 1, in ?
192 File "stdin", line 2, in generate_ints
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000193StopIteration
194\end{verbatim}
195
196You could equally write \code{for i in generate_ints(5)}, or
197\code{a,b,c = generate_ints(3)}.
198
199Inside a generator function, the \keyword{return} statement can only
200be used without a value, and signals the end of the procession of
201values; afterwards the generator cannot return any further values.
202\keyword{return} with a value, such as \code{return 5}, is a syntax
203error inside a generator function. The end of the generator's results
204can also be indicated by raising \exception{StopIteration} manually,
205or by just letting the flow of execution fall off the bottom of the
206function.
207
208You could achieve the effect of generators manually by writing your
209own class and storing all the local variables of the generator as
210instance variables. For example, returning a list of integers could
211be done by setting \code{self.count} to 0, and having the
212\method{next()} method increment \code{self.count} and return it.
213However, for a moderately complicated generator, writing a
214corresponding class would be much messier.
215\file{Lib/test/test_generators.py} contains a number of more
216interesting examples. The simplest one implements an in-order
217traversal of a tree using generators recursively.
218
219\begin{verbatim}
220# A recursive generator that generates Tree leaves in in-order.
221def inorder(t):
222 if t:
223 for x in inorder(t.left):
224 yield x
225 yield t.label
226 for x in inorder(t.right):
227 yield x
228\end{verbatim}
229
230Two other examples in \file{Lib/test/test_generators.py} produce
231solutions for the N-Queens problem (placing $N$ queens on an $NxN$
232chess board so that no queen threatens another) and the Knight's Tour
233(a route that takes a knight to every square of an $NxN$ chessboard
Fred Drake5c4cf152002-11-13 14:59:06 +0000234without visiting any square twice).
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000235
236The idea of generators comes from other programming languages,
237especially Icon (\url{http://www.cs.arizona.edu/icon/}), where the
238idea of generators is central. In Icon, every
239expression and function call behaves like a generator. One example
240from ``An Overview of the Icon Programming Language'' at
241\url{http://www.cs.arizona.edu/icon/docs/ipd266.htm} gives an idea of
242what this looks like:
243
244\begin{verbatim}
245sentence := "Store it in the neighboring harbor"
246if (i := find("or", sentence)) > 5 then write(i)
247\end{verbatim}
248
249In Icon the \function{find()} function returns the indexes at which the
250substring ``or'' is found: 3, 23, 33. In the \keyword{if} statement,
251\code{i} is first assigned a value of 3, but 3 is less than 5, so the
252comparison fails, and Icon retries it with the second value of 23. 23
253is greater than 5, so the comparison now succeeds, and the code prints
254the value 23 to the screen.
255
256Python doesn't go nearly as far as Icon in adopting generators as a
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000257central concept. Generators are considered part of the core
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000258Python language, but learning or using them isn't compulsory; if they
259don't solve any problems that you have, feel free to ignore them.
260One novel feature of Python's interface as compared to
261Icon's is that a generator's state is represented as a concrete object
262(the iterator) that can be passed around to other functions or stored
263in a data structure.
264
265\begin{seealso}
266
267\seepep{255}{Simple Generators}{Written by Neil Schemenauer, Tim
268Peters, Magnus Lie Hetland. Implemented mostly by Neil Schemenauer
269and Tim Peters, with other fixes from the Python Labs crew.}
270
271\end{seealso}
272
273
274%======================================================================
Fred Drake13090e12002-08-22 16:51:08 +0000275\section{PEP 263: Source Code Encodings \label{section-encodings}}
Andrew M. Kuchling950725f2002-08-06 01:40:48 +0000276
277Python source files can now be declared as being in different
278character set encodings. Encodings are declared by including a
279specially formatted comment in the first or second line of the source
280file. For example, a UTF-8 file can be declared with:
281
282\begin{verbatim}
283#!/usr/bin/env python
284# -*- coding: UTF-8 -*-
285\end{verbatim}
286
287Without such an encoding declaration, the default encoding used is
Fred Drake5c4cf152002-11-13 14:59:06 +0000288ISO-8859-1, also known as Latin1.
Andrew M. Kuchling950725f2002-08-06 01:40:48 +0000289
290The encoding declaration only affects Unicode string literals; the
291text in the source code will be converted to Unicode using the
292specified encoding. Note that Python identifiers are still restricted
293to ASCII characters, so you can't have variable names that use
294characters outside of the usual alphanumerics.
295
296\begin{seealso}
297
298\seepep{263}{Defining Python Source Code Encodings}{Written by
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000299Marc-Andr\'e Lemburg and Martin von L\"owis; implemented by SUZUKI
300Hisao and Martin von L\"owis.}
Andrew M. Kuchling950725f2002-08-06 01:40:48 +0000301
302\end{seealso}
303
304
305%======================================================================
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000306\section{PEP 277: Unicode file name support for Windows NT}
Andrew M. Kuchling0f345562002-10-04 22:34:11 +0000307
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000308On Windows NT, 2000, and XP, the system stores file names as Unicode
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000309strings. Traditionally, Python has represented file names as byte
310strings, which is inadequate because it renders some file names
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000311inaccessible.
312
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000313Python now allows using arbitrary Unicode strings (within the
314limitations of the file system) for all functions that expect file
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000315names, most notably the \function{open()} built-in function. If a Unicode
316string is passed to \function{os.listdir()}, Python now returns a list
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000317of Unicode strings. A new function, \function{os.getcwdu()}, returns
318the current directory as a Unicode string.
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000319
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000320Byte strings still work as file names, and on Windows Python will
321transparently convert them to Unicode using the \code{mbcs} encoding.
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000322
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000323Other systems also allow Unicode strings as file names but convert
324them to byte strings before passing them to the system, which can
325cause a \exception{UnicodeError} to be raised. Applications can test
326whether arbitrary Unicode strings are supported as file names by
Andrew M. Kuchlingb9ba4e62003-02-03 15:16:15 +0000327checking \member{os.path.supports_unicode_filenames}, a Boolean value.
Martin v. Löwisbd5e38d2002-10-07 18:52:29 +0000328
329\begin{seealso}
330
331\seepep{277}{Unicode file name support for Windows NT}{Written by Neil
332Hodgson; implemented by Neil Hodgson, Martin von L\"owis, and Mark
333Hammond.}
334
335\end{seealso}
Andrew M. Kuchling0f345562002-10-04 22:34:11 +0000336
337
338%======================================================================
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000339\section{PEP 278: Universal Newline Support}
340
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000341The three major operating systems used today are Microsoft Windows,
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000342Apple's Macintosh OS, and the various \UNIX\ derivatives. A minor
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000343irritation is that these three platforms all use different characters
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000344to mark the ends of lines in text files. \UNIX\ uses the linefeed
345(ASCII character 10), while MacOS uses the carriage return (ASCII
346character 13), and Windows uses a two-character sequence containing a
347carriage return plus a newline.
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000348
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000349Python's file objects can now support end of line conventions other
350than the one followed by the platform on which Python is running.
Fred Drake5c4cf152002-11-13 14:59:06 +0000351Opening a file with the mode \code{'U'} or \code{'rU'} will open a file
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000352for reading in universal newline mode. All three line ending
Fred Drake5c4cf152002-11-13 14:59:06 +0000353conventions will be translated to a \character{\e n} in the strings
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000354returned by the various file methods such as \method{read()} and
Fred Drake5c4cf152002-11-13 14:59:06 +0000355\method{readline()}.
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000356
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000357Universal newline support is also used when importing modules and when
358executing a file with the \function{execfile()} function. This means
359that Python modules can be shared between all three operating systems
360without needing to convert the line-endings.
361
Fred Drake5c4cf152002-11-13 14:59:06 +0000362This feature can be disabled at compile-time by specifying
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000363\longprogramopt{without-universal-newlines} when running Python's
Fred Drake5c4cf152002-11-13 14:59:06 +0000364\program{configure} script.
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000365
366\begin{seealso}
367
Fred Drake5c4cf152002-11-13 14:59:06 +0000368\seepep{278}{Universal Newline Support}{Written
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000369and implemented by Jack Jansen.}
370
371\end{seealso}
372
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +0000373
374%======================================================================
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000375\section{PEP 279: The \function{enumerate()} Built-in Function\label{section-enumerate}}
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +0000376
377A new built-in function, \function{enumerate()}, will make
378certain loops a bit clearer. \code{enumerate(thing)}, where
379\var{thing} is either an iterator or a sequence, returns a iterator
380that will return \code{(0, \var{thing[0]})}, \code{(1,
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000381\var{thing[1]})}, \code{(2, \var{thing[2]})}, and so forth.
382
383Fairly often you'll see code to change every element of a list that
384looks like this:
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +0000385
386\begin{verbatim}
387for i in range(len(L)):
388 item = L[i]
389 # ... compute some result based on item ...
390 L[i] = result
391\end{verbatim}
392
393This can be rewritten using \function{enumerate()} as:
394
395\begin{verbatim}
396for i, item in enumerate(L):
397 # ... compute some result based on item ...
398 L[i] = result
399\end{verbatim}
400
401
402\begin{seealso}
403
Fred Drake5c4cf152002-11-13 14:59:06 +0000404\seepep{279}{The enumerate() built-in function}{Written
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000405and implemented by Raymond D. Hettinger.}
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +0000406
407\end{seealso}
408
409
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000410%======================================================================
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000411\section{PEP 282: The \module{logging} Package}
412
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000413A standard package for writing logs, \module{logging}, has been added
414to Python 2.3. It provides a powerful and flexible mechanism for
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000415components to generate logging output which can then be filtered and
416processed in various ways. A standard configuration file format can
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000417be used to control the logging behavior of a program. Python's
418standard library includes handlers that will write log records to
419standard error or to a file or socket, send them to the system log, or
420even e-mail them to a particular address, and of course it's also
421possible to write your own handler classes.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000422
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000423The \class{Logger} class is the primary class.
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000424Most application code will deal with one or more \class{Logger}
425objects, each one used by a particular subsystem of the application.
426Each \class{Logger} is identified by a name, and names are organized
427into a hierarchy using \samp{.} as the component separator. For
428example, you might have \class{Logger} instances named \samp{server},
429\samp{server.auth} and \samp{server.network}. The latter two
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000430instances are below \samp{server} in the hierarchy. This means that
431if you turn up the verbosity for \samp{server} or direct \samp{server}
432messages to a different handler, the changes will also apply to
433records logged to \samp{server.auth} and \samp{server.network}.
434There's also a root \class{Logger} that's the parent of all other
435loggers.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000436
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000437For simple uses, the \module{logging} package contains some
438convenience functions that always use the root log:
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000439
440\begin{verbatim}
441import logging
442
443logging.debug('Debugging information')
444logging.info('Informational message')
Andrew M. Kuchlingb1e4bf92002-12-03 13:35:17 +0000445logging.warn('Warning:config file %s not found', 'server.conf')
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000446logging.error('Error occurred')
447logging.critical('Critical error -- shutting down')
448\end{verbatim}
449
450This produces the following output:
451
452\begin{verbatim}
Andrew M. Kuchlingb1e4bf92002-12-03 13:35:17 +0000453WARN:root:Warning:config file server.conf not found
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000454ERROR:root:Error occurred
455CRITICAL:root:Critical error -- shutting down
456\end{verbatim}
457
458In the default configuration, informational and debugging messages are
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000459suppressed and the output is sent to standard error. You can enable
460the display of information and debugging messages by calling the
461\method{setLevel()} method on the root logger.
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000462
463Notice the \function{warn()} call's use of string formatting
464operators; all of the functions for logging messages take the
465arguments \code{(\var{msg}, \var{arg1}, \var{arg2}, ...)} and log the
466string resulting from \code{\var{msg} \% (\var{arg1}, \var{arg2},
467...)}.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000468
469There's also an \function{exception()} function that records the most
470recent traceback. Any of the other functions will also record the
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000471traceback if you specify a true value for the keyword argument
Fred Drakeaac8c582003-01-17 22:50:10 +0000472\var{exc_info}.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000473
474\begin{verbatim}
475def f():
476 try: 1/0
477 except: logging.exception('Problem recorded')
478
479f()
480\end{verbatim}
481
482This produces the following output:
483
484\begin{verbatim}
485ERROR:root:Problem recorded
486Traceback (most recent call last):
487 File "t.py", line 6, in f
488 1/0
489ZeroDivisionError: integer division or modulo by zero
490\end{verbatim}
491
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000492Slightly more advanced programs will use a logger other than the root
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000493logger. The \function{getLogger(\var{name})} function is used to get
494a particular log, creating it if it doesn't exist yet.
Andrew M. Kuchlingb1e4bf92002-12-03 13:35:17 +0000495\function{getLogger(None)} returns the root logger.
496
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000497
498\begin{verbatim}
499log = logging.getLogger('server')
500 ...
501log.info('Listening on port %i', port)
502 ...
503log.critical('Disk full')
504 ...
505\end{verbatim}
506
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000507Log records are usually propagated up the hierarchy, so a message
508logged to \samp{server.auth} is also seen by \samp{server} and
509\samp{root}, but a handler can prevent this by setting its
Fred Drakeaac8c582003-01-17 22:50:10 +0000510\member{propagate} attribute to \constant{False}.
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000511
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000512There are more classes provided by the \module{logging} package that
513can be customized. When a \class{Logger} instance is told to log a
514message, it creates a \class{LogRecord} instance that is sent to any
515number of different \class{Handler} instances. Loggers and handlers
516can also have an attached list of filters, and each filter can cause
517the \class{LogRecord} to be ignored or can modify the record before
518passing it along. \class{LogRecord} instances are converted to text
519for output by a \class{Formatter} class. All of these classes can be
520replaced by your own specially-written classes.
521
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +0000522With all of these features the \module{logging} package should provide
523enough flexibility for even the most complicated applications. This
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000524is only a partial overview of the \module{logging} package, so please
525see the \ulink{package's reference
Fred Drake693aea22003-02-07 14:52:18 +0000526documentation}{../lib/module-logging.html} for all of the details.
527Reading \pep{282} will also be helpful.
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +0000528
529
530\begin{seealso}
531
532\seepep{282}{A Logging System}{Written by Vinay Sajip and Trent Mick;
533implemented by Vinay Sajip.}
534
535\end{seealso}
536
537
538%======================================================================
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000539\section{PEP 285: The \class{bool} Type\label{section-bool}}
540
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000541A Boolean type was added to Python 2.3. Two new constants were added
542to the \module{__builtin__} module, \constant{True} and
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000543\constant{False}. (\constant{True} and
544\constant{False} constants were added to the built-ins
Michael W. Hudson065f5fa2003-02-10 19:24:50 +0000545in Python 2.2.1, but the 2.2.1 versions simply have integer values of
Andrew M. Kuchling5a224532003-01-03 16:52:27 +00005461 and 0 and aren't a different type.)
547
548The type object for this new type is named
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000549\class{bool}; the constructor for it takes any Python value and
550converts it to \constant{True} or \constant{False}.
551
552\begin{verbatim}
553>>> bool(1)
554True
555>>> bool(0)
556False
557>>> bool([])
558False
559>>> bool( (1,) )
560True
561\end{verbatim}
562
563Most of the standard library modules and built-in functions have been
564changed to return Booleans.
565
566\begin{verbatim}
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000567>>> obj = []
568>>> hasattr(obj, 'append')
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000569True
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000570>>> isinstance(obj, list)
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000571True
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000572>>> isinstance(obj, tuple)
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000573False
574\end{verbatim}
575
576Python's Booleans were added with the primary goal of making code
577clearer. For example, if you're reading a function and encounter the
Fred Drake5c4cf152002-11-13 14:59:06 +0000578statement \code{return 1}, you might wonder whether the \code{1}
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000579represents a Boolean truth value, an index, or a
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000580coefficient that multiplies some other quantity. If the statement is
581\code{return True}, however, the meaning of the return value is quite
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000582clear.
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000583
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000584Python's Booleans were \emph{not} added for the sake of strict
585type-checking. A very strict language such as Pascal would also
586prevent you performing arithmetic with Booleans, and would require
587that the expression in an \keyword{if} statement always evaluate to a
588Boolean. Python is not this strict, and it never will be, as
589\pep{285} explicitly says. This means you can still use any
590expression in an \keyword{if} statement, even ones that evaluate to a
591list or tuple or some random object, and the Boolean type is a
592subclass of the \class{int} class so that arithmetic using a Boolean
593still works.
Andrew M. Kuchling821013e2002-05-06 17:46:39 +0000594
595\begin{verbatim}
596>>> True + 1
5972
598>>> False + 1
5991
600>>> False * 75
6010
602>>> True * 75
60375
604\end{verbatim}
605
606To sum up \constant{True} and \constant{False} in a sentence: they're
607alternative ways to spell the integer values 1 and 0, with the single
608difference that \function{str()} and \function{repr()} return the
Fred Drake5c4cf152002-11-13 14:59:06 +0000609strings \code{'True'} and \code{'False'} instead of \code{'1'} and
610\code{'0'}.
Andrew M. Kuchling3a52ff62002-04-03 22:44:47 +0000611
612\begin{seealso}
613
614\seepep{285}{Adding a bool type}{Written and implemented by GvR.}
615
616\end{seealso}
617
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000618
Andrew M. Kuchling65b72822002-09-03 00:53:21 +0000619%======================================================================
620\section{PEP 293: Codec Error Handling Callbacks}
621
Martin v. Löwis20eae692002-10-07 19:01:07 +0000622When encoding a Unicode string into a byte string, unencodable
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000623characters may be encountered. So far, Python has allowed specifying
624the error processing as either ``strict'' (raising
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000625\exception{UnicodeError}), ``ignore'' (skipping the character), or
626``replace'' (using a question mark in the output string), with
627``strict'' being the default behavior. It may be desirable to specify
628alternative processing of such errors, such as inserting an XML
629character reference or HTML entity reference into the converted
630string.
Martin v. Löwis20eae692002-10-07 19:01:07 +0000631
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +0000632Python now has a flexible framework to add different processing
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000633strategies. New error handlers can be added with
Martin v. Löwis20eae692002-10-07 19:01:07 +0000634\function{codecs.register_error}. Codecs then can access the error
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000635handler with \function{codecs.lookup_error}. An equivalent C API has
636been added for codecs written in C. The error handler gets the
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000637necessary state information such as the string being converted, the
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000638position in the string where the error was detected, and the target
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000639encoding. The handler can then either raise an exception or return a
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000640replacement string.
Martin v. Löwis20eae692002-10-07 19:01:07 +0000641
642Two additional error handlers have been implemented using this
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000643framework: ``backslashreplace'' uses Python backslash quoting to
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +0000644represent unencodable characters and ``xmlcharrefreplace'' emits
Martin v. Löwis20eae692002-10-07 19:01:07 +0000645XML character references.
Andrew M. Kuchling65b72822002-09-03 00:53:21 +0000646
647\begin{seealso}
648
Fred Drake5c4cf152002-11-13 14:59:06 +0000649\seepep{293}{Codec Error Handling Callbacks}{Written and implemented by
Andrew M. Kuchling0a6fa962002-10-09 12:11:10 +0000650Walter D\"orwald.}
Andrew M. Kuchling65b72822002-09-03 00:53:21 +0000651
652\end{seealso}
653
654
655%======================================================================
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000656\section{PEP 273: Importing Modules from Zip Archives}
657
658The new \module{zipimport} module adds support for importing
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000659modules from a ZIP-format archive. You don't need to import the
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000660module explicitly; it will be automatically imported if a ZIP
661archive's filename is added to \code{sys.path}. For example:
662
663\begin{verbatim}
664amk@nyman:~/src/python$ unzip -l /tmp/example.zip
665Archive: /tmp/example.zip
666 Length Date Time Name
667 -------- ---- ---- ----
668 8467 11-26-02 22:30 jwzthreading.py
669 -------- -------
670 8467 1 file
671amk@nyman:~/src/python$ ./python
672Python 2.3a0 (#1, Dec 30 2002, 19:54:32)
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000673>>> import sys
674>>> sys.path.insert(0, '/tmp/example.zip') # Add .zip file to front of path
675>>> import jwzthreading
676>>> jwzthreading.__file__
677'/tmp/example.zip/jwzthreading.py'
678>>>
679\end{verbatim}
680
681An entry in \code{sys.path} can now be the filename of a ZIP archive.
682The ZIP archive can contain any kind of files, but only files named
Fred Drakeaac8c582003-01-17 22:50:10 +0000683\file{*.py}, \file{*.pyc}, or \file{*.pyo} can be imported. If an
684archive only contains \file{*.py} files, Python will not attempt to
685modify the archive by adding the corresponding \file{*.pyc} file, meaning
686that if a ZIP archive doesn't contain \file{*.pyc} files, importing may be
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000687rather slow.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000688
689A path within the archive can also be specified to only import from a
690subdirectory; for example, the path \file{/tmp/example.zip/lib/}
691would only import from the \file{lib/} subdirectory within the
692archive.
693
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000694\begin{seealso}
695
696\seepep{273}{Import Modules from Zip Archives}{Written by James C. Ahlstrom,
697who also provided an implementation.
698Python 2.3 follows the specification in \pep{273},
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +0000699but uses an implementation written by Just van~Rossum
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000700that uses the import hooks described in \pep{302}.
701See section~\ref{section-pep302} for a description of the new import hooks.
702}
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000703
704\end{seealso}
705
706%======================================================================
Fred Drake693aea22003-02-07 14:52:18 +0000707\section{PEP 301: Package Index and Metadata for
708Distutils\label{section-pep301}}
Andrew M. Kuchling87cebbf2003-01-03 16:24:28 +0000709
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000710Support for the long-requested Python catalog makes its first
711appearance in 2.3.
712
Fred Drake693aea22003-02-07 14:52:18 +0000713The core component is the new Distutils \command{register} command.
714Running \code{python setup.py register} will collect the metadata
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000715describing a package, such as its name, version, maintainer,
Fred Drake693aea22003-02-07 14:52:18 +0000716description, \&c., and send it to a central catalog server.
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000717Currently the catalog can be browsed at
718\url{http://www.amk.ca/cgi-bin/pypi.cgi}, but it will move to
719some hostname in the \code{python.org} domain before the final version
720of 2.3 is released.
721
722To make the catalog a bit more useful, a new optional
Fred Drake693aea22003-02-07 14:52:18 +0000723\var{classifiers} keyword argument has been added to the Distutils
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000724\function{setup()} function. A list of
Fred Drake693aea22003-02-07 14:52:18 +0000725\ulink{Trove}{http://catb.org/\textasciitilde esr/trove/}-style
726strings can be supplied to help classify the software.
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000727
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +0000728Here's an example \file{setup.py} with classifiers, written to be compatible
729with older versions of the Distutils:
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000730
731\begin{verbatim}
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +0000732from distutils import core
Fred Drake693aea22003-02-07 14:52:18 +0000733kw = {'name': "Quixote",
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +0000734 'version': "0.5.1",
735 'description': "A highly Pythonic Web application framework",
Fred Drake693aea22003-02-07 14:52:18 +0000736 # ...
737 }
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +0000738
Fred Drake693aea22003-02-07 14:52:18 +0000739if ( hasattr(core, 'setup_keywords') and
740 'classifiers' in core.setup_keywords):
741 kw['classifiers'] = \
742 ['Topic :: Internet :: WWW/HTTP :: Dynamic Content',
743 'Environment :: No Input/Output (Daemon)',
744 'Intended Audience :: Developers'],
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +0000745
Fred Drake693aea22003-02-07 14:52:18 +0000746core.setup(**kw)
Andrew M. Kuchling5a224532003-01-03 16:52:27 +0000747\end{verbatim}
748
749The full list of classifiers can be obtained by running
750\code{python setup.py register --list-classifiers}.
Andrew M. Kuchling87cebbf2003-01-03 16:24:28 +0000751
752\begin{seealso}
753
Fred Drake693aea22003-02-07 14:52:18 +0000754\seepep{301}{Package Index and Metadata for Distutils}{Written and
755implemented by Richard Jones.}
Andrew M. Kuchling87cebbf2003-01-03 16:24:28 +0000756
757\end{seealso}
758
759
760%======================================================================
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000761\section{PEP 302: New Import Hooks \label{section-pep302}}
762
763While it's been possible to write custom import hooks ever since the
764\module{ihooks} module was introduced in Python 1.3, no one has ever
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000765been really happy with it because writing new import hooks is
766difficult and messy. There have been various proposed alternatives
767such as the \module{imputil} and \module{iu} modules, but none of them
768has ever gained much acceptance, and none of them were easily usable
769from \C{} code.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000770
771\pep{302} borrows ideas from its predecessors, especially from
772Gordon McMillan's \module{iu} module. Three new items
773are added to the \module{sys} module:
774
775\begin{itemize}
Andrew M. Kuchlingd5ac8d02003-01-02 21:33:15 +0000776 \item \code{sys.path_hooks} is a list of callable objects; most
Fred Drakeaac8c582003-01-17 22:50:10 +0000777 often they'll be classes. Each callable takes a string containing a
778 path and either returns an importer object that will handle imports
779 from this path or raises an \exception{ImportError} exception if it
780 can't handle this path.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000781
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000782 \item \code{sys.path_importer_cache} caches importer objects for
Fred Drakeaac8c582003-01-17 22:50:10 +0000783 each path, so \code{sys.path_hooks} will only need to be traversed
784 once for each path.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000785
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000786 \item \code{sys.meta_path} is a list of importer objects that will
787 be traversed before \code{sys.path} is checked. This list is
788 initially empty, but user code can add objects to it. Additional
789 built-in and frozen modules can be imported by an object added to
790 this list.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000791
792\end{itemize}
793
794Importer objects must have a single method,
795\method{find_module(\var{fullname}, \var{path}=None)}. \var{fullname}
796will be a module or package name, e.g. \samp{string} or
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000797\samp{distutils.core}. \method{find_module()} must return a loader object
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000798that has a single method, \method{load_module(\var{fullname})}, that
799creates and returns the corresponding module object.
800
801Pseudo-code for Python's new import logic, therefore, looks something
802like this (simplified a bit; see \pep{302} for the full details):
803
804\begin{verbatim}
805for mp in sys.meta_path:
806 loader = mp(fullname)
807 if loader is not None:
Andrew M. Kuchlingd5ac8d02003-01-02 21:33:15 +0000808 <module> = loader.load_module(fullname)
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000809
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000810for path in sys.path:
811 for hook in sys.path_hooks:
Andrew M. Kuchlingd5ac8d02003-01-02 21:33:15 +0000812 try:
813 importer = hook(path)
814 except ImportError:
815 # ImportError, so try the other path hooks
816 pass
817 else:
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000818 loader = importer.find_module(fullname)
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000819 <module> = loader.load_module(fullname)
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000820
821# Not found!
822raise ImportError
823\end{verbatim}
824
825\begin{seealso}
826
827\seepep{302}{New Import Hooks}{Written by Just van~Rossum and Paul Moore.
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +0000828Implemented by Just van~Rossum.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000829}
830
831\end{seealso}
832
833
834%======================================================================
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000835\section{Extended Slices\label{section-slices}}
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000836
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000837Ever since Python 1.4, the slicing syntax has supported an optional
838third ``step'' or ``stride'' argument. For example, these are all
839legal Python syntax: \code{L[1:10:2]}, \code{L[:-1:1]},
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000840\code{L[::-1]}. This was added to Python at the request of
841the developers of Numerical Python, which uses the third argument
842extensively. However, Python's built-in list, tuple, and string
843sequence types have never supported this feature, and you got a
844\exception{TypeError} if you tried it. Michael Hudson contributed a
845patch to fix this shortcoming.
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000846
847For example, you can now easily extract the elements of a list that
848have even indexes:
Fred Drakedf872a22002-07-03 12:02:01 +0000849
850\begin{verbatim}
851>>> L = range(10)
852>>> L[::2]
853[0, 2, 4, 6, 8]
854\end{verbatim}
855
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000856Negative values also work to make a copy of the same list in reverse
857order:
Fred Drakedf872a22002-07-03 12:02:01 +0000858
859\begin{verbatim}
860>>> L[::-1]
861[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
862\end{verbatim}
Andrew M. Kuchling3a52ff62002-04-03 22:44:47 +0000863
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000864This also works for tuples, arrays, and strings:
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000865
866\begin{verbatim}
867>>> s='abcd'
868>>> s[::2]
869'ac'
870>>> s[::-1]
871'dcba'
872\end{verbatim}
873
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000874If you have a mutable sequence such as a list or an array you can
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000875assign to or delete an extended slice, but there are some differences
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000876between assignment to extended and regular slices. Assignment to a
877regular slice can be used to change the length of the sequence:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000878
879\begin{verbatim}
880>>> a = range(3)
881>>> a
882[0, 1, 2]
883>>> a[1:3] = [4, 5, 6]
884>>> a
885[0, 4, 5, 6]
886\end{verbatim}
887
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000888Extended slices aren't this flexible. When assigning to an extended
889slice the list on the right hand side of the statement must contain
890the same number of items as the slice it is replacing:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000891
892\begin{verbatim}
893>>> a = range(4)
894>>> a
895[0, 1, 2, 3]
896>>> a[::2]
897[0, 2]
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000898>>> a[::2] = [0, -1]
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000899>>> a
900[0, 1, -1, 3]
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000901>>> a[::2] = [0,1,2]
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000902Traceback (most recent call last):
903 File "<stdin>", line 1, in ?
Raymond Hettingeree1bded2003-01-17 16:20:23 +0000904ValueError: attempt to assign sequence of size 3 to extended slice of size 2
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000905\end{verbatim}
906
907Deletion is more straightforward:
908
909\begin{verbatim}
910>>> a = range(4)
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000911>>> a
912[0, 1, 2, 3]
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000913>>> a[::2]
914[0, 2]
915>>> del a[::2]
916>>> a
917[1, 3]
918\end{verbatim}
919
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000920One can also now pass slice objects to the
921\method{__getitem__} methods of the built-in sequences:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000922
923\begin{verbatim}
924>>> range(10).__getitem__(slice(0, 5, 2))
925[0, 2, 4]
926\end{verbatim}
927
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000928Or use slice objects directly in subscripts:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000929
930\begin{verbatim}
931>>> range(10)[slice(0, 5, 2)]
932[0, 2, 4]
933\end{verbatim}
934
Andrew M. Kuchlingb6f79592002-11-29 19:43:45 +0000935To simplify implementing sequences that support extended slicing,
936slice objects now have a method \method{indices(\var{length})} which,
Fred Drakeaac8c582003-01-17 22:50:10 +0000937given the length of a sequence, returns a \code{(\var{start},
938\var{stop}, \var{step})} tuple that can be passed directly to
939\function{range()}.
Andrew M. Kuchlingb6f79592002-11-29 19:43:45 +0000940\method{indices()} handles omitted and out-of-bounds indices in a
941manner consistent with regular slices (and this innocuous phrase hides
942a welter of confusing details!). The method is intended to be used
943like this:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000944
945\begin{verbatim}
946class FakeSeq:
947 ...
948 def calc_item(self, i):
949 ...
950 def __getitem__(self, item):
951 if isinstance(item, slice):
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000952 indices = item.indices(len(self))
953 return FakeSeq([self.calc_item(i) in range(*indices)])
Fred Drake5c4cf152002-11-13 14:59:06 +0000954 else:
Michael W. Hudson4da01ed2002-07-19 15:48:56 +0000955 return self.calc_item(i)
956\end{verbatim}
957
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +0000958From this example you can also see that the built-in \class{slice}
Andrew M. Kuchling90e9a792002-08-15 00:40:21 +0000959object is now the type object for the slice type, and is no longer a
960function. This is consistent with Python 2.2, where \class{int},
961\class{str}, etc., underwent the same change.
962
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000963
Andrew M. Kuchling3a52ff62002-04-03 22:44:47 +0000964%======================================================================
Fred Drakedf872a22002-07-03 12:02:01 +0000965\section{Other Language Changes}
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000966
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000967Here are all of the changes that Python 2.3 makes to the core Python
968language.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000969
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000970\begin{itemize}
971\item The \keyword{yield} statement is now always a keyword, as
972described in section~\ref{section-generators} of this document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000973
Fred Drake5c4cf152002-11-13 14:59:06 +0000974\item A new built-in function \function{enumerate()}
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000975was added, as described in section~\ref{section-enumerate} of this
976document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000977
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000978\item Two new constants, \constant{True} and \constant{False} were
979added along with the built-in \class{bool} type, as described in
980section~\ref{section-bool} of this document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000981
Andrew M. Kuchling495172c2002-11-20 13:50:15 +0000982\item The \function{int()} type constructor will now return a long
983integer instead of raising an \exception{OverflowError} when a string
984or floating-point number is too large to fit into an integer. This
985can lead to the paradoxical result that
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +0000986\code{isinstance(int(\var{expression}), int)} is false, but that seems
987unlikely to cause problems in practice.
Andrew M. Kuchling495172c2002-11-20 13:50:15 +0000988
Fred Drake5c4cf152002-11-13 14:59:06 +0000989\item Built-in types now support the extended slicing syntax,
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000990as described in section~\ref{section-slices} of this document.
Andrew M. Kuchling517109b2002-05-07 21:01:16 +0000991
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +0000992\item Dictionaries have a new method, \method{pop(\var{key})}, that
993returns the value corresponding to \var{key} and removes that
994key/value pair from the dictionary. \method{pop()} will raise a
995\exception{KeyError} if the requested key isn't present in the
996dictionary:
997
998\begin{verbatim}
999>>> d = {1:2}
1000>>> d
1001{1: 2}
1002>>> d.pop(4)
1003Traceback (most recent call last):
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +00001004 File "stdin", line 1, in ?
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001005KeyError: 4
1006>>> d.pop(1)
10072
1008>>> d.pop(1)
1009Traceback (most recent call last):
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +00001010 File "stdin", line 1, in ?
Raymond Hettingeree1bded2003-01-17 16:20:23 +00001011KeyError: 'pop(): dictionary is empty'
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001012>>> d
1013{}
1014>>>
1015\end{verbatim}
1016
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001017There's also a new class method,
1018\method{dict.fromkeys(\var{iterable}, \var{value})}, that
1019creates a dictionary with keys taken from the supplied iterator
1020\var{iterable} and all values set to \var{value}, defaulting to
1021\code{None}.
1022
1023(Patches contributed by Raymond Hettinger.)
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001024
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001025Also, the \function{dict()} constructor now accepts keyword arguments to
Raymond Hettinger45bda572002-12-14 20:20:45 +00001026simplify creating small dictionaries:
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001027
1028\begin{verbatim}
1029>>> dict(red=1, blue=2, green=3, black=4)
1030{'blue': 2, 'black': 4, 'green': 3, 'red': 1}
1031\end{verbatim}
1032
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +00001033(Contributed by Just van~Rossum.)
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001034
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +00001035\item The \keyword{assert} statement no longer checks the \code{__debug__}
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001036flag, so you can no longer disable assertions by assigning to \code{__debug__}.
Fred Drake5c4cf152002-11-13 14:59:06 +00001037Running Python with the \programopt{-O} switch will still generate
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001038code that doesn't execute any assertions.
1039
1040\item Most type objects are now callable, so you can use them
1041to create new objects such as functions, classes, and modules. (This
1042means that the \module{new} module can be deprecated in a future
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001043Python version, because you can now use the type objects available in
1044the \module{types} module.)
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001045% XXX should new.py use PendingDeprecationWarning?
1046For example, you can create a new module object with the following code:
1047
1048\begin{verbatim}
1049>>> import types
1050>>> m = types.ModuleType('abc','docstring')
1051>>> m
1052<module 'abc' (built-in)>
1053>>> m.__doc__
1054'docstring'
1055\end{verbatim}
1056
Fred Drake5c4cf152002-11-13 14:59:06 +00001057\item
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001058A new warning, \exception{PendingDeprecationWarning} was added to
1059indicate features which are in the process of being
1060deprecated. The warning will \emph{not} be printed by default. To
1061check for use of features that will be deprecated in the future,
1062supply \programopt{-Walways::PendingDeprecationWarning::} on the
1063command line or use \function{warnings.filterwarnings()}.
1064
Andrew M. Kuchlingc1dd1742003-01-13 13:59:22 +00001065\item The process of deprecating string-based exceptions, as
1066in \code{raise "Error occurred"}, has begun. Raising a string will
1067now trigger \exception{PendingDeprecationWarning}.
1068
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001069\item Using \code{None} as a variable name will now result in a
1070\exception{SyntaxWarning} warning. In a future version of Python,
1071\code{None} may finally become a keyword.
1072
Andrew M. Kuchlingb60ea3f2002-11-15 14:37:10 +00001073\item The method resolution order used by new-style classes has
1074changed, though you'll only notice the difference if you have a really
1075complicated inheritance hierarchy. (Classic classes are unaffected by
1076this change.) Python 2.2 originally used a topological sort of a
1077class's ancestors, but 2.3 now uses the C3 algorithm as described in
Andrew M. Kuchling6f429c32002-11-19 13:09:00 +00001078the paper \ulink{``A Monotonic Superclass Linearization for
1079Dylan''}{http://www.webcom.com/haahr/dylan/linearization-oopsla96.html}.
Andrew M. Kuchlingc1dd1742003-01-13 13:59:22 +00001080To understand the motivation for this change,
1081read Michele Simionato's article
Fred Drake693aea22003-02-07 14:52:18 +00001082\ulink{``Python 2.3 Method Resolution Order''}
Andrew M. Kuchlingb8a39052003-02-07 20:22:33 +00001083 {http://www.python.org/2.3/mro.html}, or
Andrew M. Kuchlingc1dd1742003-01-13 13:59:22 +00001084read the thread on python-dev starting with the message at
Andrew M. Kuchlingb60ea3f2002-11-15 14:37:10 +00001085\url{http://mail.python.org/pipermail/python-dev/2002-October/029035.html}.
1086Samuele Pedroni first pointed out the problem and also implemented the
1087fix by coding the C3 algorithm.
1088
Andrew M. Kuchlingdcfd8252002-09-13 22:21:42 +00001089\item Python runs multithreaded programs by switching between threads
1090after executing N bytecodes. The default value for N has been
1091increased from 10 to 100 bytecodes, speeding up single-threaded
1092applications by reducing the switching overhead. Some multithreaded
1093applications may suffer slower response time, but that's easily fixed
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001094by setting the limit back to a lower number using
Andrew M. Kuchlingdcfd8252002-09-13 22:21:42 +00001095\function{sys.setcheckinterval(\var{N})}.
1096
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001097\item One minor but far-reaching change is that the names of extension
1098types defined by the modules included with Python now contain the
Fred Drake5c4cf152002-11-13 14:59:06 +00001099module and a \character{.} in front of the type name. For example, in
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001100Python 2.2, if you created a socket and printed its
1101\member{__class__}, you'd get this output:
1102
1103\begin{verbatim}
1104>>> s = socket.socket()
1105>>> s.__class__
1106<type 'socket'>
1107\end{verbatim}
1108
1109In 2.3, you get this:
1110\begin{verbatim}
1111>>> s.__class__
1112<type '_socket.socket'>
1113\end{verbatim}
1114
Michael W. Hudson96bc3b42002-11-26 14:48:23 +00001115\item One of the noted incompatibilities between old- and new-style
1116 classes has been removed: you can now assign to the
1117 \member{__name__} and \member{__bases__} attributes of new-style
1118 classes. There are some restrictions on what can be assigned to
1119 \member{__bases__} along the lines of those relating to assigning to
1120 an instance's \member{__class__} attribute.
1121
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001122\end{itemize}
1123
1124
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001125%======================================================================
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001126\subsection{String Changes}
1127
1128\begin{itemize}
1129
Fred Drakeaac8c582003-01-17 22:50:10 +00001130\item The \keyword{in} operator now works differently for strings.
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001131Previously, when evaluating \code{\var{X} in \var{Y}} where \var{X}
1132and \var{Y} are strings, \var{X} could only be a single character.
1133That's now changed; \var{X} can be a string of any length, and
1134\code{\var{X} in \var{Y}} will return \constant{True} if \var{X} is a
1135substring of \var{Y}. If \var{X} is the empty string, the result is
1136always \constant{True}.
1137
1138\begin{verbatim}
1139>>> 'ab' in 'abcd'
1140True
1141>>> 'ad' in 'abcd'
1142False
1143>>> '' in 'abcd'
1144True
1145\end{verbatim}
1146
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001147Note that this doesn't tell you where the substring starts; if you
1148need that information, you must use the \method{find()} method
1149instead.
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001150
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001151\item The \method{strip()}, \method{lstrip()}, and \method{rstrip()}
1152string methods now have an optional argument for specifying the
1153characters to strip. The default is still to remove all whitespace
1154characters:
1155
1156\begin{verbatim}
1157>>> ' abc '.strip()
1158'abc'
1159>>> '><><abc<><><>'.strip('<>')
1160'abc'
1161>>> '><><abc<><><>\n'.strip('<>')
1162'abc<><><>\n'
1163>>> u'\u4000\u4001abc\u4000'.strip(u'\u4000')
1164u'\u4001abc'
1165>>>
1166\end{verbatim}
1167
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001168(Suggested by Simon Brunning and implemented by Walter D\"orwald.)
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00001169
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001170\item The \method{startswith()} and \method{endswith()}
1171string methods now accept negative numbers for the start and end
1172parameters.
1173
1174\item Another new string method is \method{zfill()}, originally a
1175function in the \module{string} module. \method{zfill()} pads a
1176numeric string with zeros on the left until it's the specified width.
1177Note that the \code{\%} operator is still more flexible and powerful
1178than \method{zfill()}.
1179
1180\begin{verbatim}
1181>>> '45'.zfill(4)
1182'0045'
1183>>> '12345'.zfill(4)
1184'12345'
1185>>> 'goofy'.zfill(6)
1186'0goofy'
1187\end{verbatim}
1188
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00001189(Contributed by Walter D\"orwald.)
1190
Fred Drake5c4cf152002-11-13 14:59:06 +00001191\item A new type object, \class{basestring}, has been added.
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001192 Both 8-bit strings and Unicode strings inherit from this type, so
1193 \code{isinstance(obj, basestring)} will return \constant{True} for
1194 either kind of string. It's a completely abstract type, so you
1195 can't create \class{basestring} instances.
1196
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001197\item Interned strings are no longer immortal, and will now be
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001198garbage-collected in the usual way when the only reference to them is
1199from the internal dictionary of interned strings. (Implemented by
1200Oren Tirosh.)
1201
1202\end{itemize}
1203
1204
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001205%======================================================================
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001206\subsection{Optimizations}
1207
1208\begin{itemize}
1209
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001210\item The creation of new-style class instances has been made much
1211faster; they're now faster than classic classes!
1212
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001213\item The \method{sort()} method of list objects has been extensively
1214rewritten by Tim Peters, and the implementation is significantly
1215faster.
1216
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001217\item Multiplication of large long integers is now much faster thanks
1218to an implementation of Karatsuba multiplication, an algorithm that
1219scales better than the O(n*n) required for the grade-school
1220multiplication algorithm. (Original patch by Christopher A. Craig,
1221and significantly reworked by Tim Peters.)
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001222
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001223\item The \code{SET_LINENO} opcode is now gone. This may provide a
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001224small speed increase, depending on your compiler's idiosyncrasies.
1225See section~\ref{section-other} for a longer explanation.
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001226(Removed by Michael Hudson.)
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001227
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001228\item \function{xrange()} objects now have their own iterator, making
1229\code{for i in xrange(n)} slightly faster than
1230\code{for i in range(n)}. (Patch by Raymond Hettinger.)
1231
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001232\item A number of small rearrangements have been made in various
1233hotspots to improve performance, inlining a function here, removing
1234some code there. (Implemented mostly by GvR, but lots of people have
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001235contributed single changes.)
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001236
1237\end{itemize}
Neal Norwitzd68f5172002-05-29 15:54:55 +00001238
Andrew M. Kuchling6974aa92002-08-20 00:54:36 +00001239
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001240%======================================================================
Andrew M. Kuchlingef893fe2003-01-06 20:04:17 +00001241\section{New, Improved, and Deprecated Modules}
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00001242
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001243As usual, Python's standard library received a number of enhancements and
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001244bug fixes. Here's a partial list of the most notable changes, sorted
1245alphabetically by module name. Consult the
1246\file{Misc/NEWS} file in the source tree for a more
1247complete list of changes, or look through the CVS logs for all the
1248details.
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00001249
1250\begin{itemize}
1251
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001252\item The \module{array} module now supports arrays of Unicode
Fred Drake5c4cf152002-11-13 14:59:06 +00001253characters using the \character{u} format character. Arrays also now
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001254support using the \code{+=} assignment operator to add another array's
1255contents, and the \code{*=} assignment operator to repeat an array.
1256(Contributed by Jason Orendorff.)
1257
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001258\item The \module{bsddb} module has been replaced by version 4.1.1
Andrew M. Kuchling669249e2002-11-19 13:05:33 +00001259of the \ulink{PyBSDDB}{http://pybsddb.sourceforge.net} package,
1260providing a more complete interface to the transactional features of
1261the BerkeleyDB library.
1262The old version of the module has been renamed to
1263\module{bsddb185} and is no longer built automatically; you'll
1264have to edit \file{Modules/Setup} to enable it. Note that the new
1265\module{bsddb} package is intended to be compatible with the
1266old module, so be sure to file bugs if you discover any
1267incompatibilities.
1268
Fred Drake5c4cf152002-11-13 14:59:06 +00001269\item The Distutils \class{Extension} class now supports
1270an extra constructor argument named \var{depends} for listing
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001271additional source files that an extension depends on. This lets
1272Distutils recompile the module if any of the dependency files are
Fred Drake5c4cf152002-11-13 14:59:06 +00001273modified. For example, if \file{sampmodule.c} includes the header
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001274file \file{sample.h}, you would create the \class{Extension} object like
1275this:
1276
1277\begin{verbatim}
1278ext = Extension("samp",
1279 sources=["sampmodule.c"],
1280 depends=["sample.h"])
1281\end{verbatim}
1282
1283Modifying \file{sample.h} would then cause the module to be recompiled.
1284(Contributed by Jeremy Hylton.)
1285
Andrew M. Kuchlingdc3f7e12002-11-04 20:05:10 +00001286\item Other minor changes to Distutils:
1287it now checks for the \envvar{CC}, \envvar{CFLAGS}, \envvar{CPP},
1288\envvar{LDFLAGS}, and \envvar{CPPFLAGS} environment variables, using
1289them to override the settings in Python's configuration (contributed
Andrew M. Kuchlinga31bb372003-01-27 16:36:34 +00001290by Robert Weber).
Andrew M. Kuchlingdc3f7e12002-11-04 20:05:10 +00001291
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001292\item The \module{getopt} module gained a new function,
1293\function{gnu_getopt()}, that supports the same arguments as the existing
Fred Drake5c4cf152002-11-13 14:59:06 +00001294\function{getopt()} function but uses GNU-style scanning mode.
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001295The existing \function{getopt()} stops processing options as soon as a
1296non-option argument is encountered, but in GNU-style mode processing
1297continues, meaning that options and arguments can be mixed. For
1298example:
1299
1300\begin{verbatim}
1301>>> getopt.getopt(['-f', 'filename', 'output', '-v'], 'f:v')
1302([('-f', 'filename')], ['output', '-v'])
1303>>> getopt.gnu_getopt(['-f', 'filename', 'output', '-v'], 'f:v')
1304([('-f', 'filename'), ('-v', '')], ['output'])
1305\end{verbatim}
1306
1307(Contributed by Peter \AA{strand}.)
1308
1309\item The \module{grp}, \module{pwd}, and \module{resource} modules
Fred Drake5c4cf152002-11-13 14:59:06 +00001310now return enhanced tuples:
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001311
1312\begin{verbatim}
1313>>> import grp
1314>>> g = grp.getgrnam('amk')
1315>>> g.gr_name, g.gr_gid
1316('amk', 500)
1317\end{verbatim}
1318
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001319\item The \module{gzip} module can now handle files exceeding 2~Gb.
1320
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001321\item The new \module{heapq} module contains an implementation of a
1322heap queue algorithm. A heap is an array-like data structure that
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001323keeps items in a partially sorted order such that, for every index
1324\var{k}, \code{heap[\var{k}] <= heap[2*\var{k}+1]} and
1325\code{heap[\var{k}] <= heap[2*\var{k}+2]}. This makes it quick to
1326remove the smallest item, and inserting a new item while maintaining
1327the heap property is O(lg~n). (See
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001328\url{http://www.nist.gov/dads/HTML/priorityque.html} for more
1329information about the priority queue data structure.)
1330
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001331The \module{heapq} module provides \function{heappush()} and
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001332\function{heappop()} functions for adding and removing items while
1333maintaining the heap property on top of some other mutable Python
1334sequence type. For example:
1335
1336\begin{verbatim}
1337>>> import heapq
1338>>> heap = []
1339>>> for item in [3, 7, 5, 11, 1]:
1340... heapq.heappush(heap, item)
1341...
1342>>> heap
1343[1, 3, 5, 11, 7]
1344>>> heapq.heappop(heap)
13451
1346>>> heapq.heappop(heap)
13473
1348>>> heap
1349[5, 7, 11]
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00001350\end{verbatim}
1351
1352(Contributed by Kevin O'Connor.)
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001353
Andrew M. Kuchling87cebbf2003-01-03 16:24:28 +00001354\item The \module{imaplib} module now supports IMAP over SSL.
1355(Contributed by Piers Lauder and Tino Lange.)
1356
Fred Drake5c4cf152002-11-13 14:59:06 +00001357\item Two new functions in the \module{math} module,
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001358\function{degrees(\var{rads})} and \function{radians(\var{degs})},
Fred Drake5c4cf152002-11-13 14:59:06 +00001359convert between radians and degrees. Other functions in the
Andrew M. Kuchling8e5b53b2002-12-15 20:17:38 +00001360\module{math} module such as \function{math.sin()} and
1361\function{math.cos()} have always required input values measured in
1362radians. Also, an optional \var{base} argument was added to
1363\function{math.log()} to make it easier to compute logarithms for
1364bases other than \code{e} and \code{10}. (Contributed by Raymond
1365Hettinger.)
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001366
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +00001367\item Several new functions (\function{getpgid()}, \function{killpg()},
1368\function{lchown()}, \function{loadavg()}, \function{major()}, \function{makedev()},
1369\function{minor()}, and \function{mknod()}) were added to the
Andrew M. Kuchlingc309cca2002-10-10 16:04:08 +00001370\module{posix} module that underlies the \module{os} module.
Andrew M. Kuchlingae3bbf52002-12-31 14:03:45 +00001371(Contributed by Gustavo Niemeyer, Geert Jansen, and Denis S. Otkidach.)
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001372
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001373\item In the \module{os} module, the \function{*stat()} family of functions can now report
1374fractions of a second in a timestamp. Such time stamps are
1375represented as floats, similar to \function{time.time()}.
1376
1377During testing, it was found that some applications will break if time
1378stamps are floats. For compatibility, when using the tuple interface
1379of the \class{stat_result} time stamps will be represented as integers.
1380When using named fields (a feature first introduced in Python 2.2),
1381time stamps are still represented as integers, unless
1382\function{os.stat_float_times()} is invoked to enable float return
1383values:
1384
1385\begin{verbatim}
1386>>> os.stat("/tmp").st_mtime
13871034791200
1388>>> os.stat_float_times(True)
1389>>> os.stat("/tmp").st_mtime
13901034791200.6335014
1391\end{verbatim}
1392
1393In Python 2.4, the default will change to always returning floats.
1394
1395Application developers should enable this feature only if all their
1396libraries work properly when confronted with floating point time
1397stamps, or if they use the tuple API. If used, the feature should be
1398activated on an application level instead of trying to enable it on a
1399per-use basis.
1400
Andrew M. Kuchling53262572002-12-01 14:00:21 +00001401\item The old and never-documented \module{linuxaudiodev} module has
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001402been deprecated, and a new version named \module{ossaudiodev} has been
1403added. The module was renamed because the OSS sound drivers can be
1404used on platforms other than Linux, and the interface has also been
1405tidied and brought up to date in various ways. (Contributed by Greg
Greg Wardaa1d3aa2003-01-03 18:03:21 +00001406Ward and Nicholas FitzRoy-Dale.)
Andrew M. Kuchling53262572002-12-01 14:00:21 +00001407
Fred Drake5c4cf152002-11-13 14:59:06 +00001408\item The parser objects provided by the \module{pyexpat} module
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001409can now optionally buffer character data, resulting in fewer calls to
1410your character data handler and therefore faster performance. Setting
Fred Drake5c4cf152002-11-13 14:59:06 +00001411the parser object's \member{buffer_text} attribute to \constant{True}
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001412will enable buffering.
1413
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001414\item The \function{sample(\var{population}, \var{k})} function was
1415added to the \module{random} module. \var{population} is a sequence
Fred Drakeaac8c582003-01-17 22:50:10 +00001416or \class{xrange} object containing the elements of a population, and
1417\function{sample()}
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001418chooses \var{k} elements from the population without replacing chosen
1419elements. \var{k} can be any value up to \code{len(\var{population})}.
1420For example:
1421
1422\begin{verbatim}
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001423>>> days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'St', 'Sn']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001424>>> random.sample(days, 3) # Choose 3 elements
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001425['St', 'Sn', 'Th']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001426>>> random.sample(days, 7) # Choose 7 elements
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001427['Tu', 'Th', 'Mo', 'We', 'St', 'Fr', 'Sn']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001428>>> random.sample(days, 7) # Choose 7 again
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001429['We', 'Mo', 'Sn', 'Fr', 'Tu', 'St', 'Th']
Michael W. Hudsoncfd38842002-12-17 16:15:34 +00001430>>> random.sample(days, 8) # Can't choose eight
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001431Traceback (most recent call last):
Andrew M. Kuchling28f2f882002-11-14 14:14:16 +00001432 File "<stdin>", line 1, in ?
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001433 File "random.py", line 414, in sample
1434 raise ValueError, "sample larger than population"
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001435ValueError: sample larger than population
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001436>>> random.sample(xrange(1,10000,2), 10) # Choose ten odd nos. under 10000
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001437[3407, 3805, 1505, 7023, 2401, 2267, 9733, 3151, 8083, 9195]
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001438\end{verbatim}
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001439
1440The \module{random} module now uses a new algorithm, the Mersenne
1441Twister, implemented in C. It's faster and more extensively studied
1442than the previous algorithm.
1443
1444(All changes contributed by Raymond Hettinger.)
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00001445
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001446\item The \module{readline} module also gained a number of new
1447functions: \function{get_history_item()},
1448\function{get_current_history_length()}, and \function{redisplay()}.
1449
Andrew M. Kuchlingef893fe2003-01-06 20:04:17 +00001450\item The \module{rexec} and \module{Bastion} modules have been
1451declared dead, and attempts to import them will fail with a
1452\exception{RuntimeError}. New-style classes provide new ways to break
1453out of the restricted execution environment provided by
1454\module{rexec}, and no one has interest in fixing them or time to do
1455so. If you have applications using \module{rexec}, rewrite them to
1456use something else.
1457
1458(Sticking with Python 2.2 or 2.1 will not make your applications any
1459safer, because there are known bugs in the \module{rexec} module in
1460those versions. I repeat, if you're using \module{rexec}, stop using
1461it immediately.)
1462
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001463\item The \module{shutil} module gained a \function{move(\var{src},
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001464\var{dest})} function that recursively moves a file or directory to a new
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001465location.
1466
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001467\item Support for more advanced POSIX signal handling was added
1468to the \module{signal} module by adding the \function{sigpending},
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001469\function{sigprocmask} and \function{sigsuspend} functions where supported
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001470by the platform. These functions make it possible to avoid some previously
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001471unavoidable race conditions with signal handling.
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001472
1473\item The \module{socket} module now supports timeouts. You
1474can call the \method{settimeout(\var{t})} method on a socket object to
1475set a timeout of \var{t} seconds. Subsequent socket operations that
1476take longer than \var{t} seconds to complete will abort and raise a
Fred Drake5c4cf152002-11-13 14:59:06 +00001477\exception{socket.error} exception.
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001478
1479The original timeout implementation was by Tim O'Malley. Michael
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001480Gilfix integrated it into the Python \module{socket} module and
1481shepherded it through a lengthy review. After the code was checked
1482in, Guido van~Rossum rewrote parts of it. (This is a good example of
1483a collaborative development process in action.)
Andrew M. Kuchlinga982eb12002-07-22 18:57:36 +00001484
Mark Hammond8af50bc2002-12-03 06:13:35 +00001485\item On Windows, the \module{socket} module now ships with Secure
Michael W. Hudson065f5fa2003-02-10 19:24:50 +00001486Sockets Layer (SSL) support.
Mark Hammond8af50bc2002-12-03 06:13:35 +00001487
Fred Drake5c4cf152002-11-13 14:59:06 +00001488\item The value of the C \constant{PYTHON_API_VERSION} macro is now exposed
Fred Drake583db0d2002-09-14 02:03:25 +00001489at the Python level as \code{sys.api_version}.
Andrew M. Kuchlingdcfd8252002-09-13 22:21:42 +00001490
Andrew M. Kuchling674b0bf2003-01-07 00:07:19 +00001491\item The new \module{tarfile} module
Neal Norwitz55d555f2003-01-08 05:27:42 +00001492allows reading from and writing to \program{tar}-format archive files.
Andrew M. Kuchling674b0bf2003-01-07 00:07:19 +00001493(Contributed by Lars Gust\"abel.)
1494
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001495\item The new \module{textwrap} module contains functions for wrapping
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001496strings containing paragraphs of text. The \function{wrap(\var{text},
1497\var{width})} function takes a string and returns a list containing
1498the text split into lines of no more than the chosen width. The
1499\function{fill(\var{text}, \var{width})} function returns a single
1500string, reformatted to fit into lines no longer than the chosen width.
1501(As you can guess, \function{fill()} is built on top of
1502\function{wrap()}. For example:
1503
1504\begin{verbatim}
1505>>> import textwrap
1506>>> paragraph = "Not a whit, we defy augury: ... more text ..."
1507>>> textwrap.wrap(paragraph, 60)
Fred Drake5c4cf152002-11-13 14:59:06 +00001508["Not a whit, we defy augury: there's a special providence in",
1509 "the fall of a sparrow. If it be now, 'tis not to come; if it",
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001510 ...]
1511>>> print textwrap.fill(paragraph, 35)
1512Not a whit, we defy augury: there's
1513a special providence in the fall of
1514a sparrow. If it be now, 'tis not
1515to come; if it be not to come, it
1516will be now; if it be not now, yet
1517it will come: the readiness is all.
Fred Drake5c4cf152002-11-13 14:59:06 +00001518>>>
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001519\end{verbatim}
1520
1521The module also contains a \class{TextWrapper} class that actually
Fred Drake5c4cf152002-11-13 14:59:06 +00001522implements the text wrapping strategy. Both the
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001523\class{TextWrapper} class and the \function{wrap()} and
1524\function{fill()} functions support a number of additional keyword
1525arguments for fine-tuning the formatting; consult the module's
Fred Drake5c4cf152002-11-13 14:59:06 +00001526documentation for details.
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001527%XXX add a link to the module docs?
Andrew M. Kuchlingd003a2a2002-06-26 13:23:55 +00001528(Contributed by Greg Ward.)
1529
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001530\item The \module{thread} and \module{threading} modules now have
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001531companion modules, \module{dummy_thread} and \module{dummy_threading},
1532that provide a do-nothing implementation of the \module{thread}
1533module's interface for platforms where threads are not supported. The
1534intention is to simplify thread-aware modules (ones that \emph{don't}
1535rely on threads to run) by putting the following code at the top:
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001536
1537% XXX why as _threading?
1538\begin{verbatim}
1539try:
1540 import threading as _threading
1541except ImportError:
1542 import dummy_threading as _threading
1543\end{verbatim}
1544
1545Code can then call functions and use classes in \module{_threading}
1546whether or not threads are supported, avoiding an \keyword{if}
1547statement and making the code slightly clearer. This module will not
1548magically make multithreaded code run without threads; code that waits
1549for another thread to return or to do something will simply hang
1550forever.
1551
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001552\item The \module{time} module's \function{strptime()} function has
Fred Drake5c4cf152002-11-13 14:59:06 +00001553long been an annoyance because it uses the platform C library's
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001554\function{strptime()} implementation, and different platforms
1555sometimes have odd bugs. Brett Cannon contributed a portable
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001556implementation that's written in pure Python and should behave
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001557identically on all platforms.
1558
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001559\item The \module{UserDict} module has a new \class{DictMixin} class which
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001560defines all dictionary methods for classes that already have a minimum
1561mapping interface. This greatly simplifies writing classes that need
1562to be substitutable for dictionaries, such as the classes in
1563the \module{shelve} module.
1564
1565Adding the mixin as a superclass provides the full dictionary
1566interface whenever the class defines \method{__getitem__},
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001567\method{__setitem__}, \method{__delitem__}, and \method{keys}.
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001568For example:
1569
1570\begin{verbatim}
1571>>> import UserDict
1572>>> class SeqDict(UserDict.DictMixin):
1573 """Dictionary lookalike implemented with lists."""
1574 def __init__(self):
1575 self.keylist = []
1576 self.valuelist = []
1577 def __getitem__(self, key):
1578 try:
1579 i = self.keylist.index(key)
1580 except ValueError:
1581 raise KeyError
1582 return self.valuelist[i]
1583 def __setitem__(self, key, value):
1584 try:
1585 i = self.keylist.index(key)
1586 self.valuelist[i] = value
1587 except ValueError:
1588 self.keylist.append(key)
1589 self.valuelist.append(value)
1590 def __delitem__(self, key):
1591 try:
1592 i = self.keylist.index(key)
1593 except ValueError:
1594 raise KeyError
1595 self.keylist.pop(i)
1596 self.valuelist.pop(i)
1597 def keys(self):
1598 return list(self.keylist)
1599
1600>>> s = SeqDict()
1601>>> dir(s) # See that other dictionary methods are implemented
1602['__cmp__', '__contains__', '__delitem__', '__doc__', '__getitem__',
1603 '__init__', '__iter__', '__len__', '__module__', '__repr__',
1604 '__setitem__', 'clear', 'get', 'has_key', 'items', 'iteritems',
1605 'iterkeys', 'itervalues', 'keylist', 'keys', 'pop', 'popitem',
1606 'setdefault', 'update', 'valuelist', 'values']
Neal Norwitzc7d8c682002-12-24 14:51:43 +00001607\end{verbatim}
Andrew M. Kuchling449a87d2002-12-11 15:03:51 +00001608
1609(Contributed by Raymond Hettinger.)
1610
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001611\item The DOM implementation
1612in \module{xml.dom.minidom} can now generate XML output in a
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001613particular encoding by providing an optional encoding argument to
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00001614the \method{toxml()} and \method{toprettyxml()} methods of DOM nodes.
1615
Andrew M. Kuchlingef893fe2003-01-06 20:04:17 +00001616item The \module{Tix} module has received various bug fixes and
1617updates for the current version of the Tix package.
1618
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001619\item The \module{Tkinter} module now works with a thread-enabled
1620version of Tcl. Tcl's threading model requires that widgets only be
1621accessed from the thread in which they're created; accesses from
1622another thread can cause Tcl to panic. For certain Tcl interfaces,
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001623\module{Tkinter} will now automatically avoid this
1624when a widget is accessed from a different thread by marshalling a
1625command, passing it to the correct thread, and waiting for the
1626results. Other interfaces can't be handled automatically but
1627\module{Tkinter} will now raise an exception on such an access so that
1628at least you can find out about the problem. See
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001629\url{http://mail.python.org/pipermail/python-dev/2002-December/031107.html}
1630for a more detailed explanation of this change. (Implemented by
1631Martin von L\"owis.)
1632
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001633\item Calling Tcl methods through \module{_tkinter} no longer
1634returns only strings. Instead, if Tcl returns other objects those
1635objects are converted to their Python equivalent, if one exists, or
1636wrapped with a \class{_tkinter.Tcl_Obj} object if no Python equivalent
Raymond Hettinger45bda572002-12-14 20:20:45 +00001637exists. This behavior can be controlled through the
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001638\method{wantobjects()} method of \class{tkapp} objects.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001639
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001640When using \module{_tkinter} through the \module{Tkinter} module (as
1641most Tkinter applications will), this feature is always activated. It
1642should not cause compatibility problems, since Tkinter would always
1643convert string results to Python types where possible.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001644
Raymond Hettinger45bda572002-12-14 20:20:45 +00001645If any incompatibilities are found, the old behavior can be restored
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00001646by setting the \member{wantobjects} variable in the \module{Tkinter}
1647module to false before creating the first \class{tkapp} object.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001648
1649\begin{verbatim}
1650import Tkinter
Martin v. Löwis8c8aa5d2002-11-26 21:39:48 +00001651Tkinter.wantobjects = 0
Martin v. Löwis39b48522002-11-26 09:47:25 +00001652\end{verbatim}
1653
Andrew M. Kuchling6c50df22002-12-13 12:53:16 +00001654Any breakage caused by this change should be reported as a bug.
Martin v. Löwis39b48522002-11-26 09:47:25 +00001655
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00001656\end{itemize}
1657
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00001658
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001659%======================================================================
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001660\subsection{Date/Time Type}
1661
Michael W. Hudson065f5fa2003-02-10 19:24:50 +00001662% XXX This is out-of-date already: timetz and so on have gone away.
1663
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001664Date and time types suitable for expressing timestamps were added as
1665the \module{datetime} module. The types don't support different
1666calendars or many fancy features, and just stick to the basics of
1667representing time.
1668
1669The three primary types are: \class{date}, representing a day, month,
1670and year; \class{time}, consisting of hour, minute, and second; and
1671\class{datetime}, which contains all the attributes of both
1672\class{date} and \class{time}. These basic types don't understand
1673time zones, but there are subclasses named \class{timetz} and
1674\class{datetimetz} that do. There's also a
1675\class{timedelta} class representing a difference between two points
1676in time, and time zone logic is implemented by classes inheriting from
1677the abstract \class{tzinfo} class.
1678
1679You can create instances of \class{date} and \class{time} by either
1680supplying keyword arguments to the appropriate constructor,
1681e.g. \code{datetime.date(year=1972, month=10, day=15)}, or by using
1682one of a number of class methods. For example, the \method{today()}
1683class method returns the current local date.
1684
1685Once created, instances of the date/time classes are all immutable.
1686There are a number of methods for producing formatted strings from
1687objects:
1688
1689\begin{verbatim}
1690>>> import datetime
1691>>> now = datetime.datetime.now()
1692>>> now.isoformat()
1693'2002-12-30T21:27:03.994956'
1694>>> now.ctime() # Only available on date, datetime
1695'Mon Dec 30 21:27:03 2002'
Raymond Hettingeree1bded2003-01-17 16:20:23 +00001696>>> now.strftime('%Y %d %b')
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001697'2002 30 Dec'
1698\end{verbatim}
1699
1700The \method{replace()} method allows modifying one or more fields
1701of a \class{date} or \class{datetime} instance:
1702
1703\begin{verbatim}
1704>>> d = datetime.datetime.now()
1705>>> d
1706datetime.datetime(2002, 12, 30, 22, 15, 38, 827738)
1707>>> d.replace(year=2001, hour = 12)
1708datetime.datetime(2001, 12, 30, 12, 15, 38, 827738)
1709>>>
1710\end{verbatim}
1711
1712Instances can be compared, hashed, and converted to strings (the
1713result is the same as that of \method{isoformat()}). \class{date} and
1714\class{datetime} instances can be subtracted from each other, and
1715added to \class{timedelta} instances.
1716
1717For more information, refer to the \ulink{module's reference
Fred Drake693aea22003-02-07 14:52:18 +00001718documentation}{..//lib/module-datetime.html}.
Andrew M. Kuchlinga974b392003-01-13 19:09:03 +00001719(Contributed by Tim Peters.)
1720
1721
1722%======================================================================
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001723\subsection{The \module{optparse} Module}
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001724
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001725The \module{getopt} module provides simple parsing of command-line
1726arguments. The new \module{optparse} module (originally named Optik)
1727provides more elaborate command-line parsing that follows the Unix
1728conventions, automatically creates the output for \longprogramopt{help},
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001729and can perform different actions for different options.
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001730
1731You start by creating an instance of \class{OptionParser} and telling
1732it what your program's options are.
1733
1734\begin{verbatim}
1735from optparse import OptionParser
1736
1737op = OptionParser()
1738op.add_option('-i', '--input',
1739 action='store', type='string', dest='input',
1740 help='set input filename')
1741op.add_option('-l', '--length',
1742 action='store', type='int', dest='length',
1743 help='set maximum length of output')
1744\end{verbatim}
1745
1746Parsing a command line is then done by calling the \method{parse_args()}
1747method.
1748
1749\begin{verbatim}
1750options, args = op.parse_args(sys.argv[1:])
1751print options
1752print args
1753\end{verbatim}
1754
1755This returns an object containing all of the option values,
1756and a list of strings containing the remaining arguments.
1757
1758Invoking the script with the various arguments now works as you'd
1759expect it to. Note that the length argument is automatically
1760converted to an integer.
1761
1762\begin{verbatim}
1763$ ./python opt.py -i data arg1
1764<Values at 0x400cad4c: {'input': 'data', 'length': None}>
1765['arg1']
1766$ ./python opt.py --input=data --length=4
1767<Values at 0x400cad2c: {'input': 'data', 'length': 4}>
1768['arg1']
1769$
1770\end{verbatim}
1771
1772The help message is automatically generated for you:
1773
1774\begin{verbatim}
1775$ ./python opt.py --help
1776usage: opt.py [options]
1777
1778options:
1779 -h, --help show this help message and exit
1780 -iINPUT, --input=INPUT
1781 set input filename
1782 -lLENGTH, --length=LENGTH
1783 set maximum length of output
1784$
1785\end{verbatim}
Andrew M. Kuchling669249e2002-11-19 13:05:33 +00001786% $ prevent Emacs tex-mode from getting confused
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001787
1788Optik was written by Greg Ward, with suggestions from the readers of
1789the Getopt SIG.
1790
1791\begin{seealso}
Fred Drake693aea22003-02-07 14:52:18 +00001792\seeurl{http://optik.sourceforge.net/}
Andrew M. Kuchling24d5a522002-11-14 23:40:42 +00001793{The Optik site has tutorial and reference documentation for
1794\module{optparse}.
1795% XXX change to point to Python docs, when those docs get written.
1796}
1797\end{seealso}
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001798
1799
1800%======================================================================
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001801\section{Specialized Object Allocator (pymalloc)\label{section-pymalloc}}
1802
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001803An experimental feature added to Python 2.1 was pymalloc, a
1804specialized object allocator written by Vladimir Marangozov. Pymalloc
1805is intended to be faster than the system \cfunction{malloc()} and
1806to have less memory overhead for allocation patterns typical of Python
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001807programs. The allocator uses C's \cfunction{malloc()} function to get
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001808large pools of memory and then fulfills smaller memory requests from
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001809these pools.
1810
1811In 2.1 and 2.2, pymalloc was an experimental feature and wasn't
1812enabled by default; you had to explicitly turn it on by providing the
1813\longprogramopt{with-pymalloc} option to the \program{configure}
1814script. In 2.3, pymalloc has had further enhancements and is now
1815enabled by default; you'll have to supply
1816\longprogramopt{without-pymalloc} to disable it.
1817
1818This change is transparent to code written in Python; however,
1819pymalloc may expose bugs in C extensions. Authors of C extension
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001820modules should test their code with pymalloc enabled,
1821because some incorrect code may cause core dumps at runtime.
1822
1823There's one particularly common error that causes problems. There are
1824a number of memory allocation functions in Python's C API that have
1825previously just been aliases for the C library's \cfunction{malloc()}
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001826and \cfunction{free()}, meaning that if you accidentally called
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001827mismatched functions the error wouldn't be noticeable. When the
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001828object allocator is enabled, these functions aren't aliases of
1829\cfunction{malloc()} and \cfunction{free()} any more, and calling the
1830wrong function to free memory may get you a core dump. For example,
1831if memory was allocated using \cfunction{PyObject_Malloc()}, it has to
1832be freed using \cfunction{PyObject_Free()}, not \cfunction{free()}. A
1833few modules included with Python fell afoul of this and had to be
1834fixed; doubtless there are more third-party modules that will have the
1835same problem.
1836
1837As part of this change, the confusing multiple interfaces for
1838allocating memory have been consolidated down into two API families.
1839Memory allocated with one family must not be manipulated with
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001840functions from the other family. There is one family for allocating
1841chunks of memory, and another family of functions specifically for
1842allocating Python objects.
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001843
1844\begin{itemize}
1845 \item To allocate and free an undistinguished chunk of memory use
1846 the ``raw memory'' family: \cfunction{PyMem_Malloc()},
1847 \cfunction{PyMem_Realloc()}, and \cfunction{PyMem_Free()}.
1848
1849 \item The ``object memory'' family is the interface to the pymalloc
1850 facility described above and is biased towards a large number of
1851 ``small'' allocations: \cfunction{PyObject_Malloc},
1852 \cfunction{PyObject_Realloc}, and \cfunction{PyObject_Free}.
1853
1854 \item To allocate and free Python objects, use the ``object'' family
1855 \cfunction{PyObject_New()}, \cfunction{PyObject_NewVar()}, and
1856 \cfunction{PyObject_Del()}.
1857\end{itemize}
1858
1859Thanks to lots of work by Tim Peters, pymalloc in 2.3 also provides
1860debugging features to catch memory overwrites and doubled frees in
1861both extension modules and in the interpreter itself. To enable this
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001862support, compile a debugging version of the Python interpreter by
1863running \program{configure} with \longprogramopt{with-pydebug}.
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001864
1865To aid extension writers, a header file \file{Misc/pymemcompat.h} is
1866distributed with the source to Python 2.3 that allows Python
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001867extensions to use the 2.3 interfaces to memory allocation while
1868compiling against any version of Python since 1.5.2. You would copy
1869the file from Python's source distribution and bundle it with the
1870source of your extension.
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001871
1872\begin{seealso}
1873
1874\seeurl{http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Objects/obmalloc.c}
1875{For the full details of the pymalloc implementation, see
1876the comments at the top of the file \file{Objects/obmalloc.c} in the
1877Python source code. The above link points to the file within the
1878SourceForge CVS browser.}
1879
1880\end{seealso}
1881
1882
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00001883% ======================================================================
1884\section{Build and C API Changes}
1885
Andrew M. Kuchling3c305d92002-07-22 18:50:11 +00001886Changes to Python's build process and to the C API include:
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00001887
1888\begin{itemize}
1889
Andrew M. Kuchlingef5d06b2002-07-22 19:21:06 +00001890\item The C-level interface to the garbage collector has been changed,
1891to make it easier to write extension types that support garbage
1892collection, and to make it easier to debug misuses of the functions.
1893Various functions have slightly different semantics, so a bunch of
1894functions had to be renamed. Extensions that use the old API will
1895still compile but will \emph{not} participate in garbage collection,
1896so updating them for 2.3 should be considered fairly high priority.
1897
1898To upgrade an extension module to the new API, perform the following
1899steps:
1900
1901\begin{itemize}
1902
1903\item Rename \cfunction{Py_TPFLAGS_GC} to \cfunction{PyTPFLAGS_HAVE_GC}.
1904
1905\item Use \cfunction{PyObject_GC_New} or \cfunction{PyObject_GC_NewVar} to
1906allocate objects, and \cfunction{PyObject_GC_Del} to deallocate them.
1907
1908\item Rename \cfunction{PyObject_GC_Init} to \cfunction{PyObject_GC_Track} and
1909\cfunction{PyObject_GC_Fini} to \cfunction{PyObject_GC_UnTrack}.
1910
1911\item Remove \cfunction{PyGC_HEAD_SIZE} from object size calculations.
1912
1913\item Remove calls to \cfunction{PyObject_AS_GC} and \cfunction{PyObject_FROM_GC}.
1914
1915\end{itemize}
1916
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001917\item The cycle detection implementation used by the garbage collection
1918has proven to be stable, so it's now being made mandatory; you can no
1919longer compile Python without it, and the
1920\longprogramopt{with-cycle-gc} switch to \program{configure} has been removed.
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001921
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001922\item Python can now optionally be built as a shared library
1923(\file{libpython2.3.so}) by supplying \longprogramopt{enable-shared}
Fred Drake5c4cf152002-11-13 14:59:06 +00001924when running Python's \program{configure} script. (Contributed by Ondrej
Andrew M. Kuchlingfad2f592002-05-10 21:00:05 +00001925Palkovsky.)
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +00001926
Michael W. Hudsondd32a912002-08-15 14:59:02 +00001927\item The \csimplemacro{DL_EXPORT} and \csimplemacro{DL_IMPORT} macros
1928are now deprecated. Initialization functions for Python extension
1929modules should now be declared using the new macro
Andrew M. Kuchling3c305d92002-07-22 18:50:11 +00001930\csimplemacro{PyMODINIT_FUNC}, while the Python core will generally
1931use the \csimplemacro{PyAPI_FUNC} and \csimplemacro{PyAPI_DATA}
1932macros.
Neal Norwitzbba23a82002-07-22 13:18:59 +00001933
Fred Drake5c4cf152002-11-13 14:59:06 +00001934\item The interpreter can be compiled without any docstrings for
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001935the built-in functions and modules by supplying
Fred Drake5c4cf152002-11-13 14:59:06 +00001936\longprogramopt{without-doc-strings} to the \program{configure} script.
Andrew M. Kuchlinge995d162002-07-11 20:09:50 +00001937This makes the Python executable about 10\% smaller, but will also
1938mean that you can't get help for Python's built-ins. (Contributed by
1939Gustavo Niemeyer.)
1940
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001941\item The \cfunction{PyArg_NoArgs()} macro is now deprecated, and code
Andrew M. Kuchling7845e7c2002-07-11 19:27:46 +00001942that uses it should be changed. For Python 2.2 and later, the method
1943definition table can specify the
Fred Drake5c4cf152002-11-13 14:59:06 +00001944\constant{METH_NOARGS} flag, signalling that there are no arguments, and
Andrew M. Kuchling7845e7c2002-07-11 19:27:46 +00001945the argument checking can then be removed. If compatibility with
1946pre-2.2 versions of Python is important, the code could use
Fred Drakeaac8c582003-01-17 22:50:10 +00001947\code{PyArg_ParseTuple(\var{args}, "")} instead, but this will be slower
Andrew M. Kuchling7845e7c2002-07-11 19:27:46 +00001948than using \constant{METH_NOARGS}.
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00001949
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001950\item A new function, \cfunction{PyObject_DelItemString(\var{mapping},
1951char *\var{key})} was added
Fred Drake5c4cf152002-11-13 14:59:06 +00001952as shorthand for
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001953\code{PyObject_DelItem(\var{mapping}, PyString_New(\var{key})}.
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00001954
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001955\item The \method{xreadlines()} method of file objects, introduced in
1956Python 2.1, is no longer necessary because files now behave as their
1957own iterator. \method{xreadlines()} was originally introduced as a
1958faster way to loop over all the lines in a file, but now you can
1959simply write \code{for line in file_obj}.
1960
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001961\item File objects now manage their internal string buffer
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00001962differently, increasing it exponentially when needed. This results in
1963the benchmark tests in \file{Lib/test/test_bufio.py} speeding up
1964considerably (from 57 seconds to 1.7 seconds, according to one
1965measurement).
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00001966
Andrew M. Kuchling72b58e02002-05-29 17:30:34 +00001967\item It's now possible to define class and static methods for a C
1968extension type by setting either the \constant{METH_CLASS} or
1969\constant{METH_STATIC} flags in a method's \ctype{PyMethodDef}
1970structure.
Andrew M. Kuchling45afd542002-04-02 14:25:25 +00001971
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00001972\item Python now includes a copy of the Expat XML parser's source code,
1973removing any dependence on a system version or local installation of
Fred Drake5c4cf152002-11-13 14:59:06 +00001974Expat.
Andrew M. Kuchling346386f2002-07-12 20:24:42 +00001975
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00001976\end{itemize}
1977
Andrew M. Kuchling366c10c2002-11-14 23:07:57 +00001978
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00001979%======================================================================
Andrew M. Kuchling821013e2002-05-06 17:46:39 +00001980\subsection{Port-Specific Changes}
1981
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00001982Support for a port to IBM's OS/2 using the EMX runtime environment was
1983merged into the main Python source tree. EMX is a POSIX emulation
1984layer over the OS/2 system APIs. The Python port for EMX tries to
1985support all the POSIX-like capability exposed by the EMX runtime, and
1986mostly succeeds; \function{fork()} and \function{fcntl()} are
1987restricted by the limitations of the underlying emulation layer. The
1988standard OS/2 port, which uses IBM's Visual Age compiler, also gained
1989support for case-sensitive import semantics as part of the integration
1990of the EMX port into CVS. (Contributed by Andrew MacIntyre.)
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00001991
Andrew M. Kuchling72b58e02002-05-29 17:30:34 +00001992On MacOS, most toolbox modules have been weaklinked to improve
1993backward compatibility. This means that modules will no longer fail
1994to load if a single routine is missing on the curent OS version.
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00001995Instead calling the missing routine will raise an exception.
1996(Contributed by Jack Jansen.)
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00001997
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00001998The RPM spec files, found in the \file{Misc/RPM/} directory in the
1999Python source distribution, were updated for 2.3. (Contributed by
2000Sean Reifschneider.)
Fred Drake03e10312002-03-26 19:17:43 +00002001
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002002Other new platforms now supported by Python include AtheOS
Fred Drake693aea22003-02-07 14:52:18 +00002003(\url{http://www.atheos.cx/}), GNU/Hurd, and OpenVMS.
Andrew M. Kuchling20e5abc2002-07-11 20:50:34 +00002004
Fred Drake03e10312002-03-26 19:17:43 +00002005
2006%======================================================================
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002007\section{Other Changes and Fixes \label{section-other}}
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002008
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +00002009As usual, there were a bunch of other improvements and bugfixes
2010scattered throughout the source tree. A search through the CVS change
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002011logs finds there were 121 patches applied and 103 bugs fixed between
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +00002012Python 2.2 and 2.3. Both figures are likely to be underestimates.
2013
2014Some of the more notable changes are:
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002015
2016\begin{itemize}
2017
Fred Drake54fe3fd2002-11-26 22:07:35 +00002018\item The \file{regrtest.py} script now provides a way to allow ``all
2019resources except \var{foo}.'' A resource name passed to the
2020\programopt{-u} option can now be prefixed with a hyphen
2021(\character{-}) to mean ``remove this resource.'' For example, the
2022option `\code{\programopt{-u}all,-bsddb}' could be used to enable the
2023use of all resources except \code{bsddb}.
2024
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002025\item The tools used to build the documentation now work under Cygwin
2026as well as \UNIX.
2027
Michael W. Hudsondd32a912002-08-15 14:59:02 +00002028\item The \code{SET_LINENO} opcode has been removed. Back in the
2029mists of time, this opcode was needed to produce line numbers in
2030tracebacks and support trace functions (for, e.g., \module{pdb}).
2031Since Python 1.5, the line numbers in tracebacks have been computed
2032using a different mechanism that works with ``python -O''. For Python
20332.3 Michael Hudson implemented a similar scheme to determine when to
2034call the trace function, removing the need for \code{SET_LINENO}
2035entirely.
2036
Andrew M. Kuchling7a82b8c2002-11-04 20:17:24 +00002037It would be difficult to detect any resulting difference from Python
2038code, apart from a slight speed up when Python is run without
Michael W. Hudsondd32a912002-08-15 14:59:02 +00002039\programopt{-O}.
2040
2041C extensions that access the \member{f_lineno} field of frame objects
2042should instead call \code{PyCode_Addr2Line(f->f_code, f->f_lasti)}.
2043This will have the added effect of making the code work as desired
2044under ``python -O'' in earlier versions of Python.
2045
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002046A nifty new feature is that trace functions can now assign to the
2047\member{f_lineno} attribute of frame objects, changing the line that
2048will be executed next. A \samp{jump} command has been added to the
2049\module{pdb} debugger taking advantage of this new feature.
2050(Implemented by Richie Hindle.)
Andrew M. Kuchling974ab9d2002-12-31 01:20:30 +00002051
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002052\end{itemize}
2053
Andrew M. Kuchling187b1d82002-05-29 19:20:57 +00002054
Andrew M. Kuchling517109b2002-05-07 21:01:16 +00002055%======================================================================
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00002056\section{Porting to Python 2.3}
2057
Andrew M. Kuchlingf15fb292002-12-31 18:34:54 +00002058This section lists previously described changes that may require
2059changes to your code:
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002060
2061\begin{itemize}
2062
2063\item \keyword{yield} is now always a keyword; if it's used as a
2064variable name in your code, a different name must be chosen.
2065
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002066\item For strings \var{X} and \var{Y}, \code{\var{X} in \var{Y}} now works
2067if \var{X} is more than one character long.
2068
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00002069\item The \function{int()} type constructor will now return a long
2070integer instead of raising an \exception{OverflowError} when a string
2071or floating-point number is too large to fit into an integer.
2072
Andrew M. Kuchlingb492fa92002-11-27 19:11:10 +00002073\item Calling Tcl methods through \module{_tkinter} no longer
2074returns only strings. Instead, if Tcl returns other objects those
2075objects are converted to their Python equivalent, if one exists, or
2076wrapped with a \class{_tkinter.Tcl_Obj} object if no Python equivalent
2077exists.
2078
Andrew M. Kuchling80fd7852003-02-06 15:14:04 +00002079\item Large octal and hex literals such as
Andrew M. Kuchling72df65a2003-02-10 15:08:16 +00002080\code{0xffffffff} now trigger a \exception{FutureWarning}. Currently
Andrew M. Kuchling80fd7852003-02-06 15:14:04 +00002081they're stored as 32-bit numbers and result in a negative value, but
Andrew M. Kuchling72df65a2003-02-10 15:08:16 +00002082in Python 2.4 they'll become positive long integers.
2083
2084There are a few ways to fix this warning. If you really need a
2085positive number, just add an \samp{L} to the end of the literal. If
2086you're trying to get a 32-bit integer with low bits set and have
2087previously used an expression such as \code{~(1 << 31)}, it's probably
2088clearest to start with all bits set and clear the desired upper bits.
2089For example, to clear just the top bit (bit 31), you could write
2090\code{0xffffffffL {\&}{\textasciitilde}(1L<<31)}.
Andrew M. Kuchling80fd7852003-02-06 15:14:04 +00002091
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00002092\item You can no longer disable assertions by assigning to \code{__debug__}.
2093
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002094\item The Distutils \function{setup()} function has gained various new
Fred Drake5c4cf152002-11-13 14:59:06 +00002095keyword arguments such as \var{depends}. Old versions of the
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002096Distutils will abort if passed unknown keywords. The fix is to check
2097for the presence of the new \function{get_distutil_options()} function
2098in your \file{setup.py} if you want to only support the new keywords
2099with a version of the Distutils that supports them:
2100
2101\begin{verbatim}
2102from distutils import core
2103
2104kw = {'sources': 'foo.c', ...}
2105if hasattr(core, 'get_distutil_options'):
2106 kw['depends'] = ['foo.h']
Fred Drake5c4cf152002-11-13 14:59:06 +00002107ext = Extension(**kw)
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002108\end{verbatim}
2109
Andrew M. Kuchling495172c2002-11-20 13:50:15 +00002110\item Using \code{None} as a variable name will now result in a
2111\exception{SyntaxWarning} warning.
2112
2113\item Names of extension types defined by the modules included with
2114Python now contain the module and a \character{.} in front of the type
2115name.
2116
Andrew M. Kuchling8a61f492002-11-13 13:24:41 +00002117\end{itemize}
Andrew M. Kuchling950725f2002-08-06 01:40:48 +00002118
2119
2120%======================================================================
Fred Drake03e10312002-03-26 19:17:43 +00002121\section{Acknowledgements \label{acks}}
2122
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00002123The author would like to thank the following people for offering
2124suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchlingb9ba4e62003-02-03 15:16:15 +00002125article: Simon Brunning, Michael Chermside, Andrew Dalke, Scott David
2126Daniels, Fred~L. Drake, Jr., Kelly Gerber, Raymond Hettinger, Michael
2127Hudson, Detlef Lannert, Martin von L\"owis, Andrew MacIntyre, Lalo
2128Martins, Gustavo Niemeyer, Neal Norwitz, Hans Nowak, Chris Reedy,
2129Vinay Sajip, Neil Schemenauer, Jason Tishler, Just van~Rossum.
Fred Drake03e10312002-03-26 19:17:43 +00002130
2131\end{document}