Bump to 2.3.1 to pick up the missing file.
[python/dscho.git] / Doc / whatsnew / whatsnew23.tex
blob5375775b781e43e09f2e808164c858d124fba1f2
1 \documentclass{howto}
2 % $Id$
4 \title{What's New in Python 2.3}
5 \release{0.03}
6 \author{A.M. Kuchling}
7 \authoraddress{\email{akuchlin@mems-exchange.org}}
9 \begin{document}
10 \maketitle
11 \tableofcontents
13 % Optik (or whatever it gets called)
15 % MacOS framework-related changes (section of its own, probably)
17 % New sorting code
19 % xreadlines obsolete; files are their own iterator
21 %\section{Introduction \label{intro}}
23 {\large This article is a draft, and is currently up to date for some
24 random version of the CVS tree around mid-July 2002. Please send any
25 additions, comments or errata to the author.}
27 This article explains the new features in Python 2.3. The tentative
28 release date of Python 2.3 is currently scheduled for some undefined
29 time before the end of 2002.
31 This article doesn't attempt to provide a complete specification of
32 the new features, but instead provides a convenient overview. For
33 full details, you should refer to the documentation for Python 2.3,
34 such as the
35 \citetitle[http://www.python.org/doc/2.3/lib/lib.html]{Python Library
36 Reference} and the
37 \citetitle[http://www.python.org/doc/2.3/ref/ref.html]{Python
38 Reference Manual}. If you want to understand the complete
39 implementation and design rationale for a change, refer to the PEP for
40 a particular new feature.
43 %======================================================================
44 \section{PEP 218: A Standard Set Datatype}
46 The new \module{sets} module contains an implementation of a set
47 datatype. The \class{Set} class is for mutable sets, sets that can
48 have members added and removed. The \class{ImmutableSet} class is for
49 sets that can't be modified, and can be used as dictionary keys. Sets
50 are built on top of dictionaries, so the elements within a set must be
51 hashable.
53 As a simple example,
55 \begin{verbatim}
56 >>> import sets
57 >>> S = sets.Set([1,2,3])
58 >>> S
59 Set([1, 2, 3])
60 >>> 1 in S
61 True
62 >>> 0 in S
63 False
64 >>> S.add(5)
65 >>> S.remove(3)
66 >>> S
67 Set([1, 2, 5])
68 >>>
69 \end{verbatim}
71 The union and intersection of sets can be computed with the
72 \method{union()} and \method{intersection()} methods, or,
73 alternatively, using the bitwise operators \samp{\&} and \samp{|}.
74 Mutable sets also have in-place versions of these methods,
75 \method{union_update()} and \method{intersection_update()}.
77 \begin{verbatim}
78 >>> S1 = sets.Set([1,2,3])
79 >>> S2 = sets.Set([4,5,6])
80 >>> S1.union(S2)
81 Set([1, 2, 3, 4, 5, 6])
82 >>> S1 | S2 # Alternative notation
83 Set([1, 2, 3, 4, 5, 6])
84 >>> S1.intersection(S2)
85 Set([])
86 >>> S1 & S2 # Alternative notation
87 Set([])
88 >>> S1.union_update(S2)
89 Set([1, 2, 3, 4, 5, 6])
90 >>> S1
91 Set([1, 2, 3, 4, 5, 6])
92 >>>
93 \end{verbatim}
95 It's also possible to take the symmetric difference of two sets. This
96 is the set of all elements in the union that aren't in the
97 intersection. An alternative way of expressing the symmetric
98 difference is that it contains all elements that are in exactly one
99 set. Again, there's an in-place version, with the ungainly name
100 \method{symmetric_difference_update()}.
102 \begin{verbatim}
103 >>> S1 = sets.Set([1,2,3,4])
104 >>> S2 = sets.Set([3,4,5,6])
105 >>> S1.symmetric_difference(S2)
106 Set([1, 2, 5, 6])
107 >>> S1 ^ S2
108 Set([1, 2, 5, 6])
110 \end{verbatim}
112 There are also methods, \method{issubset()} and \method{issuperset()},
113 for checking whether one set is a strict subset or superset of
114 another:
116 \begin{verbatim}
117 >>> S1 = sets.Set([1,2,3])
118 >>> S2 = sets.Set([2,3])
119 >>> S2.issubset(S1)
120 True
121 >>> S1.issubset(S2)
122 False
123 >>> S1.issuperset(S2)
124 True
126 \end{verbatim}
129 \begin{seealso}
131 \seepep{218}{Adding a Built-In Set Object Type}{PEP written by Greg V. Wilson.
132 Implemented by Greg V. Wilson, Alex Martelli, and GvR.}
134 \end{seealso}
138 %======================================================================
139 \section{PEP 255: Simple Generators\label{section-generators}}
141 In Python 2.2, generators were added as an optional feature, to be
142 enabled by a \code{from __future__ import generators} directive. In
143 2.3 generators no longer need to be specially enabled, and are now
144 always present; this means that \keyword{yield} is now always a
145 keyword. The rest of this section is a copy of the description of
146 generators from the ``What's New in Python 2.2'' document; if you read
147 it when 2.2 came out, you can skip the rest of this section.
149 You're doubtless familiar with how function calls work in Python or C.
150 When you call a function, it gets a private namespace where its local
151 variables are created. When the function reaches a \keyword{return}
152 statement, the local variables are destroyed and the resulting value
153 is returned to the caller. A later call to the same function will get
154 a fresh new set of local variables. But, what if the local variables
155 weren't thrown away on exiting a function? What if you could later
156 resume the function where it left off? This is what generators
157 provide; they can be thought of as resumable functions.
159 Here's the simplest example of a generator function:
161 \begin{verbatim}
162 def generate_ints(N):
163 for i in range(N):
164 yield i
165 \end{verbatim}
167 A new keyword, \keyword{yield}, was introduced for generators. Any
168 function containing a \keyword{yield} statement is a generator
169 function; this is detected by Python's bytecode compiler which
170 compiles the function specially as a result.
172 When you call a generator function, it doesn't return a single value;
173 instead it returns a generator object that supports the iterator
174 protocol. On executing the \keyword{yield} statement, the generator
175 outputs the value of \code{i}, similar to a \keyword{return}
176 statement. The big difference between \keyword{yield} and a
177 \keyword{return} statement is that on reaching a \keyword{yield} the
178 generator's state of execution is suspended and local variables are
179 preserved. On the next call to the generator's \code{.next()} method,
180 the function will resume executing immediately after the
181 \keyword{yield} statement. (For complicated reasons, the
182 \keyword{yield} statement isn't allowed inside the \keyword{try} block
183 of a \code{try...finally} statement; read \pep{255} for a full
184 explanation of the interaction between \keyword{yield} and
185 exceptions.)
187 Here's a sample usage of the \function{generate_ints} generator:
189 \begin{verbatim}
190 >>> gen = generate_ints(3)
191 >>> gen
192 <generator object at 0x8117f90>
193 >>> gen.next()
195 >>> gen.next()
197 >>> gen.next()
199 >>> gen.next()
200 Traceback (most recent call last):
201 File "stdin", line 1, in ?
202 File "stdin", line 2, in generate_ints
203 StopIteration
204 \end{verbatim}
206 You could equally write \code{for i in generate_ints(5)}, or
207 \code{a,b,c = generate_ints(3)}.
209 Inside a generator function, the \keyword{return} statement can only
210 be used without a value, and signals the end of the procession of
211 values; afterwards the generator cannot return any further values.
212 \keyword{return} with a value, such as \code{return 5}, is a syntax
213 error inside a generator function. The end of the generator's results
214 can also be indicated by raising \exception{StopIteration} manually,
215 or by just letting the flow of execution fall off the bottom of the
216 function.
218 You could achieve the effect of generators manually by writing your
219 own class and storing all the local variables of the generator as
220 instance variables. For example, returning a list of integers could
221 be done by setting \code{self.count} to 0, and having the
222 \method{next()} method increment \code{self.count} and return it.
223 However, for a moderately complicated generator, writing a
224 corresponding class would be much messier.
225 \file{Lib/test/test_generators.py} contains a number of more
226 interesting examples. The simplest one implements an in-order
227 traversal of a tree using generators recursively.
229 \begin{verbatim}
230 # A recursive generator that generates Tree leaves in in-order.
231 def inorder(t):
232 if t:
233 for x in inorder(t.left):
234 yield x
235 yield t.label
236 for x in inorder(t.right):
237 yield x
238 \end{verbatim}
240 Two other examples in \file{Lib/test/test_generators.py} produce
241 solutions for the N-Queens problem (placing $N$ queens on an $NxN$
242 chess board so that no queen threatens another) and the Knight's Tour
243 (a route that takes a knight to every square of an $NxN$ chessboard
244 without visiting any square twice).
246 The idea of generators comes from other programming languages,
247 especially Icon (\url{http://www.cs.arizona.edu/icon/}), where the
248 idea of generators is central. In Icon, every
249 expression and function call behaves like a generator. One example
250 from ``An Overview of the Icon Programming Language'' at
251 \url{http://www.cs.arizona.edu/icon/docs/ipd266.htm} gives an idea of
252 what this looks like:
254 \begin{verbatim}
255 sentence := "Store it in the neighboring harbor"
256 if (i := find("or", sentence)) > 5 then write(i)
257 \end{verbatim}
259 In Icon the \function{find()} function returns the indexes at which the
260 substring ``or'' is found: 3, 23, 33. In the \keyword{if} statement,
261 \code{i} is first assigned a value of 3, but 3 is less than 5, so the
262 comparison fails, and Icon retries it with the second value of 23. 23
263 is greater than 5, so the comparison now succeeds, and the code prints
264 the value 23 to the screen.
266 Python doesn't go nearly as far as Icon in adopting generators as a
267 central concept. Generators are considered a new part of the core
268 Python language, but learning or using them isn't compulsory; if they
269 don't solve any problems that you have, feel free to ignore them.
270 One novel feature of Python's interface as compared to
271 Icon's is that a generator's state is represented as a concrete object
272 (the iterator) that can be passed around to other functions or stored
273 in a data structure.
275 \begin{seealso}
277 \seepep{255}{Simple Generators}{Written by Neil Schemenauer, Tim
278 Peters, Magnus Lie Hetland. Implemented mostly by Neil Schemenauer
279 and Tim Peters, with other fixes from the Python Labs crew.}
281 \end{seealso}
284 %======================================================================
285 \section{PEP 263: Source Code Encodings \label{section-encodings}}
287 Python source files can now be declared as being in different
288 character set encodings. Encodings are declared by including a
289 specially formatted comment in the first or second line of the source
290 file. For example, a UTF-8 file can be declared with:
292 \begin{verbatim}
293 #!/usr/bin/env python
294 # -*- coding: UTF-8 -*-
295 \end{verbatim}
297 Without such an encoding declaration, the default encoding used is
298 ISO-8859-1, also known as Latin1.
300 The encoding declaration only affects Unicode string literals; the
301 text in the source code will be converted to Unicode using the
302 specified encoding. Note that Python identifiers are still restricted
303 to ASCII characters, so you can't have variable names that use
304 characters outside of the usual alphanumerics.
306 \begin{seealso}
308 \seepep{263}{Defining Python Source Code Encodings}{Written by
309 Marc-Andr\'e Lemburg and Martin von L\"owis; implemented by Martin von
310 L\"owis.}
312 \end{seealso}
315 %======================================================================
316 \section{PEP 278: Universal Newline Support}
318 The three major operating systems used today are Microsoft Windows,
319 Apple's Macintosh OS, and the various \UNIX\ derivatives. A minor
320 irritation is that these three platforms all use different characters
321 to mark the ends of lines in text files. \UNIX\ uses character 10,
322 the ASCII linefeed, while MacOS uses character 13, the ASCII carriage
323 return, and Windows uses a two-character sequence of a carriage return
324 plus a newline.
326 Python's file objects can now support end of line conventions other
327 than the one followed by the platform on which Python is running.
328 Opening a file with the mode \samp{U} or \samp{rU} will open a file
329 for reading in universal newline mode. All three line ending
330 conventions will be translated to a \samp{\e n} in the strings
331 returned by the various file methods such as \method{read()} and
332 \method{readline()}.
334 Universal newline support is also used when importing modules and when
335 executing a file with the \function{execfile()} function. This means
336 that Python modules can be shared between all three operating systems
337 without needing to convert the line-endings.
339 This feature can be disabled at compile-time by specifying
340 \longprogramopt{without-universal-newlines} when running Python's
341 \file{configure} script.
343 \begin{seealso}
345 \seepep{278}{Universal Newline Support}{Written
346 and implemented by Jack Jansen.}
348 \end{seealso}
351 %======================================================================
352 \section{PEP 279: The \function{enumerate()} Built-in Function\label{section-enumerate}}
354 A new built-in function, \function{enumerate()}, will make
355 certain loops a bit clearer. \code{enumerate(thing)}, where
356 \var{thing} is either an iterator or a sequence, returns a iterator
357 that will return \code{(0, \var{thing[0]})}, \code{(1,
358 \var{thing[1]})}, \code{(2, \var{thing[2]})}, and so forth. Fairly
359 often you'll see code to change every element of a list that looks
360 like this:
362 \begin{verbatim}
363 for i in range(len(L)):
364 item = L[i]
365 # ... compute some result based on item ...
366 L[i] = result
367 \end{verbatim}
369 This can be rewritten using \function{enumerate()} as:
371 \begin{verbatim}
372 for i, item in enumerate(L):
373 # ... compute some result based on item ...
374 L[i] = result
375 \end{verbatim}
378 \begin{seealso}
380 \seepep{279}{The enumerate() built-in function}{Written
381 by Raymond D. Hettinger.}
383 \end{seealso}
386 %======================================================================
387 \section{PEP 285: The \class{bool} Type\label{section-bool}}
389 A Boolean type was added to Python 2.3. Two new constants were added
390 to the \module{__builtin__} module, \constant{True} and
391 \constant{False}. The type object for this new type is named
392 \class{bool}; the constructor for it takes any Python value and
393 converts it to \constant{True} or \constant{False}.
395 \begin{verbatim}
396 >>> bool(1)
397 True
398 >>> bool(0)
399 False
400 >>> bool([])
401 False
402 >>> bool( (1,) )
403 True
404 \end{verbatim}
406 Most of the standard library modules and built-in functions have been
407 changed to return Booleans.
409 \begin{verbatim}
410 >>> obj = []
411 >>> hasattr(obj, 'append')
412 True
413 >>> isinstance(obj, list)
414 True
415 >>> isinstance(obj, tuple)
416 False
417 \end{verbatim}
419 Python's Booleans were added with the primary goal of making code
420 clearer. For example, if you're reading a function and encounter the
421 statement \code{return 1}, you might wonder whether the \samp{1}
422 represents a truth value, or whether it's an index, or whether it's a
423 coefficient that multiplies some other quantity. If the statement is
424 \code{return True}, however, the meaning of the return value is quite
425 clearly a truth value.
427 Python's Booleans were not added for the sake of strict type-checking.
428 A very strict language such as Pascal would also prevent you
429 performing arithmetic with Booleans, and would require that the
430 expression in an \keyword{if} statement always evaluate to a Boolean.
431 Python is not this strict, and it never will be. (\pep{285}
432 explicitly says so.) So you can still use any expression in an
433 \keyword{if}, even ones that evaluate to a list or tuple or some
434 random object, and the Boolean type is a subclass of the
435 \class{int} class, so arithmetic using a Boolean still works.
437 \begin{verbatim}
438 >>> True + 1
440 >>> False + 1
442 >>> False * 75
444 >>> True * 75
446 \end{verbatim}
448 To sum up \constant{True} and \constant{False} in a sentence: they're
449 alternative ways to spell the integer values 1 and 0, with the single
450 difference that \function{str()} and \function{repr()} return the
451 strings \samp{True} and \samp{False} instead of \samp{1} and \samp{0}.
453 \begin{seealso}
455 \seepep{285}{Adding a bool type}{Written and implemented by GvR.}
457 \end{seealso}
460 %======================================================================
461 \section{PEP 293: Codec Error Handling Callbacks}
463 XXX write this section
465 \begin{seealso}
467 \seepep{293}{Codec Error Handling Callbacks}{Written and implemented by
468 Walter Dörwald.}
470 \end{seealso}
473 %======================================================================
474 \section{Extended Slices\label{section-slices}}
476 Ever since Python 1.4, the slicing syntax has supported an optional
477 third ``step'' or ``stride'' argument. For example, these are all
478 legal Python syntax: \code{L[1:10:2]}, \code{L[:-1:1]},
479 \code{L[::-1]}. This was added to Python included at the request of
480 the developers of Numerical Python. However, the built-in sequence
481 types of lists, tuples, and strings have never supported this feature,
482 and you got a \exception{TypeError} if you tried it. Michael Hudson
483 contributed a patch that was applied to Python 2.3 and fixed this
484 shortcoming.
486 For example, you can now easily extract the elements of a list that
487 have even indexes:
489 \begin{verbatim}
490 >>> L = range(10)
491 >>> L[::2]
492 [0, 2, 4, 6, 8]
493 \end{verbatim}
495 Negative values also work, so you can make a copy of the same list in
496 reverse order:
498 \begin{verbatim}
499 >>> L[::-1]
500 [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
501 \end{verbatim}
503 This also works for strings:
505 \begin{verbatim}
506 >>> s='abcd'
507 >>> s[::2]
508 'ac'
509 >>> s[::-1]
510 'dcba'
511 \end{verbatim}
513 as well as tuples and arrays.
515 If you have a mutable sequence (i.e. a list or an array) you can
516 assign to or delete an extended slice, but there are some differences
517 in assignment to extended and regular slices. Assignment to a regular
518 slice can be used to change the length of the sequence:
520 \begin{verbatim}
521 >>> a = range(3)
522 >>> a
523 [0, 1, 2]
524 >>> a[1:3] = [4, 5, 6]
525 >>> a
526 [0, 4, 5, 6]
527 \end{verbatim}
529 but when assigning to an extended slice the list on the right hand
530 side of the statement must contain the same number of items as the
531 slice it is replacing:
533 \begin{verbatim}
534 >>> a = range(4)
535 >>> a
536 [0, 1, 2, 3]
537 >>> a[::2]
538 [0, 2]
539 >>> a[::2] = range(0, -2, -1)
540 >>> a
541 [0, 1, -1, 3]
542 >>> a[::2] = range(3)
543 Traceback (most recent call last):
544 File "<stdin>", line 1, in ?
545 ValueError: attempt to assign list of size 3 to extended slice of size 2
546 \end{verbatim}
548 Deletion is more straightforward:
550 \begin{verbatim}
551 >>> a = range(4)
552 >>> a[::2]
553 [0, 2]
554 >>> del a[::2]
555 >>> a
556 [1, 3]
557 \end{verbatim}
559 One can also now pass slice objects to builtin sequences
560 \method{__getitem__} methods:
562 \begin{verbatim}
563 >>> range(10).__getitem__(slice(0, 5, 2))
564 [0, 2, 4]
565 \end{verbatim}
567 or use them directly in subscripts:
569 \begin{verbatim}
570 >>> range(10)[slice(0, 5, 2)]
571 [0, 2, 4]
572 \end{verbatim}
574 To make implementing sequences that support extended slicing in Python
575 easier, slice ojects now have a method \method{indices} which given
576 the length of a sequence returns \code{(start, stop, step)} handling
577 omitted and out-of-bounds indices in a manner consistent with regular
578 slices (and this innocuous phrase hides a welter of confusing
579 details!). The method is intended to be used like this:
581 \begin{verbatim}
582 class FakeSeq:
584 def calc_item(self, i):
586 def __getitem__(self, item):
587 if isinstance(item, slice):
588 return FakeSeq([self.calc_item(i)
589 in range(*item.indices(len(self)))])
590 else:
591 return self.calc_item(i)
592 \end{verbatim}
594 From this example you can also see that the builtin ``\class{slice}''
595 object is now the type object for the slice type, and is no longer a
596 function. This is consistent with Python 2.2, where \class{int},
597 \class{str}, etc., underwent the same change.
600 %======================================================================
601 \section{Other Language Changes}
603 Here are all of the changes that Python 2.3 makes to the core Python
604 language.
606 \begin{itemize}
607 \item The \keyword{yield} statement is now always a keyword, as
608 described in section~\ref{section-generators} of this document.
610 \item A new built-in function \function{enumerate()}
611 was added, as described in section~\ref{section-enumerate} of this
612 document.
614 \item Two new constants, \constant{True} and \constant{False} were
615 added along with the built-in \class{bool} type, as described in
616 section~\ref{section-bool} of this document.
618 \item Built-in types now support the extended slicing syntax,
619 as described in section~\ref{section-slices} of this document.
621 \item Dictionaries have a new method, \method{pop(\var{key})}, that
622 returns the value corresponding to \var{key} and removes that
623 key/value pair from the dictionary. \method{pop()} will raise a
624 \exception{KeyError} if the requested key isn't present in the
625 dictionary:
627 \begin{verbatim}
628 >>> d = {1:2}
629 >>> d
630 {1: 2}
631 >>> d.pop(4)
632 Traceback (most recent call last):
633 File ``stdin'', line 1, in ?
634 KeyError: 4
635 >>> d.pop(1)
637 >>> d.pop(1)
638 Traceback (most recent call last):
639 File ``stdin'', line 1, in ?
640 KeyError: pop(): dictionary is empty
641 >>> d
644 \end{verbatim}
646 (Patch contributed by Raymond Hettinger.)
648 \item The \keyword{assert} statement no longer checks the \code{__debug__}
649 flag, so you can no longer disable assertions by assigning to \code{__debug__}.
650 Running Python with the \programopt{-O} switch will still generate
651 code that doesn't execute any assertions.
653 \item Most type objects are now callable, so you can use them
654 to create new objects such as functions, classes, and modules. (This
655 means that the \module{new} module can be deprecated in a future
656 Python version, because you can now use the type objects available
657 in the \module{types} module.)
658 % XXX should new.py use PendingDeprecationWarning?
659 For example, you can create a new module object with the following code:
661 \begin{verbatim}
662 >>> import types
663 >>> m = types.ModuleType('abc','docstring')
664 >>> m
665 <module 'abc' (built-in)>
666 >>> m.__doc__
667 'docstring'
668 \end{verbatim}
670 \item
671 A new warning, \exception{PendingDeprecationWarning} was added to
672 indicate features which are in the process of being
673 deprecated. The warning will \emph{not} be printed by default. To
674 check for use of features that will be deprecated in the future,
675 supply \programopt{-Walways::PendingDeprecationWarning::} on the
676 command line or use \function{warnings.filterwarnings()}.
678 \item Using \code{None} as a variable name will now result in a
679 \exception{SyntaxWarning} warning. In a future version of Python,
680 \code{None} may finally become a keyword.
682 \item One minor but far-reaching change is that the names of extension
683 types defined by the modules included with Python now contain the
684 module and a \samp{.} in front of the type name. For example, in
685 Python 2.2, if you created a socket and printed its
686 \member{__class__}, you'd get this output:
688 \begin{verbatim}
689 >>> s = socket.socket()
690 >>> s.__class__
691 <type 'socket'>
692 \end{verbatim}
694 In 2.3, you get this:
695 \begin{verbatim}
696 >>> s.__class__
697 <type '_socket.socket'>
698 \end{verbatim}
700 \end{itemize}
703 \subsection{String Changes}
705 \begin{itemize}
707 \item The \code{in} operator now works differently for strings.
708 Previously, when evaluating \code{\var{X} in \var{Y}} where \var{X}
709 and \var{Y} are strings, \var{X} could only be a single character.
710 That's now changed; \var{X} can be a string of any length, and
711 \code{\var{X} in \var{Y}} will return \constant{True} if \var{X} is a
712 substring of \var{Y}. If \var{X} is the empty string, the result is
713 always \constant{True}.
715 \begin{verbatim}
716 >>> 'ab' in 'abcd'
717 True
718 >>> 'ad' in 'abcd'
719 False
720 >>> '' in 'abcd'
721 True
722 \end{verbatim}
724 Note that this doesn't tell you where the substring starts; the
725 \method{find()} method is still necessary to figure that out.
727 \item The \method{strip()}, \method{lstrip()}, and \method{rstrip()}
728 string methods now have an optional argument for specifying the
729 characters to strip. The default is still to remove all whitespace
730 characters:
732 \begin{verbatim}
733 >>> ' abc '.strip()
734 'abc'
735 >>> '><><abc<><><>'.strip('<>')
736 'abc'
737 >>> '><><abc<><><>\n'.strip('<>')
738 'abc<><><>\n'
739 >>> u'\u4000\u4001abc\u4000'.strip(u'\u4000')
740 u'\u4001abc'
742 \end{verbatim}
744 (Contributed by Simon Brunning.)
746 \item The \method{startswith()} and \method{endswith()}
747 string methods now accept negative numbers for the start and end
748 parameters.
750 \item Another new string method is \method{zfill()}, originally a
751 function in the \module{string} module. \method{zfill()} pads a
752 numeric string with zeros on the left until it's the specified width.
753 Note that the \code{\%} operator is still more flexible and powerful
754 than \method{zfill()}.
756 \begin{verbatim}
757 >>> '45'.zfill(4)
758 '0045'
759 >>> '12345'.zfill(4)
760 '12345'
761 >>> 'goofy'.zfill(6)
762 '0goofy'
763 \end{verbatim}
765 (Contributed by Walter D\"orwald.)
767 \item A new type object, \class{basestring}, has been added.
768 Both 8-bit strings and Unicode strings inherit from this type, so
769 \code{isinstance(obj, basestring)} will return \constant{True} for
770 either kind of string. It's a completely abstract type, so you
771 can't create \class{basestring} instances.
773 \item Interned strings are no longer immortal. Interned will now be
774 garbage-collected in the usual way when the only reference to them is
775 from the internal dictionary of interned strings. (Implemented by
776 Oren Tirosh.)
778 \end{itemize}
781 \subsection{Optimizations}
783 \begin{itemize}
785 \item The \method{sort()} method of list objects has been extensively
786 rewritten by Tim Peters, and the implementation is significantly
787 faster.
789 \item Multiplication of large long integers is now much faster thanks
790 to an implementation of Karatsuba multiplication, an algorithm that
791 scales better than the O(n*n) required for the grade-school
792 multiplication algorithm. (Original patch by Christopher A. Craig,
793 and significantly reworked by Tim Peters.)
795 \item The \code{SET_LINENO} opcode is now gone. This may provide a
796 small speed increase, subject to your compiler's idiosyncrasies.
797 (Removed by Michael Hudson.)
799 \item A number of small rearrangements have been made in various
800 hotspots to improve performance, inlining a function here, removing
801 some code there. (Implemented mostly by GvR, but lots of people have
802 contributed to one change or another.)
804 \end{itemize}
807 %======================================================================
808 \section{New and Improved Modules}
810 As usual, Python's standard modules had a number of enhancements and
811 bug fixes. Here's a partial list of the most notable changes, sorted
812 alphabetically by module name. Consult the
813 \file{Misc/NEWS} file in the source tree for a more
814 complete list of changes, or look through the CVS logs for all the
815 details.
817 \begin{itemize}
819 \item The \module{array} module now supports arrays of Unicode
820 characters using the \samp{u} format character. Arrays also now
821 support using the \code{+=} assignment operator to add another array's
822 contents, and the \code{*=} assignment operator to repeat an array.
823 (Contributed by Jason Orendorff.)
825 \item The Distutils \class{Extension} class now supports
826 an extra constructor argument named \samp{depends} for listing
827 additional source files that an extension depends on. This lets
828 Distutils recompile the module if any of the dependency files are
829 modified. For example, if \samp{sampmodule.c} includes the header
830 file \file{sample.h}, you would create the \class{Extension} object like
831 this:
833 \begin{verbatim}
834 ext = Extension("samp",
835 sources=["sampmodule.c"],
836 depends=["sample.h"])
837 \end{verbatim}
839 Modifying \file{sample.h} would then cause the module to be recompiled.
840 (Contributed by Jeremy Hylton.)
842 \item Two new binary packagers were added to the Distutils.
843 \code{bdist_pkgtool} builds \file{.pkg} files to use with Solaris
844 \program{pkgtool}, and \code{bdist_sdux} builds \program{swinstall}
845 packages for use on HP-UX.
846 An abstract binary packager class,
847 \module{distutils.command.bdist_packager}, was added; this may make it
848 easier to write binary packaging commands. (Contributed by Mark
849 Alexander.)
851 \item The \module{getopt} module gained a new function,
852 \function{gnu_getopt()}, that supports the same arguments as the existing
853 \function{getopt()} function but uses GNU-style scanning mode.
854 The existing \function{getopt()} stops processing options as soon as a
855 non-option argument is encountered, but in GNU-style mode processing
856 continues, meaning that options and arguments can be mixed. For
857 example:
859 \begin{verbatim}
860 >>> getopt.getopt(['-f', 'filename', 'output', '-v'], 'f:v')
861 ([('-f', 'filename')], ['output', '-v'])
862 >>> getopt.gnu_getopt(['-f', 'filename', 'output', '-v'], 'f:v')
863 ([('-f', 'filename'), ('-v', '')], ['output'])
864 \end{verbatim}
866 (Contributed by Peter \AA{strand}.)
868 \item The \module{grp}, \module{pwd}, and \module{resource} modules
869 now return enhanced tuples:
871 \begin{verbatim}
872 >>> import grp
873 >>> g = grp.getgrnam('amk')
874 >>> g.gr_name, g.gr_gid
875 ('amk', 500)
876 \end{verbatim}
878 \item The new \module{heapq} module contains an implementation of a
879 heap queue algorithm. A heap is an array-like data structure that
880 keeps items in a sorted order such that, for every index k, heap[k] <=
881 heap[2*k+1] and heap[k] <= heap[2*k+2]. This makes it quick to remove
882 the smallest item, and inserting a new item while maintaining the heap
883 property is O(lg~n). (See
884 \url{http://www.nist.gov/dads/HTML/priorityque.html} for more
885 information about the priority queue data structure.)
887 The Python \module{heapq} module provides \function{heappush()} and
888 \function{heappop()} functions for adding and removing items while
889 maintaining the heap property on top of some other mutable Python
890 sequence type. For example:
892 \begin{verbatim}
893 >>> import heapq
894 >>> heap = []
895 >>> for item in [3, 7, 5, 11, 1]:
896 ... heapq.heappush(heap, item)
898 >>> heap
899 [1, 3, 5, 11, 7]
900 >>> heapq.heappop(heap)
902 >>> heapq.heappop(heap)
904 >>> heap
905 [5, 7, 11]
907 >>> heapq.heappush(heap, 5)
908 >>> heap = []
909 >>> for item in [3, 7, 5, 11, 1]:
910 ... heapq.heappush(heap, item)
912 >>> heap
913 [1, 3, 5, 11, 7]
914 >>> heapq.heappop(heap)
916 >>> heapq.heappop(heap)
918 >>> heap
919 [5, 7, 11]
921 \end{verbatim}
923 (Contributed by Kevin O'Connor.)
925 \item Two new functions in the \module{math} module,
926 \function{degrees(\var{rads})} and \function{radians(\var{degs})},
927 convert between radians and degrees. Other functions in the
928 \module{math} module such as
929 \function{math.sin()} and \function{math.cos()} have always required
930 input values measured in radians. (Contributed by Raymond Hettinger.)
932 \item Four new functions, \function{getpgid()}, \function{killpg()}, \function{lchown()}, and \function{mknod()}, were added to the \module{posix} module that
933 underlies the \module{os} module. (Contributed by Gustavo Niemeyer
934 and Geert Jansen.)
936 \item The parser objects provided by the \module{pyexpat} module
937 can now optionally buffer character data, resulting in fewer calls to
938 your character data handler and therefore faster performance. Setting
939 the parser object's \member{buffer_text} attribute to \constant{True}
940 will enable buffering.
942 \item The \module{readline} module also gained a number of new
943 functions: \function{get_history_item()},
944 \function{get_current_history_length()}, and \function{redisplay()}.
946 \item Support for more advanced POSIX signal handling was added
947 to the \module{signal} module by adding the \function{sigpending},
948 \function{sigprocmask} and \function{sigsuspend} functions, where supported
949 by the platform. These functions make it possible to avoid some previously
950 unavoidable race conditions.
952 \item The \module{socket} module now supports timeouts. You
953 can call the \method{settimeout(\var{t})} method on a socket object to
954 set a timeout of \var{t} seconds. Subsequent socket operations that
955 take longer than \var{t} seconds to complete will abort and raise a
956 \exception{socket.error} exception.
958 The original timeout implementation was by Tim O'Malley. Michael
959 Gilfix integrated it into the Python \module{socket} module, after the
960 patch had undergone a lengthy review. After it was checked in, Guido
961 van~Rossum rewrote parts of it. This is a good example of the free
962 software development process in action.
964 \item The new \module{textwrap} module contains functions for wrapping
965 strings containing paragraphs of text. The \function{wrap(\var{text},
966 \var{width})} function takes a string and returns a list containing
967 the text split into lines of no more than the chosen width. The
968 \function{fill(\var{text}, \var{width})} function returns a single
969 string, reformatted to fit into lines no longer than the chosen width.
970 (As you can guess, \function{fill()} is built on top of
971 \function{wrap()}. For example:
973 \begin{verbatim}
974 >>> import textwrap
975 >>> paragraph = "Not a whit, we defy augury: ... more text ..."
976 >>> textwrap.wrap(paragraph, 60)
977 ["Not a whit, we defy augury: there's a special providence in",
978 "the fall of a sparrow. If it be now, 'tis not to come; if it",
979 ...]
980 >>> print textwrap.fill(paragraph, 35)
981 Not a whit, we defy augury: there's
982 a special providence in the fall of
983 a sparrow. If it be now, 'tis not
984 to come; if it be not to come, it
985 will be now; if it be not now, yet
986 it will come: the readiness is all.
987 >>>
988 \end{verbatim}
990 The module also contains a \class{TextWrapper} class that actually
991 implements the text wrapping strategy. Both the
992 \class{TextWrapper} class and the \function{wrap()} and
993 \function{fill()} functions support a number of additional keyword
994 arguments for fine-tuning the formatting; consult the module's
995 documentation for details.
996 % XXX add a link to the module docs?
997 (Contributed by Greg Ward.)
999 \item The \module{time} module's \function{strptime()} function has
1000 long been an annoyance because it uses the platform C library's
1001 \function{strptime()} implementation, and different platforms
1002 sometimes have odd bugs. Brett Cannon contributed a portable
1003 implementation that's written in pure Python, which should behave
1004 identically on all platforms.
1006 \item The DOM implementation
1007 in \module{xml.dom.minidom} can now generate XML output in a
1008 particular encoding, by specifying an optional encoding argument to
1009 the \method{toxml()} and \method{toprettyxml()} methods of DOM nodes.
1011 \end{itemize}
1014 %======================================================================
1015 \section{Specialized Object Allocator (pymalloc)\label{section-pymalloc}}
1017 An experimental feature added to Python 2.1 was a specialized object
1018 allocator called pymalloc, written by Vladimir Marangozov. Pymalloc
1019 was intended to be faster than the system \cfunction{malloc()} and have
1020 less memory overhead for typical allocation patterns of Python
1021 programs. The allocator uses C's \cfunction{malloc()} function to get
1022 large pools of memory, and then fulfills smaller memory requests from
1023 these pools.
1025 In 2.1 and 2.2, pymalloc was an experimental feature and wasn't
1026 enabled by default; you had to explicitly turn it on by providing the
1027 \longprogramopt{with-pymalloc} option to the \program{configure}
1028 script. In 2.3, pymalloc has had further enhancements and is now
1029 enabled by default; you'll have to supply
1030 \longprogramopt{without-pymalloc} to disable it.
1032 This change is transparent to code written in Python; however,
1033 pymalloc may expose bugs in C extensions. Authors of C extension
1034 modules should test their code with the object allocator enabled,
1035 because some incorrect code may cause core dumps at runtime. There
1036 are a bunch of memory allocation functions in Python's C API that have
1037 previously been just aliases for the C library's \cfunction{malloc()}
1038 and \cfunction{free()}, meaning that if you accidentally called
1039 mismatched functions, the error wouldn't be noticeable. When the
1040 object allocator is enabled, these functions aren't aliases of
1041 \cfunction{malloc()} and \cfunction{free()} any more, and calling the
1042 wrong function to free memory may get you a core dump. For example,
1043 if memory was allocated using \cfunction{PyObject_Malloc()}, it has to
1044 be freed using \cfunction{PyObject_Free()}, not \cfunction{free()}. A
1045 few modules included with Python fell afoul of this and had to be
1046 fixed; doubtless there are more third-party modules that will have the
1047 same problem.
1049 As part of this change, the confusing multiple interfaces for
1050 allocating memory have been consolidated down into two API families.
1051 Memory allocated with one family must not be manipulated with
1052 functions from the other family.
1054 There is another family of functions specifically for allocating
1055 Python \emph{objects} (as opposed to memory).
1057 \begin{itemize}
1058 \item To allocate and free an undistinguished chunk of memory use
1059 the ``raw memory'' family: \cfunction{PyMem_Malloc()},
1060 \cfunction{PyMem_Realloc()}, and \cfunction{PyMem_Free()}.
1062 \item The ``object memory'' family is the interface to the pymalloc
1063 facility described above and is biased towards a large number of
1064 ``small'' allocations: \cfunction{PyObject_Malloc},
1065 \cfunction{PyObject_Realloc}, and \cfunction{PyObject_Free}.
1067 \item To allocate and free Python objects, use the ``object'' family
1068 \cfunction{PyObject_New()}, \cfunction{PyObject_NewVar()}, and
1069 \cfunction{PyObject_Del()}.
1070 \end{itemize}
1072 Thanks to lots of work by Tim Peters, pymalloc in 2.3 also provides
1073 debugging features to catch memory overwrites and doubled frees in
1074 both extension modules and in the interpreter itself. To enable this
1075 support, turn on the Python interpreter's debugging code by running
1076 \program{configure} with \longprogramopt{with-pydebug}.
1078 To aid extension writers, a header file \file{Misc/pymemcompat.h} is
1079 distributed with the source to Python 2.3 that allows Python
1080 extensions to use the 2.3 interfaces to memory allocation and compile
1081 against any version of Python since 1.5.2. You would copy the file
1082 from Python's source distribution and bundle it with the source of
1083 your extension.
1085 \begin{seealso}
1087 \seeurl{http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Objects/obmalloc.c}
1088 {For the full details of the pymalloc implementation, see
1089 the comments at the top of the file \file{Objects/obmalloc.c} in the
1090 Python source code. The above link points to the file within the
1091 SourceForge CVS browser.}
1093 \end{seealso}
1096 % ======================================================================
1097 \section{Build and C API Changes}
1099 Changes to Python's build process and to the C API include:
1101 \begin{itemize}
1103 \item The C-level interface to the garbage collector has been changed,
1104 to make it easier to write extension types that support garbage
1105 collection, and to make it easier to debug misuses of the functions.
1106 Various functions have slightly different semantics, so a bunch of
1107 functions had to be renamed. Extensions that use the old API will
1108 still compile but will \emph{not} participate in garbage collection,
1109 so updating them for 2.3 should be considered fairly high priority.
1111 To upgrade an extension module to the new API, perform the following
1112 steps:
1114 \begin{itemize}
1116 \item Rename \cfunction{Py_TPFLAGS_GC} to \cfunction{PyTPFLAGS_HAVE_GC}.
1118 \item Use \cfunction{PyObject_GC_New} or \cfunction{PyObject_GC_NewVar} to
1119 allocate objects, and \cfunction{PyObject_GC_Del} to deallocate them.
1121 \item Rename \cfunction{PyObject_GC_Init} to \cfunction{PyObject_GC_Track} and
1122 \cfunction{PyObject_GC_Fini} to \cfunction{PyObject_GC_UnTrack}.
1124 \item Remove \cfunction{PyGC_HEAD_SIZE} from object size calculations.
1126 \item Remove calls to \cfunction{PyObject_AS_GC} and \cfunction{PyObject_FROM_GC}.
1128 \end{itemize}
1130 \item Python can now optionally be built as a shared library
1131 (\file{libpython2.3.so}) by supplying \longprogramopt{enable-shared}
1132 when running Python's \file{configure} script. (Contributed by Ondrej
1133 Palkovsky.)
1135 \item The \csimplemacro{DL_EXPORT} and \csimplemacro{DL_IMPORT} macros
1136 are now deprecated. Initialization functions for Python extension
1137 modules should now be declared using the new macro
1138 \csimplemacro{PyMODINIT_FUNC}, while the Python core will generally
1139 use the \csimplemacro{PyAPI_FUNC} and \csimplemacro{PyAPI_DATA}
1140 macros.
1142 \item The interpreter can be compiled without any docstrings for
1143 the built-in functions and modules by supplying
1144 \longprogramopt{without-doc-strings} to the \file{configure} script.
1145 This makes the Python executable about 10\% smaller, but will also
1146 mean that you can't get help for Python's built-ins. (Contributed by
1147 Gustavo Niemeyer.)
1149 \item The cycle detection implementation used by the garbage collection
1150 has proven to be stable, so it's now being made mandatory; you can no
1151 longer compile Python without it, and the
1152 \longprogramopt{with-cycle-gc} switch to \file{configure} has been removed.
1154 \item The \cfunction{PyArg_NoArgs()} macro is now deprecated, and code
1155 that uses it should be changed. For Python 2.2 and later, the method
1156 definition table can specify the
1157 \constant{METH_NOARGS} flag, signalling that there are no arguments, and
1158 the argument checking can then be removed. If compatibility with
1159 pre-2.2 versions of Python is important, the code could use
1160 \code{PyArg_ParseTuple(args, "")} instead, but this will be slower
1161 than using \constant{METH_NOARGS}.
1163 \item A new function, \cfunction{PyObject_DelItemString(\var{mapping},
1164 char *\var{key})} was added
1165 as shorthand for
1166 \code{PyObject_DelItem(\var{mapping}, PyString_New(\var{key})}.
1168 \item The source code for the Expat XML parser is now included with
1169 the Python source, so the \module{pyexpat} module is no longer
1170 dependent on having a system library containing Expat.
1172 \item File objects now manage their internal string buffer
1173 differently by increasing it exponentially when needed.
1174 This results in the benchmark tests in \file{Lib/test/test_bufio.py}
1175 speeding up from 57 seconds to 1.7 seconds, according to one
1176 measurement.
1178 \item It's now possible to define class and static methods for a C
1179 extension type by setting either the \constant{METH_CLASS} or
1180 \constant{METH_STATIC} flags in a method's \ctype{PyMethodDef}
1181 structure.
1183 \item Python now includes a copy of the Expat XML parser's source code,
1184 removing any dependence on a system version or local installation of
1185 Expat.
1187 \end{itemize}
1189 \subsection{Port-Specific Changes}
1191 Support for a port to IBM's OS/2 using the EMX runtime environment was
1192 merged into the main Python source tree. EMX is a POSIX emulation
1193 layer over the OS/2 system APIs. The Python port for EMX tries to
1194 support all the POSIX-like capability exposed by the EMX runtime, and
1195 mostly succeeds; \function{fork()} and \function{fcntl()} are
1196 restricted by the limitations of the underlying emulation layer. The
1197 standard OS/2 port, which uses IBM's Visual Age compiler, also gained
1198 support for case-sensitive import semantics as part of the integration
1199 of the EMX port into CVS. (Contributed by Andrew MacIntyre.)
1201 On MacOS, most toolbox modules have been weaklinked to improve
1202 backward compatibility. This means that modules will no longer fail
1203 to load if a single routine is missing on the curent OS version.
1204 Instead calling the missing routine will raise an exception.
1205 (Contributed by Jack Jansen.)
1207 The RPM spec files, found in the \file{Misc/RPM/} directory in the
1208 Python source distribution, were updated for 2.3. (Contributed by
1209 Sean Reifschneider.)
1211 Python now supports AtheOS (\url{www.atheos.cx}) and GNU/Hurd.
1214 %======================================================================
1215 \section{Other Changes and Fixes}
1217 Finally, there are various miscellaneous fixes:
1219 \begin{itemize}
1221 \item The tools used to build the documentation now work under Cygwin
1222 as well as \UNIX.
1224 \item The \code{SET_LINENO} opcode has been removed. Back in the
1225 mists of time, this opcode was needed to produce line numbers in
1226 tracebacks and support trace functions (for, e.g., \module{pdb}).
1227 Since Python 1.5, the line numbers in tracebacks have been computed
1228 using a different mechanism that works with ``python -O''. For Python
1229 2.3 Michael Hudson implemented a similar scheme to determine when to
1230 call the trace function, removing the need for \code{SET_LINENO}
1231 entirely.
1233 Python code will be hard pushed to notice a difference from this
1234 change, apart from a slight speed up when python is run without
1235 \programopt{-O}.
1237 C extensions that access the \member{f_lineno} field of frame objects
1238 should instead call \code{PyCode_Addr2Line(f->f_code, f->f_lasti)}.
1239 This will have the added effect of making the code work as desired
1240 under ``python -O'' in earlier versions of Python.
1242 \end{itemize}
1245 %======================================================================
1246 \section{Porting to Python 2.3}
1248 XXX write this
1251 %======================================================================
1252 \section{Acknowledgements \label{acks}}
1254 The author would like to thank the following people for offering
1255 suggestions, corrections and assistance with various drafts of this
1256 article: Michael Chermside, Scott David Daniels, Fred~L. Drake, Jr.,
1257 Michael Hudson, Detlef Lannert, Martin von L\"owis, Andrew MacIntyre,
1258 Gustavo Niemeyer, Neal Norwitz, Jason Tishler.
1260 \end{document}