2002-03-26 15:17:43 -04:00
\documentclass { howto}
2002-03-26 22:29:48 -04:00
% $Id$
2002-05-07 18:01:16 -03:00
% TODO:
% Go through and get the contributor's name for all the various changes
2002-03-26 22:29:48 -04:00
\title { What's New in Python 2.3}
2002-07-11 17:50:34 -03:00
\release { 0.03}
2002-03-26 22:29:48 -04:00
\author { A.M. Kuchling}
\authoraddress { \email { akuchlin@mems-exchange.org} }
2002-03-26 15:17:43 -04:00
\begin { document}
\maketitle
\tableofcontents
2002-06-10 10:22:46 -03:00
% Optik (or whatever it gets called)
%
2002-07-12 17:24:42 -03:00
% Bug #580462: changes to GC API
2002-06-17 10:40:04 -03:00
%
2002-08-03 22:20:05 -03:00
% heapq module
%
% MacOS framework-related changes (section of its own, probably)
%
2002-06-10 10:22:46 -03:00
2002-03-26 22:29:48 -04:00
%\section{Introduction \label{intro}}
{ \large This article is a draft, and is currently up to date for some
2002-07-11 17:50:34 -03:00
random version of the CVS tree around mid-July 2002. Please send any
2002-03-26 22:29:48 -04:00
additions, comments or errata to the author.}
This article explains the new features in Python 2.3. The tentative
2002-07-11 17:50:34 -03:00
release date of Python 2.3 is currently scheduled for some undefined
time before the end of 2002.
2002-03-26 22:29:48 -04:00
This article doesn't attempt to provide a complete specification of
the new features, but instead provides a convenient overview. For
full details, you should refer to the documentation for Python 2.3,
such as the
\citetitle [http://www.python.org/doc/2.3/lib/lib.html] { Python Library
Reference} and the
\citetitle [http://www.python.org/doc/2.3/ref/ref.html] { Python
Reference Manual} . If you want to understand the complete
implementation and design rationale for a change, refer to the PEP for
a particular new feature.
2002-04-01 15:28:09 -04:00
%======================================================================
2002-05-07 18:01:16 -03:00
\section { PEP 255: Simple Generators\label { section-generators} }
2002-04-01 15:28:09 -04:00
In Python 2.2, generators were added as an optional feature, to be
enabled by a \code { from _ _ future_ _ import generators} directive. In
2.3 generators no longer need to be specially enabled, and are now
always present; this means that \keyword { yield} is now always a
keyword. The rest of this section is a copy of the description of
generators from the ``What's New in Python 2.2'' document; if you read
it when 2.2 came out, you can skip the rest of this section.
2002-05-07 18:01:16 -03:00
You're doubtless familiar with how function calls work in Python or C.
When you call a function, it gets a private namespace where its local
2002-04-01 15:28:09 -04:00
variables are created. When the function reaches a \keyword { return}
statement, the local variables are destroyed and the resulting value
is returned to the caller. A later call to the same function will get
2002-05-07 18:01:16 -03:00
a fresh new set of local variables. But, what if the local variables
2002-04-01 15:28:09 -04:00
weren't thrown away on exiting a function? What if you could later
resume the function where it left off? This is what generators
provide; they can be thought of as resumable functions.
Here's the simplest example of a generator function:
\begin { verbatim}
def generate_ ints(N):
for i in range(N):
yield i
\end { verbatim}
A new keyword, \keyword { yield} , was introduced for generators. Any
function containing a \keyword { yield} statement is a generator
function; this is detected by Python's bytecode compiler which
compiles the function specially as a result.
When you call a generator function, it doesn't return a single value;
instead it returns a generator object that supports the iterator
protocol. On executing the \keyword { yield} statement, the generator
outputs the value of \code { i} , similar to a \keyword { return}
statement. The big difference between \keyword { yield} and a
\keyword { return} statement is that on reaching a \keyword { yield} the
generator's state of execution is suspended and local variables are
preserved. On the next call to the generator's \code { .next()} method,
the function will resume executing immediately after the
\keyword { yield} statement. (For complicated reasons, the
\keyword { yield} statement isn't allowed inside the \keyword { try} block
of a \code { try...finally} statement; read \pep { 255} for a full
explanation of the interaction between \keyword { yield} and
exceptions.)
Here's a sample usage of the \function { generate_ ints} generator:
\begin { verbatim}
>>> gen = generate_ ints(3)
>>> gen
<generator object at 0x8117f90>
>>> gen.next()
0
>>> gen.next()
1
>>> gen.next()
2
>>> gen.next()
Traceback (most recent call last):
2002-06-17 10:40:04 -03:00
File "stdin", line 1, in ?
File "stdin", line 2, in generate_ ints
2002-04-01 15:28:09 -04:00
StopIteration
\end { verbatim}
You could equally write \code { for i in generate_ ints(5)} , or
\code { a,b,c = generate_ ints(3)} .
Inside a generator function, the \keyword { return} statement can only
be used without a value, and signals the end of the procession of
values; afterwards the generator cannot return any further values.
\keyword { return} with a value, such as \code { return 5} , is a syntax
error inside a generator function. The end of the generator's results
can also be indicated by raising \exception { StopIteration} manually,
or by just letting the flow of execution fall off the bottom of the
function.
You could achieve the effect of generators manually by writing your
own class and storing all the local variables of the generator as
instance variables. For example, returning a list of integers could
be done by setting \code { self.count} to 0, and having the
\method { next()} method increment \code { self.count} and return it.
However, for a moderately complicated generator, writing a
corresponding class would be much messier.
\file { Lib/test/test_ generators.py} contains a number of more
interesting examples. The simplest one implements an in-order
traversal of a tree using generators recursively.
\begin { verbatim}
# A recursive generator that generates Tree leaves in in-order.
def inorder(t):
if t:
for x in inorder(t.left):
yield x
yield t.label
for x in inorder(t.right):
yield x
\end { verbatim}
Two other examples in \file { Lib/test/test_ generators.py} produce
solutions for the N-Queens problem (placing $ N $ queens on an $ NxN $
chess board so that no queen threatens another) and the Knight's Tour
(a route that takes a knight to every square of an $ NxN $ chessboard
without visiting any square twice).
The idea of generators comes from other programming languages,
especially Icon (\url { http://www.cs.arizona.edu/icon/} ), where the
idea of generators is central. In Icon, every
expression and function call behaves like a generator. One example
from ``An Overview of the Icon Programming Language'' at
\url { http://www.cs.arizona.edu/icon/docs/ipd266.htm} gives an idea of
what this looks like:
\begin { verbatim}
sentence := "Store it in the neighboring harbor"
if (i := find("or", sentence)) > 5 then write(i)
\end { verbatim}
In Icon the \function { find()} function returns the indexes at which the
substring ``or'' is found: 3, 23, 33. In the \keyword { if} statement,
\code { i} is first assigned a value of 3, but 3 is less than 5, so the
comparison fails, and Icon retries it with the second value of 23. 23
is greater than 5, so the comparison now succeeds, and the code prints
the value 23 to the screen.
Python doesn't go nearly as far as Icon in adopting generators as a
central concept. Generators are considered a new part of the core
Python language, but learning or using them isn't compulsory; if they
don't solve any problems that you have, feel free to ignore them.
One novel feature of Python's interface as compared to
Icon's is that a generator's state is represented as a concrete object
(the iterator) that can be passed around to other functions or stored
in a data structure.
\begin { seealso}
\seepep { 255} { Simple Generators} { Written by Neil Schemenauer, Tim
Peters, Magnus Lie Hetland. Implemented mostly by Neil Schemenauer
and Tim Peters, with other fixes from the Python Labs crew.}
\end { seealso}
2002-04-14 23:27:55 -03:00
%======================================================================
\section { PEP 278: Universal Newline Support}
2002-05-06 14:46:39 -03:00
The three major operating systems used today are Microsoft Windows,
2002-05-07 18:01:16 -03:00
Apple's Macintosh OS, and the various \UNIX \ derivatives. A minor
2002-05-06 14:46:39 -03:00
irritation is that these three platforms all use different characters
2002-05-07 18:01:16 -03:00
to mark the ends of lines in text files. \UNIX \ uses character 10,
the ASCII linefeed, while MacOS uses character 13, the ASCII carriage
return, and Windows uses a two-character sequence of a carriage return
plus a newline.
2002-05-06 14:46:39 -03:00
Python's file objects can now support end of line conventions other
than the one followed by the platform on which Python is running.
Opening a file with the mode \samp { U} or \samp { rU} will open a file
for reading in universal newline mode. All three line ending
conventions will be translated to a \samp { \e n} in the strings
returned by the various file methods such as \method { read()} and
\method { readline()} .
Universal newline support is also used when importing modules and when
executing a file with the \function { execfile()} function. This means
that Python modules can be shared between all three operating systems
without needing to convert the line-endings.
2002-05-07 18:01:16 -03:00
This feature can be disabled at compile-time by specifying
2002-05-06 14:46:39 -03:00
\longprogramopt { without-universal-newlines} when running Python's
2002-05-07 18:01:16 -03:00
\file { configure} script.
2002-04-14 23:27:55 -03:00
\begin { seealso}
\seepep { 278} { Universal Newline Support} { Written
and implemented by Jack Jansen.}
\end { seealso}
2002-05-10 18:00:05 -03:00
2002-04-03 18:44:47 -04:00
%======================================================================
2002-07-11 17:09:50 -03:00
\section { PEP 279: The \function { enumerate()} Built-in Function\label { section-enumerate} }
2002-05-10 18:00:05 -03:00
A new built-in function, \function { enumerate()} , will make
certain loops a bit clearer. \code { enumerate(thing)} , where
\var { thing} is either an iterator or a sequence, returns a iterator
that will return \code { (0, \var { thing[0]} )} , \code { (1,
\var { thing[1]} )} , \code { (2, \var { thing[2]} )} , and so forth. Fairly
often you'll see code to change every element of a list that looks
like this:
\begin { verbatim}
for i in range(len(L)):
item = L[i]
# ... compute some result based on item ...
L[i] = result
\end { verbatim}
2002-05-07 18:01:16 -03:00
2002-05-10 18:00:05 -03:00
This can be rewritten using \function { enumerate()} as:
\begin { verbatim}
for i, item in enumerate(L):
# ... compute some result based on item ...
L[i] = result
\end { verbatim}
\begin { seealso}
\seepep { 279} { The enumerate() built-in function} { Written
by Raymond D. Hettinger.}
\end { seealso}
%======================================================================
\section { PEP 285: The \class { bool} Type\label { section-bool} }
2002-05-06 14:46:39 -03:00
A Boolean type was added to Python 2.3. Two new constants were added
to the \module { _ _ builtin_ _ } module, \constant { True} and
\constant { False} . The type object for this new type is named
\class { bool} ; the constructor for it takes any Python value and
converts it to \constant { True} or \constant { False} .
\begin { verbatim}
>>> bool(1)
True
>>> bool(0)
False
>>> bool([])
False
>>> bool( (1,) )
True
\end { verbatim}
Most of the standard library modules and built-in functions have been
changed to return Booleans.
\begin { verbatim}
2002-05-07 18:01:16 -03:00
>>> obj = []
>>> hasattr(obj, 'append')
2002-05-06 14:46:39 -03:00
True
2002-05-07 18:01:16 -03:00
>>> isinstance(obj, list)
2002-05-06 14:46:39 -03:00
True
2002-05-07 18:01:16 -03:00
>>> isinstance(obj, tuple)
2002-05-06 14:46:39 -03:00
False
\end { verbatim}
Python's Booleans were added with the primary goal of making code
clearer. For example, if you're reading a function and encounter the
statement \code { return 1} , you might wonder whether the \samp { 1}
represents a truth value, or whether it's an index, or whether it's a
coefficient that multiplies some other quantity. If the statement is
\code { return True} , however, the meaning of the return value is quite
clearly a truth value.
Python's Booleans were not added for the sake of strict type-checking.
2002-05-24 18:08:58 -03:00
A very strict language such as Pascal would also prevent you
performing arithmetic with Booleans, and would require that the
expression in an \keyword { if} statement always evaluate to a Boolean.
Python is not this strict, and it never will be. (\pep { 285}
explicitly says so.) So you can still use any expression in an
\keyword { if} , even ones that evaluate to a list or tuple or some
random object, and the Boolean type is a subclass of the
2002-05-06 14:46:39 -03:00
\class { int} class, so arithmetic using a Boolean still works.
\begin { verbatim}
>>> True + 1
2
>>> False + 1
1
>>> False * 75
0
>>> True * 75
75
\end { verbatim}
2002-04-03 18:44:47 -04:00
2002-05-06 14:46:39 -03:00
To sum up \constant { True} and \constant { False} in a sentence: they're
alternative ways to spell the integer values 1 and 0, with the single
difference that \function { str()} and \function { repr()} return the
strings \samp { True} and \samp { False} instead of \samp { 1} and \samp { 0} .
2002-04-03 18:44:47 -04:00
\begin { seealso}
\seepep { 285} { Adding a bool type} { Written and implemented by GvR.}
\end { seealso}
2002-06-11 07:55:12 -03:00
2002-07-11 17:09:50 -03:00
\section { Extended Slices\label { section-slices} }
Ever since Python 1.4, the slicing syntax has supported an optional
third ``step'' or ``stride'' argument. For example, these are all
legal Python syntax: \code { L[1:10:2]} , \code { L[:-1:1]} ,
\code { L[::-1]} . This was added to Python included at the request of
the developers of Numerical Python. However, the built-in sequence
types of lists, tuples, and strings have never supported this feature,
and you got a \exception { TypeError} if you tried it. Michael Hudson
contributed a patch that was applied to Python 2.3 and fixed this
shortcoming.
2002-06-11 07:55:12 -03:00
2002-07-11 17:09:50 -03:00
For example, you can now easily extract the elements of a list that
have even indexes:
2002-07-03 09:02:01 -03:00
\begin { verbatim}
>>> L = range(10)
>>> L[::2]
[0, 2, 4, 6, 8]
\end { verbatim}
2002-07-11 17:09:50 -03:00
Negative values also work, so you can make a copy of the same list in
reverse order:
2002-07-03 09:02:01 -03:00
\begin { verbatim}
>>> L[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
\end { verbatim}
2002-04-03 18:44:47 -04:00
2002-07-11 17:09:50 -03:00
This also works for strings:
\begin { verbatim}
>>> s='abcd'
>>> s[::2]
'ac'
>>> s[::-1]
'dcba'
\end { verbatim}
2002-07-19 12:48:56 -03:00
as well as tuples and arrays.
2002-07-11 17:09:50 -03:00
2002-07-19 12:48:56 -03:00
If you have a mutable sequence (i.e. a list or an array) you can
assign to or delete an extended slice, but there are some differences
in assignment to extended and regular slices. Assignment to a regular
slice can be used to change the length of the sequence:
\begin { verbatim}
>>> a = range(3)
>>> a
[0, 1, 2]
>>> a[1:3] = [4, 5, 6]
>>> a
[0, 4, 5, 6]
\end { verbatim}
but when assigning to an extended slice the list on the right hand
side of the statement must contain the same number of items as the
slice it is replacing:
\begin { verbatim}
>>> a = range(4)
>>> a
[0, 1, 2, 3]
>>> a[::2]
[0, 2]
>>> a[::2] = range(0, -2, -1)
>>> a
[0, 1, -1, 3]
>>> a[::2] = range(3)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: attempt to assign list of size 3 to extended slice of size 2
\end { verbatim}
Deletion is more straightforward:
\begin { verbatim}
>>> a = range(4)
>>> a[::2]
[0, 2]
>>> del a[::2]
>>> a
[1, 3]
\end { verbatim}
One can also now pass slice objects to builtin sequences
\method { _ _ getitem_ _ } methods:
\begin { verbatim}
>>> range(10)._ _ getitem_ _ (slice(0, 5, 2))
[0, 2, 4]
\end { verbatim}
or use them directly in subscripts:
\begin { verbatim}
>>> range(10)[slice(0, 5, 2)]
[0, 2, 4]
\end { verbatim}
To make implementing sequences that support extended slicing in Python
easier, slice ojects now have a method \method { indices} which given
the length of a sequence returns \code { (start, stop, step)} handling
omitted and out-of-bounds indices in a manner consistent with regular
slices (and this innocuous phrase hides a welter of confusing
details!). The method is intended to be used like this:
\begin { verbatim}
class FakeSeq:
...
def calc_ item(self, i):
...
def _ _ getitem_ _ (self, item):
if isinstance(item, slice):
return FakeSeq([self.calc_ item(i)
in range(*item.indices(len(self)))])
else:
return self.calc_ item(i)
\end { verbatim}
From this example you can also see that the builtin ``\var { slice} ''
object is now the type of slice objects, not a function (so is now
consistent with \var { int} , \var { str} , etc from 2.2).
2002-07-11 17:09:50 -03:00
2002-05-07 18:01:16 -03:00
%======================================================================
2002-07-03 09:02:01 -03:00
\section { Other Language Changes}
2002-05-07 18:01:16 -03:00
2002-07-11 17:09:50 -03:00
Here are all of the changes that Python 2.3 makes to the core Python
language.
\begin { itemize}
\item The \keyword { yield} statement is now always a keyword, as
described in section~\ref { section-generators} of this document.
\item A new built-in function \function { enumerate()}
was added, as described in section~\ref { section-enumerate} of this
document.
\item Two new constants, \constant { True} and \constant { False} were
added along with the built-in \class { bool} type, as described in
section~\ref { section-bool} of this document.
2002-05-07 18:01:16 -03:00
2002-07-11 17:09:50 -03:00
\item Built-in types now support the extended slicing syntax,
as described in section~\ref { section-slices} of this document.
2002-05-07 18:01:16 -03:00
2002-07-11 17:09:50 -03:00
\item Dictionaries have a new method, \method { pop(\var { key} )} , that
returns the value corresponding to \var { key} and removes that
key/value pair from the dictionary. \method { pop()} will raise a
\exception { KeyError} if the requested key isn't present in the
dictionary:
\begin { verbatim}
>>> d = { 1:2}
>>> d
{ 1: 2}
>>> d.pop(4)
Traceback (most recent call last):
File ``stdin'', line 1, in ?
KeyError: 4
>>> d.pop(1)
2
>>> d.pop(1)
Traceback (most recent call last):
File ``stdin'', line 1, in ?
KeyError: pop(): dictionary is empty
>>> d
{ }
>>>
\end { verbatim}
2002-05-07 18:01:16 -03:00
2002-07-11 17:09:50 -03:00
(Patch contributed by Raymond Hettinger.)
2002-05-07 18:01:16 -03:00
2002-07-11 17:09:50 -03:00
\item The \method { strip()} , \method { lstrip()} , and \method { rstrip()}
string methods now have an optional argument for specifying the
characters to strip. The default is still to remove all whitespace
characters:
2002-05-07 18:01:16 -03:00
2002-07-11 17:09:50 -03:00
\begin { verbatim}
>>> ' abc '.strip()
'abc'
>>> '><><abc<><><>'.strip('<>')
'abc'
>>> '><><abc<><><>\n '.strip('<>')
'abc<><><>\n '
>>> u'\u 4000\u 4001abc\u 4000'.strip(u'\u 4000')
u'\u 4001abc'
>>>
\end { verbatim}
2002-07-12 17:24:42 -03:00
(Contributed by Simon Brunning.)
2002-07-11 17:09:50 -03:00
\item The \method { startswith()} and \method { endswith()}
string methods now accept negative numbers for the start and end
parameters.
\item Another new string method is \method { zfill()} , originally a
function in the \module { string} module. \method { zfill()} pads a
numeric string with zeros on the left until it's the specified width.
Note that the \code { \% } operator is still more flexible and powerful
than \method { zfill()} .
\begin { verbatim}
>>> '45'.zfill(4)
'0045'
>>> '12345'.zfill(4)
'12345'
>>> 'goofy'.zfill(6)
'0goofy'
\end { verbatim}
2002-07-12 17:24:42 -03:00
(Contributed by Walter D\" orwald.)
\item The \keyword { assert} statement no longer checks the \code { _ _ debug_ _ }
flag, so you can no longer disable assertions by assigning to \code { _ _ debug_ _ } .
Running Python with the \programopt { -O} switch will still generate
code that doesn't execute any assertions.
2002-07-11 17:50:34 -03:00
\item A new type object, \class { basestring} , has been added.
Both 8-bit strings and Unicode strings inherit from this type, so
\code { isinstance(obj, basestring)} will return \constant { True} for
either kind of string. It's a completely abstract type, so you
can't create \class { basestring} instances.
\item Most type objects are now callable, so you can use them
to create new objects such as functions, classes, and modules. (This
means that the \module { new} module can be deprecated in a future
Python version, because you can now use the type objects available
in the \module { types} module.)
% XXX should new.py use PendingDeprecationWarning?
For example, you can create a new module object with the following code:
\begin { verbatim}
>>> import types
>>> m = types.ModuleType('abc','docstring')
>>> m
<module 'abc' (built-in)>
>>> m._ _ doc_ _
'docstring'
\end { verbatim}
2002-07-11 17:09:50 -03:00
\item
2002-07-03 09:02:01 -03:00
A new warning, \exception { PendingDeprecationWarning} was added to
2002-07-11 17:50:34 -03:00
indicate features which are in the process of being
2002-07-11 17:09:50 -03:00
deprecated. The warning will \emph { not} be printed by default. To
check for use of features that will be deprecated in the future,
supply \programopt { -Walways::PendingDeprecationWarning::} on the
command line or use \function { warnings.filterwarnings()} .
\item One minor but far-reaching change is that the names of extension
types defined by the modules included with Python now contain the
module and a \samp { .} in front of the type name. For example, in
Python 2.2, if you created a socket and printed its
\member { _ _ class_ _ } , you'd get this output:
\begin { verbatim}
>>> s = socket.socket()
>>> s._ _ class_ _
<type 'socket'>
\end { verbatim}
In 2.3, you get this:
\begin { verbatim}
>>> s._ _ class_ _
<type '_ socket.socket'>
\end { verbatim}
\end { itemize}
2002-05-29 12:54:55 -03:00
2002-03-26 22:29:48 -04:00
%======================================================================
\section { New and Improved Modules}
2002-05-06 14:46:39 -03:00
As usual, Python's standard modules had a number of enhancements and
2002-07-22 15:57:36 -03:00
bug fixes. Here's a partial list of the most notable changes, sorted
alphabetically by module name. Consult the
\file { Misc/NEWS} file in the source tree for a more
complete list of changes, or look through the CVS logs for all the
details.
2002-05-06 14:46:39 -03:00
\begin { itemize}
2002-07-22 15:57:36 -03:00
\item The \module { array} module now supports arrays of Unicode
characters using the \samp { u} format character. Arrays also now
support using the \code { +=} assignment operator to add another array's
contents, and the \code { *=} assignment operator to repeat an array.
(Contributed by Jason Orendorff.)
\item The Distutils \class { Extension} class now supports
an extra constructor argument named \samp { depends} for listing
additional source files that an extension depends on. This lets
Distutils recompile the module if any of the dependency files are
modified. For example, if \samp { sampmodule.c} includes the header
file \file { sample.h} , you would create the \class { Extension} object like
this:
2002-06-26 10:23:55 -03:00
\begin { verbatim}
2002-07-22 15:57:36 -03:00
ext = Extension("samp",
sources=["sampmodule.c"],
depends=["sample.h"])
2002-06-26 10:23:55 -03:00
\end { verbatim}
2002-07-22 15:57:36 -03:00
Modifying \file { sample.h} would then cause the module to be recompiled.
(Contributed by Jeremy Hylton.)
2002-07-11 17:50:34 -03:00
2002-07-22 15:57:36 -03:00
\item Two new binary packagers were added to the Distutils.
\code { bdist_ pkgtool} builds \file { .pkg} files to use with Solaris
\program { pkgtool} , and \code { bdist_ sdux} builds \program { swinstall}
packages for use on HP-UX.
An abstract binary packager class,
\module { distutils.command.bdist_ packager} , was added; this may make it
easier to write binary packaging commands. (Contributed by Mark
Alexander.)
2002-07-11 17:50:34 -03:00
2002-07-11 17:09:50 -03:00
\item The \module { getopt} module gained a new function,
\function { gnu_ getopt()} , that supports the same arguments as the existing
\function { getopt()} function but uses GNU-style scanning mode.
The existing \function { getopt()} stops processing options as soon as a
non-option argument is encountered, but in GNU-style mode processing
continues, meaning that options and arguments can be mixed. For
example:
\begin { verbatim}
>>> getopt.getopt(['-f', 'filename', 'output', '-v'], 'f:v')
([('-f', 'filename')], ['output', '-v'])
>>> getopt.gnu_ getopt(['-f', 'filename', 'output', '-v'], 'f:v')
([('-f', 'filename'), ('-v', '')], ['output'])
\end { verbatim}
(Contributed by Peter \AA { strand} .)
2002-03-26 15:17:43 -04:00
2002-07-11 17:50:34 -03:00
\item The \module { grp} , \module { pwd} , and \module { resource} modules
now return enhanced tuples:
2002-03-26 22:29:48 -04:00
2002-05-06 14:46:39 -03:00
\begin { verbatim}
>>> import grp
>>> g = grp.getgrnam('amk')
>>> g.gr_ name, g.gr_ gid
('amk', 500)
\end { verbatim}
2002-04-14 23:27:55 -03:00
2002-07-22 15:57:36 -03:00
\item Two new functions in the \module { math} module,
\function { degrees(\var { rads} )} and \function { radians(\var { degs} )} ,
convert between radians and degrees. Other functions in the
\module { math} module such as
\function { math.sin()} and \function { math.cos()} have always required
input values measured in radians. (Contributed by Raymond Hettinger.)
2002-07-28 17:29:03 -03:00
\item Four new functions, \function { getpgid()} , \function { killpg()} , \function { lchown()} , and \function { mknod()} , were added to the \module { posix} module that
2002-07-22 15:57:36 -03:00
underlies the \module { os} module. (Contributed by Gustavo Niemeyer
and Geert Jansen.)
\item The parser objects provided by the \module { pyexpat} module
can now optionally buffer character data, resulting in fewer calls to
your character data handler and therefore faster performance. Setting
the parser object's \member { buffer_ text} attribute to \constant { True}
will enable buffering.
2002-05-06 14:46:39 -03:00
\item The \module { readline} module also gained a number of new
functions: \function { get_ history_ item()} ,
\function { get_ current_ history_ length()} , and \function { redisplay()} .
2002-05-27 14:19:46 -03:00
\item Support for more advanced POSIX signal handling was added
to the \module { signal} module by adding the \function { sigpending} ,
\function { sigprocmask} and \function { sigsuspend} functions, where supported
by the platform. These functions make it possible to avoid some previously
unavoidable race conditions.
2002-05-27 12:08:24 -03:00
2002-07-22 15:57:36 -03:00
\item The \module { socket} module now supports timeouts. You
can call the \method { settimeout(\var { t} )} method on a socket object to
set a timeout of \var { t} seconds. Subsequent socket operations that
take longer than \var { t} seconds to complete will abort and raise a
\exception { socket.error} exception.
The original timeout implementation was by Tim O'Malley. Michael
Gilfix integrated it into the Python \module { socket} module, after the
patch had undergone a lengthy review. After it was checked in, Guido
van~Rossum rewrote parts of it. This is a good example of the free
software development process in action.
\item The new \module { textwrap} module contains functions for wrapping
strings containing paragraphs of text. The \function { wrap(\var { text} ,
\var { width} )} function takes a string and returns a list containing
the text split into lines of no more than the chosen width. The
\function { fill(\var { text} , \var { width} )} function returns a single
string, reformatted to fit into lines no longer than the chosen width.
(As you can guess, \function { fill()} is built on top of
\function { wrap()} . For example:
\begin { verbatim}
>>> import textwrap
>>> paragraph = "Not a whit, we defy augury: ... more text ..."
>>> textwrap.wrap(paragraph, 60)
["Not a whit, we defy augury: there's a special providence in",
"the fall of a sparrow. If it be now, 'tis not to come; if it",
...]
>>> print textwrap.fill(paragraph, 35)
Not a whit, we defy augury: there's
a special providence in the fall of
a sparrow. If it be now, 'tis not
to come; if it be not to come, it
will be now; if it be not now, yet
it will come: the readiness is all.
>>>
\end { verbatim}
The module also contains a \class { TextWrapper} class that actually
implements the text wrapping strategy. Both the
\class { TextWrapper} class and the \function { wrap()} and
\function { fill()} functions support a number of additional keyword
arguments for fine-tuning the formatting; consult the module's
documentation for details.
% XXX add a link to the module docs?
(Contributed by Greg Ward.)
2002-07-22 16:21:06 -03:00
\item The \module { time} module's \function { strptime()} function has
long been an annoyance because it uses the platform C library's
\function { strptime()} implementation, and different platforms
sometimes have odd bugs. Brett Cannon contributed a portable
implementation that's written in pure Python, which should behave
identically on all platforms.
2002-07-11 17:50:34 -03:00
\item The DOM implementation
in \module { xml.dom.minidom} can now generate XML output in a
particular encoding, by specifying an optional encoding argument to
the \method { toxml()} and \method { toprettyxml()} methods of DOM nodes.
2002-05-06 14:46:39 -03:00
\end { itemize}
2002-04-15 11:05:59 -03:00
2002-03-26 22:29:48 -04:00
2002-07-22 16:21:06 -03:00
%======================================================================
\section { Specialized Object Allocator (pymalloc)\label { section-pymalloc} }
An experimental feature added to Python 2.1 was a specialized object
allocator called pymalloc, written by Vladimir Marangozov. Pymalloc
was intended to be faster than the system \cfunction { malloc()} and have
less memory overhead for typical allocation patterns of Python
programs. The allocator uses C's \cfunction { malloc()} function to get
large pools of memory, and then fulfills smaller memory requests from
these pools.
In 2.1 and 2.2, pymalloc was an experimental feature and wasn't
enabled by default; you had to explicitly turn it on by providing the
\longprogramopt { with-pymalloc} option to the \program { configure}
script. In 2.3, pymalloc has had further enhancements and is now
enabled by default; you'll have to supply
\longprogramopt { without-pymalloc} to disable it.
This change is transparent to code written in Python; however,
pymalloc may expose bugs in C extensions. Authors of C extension
modules should test their code with the object allocator enabled,
because some incorrect code may cause core dumps at runtime. There
are a bunch of memory allocation functions in Python's C API that have
previously been just aliases for the C library's \cfunction { malloc()}
and \cfunction { free()} , meaning that if you accidentally called
mismatched functions, the error wouldn't be noticeable. When the
object allocator is enabled, these functions aren't aliases of
\cfunction { malloc()} and \cfunction { free()} any more, and calling the
wrong function to free memory may get you a core dump. For example,
if memory was allocated using \cfunction { PyObject_ Malloc()} , it has to
be freed using \cfunction { PyObject_ Free()} , not \cfunction { free()} . A
few modules included with Python fell afoul of this and had to be
fixed; doubtless there are more third-party modules that will have the
same problem.
As part of this change, the confusing multiple interfaces for
allocating memory have been consolidated down into two API families.
Memory allocated with one family must not be manipulated with
functions from the other family.
There is another family of functions specifically for allocating
Python \emph { objects} (as opposed to memory).
\begin { itemize}
\item To allocate and free an undistinguished chunk of memory use
the ``raw memory'' family: \cfunction { PyMem_ Malloc()} ,
\cfunction { PyMem_ Realloc()} , and \cfunction { PyMem_ Free()} .
\item The ``object memory'' family is the interface to the pymalloc
facility described above and is biased towards a large number of
``small'' allocations: \cfunction { PyObject_ Malloc} ,
\cfunction { PyObject_ Realloc} , and \cfunction { PyObject_ Free} .
\item To allocate and free Python objects, use the ``object'' family
\cfunction { PyObject_ New()} , \cfunction { PyObject_ NewVar()} , and
\cfunction { PyObject_ Del()} .
\end { itemize}
Thanks to lots of work by Tim Peters, pymalloc in 2.3 also provides
debugging features to catch memory overwrites and doubled frees in
both extension modules and in the interpreter itself. To enable this
support, turn on the Python interpreter's debugging code by running
\program { configure} with \longprogramopt { with-pydebug} .
To aid extension writers, a header file \file { Misc/pymemcompat.h} is
distributed with the source to Python 2.3 that allows Python
extensions to use the 2.3 interfaces to memory allocation and compile
against any version of Python since 1.5.2. You would copy the file
from Python's source distribution and bundle it with the source of
your extension.
\begin { seealso}
\seeurl { http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Objects/obmalloc.c}
{ For the full details of the pymalloc implementation, see
the comments at the top of the file \file { Objects/obmalloc.c} in the
Python source code. The above link points to the file within the
SourceForge CVS browser.}
\end { seealso}
2002-03-26 22:29:48 -04:00
% ======================================================================
2002-05-06 14:46:39 -03:00
\section { Build and C API Changes}
2002-07-22 15:50:11 -03:00
Changes to Python's build process and to the C API include:
2002-03-26 22:29:48 -04:00
2002-05-06 14:46:39 -03:00
\begin { itemize}
2002-07-22 16:21:06 -03:00
\item The C-level interface to the garbage collector has been changed,
to make it easier to write extension types that support garbage
collection, and to make it easier to debug misuses of the functions.
Various functions have slightly different semantics, so a bunch of
functions had to be renamed. Extensions that use the old API will
still compile but will \emph { not} participate in garbage collection,
so updating them for 2.3 should be considered fairly high priority.
To upgrade an extension module to the new API, perform the following
steps:
\begin { itemize}
\item Rename \cfunction { Py_ TPFLAGS_ GC} to \cfunction { PyTPFLAGS_ HAVE_ GC} .
\item Use \cfunction { PyObject_ GC_ New} or \cfunction { PyObject_ GC_ NewVar} to
allocate objects, and \cfunction { PyObject_ GC_ Del} to deallocate them.
\item Rename \cfunction { PyObject_ GC_ Init} to \cfunction { PyObject_ GC_ Track} and
\cfunction { PyObject_ GC_ Fini} to \cfunction { PyObject_ GC_ UnTrack} .
\item Remove \cfunction { PyGC_ HEAD_ SIZE} from object size calculations.
\item Remove calls to \cfunction { PyObject_ AS_ GC} and \cfunction { PyObject_ FROM_ GC} .
\end { itemize}
2002-05-07 18:01:16 -03:00
\item Python can now optionally be built as a shared library
(\file { libpython2.3.so} ) by supplying \longprogramopt { enable-shared}
2002-05-10 18:00:05 -03:00
when running Python's \file { configure} script. (Contributed by Ondrej
Palkovsky.)
2002-03-26 22:29:48 -04:00
2002-07-22 15:50:11 -03:00
\item The \csimplemacro { DL_ EXPORT} and \csimplemacro { DL_ IMPORT} macros are now
deprecated. Initialization functions for Python extension modules
should now be declared using the new macro
\csimplemacro { PyMODINIT_ FUNC} , while the Python core will generally
use the \csimplemacro { PyAPI_ FUNC} and \csimplemacro { PyAPI_ DATA}
macros.
2002-07-22 10:18:59 -03:00
2002-07-11 17:09:50 -03:00
\item The interpreter can be compiled without any docstrings for
the built-in functions and modules by supplying
2002-07-11 17:50:34 -03:00
\longprogramopt { without-doc-strings} to the \file { configure} script.
2002-07-11 17:09:50 -03:00
This makes the Python executable about 10\% smaller, but will also
mean that you can't get help for Python's built-ins. (Contributed by
Gustavo Niemeyer.)
2002-07-11 17:50:34 -03:00
\item The cycle detection implementation used by the garbage collection
has proven to be stable, so it's now being made mandatory; you can no
longer compile Python without it, and the
\longprogramopt { with-cycle-gc} switch to \file { configure} has been removed.
2002-05-07 18:01:16 -03:00
\item The \cfunction { PyArg_ NoArgs()} macro is now deprecated, and code
2002-07-11 16:27:46 -03:00
that uses it should be changed. For Python 2.2 and later, the method
definition table can specify the
\constant { METH_ NOARGS} flag, signalling that there are no arguments, and
the argument checking can then be removed. If compatibility with
pre-2.2 versions of Python is important, the code could use
\code { PyArg_ ParseTuple(args, "")} instead, but this will be slower
than using \constant { METH_ NOARGS} .
2002-03-26 22:29:48 -04:00
2002-05-07 18:01:16 -03:00
\item A new function, \cfunction { PyObject_ DelItemString(\var { mapping} ,
char *\var { key} )} was added
as shorthand for
\code { PyObject_ DelItem(\var { mapping} , PyString_ New(\var { key} )} .
2002-03-26 22:29:48 -04:00
2002-05-06 14:46:39 -03:00
\item The source code for the Expat XML parser is now included with
the Python source, so the \module { pyexpat} module is no longer
dependent on having a system library containing Expat.
2002-05-07 18:01:16 -03:00
\item File objects now manage their internal string buffer
differently by increasing it exponentially when needed.
This results in the benchmark tests in \file { Lib/test/test_ bufio.py}
speeding up from 57 seconds to 1.7 seconds, according to one
measurement.
2002-05-29 14:30:34 -03:00
\item It's now possible to define class and static methods for a C
extension type by setting either the \constant { METH_ CLASS} or
\constant { METH_ STATIC} flags in a method's \ctype { PyMethodDef}
structure.
2002-04-02 10:25:25 -04:00
2002-07-12 17:24:42 -03:00
\item Python now includes a copy of the Expat XML parser's source code,
removing any dependence on a system version or local installation of
Expat.
2002-05-06 14:46:39 -03:00
\end { itemize}
\subsection { Port-Specific Changes}
2002-05-29 16:20:57 -03:00
Support for a port to IBM's OS/2 using the EMX runtime environment was
merged into the main Python source tree. EMX is a POSIX emulation
layer over the OS/2 system APIs. The Python port for EMX tries to
support all the POSIX-like capability exposed by the EMX runtime, and
mostly succeeds; \function { fork()} and \function { fcntl()} are
restricted by the limitations of the underlying emulation layer. The
standard OS/2 port, which uses IBM's Visual Age compiler, also gained
support for case-sensitive import semantics as part of the integration
of the EMX port into CVS. (Contributed by Andrew MacIntyre.)
2002-03-26 22:29:48 -04:00
2002-05-29 14:30:34 -03:00
On MacOS, most toolbox modules have been weaklinked to improve
backward compatibility. This means that modules will no longer fail
to load if a single routine is missing on the curent OS version.
2002-05-29 16:20:57 -03:00
Instead calling the missing routine will raise an exception.
(Contributed by Jack Jansen.)
2002-03-26 22:29:48 -04:00
2002-05-29 16:20:57 -03:00
The RPM spec files, found in the \file { Misc/RPM/} directory in the
Python source distribution, were updated for 2.3. (Contributed by
Sean Reifschneider.)
2002-05-07 18:01:16 -03:00
2002-07-11 17:50:34 -03:00
Python now supports AtheOS (\url { www.atheos.cx} ) and GNU/Hurd.
2002-05-07 18:01:16 -03:00
%======================================================================
\section { Other Changes and Fixes}
Finally, there are various miscellaneous fixes:
\begin { itemize}
2002-03-26 15:17:43 -04:00
2002-05-07 18:01:16 -03:00
\item The tools used to build the documentation now work under Cygwin
as well as \UNIX .
\end { itemize}
2002-03-26 15:17:43 -04:00
2002-05-29 16:20:57 -03:00
2002-03-26 15:17:43 -04:00
%======================================================================
\section { Acknowledgements \label { acks} }
2002-03-26 22:29:48 -04:00
The author would like to thank the following people for offering
suggestions, corrections and assistance with various drafts of this
2002-06-10 15:58:19 -03:00
article: Michael Chermside, Scott David Daniels, Fred~L. Drake, Jr.,
2002-07-11 16:27:46 -03:00
Michael Hudson, Detlef Lannert, Martin von L\" owis, Andrew MacIntyre,
Gustavo Niemeyer, Neal Norwitz.
2002-03-26 15:17:43 -04:00
\end { document}