blob: d5577f9db016a5a2d34d09019daa09c0c86e353d [file] [log] [blame]
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +00001\documentclass{howto}
2
3% $Id$
4
5\title{What's New in Python 2.1}
Andrew M. Kuchling81b6ae72001-02-11 16:55:39 +00006\release{0.06}
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +00007\author{A.M. Kuchling}
8\authoraddress{\email{amk1@bigfoot.com}}
9\begin{document}
10\maketitle\tableofcontents
11
12\section{Introduction}
13
Andrew M. Kuchlingf33c1182001-01-23 02:48:26 +000014{\large This document is a draft, and is subject to change until
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +000015the final version of Python 2.1 is released. Currently it is up to date
Andrew M. Kuchling74d18ed2001-02-28 22:22:40 +000016for Python 2.1 beta 1. Please send any comments, bug reports, or
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +000017questions, no matter how minor, to \email{amk1@bigfoot.com}. }
Andrew M. Kuchlingf33c1182001-01-23 02:48:26 +000018
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +000019It's that time again... time for a new Python release, version 2.1.
20One recent goal of the Python development team has been to accelerate
21the pace of new releases, with a new release coming every 6 to 9
22months. 2.1 is the first release to come out at this faster pace, with
23the first alpha appearing in January, 3 months after the final version
24of 2.0 was released.
25
26This article explains the new features in 2.1. While there aren't as
27many changes in 2.1 as there were in Python 2.0, there are still some
28pleasant surprises in store. 2.1 is the first release to be steered
29through the use of Python Enhancement Proposals, or PEPs, so most of
30the sizable changes have accompanying PEPs that provide more complete
31documentation and a design rationale for the change. This article
32doesn't attempt to document the new features completely, but simply
33provides an overview of the new features for Python programmers.
34Refer to the Python 2.1 documentation, or to the specific PEP, for
35more details about any new feature that particularly interests you.
36
Andrew M. Kuchling8bad9932001-02-28 22:39:15 +000037Currently 2.1 is available in a beta release, and the final release is
38planned for April 2001.
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +000039
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +000040%======================================================================
41\section{PEP 227: Nested Scopes}
42
43The largest change in Python 2.1 is to Python's scoping rules. In
44Python 2.0, at any given time there are at most three namespaces used
45to look up variable names: local, module-level, and the built-in
46namespace. This often surprised people because it didn't match their
47intuitive expectations. For example, a nested recursive function
48definition doesn't work:
49
50\begin{verbatim}
51def f():
52 ...
53 def g(value):
54 ...
55 return g(value-1) + 1
56 ...
57\end{verbatim}
58
59The function \function{g()} will always raise a \exception{NameError}
60exception, because the binding of the name \samp{g} isn't in either
61its local namespace or in the module-level namespace. This isn't much
62of a problem in practice (how often do you recursively define interior
63functions like this?), but this also made using the \keyword{lambda}
64statement clumsier, and this was a problem in practice. In code which
65uses \keyword{lambda} you can often find local variables being copied
66by passing them as the default values of arguments.
67
68\begin{verbatim}
69def find(self, name):
70 "Return list of any entries equal to 'name'"
71 L = filter(lambda x, name=name: x == name,
72 self.list_attribute)
73 return L
74\end{verbatim}
75
76The readability of Python code written in a strongly functional style
77suffers greatly as a result.
78
79The most significant change to Python 2.1 is that static scoping has
80been added to the language to fix this problem. As a first effect,
81the \code{name=name} default argument is now unnecessary in the above
82example. Put simply, when a given variable name is not assigned a
83value within a function (by an assignment, or the \keyword{def},
84\keyword{class}, or \keyword{import} statements), references to the
85variable will be looked up in the local namespace of the enclosing
86scope. A more detailed explanation of the rules, and a dissection of
87the implementation, can be found in the PEP.
88
89This change may cause some compatibility problems for code where the
90same variable name is used both at the module level and as a local
91variable within a function that contains further function definitions.
92This seems rather unlikely though, since such code would have been
93pretty confusing to read in the first place.
94
Andrew M. Kuchling15ad28c2001-02-14 02:44:18 +000095One side effect of the change is that the \code{from \var{module}
96import *} and \keyword{exec} statements have been made illegal inside
97a function scope under certain conditions. The Python reference
98manual has said all along that \code{from \var{module} import *} is
99only legal at the top level of a module, but the CPython interpreter
100has never enforced this before. As part of the implementation of
101nested scopes, the compiler which turns Python source into bytecodes
102has to generate different code to access variables in a containing
103scope. \code{from \var{module} import *} and \keyword{exec} make it
104impossible for the compiler to figure this out, because they add names
105to the local namespace that are unknowable at compile time.
106Therefore, if a function contains function definitions or
107\keyword{lambda} expressions with free variables, the compiler will
108flag this by raising a \exception{SyntaxError} exception.
109
110To make the preceding explanation a bit clearer, here's an example:
111
112\begin{verbatim}
113x = 1
114def f():
115 # The next line is a syntax error
116 exec 'x=2'
117 def g():
118 return x
119\end{verbatim}
120
121Line 4 containing the \keyword{exec} statement is a syntax error,
122since \keyword{exec} would define a new local variable named \samp{x}
123whose value should be accessed by \function{g()}.
124
125This shouldn't be much of a limitation, since \keyword{exec} is rarely
126used in most Python code (and when it is used, it's often a sign of a
127poor design anyway).
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000128
129\begin{seealso}
130
131\seepep{227}{Statically Nested Scopes}{Written and implemented by
132Jeremy Hylton.}
133
134\end{seealso}
135
136
137%======================================================================
Andrew M. Kuchling74d18ed2001-02-28 22:22:40 +0000138\section{PEP 236: \module{__future__} Directives}
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000139
Andrew M. Kuchling74d18ed2001-02-28 22:22:40 +0000140XXX
Andrew M. Kuchlingf228fd12001-01-22 17:52:19 +0000141
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000142%======================================================================
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000143\section{PEP 207: Rich Comparisons}
144
Andrew M. Kuchlingb216ab62001-01-22 16:15:44 +0000145In earlier versions, Python's support for implementing comparisons on
146user-defined classes and extension types was quite simple. Classes
147could implement a \method{__cmp__} method that was given two instances
148of a class, and could only return 0 if they were equal or +1 or -1 if
149they weren't; the method couldn't raise an exception or return
150anything other than a Boolean value. Users of Numeric Python often
151found this model too weak and restrictive, because in the
152number-crunching programs that numeric Python is used for, it would be
153more useful to be able to perform elementwise comparisons of two
154matrices, returning a matrix containing the results of a given
155comparison for each element. If the two matrices are of different
156sizes, then the compare has to be able to raise an exception to signal
157the error.
158
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000159In Python 2.1, rich comparisons were added in order to support this
160need. Python classes can now individually overload each of the
161\code{<}, \code{<=}, \code{>}, \code{>=}, \code{==}, and \code{!=}
162operations. The new magic method names are:
Andrew M. Kuchlingb216ab62001-01-22 16:15:44 +0000163
164\begin{tableii}{c|l}{code}{Operation}{Method name}
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000165 \lineii{<}{\method{__lt__}} \lineii{<=}{\method{__le__}}
166 \lineii{>}{\method{__gt__}} \lineii{>=}{\method{__ge__}}
167 \lineii{==}{\method{__eq__}} \lineii{!=}{\method{__ne__}}
168 \end{tableii}
Andrew M. Kuchlingb216ab62001-01-22 16:15:44 +0000169
170(The magic methods are named after the corresponding Fortran operators
171\code{.LT.}. \code{.LE.}, \&c. Numeric programmers are almost
172certainly quite familar with these names and will find them easy to
173remember.)
174
175Each of these magic methods is of the form \code{\var{method}(self,
176other)}, where \code{self} will be the object on the left-hand side of
177the operator, while \code{other} will be the object on the right-hand
178side. For example, the expression \code{A < B} will cause
179\code{A.__lt__(B)} to be called.
180
181Each of these magic methods can return anything at all: a Boolean, a
182matrix, a list, or any other Python object. Alternatively they can
183raise an exception if the comparison is impossible, inconsistent, or
184otherwise meaningless.
185
186The built-in \function{cmp(A,B)} function can use the rich comparison
187machinery, and now accepts an optional argument specifying which
188comparison operation to use; this is given as one of the strings
189\code{"<"}, \code{"<="}, \code{">"}, \code{">="}, \code{"=="}, or
190\code{"!="}. If called without the optional third argument,
191\function{cmp()} will only return -1, 0, or +1 as in previous versions
192of Python; otherwise it will call the appropriate method and can
193return any Python object.
194
195There are also corresponding changes of interest to C programmers;
196there's a new slot \code{tp_richcmp} in type objects and an API for
197performing a given rich comparison. I won't cover the C API here, but
Andrew M. Kuchlingbf140142001-02-28 22:10:07 +0000198will refer you to PEP 207, or to 2.1's C API documentation, for the
199full list of related functions.
Andrew M. Kuchlingb216ab62001-01-22 16:15:44 +0000200
201\begin{seealso}
202
203\seepep{207}{Rich Comparisions}{Written by Guido van Rossum, heavily
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000204based on earlier work by David Ascher, and implemented by Guido van
205Rossum.}
Andrew M. Kuchlingb216ab62001-01-22 16:15:44 +0000206
207\end{seealso}
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000208
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000209%======================================================================
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000210\section{PEP 230: Warning Framework}
211
212Over its 10 years of existence, Python has accumulated a certain
213number of obsolete modules and features along the way. It's difficult
214to know when a feature is safe to remove, since there's no way of
Andrew M. Kuchlingf33c1182001-01-23 02:48:26 +0000215knowing how much code uses it --- perhaps no programs depend on the
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000216feature, or perhaps many do. To enable removing old features in a
217more structured way, a warning framework was added. When the Python
218developers want to get rid of a feature, it will first trigger a
219warning in the next version of Python. The following Python version
220can then drop the feature, and users will have had a full release
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000221cycle to remove uses of the old feature.
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000222
223Python 2.1 adds the warning framework to be used in this scheme. It
224adds a \module{warnings} module that provide functions to issue
225warnings, and to filter out warnings that you don't want to be
226displayed. Third-party modules can also use this framework to
227deprecate old features that they no longer wish to support.
228
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000229For example, in Python 2.1 the \module{regex} module is deprecated, so
230importing it causes a warning to be printed:
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000231
232\begin{verbatim}
233>>> import regex
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000234__main__:1: DeprecationWarning: the regex module
235 is deprecated; please use the re module
236>>>
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000237\end{verbatim}
238
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000239Warnings can be issued by calling the \function{warnings.warn}
240function:
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000241
242\begin{verbatim}
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000243warnings.warn("feature X no longer supported")
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000244\end{verbatim}
245
246The first parameter is the warning message; an additional optional
247parameters can be used to specify a particular warning category.
248
249Filters can be added to disable certain warnings; a regular expression
250pattern can be applied to the message or to the module name in order
251to suppress a warning. For example, you may have a program that uses
252the \module{regex} module and not want to spare the time to convert it
Andrew M. Kuchlingb216ab62001-01-22 16:15:44 +0000253to use the \module{re} module right now. The warning can be
254suppressed by calling
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000255
256\begin{verbatim}
Andrew M. Kuchlingb216ab62001-01-22 16:15:44 +0000257import warnings
258warnings.filterwarnings(action = 'ignore',
259 message='.*regex module is deprecated',
260 category=DeprecationWarning,
261 module = '__main__')
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000262\end{verbatim}
263
Andrew M. Kuchlingb216ab62001-01-22 16:15:44 +0000264This adds a filter that will apply only to warnings of the class
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000265\class{DeprecationWarning} triggered in the \module{__main__} module,
266and applies a regular expression to only match the message about the
267\module{regex} module being deprecated, and will cause such warnings
268to be ignored. Warnings can also be printed only once, printed every
269time the offending code is executed, or turned into exceptions that
270will cause the program to stop (unless the exceptions are caught in
271the usual way, of course).
Andrew M. Kuchlingb216ab62001-01-22 16:15:44 +0000272
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000273Functions were also added to Python's C API for issuing warnings;
Andrew M. Kuchlingb216ab62001-01-22 16:15:44 +0000274refer to PEP 230 or to Python's API documentation for the details.
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000275
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000276\begin{seealso}
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000277
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000278\seepep{5}{Guidelines for Language Evolution}{Written
279by Paul Prescod, to specify procedures to be followed when removing
280old features from Python. The policy described in this PEP hasn't
281been officially adopted, but the eventual policy probably won't be too
282different from Prescod's proposal.}
283
284\seepep{230}{Warning Framework}{Written and implemented by Guido van
285Rossum.}
286
Andrew M. Kuchlingb216ab62001-01-22 16:15:44 +0000287\end{seealso}
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000288
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000289%======================================================================
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000290\section{PEP 229: New Build System}
291
292When compiling Python, the user had to go in and edit the
293\file{Modules/Setup} file in order to enable various additional
294modules; the default set is relatively small and limited to modules
295that compile on most Unix platforms. This means that on Unix
296platforms with many more features, most notably Linux, Python
297installations often don't contain all useful modules they could.
298
299Python 2.0 added the Distutils, a set of modules for distributing and
300installing extensions. In Python 2.1, the Distutils are used to
301compile much of the standard library of extension modules,
Andrew M. Kuchlingf33c1182001-01-23 02:48:26 +0000302autodetecting which ones are supported on the current machine. It's
303hoped that this will make Python installations easier and more
304featureful.
305
306Instead of having to edit the \file{Modules/Setup} file in order to
307enable modules, a \file{setup.py} script in the top directory of the
308Python source distribution is run at build time, and attempts to
309discover which modules can be enabled by examining the modules and
Andrew M. Kuchling8bad9932001-02-28 22:39:15 +0000310header files on the system. If a module is configured in
311\file{Modules/Setup}, the \file{setup.py} script won't attempt to
312compile that module and will defer to the \file{Modules/Setup} file's
313contents. This provides a way to specific any strange command-line
314flags or libraries that are required for a specific platform.
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000315
Andrew M. Kuchling4308d3c2001-01-29 17:36:53 +0000316In another far-reaching change to the build mechanism, Neil
317Schemenauer restructured things so Python now uses a single makefile
318that isn't recursive, instead of makefiles in the top directory and in
Andrew M. Kuchling8bad9932001-02-28 22:39:15 +0000319each of the \file{Python/}, \file{Parser/}, \file{Objects/}, and
320\file{Modules/} subdirectories. This makes building Python faster
321and also makes hacking the Makefiles clearer and simpler.
Andrew M. Kuchling4308d3c2001-01-29 17:36:53 +0000322
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000323\begin{seealso}
324
325\seepep{229}{Using Distutils to Build Python}{Written
326and implemented by A.M. Kuchling.}
327
Andrew M. Kuchlingb216ab62001-01-22 16:15:44 +0000328\end{seealso}
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000329
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000330%======================================================================
Andrew M. Kuchling15ad28c2001-02-14 02:44:18 +0000331\section{PEP 205: Weak References}
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000332
Andrew M. Kuchling15ad28c2001-02-14 02:44:18 +0000333Weak references, available through the \module{weakref} module, are a
334minor but useful new data type in the Python programmer's toolbox.
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000335
Andrew M. Kuchling15ad28c2001-02-14 02:44:18 +0000336Storing a reference to an object (say, in a dictionary or a list) has
337the side effect of keeping that object alive forever. There are a few
338specific cases where this behaviour is undesirable, object caches
339being the most common one, and another being circular references in
340data structures such as trees.
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000341
Andrew M. Kuchling15ad28c2001-02-14 02:44:18 +0000342For example, consider a memoizing function that caches the results of
343another function \function{f(\var{x})} by storing the function's
344argument and its result in a dictionary:
345
346\begin{verbatim}
347_cache = {}
348def memoize(x):
349 if _cache.has_key(x):
350 return _cache[x]
351
352 retval = f(x)
353
354 # Cache the returned object
355 _cache[x] = retval
356
357 return retval
358\end{verbatim}
359
360This version works for simple things such as integers, but it has a
361side effect; the \code{_cache} dictionary holds a reference to the
362return values, so they'll never be deallocated until the Python
363process exits and cleans up This isn't very noticeable for integers,
364but if \function{f()} returns an object, or a data structure that
365takes up a lot of memory, this can be a problem.
366
367Weak references provide a way to implement a cache that won't keep
368objects alive beyond their time. If an object is only accessible
369through weak references, the object will be deallocated and the weak
370references will now indicate that the object it referred to no longer
371exists. A weak reference to an object \var{obj} is created by calling
372\code{wr = weakref.ref(\var{obj})}. The object being referred to is
373returned by calling the weak reference as if it were a function:
374\code{wr()}. It will return the referenced object, or \code{None} if
375the object no longer exists.
376
377This makes it possible to write a \function{memoize()} function whose
378cache doesn't keep objects alive, by storing weak references in the
379cache.
380
381\begin{verbatim}
382_cache = {}
383def memoize(x):
384 if _cache.has_key(x):
385 obj = _cache[x]()
386 # If weak reference object still exists,
387 # return it
388 if obj is not None: return obj
389
390 retval = f(x)
391
392 # Cache a weak reference
393 _cache[x] = weakref.ref(retval)
394
395 return retval
396\end{verbatim}
397
398The \module{weakref} module also allows creating proxy objects which
399behave like weak references --- an object referenced only by proxy
400objects is deallocated -- but instead of requiring an explicit call to
401retrieve the object, the proxy transparently forwards all operations
402to the object as long as the object still exists. If the object is
403deallocated, attempting to use a proxy will cause a
404\exception{weakref.ReferenceError} exception to be raised.
405
406\begin{verbatim}
407proxy = weakref.proxy(obj)
408proxy.attr # Equivalent to obj.attr
409proxy.meth() # Equivalent to obj.meth()
410del obj
411proxy.attr # raises weakref.ReferenceError
412\end{verbatim}
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000413
414\begin{seealso}
415
416\seepep{205}{Weak References}{Written and implemented by
417Fred~L. Drake,~Jr.}
418
419\end{seealso}
420
421%======================================================================
Andrew M. Kuchling74d18ed2001-02-28 22:22:40 +0000422\section{PEP 235: Case-Insensitive Platforms and \keyword{import}}
423
Andrew M. Kuchling8bad9932001-02-28 22:39:15 +0000424Some operating systems have filesystems that are case-insensitive,
425MacOS and Windows being the primary examples; on these systems, it's
426impossible to distinguish the filenames \samp{FILE.PY} and
427\samp{file.py}, even though they do store the file's name
428in its original case (they're case-preserving, too).
429
430In Python 2.1, the \keyword{import} statement will work to simulate
431case-sensitivity on case-insensitive platforms. Python will now
432search for the first case-sensitive match by default, raising an
433\exception{ImportError} if no such file is found, so \code{import file}
434will not import a module named \samp{FILE.PY}. Case-insensitive
435matching can be requested by setting the PYTHONCASEOK environment
436variable before starting the Python interpreter.
Andrew M. Kuchling74d18ed2001-02-28 22:22:40 +0000437
438%======================================================================
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000439\section{PEP 217: Interactive Display Hook}
440
441When using the Python interpreter interactively, the output of
442commands is displayed using the built-in \function{repr()} function.
443In Python 2.1, the variable \module{sys.displayhook} can be set to a
444callable object which will be called instead of \function{repr()}.
445For example, you can set it to a special pretty-printing function:
446
447\begin{verbatim}
Andrew M. Kuchlingb216ab62001-01-22 16:15:44 +0000448>>> # Create a recursive data structure
449... L = [1,2,3]
450>>> L.append(L)
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000451>>> L # Show Python's default output
Andrew M. Kuchlingb216ab62001-01-22 16:15:44 +0000452[1, 2, 3, [...]]
453>>> # Use pprint.pprint() as the display function
454... import sys, pprint
455>>> sys.displayhook = pprint.pprint
456>>> L
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000457[1, 2, 3, <Recursion on list with id=135143996>]
458>>>
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000459\end{verbatim}
460
Andrew M. Kuchlingb216ab62001-01-22 16:15:44 +0000461\begin{seealso}
462
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000463\seepep{217}{Display Hook for Interactive Use}{Written and implemented
464by Moshe Zadka.}
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000465
Andrew M. Kuchlingb216ab62001-01-22 16:15:44 +0000466\end{seealso}
467
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000468%======================================================================
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000469\section{PEP 208: New Coercion Model}
470
471How numeric coercion is done at the C level was significantly
472modified. This will only affect the authors of C extensions to
473Python, allowing them more flexibility in writing extension types that
474support numeric operations.
475
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000476Extension types can now set the type flag \code{Py_TPFLAGS_CHECKTYPES}
477in their \code{PyTypeObject} structure to indicate that they support
478the new coercion model. In such extension types, the numeric slot
479functions can no longer assume that they'll be passed two arguments of
480the same type; instead they may be passed two arguments of differing
481types, and can then perform their own internal coercion. If the slot
482function is passed a type it can't handle, it can indicate the failure
483by returning a reference to the \code{Py_NotImplemented} singleton
484value. The numeric functions of the other type will then be tried,
485and perhaps they can handle the operation; if the other type also
486returns \code{Py_NotImplemented}, then a \exception{TypeError} will be
487raised. Numeric methods written in Python can also return
488\code{Py_NotImplemented}, causing the interpreter to act as if the
489method did not exist (perhaps raising a \exception{TypeError}, perhaps
490trying another object's numeric methods).
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000491
Andrew M. Kuchlingb216ab62001-01-22 16:15:44 +0000492\begin{seealso}
493
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000494\seepep{208}{Reworking the Coercion Model}{Written and implemented by
495Neil Schemenauer, heavily based upon earlier work by Marc-Andr\'e
496Lemburg. Read this to understand the fine points of how numeric
497operations will now be processed at the C level.}
498
Andrew M. Kuchlingb216ab62001-01-22 16:15:44 +0000499\end{seealso}
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000500
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000501%======================================================================
Andrew M. Kuchling81b6ae72001-02-11 16:55:39 +0000502\section{New and Improved Modules}
503
504\begin{itemize}
505
Andrew M. Kuchling74d18ed2001-02-28 22:22:40 +0000506\item Ka-Ping Yee contributed two new modules: \module{inspect.py}, a module for
507getting information about live Python code, and \module{pydoc.py}, a
508module for interactively converting docstrings to HTML or text.
509As a bonus, \file{Tools/scripts/pydoc}, which is now automatically
510installed, uses \module{pydoc.py} to display documentation given a Python module, package, or class name. For example,
511\samp{pydoc xml.dom} displays the following:
512
513\begin{verbatim}
514Python Library Documentation: package xml.dom in xml
515
516NAME
517 xml.dom - W3C Document Object Model implementation for Python.
518
519FILE
520 /usr/local/lib/python2.1/xml/dom/__init__.pyc
521
522DESCRIPTION
523 The Python mapping of the Document Object Model is documented in the
524 Python Library Reference in the section on the xml.dom package.
525
526 This package contains the following modules:
527 ...
528\end{verbatim}
529
530\file{pydoc} quickly becomes addictive; try it out!
531
Andrew M. Kuchling15ad28c2001-02-14 02:44:18 +0000532\item The \module{doctest} module provides a testing framework based
533on running embedded examples in docstrings and comparing the results
534against the expected output. Contributed by Tim Peters.
535
536\item The \module{difflib} module contains a class,
537\class{SequenceMatcher}, which compares two sequences and computes the
538changes required to transform one sequence into the other. For
539example, this module can be used to write a tool similar to the Unix
540\program{diff} program, and in fact the sample program
541\file{Tools/scripts/ndiff.py} demonstrates how to write such a script.
542
Andrew M. Kuchling81b6ae72001-02-11 16:55:39 +0000543\item \module{curses.panel}, a wrapper for the panel library, part of
544ncurses and of SYSV curses, was contributed by Thomas Gellekum. The
545panel library provides windows with the additional feature of depth.
546Windows can be moved higher or lower in the depth ordering, and the
547panel library figures out where panels overlap and which sections are
548visible.
549
550\item The PyXML package has gone through a few releases since Python
5512.0, and Python 2.1 includes an updated version of the \module{xml}
Andrew M. Kuchling74d18ed2001-02-28 22:22:40 +0000552package. Some of the noteworthy changes include support for Expat 1.2
553and later versions, the ability for Expat parsers to handle files in
554any encoding supported by Python, and various bugfixes for SAX, DOM,
555and the \module{minidom} module.
Andrew M. Kuchling81b6ae72001-02-11 16:55:39 +0000556
557\item Various functions in the \module{time} module, such as
558\function{asctime()} and \function{localtime()}, require a floating
559point argument containing the time in seconds since the epoch. The
560most common use of these functions is to work with the current time,
561so the floating point argument has been made optional; when a value
562isn't provided, the current time will be used. For example, log file
563entries usually need a string containing the current time; in Python
5642.1, \code{time.asctime()} can be used, instead of the lengthier
565\code{time.asctime(time.localtime(time.time()))} that was previously
566required.
567
568This change was proposed and implemented by Thomas Wouters.
569
570\item The \module{ftplib} module now defaults to retrieving files in
571passive mode, because passive mode is more likely to work from behind
572a firewall. This request came from the Debian bug tracking system,
573since other Debian packages use \module{ftplib} to retrieve files and
574then don't work from behind a firewall. It's deemed unlikely that
575this will cause problems for anyone, because Netscape defaults to
576passive mode and few people complain, but if passive mode is
577unsuitable for your application or network setup, call
578\method{set_pasv(0)} on FTP objects to disable passive mode.
579
580\item Support for raw socket access has been added to the
581\module{socket} module, contributed by Grant Edwards.
582
Andrew M. Kuchling15ad28c2001-02-14 02:44:18 +0000583\item A new implementation-dependent function, \function{sys._getframe(\optional{depth})},
584has been added to return a given frame object from the current call stack.
585\function{sys._getframe()} returns the frame at the top of the call stack;
586if the optional integer argument \var{depth} is supplied, the function returns the frame
587that is \var{depth} calls below the top of the stack. For example, \code{sys._getframe(1)}
588returns the caller's frame object.
589
590This function is only present in CPython, not in Jython or the .NET
591implementation. Use it for debugging, and resist the temptation to
592put it into production code.
593
594
Andrew M. Kuchling81b6ae72001-02-11 16:55:39 +0000595
596\end{itemize}
597
598%======================================================================
Andrew M. Kuchling74d18ed2001-02-28 22:22:40 +0000599\section{Other Changes and Fixes}
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000600
601There were relatively few smaller changes made in Python 2.1 due to
602the shorter release cycle. A search through the CVS change logs turns
603up 57 patches applied, and 86 bugs fixed; both figures are likely to
604be underestimates. Some of the more notable changes are:
605
606\begin{itemize}
607
Andrew M. Kuchlingbf140142001-02-28 22:10:07 +0000608
609\item A specialized object allocator is now optionally available, that
610should be faster than the system \function{malloc()} and have less
611memory overhead. The allocator uses C's \function{malloc()} function
612to get large pools of memory, and then fulfills smaller memory
613requests from these pools. It can be enabled by providing the
Andrew M. Kuchling694e1812001-03-01 01:02:52 +0000614\longprogramopt{--with-pymalloc} option to the \program{configure} script; see
Andrew M. Kuchling74d18ed2001-02-28 22:22:40 +0000615\file{Objects/obmalloc.c} for the implementation details.
Andrew M. Kuchlingbf140142001-02-28 22:10:07 +0000616Contributed by Vladimir Marangozov.
617
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000618\item The speed of line-oriented file I/O has been improved because
619people often complain about its lack of speed, and because it's often
620been used as a na\"ive benchmark. The \method{readline()} method of
621file objects has therefore been rewritten to be much faster. The
622exact amount of the speedup will vary from platform to platform
623depending on how slow the C library's \function{getc()} was, but is
624around 66\%, and potentially much faster on some particular operating
Andrew M. Kuchlingf228fd12001-01-22 17:52:19 +0000625systems. Tim Peters did much of the benchmarking and coding for this
626change, motivated by a discussion in comp.lang.python.
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000627
628A new module and method for file objects was also added, contributed
629by Jeff Epler. The new method, \method{xreadlines()}, is similar to
630the existing \function{xrange()} built-in. \function{xreadlines()}
631returns an opaque sequence object that only supports being iterated
Andrew M. Kuchlingf228fd12001-01-22 17:52:19 +0000632over, reading a line on every iteration but not reading the entire
Andrew M. Kuchlingf33c1182001-01-23 02:48:26 +0000633file into memory as the existing \method{readlines()} method does.
634You'd use it like this:
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000635
636\begin{verbatim}
637for line in sys.stdin.xreadlines():
638 # ... do something for each line ...
639 ...
640\end{verbatim}
641
Andrew M. Kuchlingf228fd12001-01-22 17:52:19 +0000642For a fuller discussion of the line I/O changes, see the python-dev
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000643summary for January 1-15, 2001.
Andrew M. Kuchling91834c62001-01-22 19:51:13 +0000644
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000645\item A new method, \method{popitem()}, was added to dictionaries to
646enable destructively iterating through the contents of a dictionary;
647this can be faster for large dictionaries because .
648\code{D.popitem()} removes a random \code{(\var{key}, \var{value})}
649pair from the dictionary and returns it as a 2-tuple. This was
650implemented mostly by Tim Peters and Guido van Rossum, after a
651suggestion and preliminary patch by Moshe Zadka.
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000652
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000653\item Modules can now control which names are imported when \code{from
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000654\var{module} import *} is used, by defining an \code{__all__}
655attribute containing a list of names that will be imported. One
656common complaint is that if the module imports other modules such as
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000657\module{sys} or \module{string}, \code{from \var{module} import *}
658will add them to the importing module's namespace. To fix this,
659simply list the public names in \code{__all__}:
660
661\begin{verbatim}
662# List public names
663__all__ = ['Database', 'open']
664\end{verbatim}
665
Andrew M. Kuchlingb216ab62001-01-22 16:15:44 +0000666A stricter version of this patch was first suggested and implemented
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000667by Ben Wolfson, but after some python-dev discussion, a weaker final
668version was checked in.
Andrew M. Kuchlingb216ab62001-01-22 16:15:44 +0000669
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000670\item Applying \function{repr()} to strings previously used octal
671escapes for non-printable characters; for example, a newline was
672\code{'\e 012'}. This was a vestigial trace of Python's C ancestry, but
673today octal is of very little practical use. Ka-Ping Yee suggested
674using hex escapes instead of octal ones, and using the \code{\e n},
675\code{\e t}, \code{\e r} escapes for the appropriate characters, and
676implemented this new formatting.
Andrew M. Kuchling4308d3c2001-01-29 17:36:53 +0000677
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000678\item Syntax errors detected at compile-time can now raise exceptions
679containing the filename and line number of the error, a pleasant side
680effect of the compiler reorganization done by Jeremy Hylton.
681
Andrew M. Kuchling15ad28c2001-02-14 02:44:18 +0000682\item C extensions which import other modules have been changed to use
683\function{PyImport_ImportModule()}, which means that they will use any
684import hooks that have been installed. This is also encouraged for
685third-party extensions that need to import some other module from C
686code.
687
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000688\item The size of the Unicode character database was shrunk by another
689340K thanks to Fredrik Lundh.
Andrew M. Kuchling91834c62001-01-22 19:51:13 +0000690
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000691\end{itemize}
692
Andrew M. Kuchling74d18ed2001-02-28 22:22:40 +0000693And there's the usual list of minor bugfixes, minor memory leaks,
694docstring edits, and other tweaks, too lengthy to be worth itemizing;
695see the CVS logs for the full details if you want them.
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000696
697
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000698%======================================================================
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000699\section{Acknowledgements}
700
Andrew M. Kuchling6a360bd2001-02-05 02:47:52 +0000701The author would like to thank the following people for offering
702suggestions on various drafts of this article: Graeme Cross, David
703Goodger, Jay Graves, Michael Hudson, Marc-Andr\'e Lemburg, Fredrik
704Lundh, Neil Schemenauer, Thomas Wouters.
Andrew M. Kuchling90cecee2001-01-22 04:02:09 +0000705
706\end{document}