source: trunk/essentials/dev-lang/python/Doc/whatsnew/whatsnew21.tex

Last change on this file was 3225, checked in by bird, 19 years ago

Python 2.5

File size: 36.4 KB
Line 
1\documentclass{howto}
2
3\usepackage{distutils}
4
5% $Id: whatsnew21.tex 50964 2006-07-30 03:03:43Z fred.drake $
6
7\title{What's New in Python 2.1}
8\release{1.01}
9\author{A.M. Kuchling}
10\authoraddress{
11 \strong{Python Software Foundation}\\
12 Email: \email{[email protected]}
13}
14\begin{document}
15\maketitle\tableofcontents
16
17\section{Introduction}
18
19This article explains the new features in Python 2.1. While there aren't as
20many changes in 2.1 as there were in Python 2.0, there are still some
21pleasant surprises in store. 2.1 is the first release to be steered
22through the use of Python Enhancement Proposals, or PEPs, so most of
23the sizable changes have accompanying PEPs that provide more complete
24documentation and a design rationale for the change. This article
25doesn't attempt to document the new features completely, but simply
26provides an overview of the new features for Python programmers.
27Refer to the Python 2.1 documentation, or to the specific PEP, for
28more details about any new feature that particularly interests you.
29
30One recent goal of the Python development team has been to accelerate
31the pace of new releases, with a new release coming every 6 to 9
32months. 2.1 is the first release to come out at this faster pace, with
33the first alpha appearing in January, 3 months after the final version
34of 2.0 was released.
35
36The final release of Python 2.1 was made on April 17, 2001.
37
38%======================================================================
39\section{PEP 227: Nested Scopes}
40
41The largest change in Python 2.1 is to Python's scoping rules. In
42Python 2.0, at any given time there are at most three namespaces used
43to look up variable names: local, module-level, and the built-in
44namespace. This often surprised people because it didn't match their
45intuitive expectations. For example, a nested recursive function
46definition doesn't work:
47
48\begin{verbatim}
49def f():
50 ...
51 def g(value):
52 ...
53 return g(value-1) + 1
54 ...
55\end{verbatim}
56
57The function \function{g()} will always raise a \exception{NameError}
58exception, because the binding of the name \samp{g} isn't in either
59its local namespace or in the module-level namespace. This isn't much
60of a problem in practice (how often do you recursively define interior
61functions like this?), but this also made using the \keyword{lambda}
62statement clumsier, and this was a problem in practice. In code which
63uses \keyword{lambda} you can often find local variables being copied
64by passing them as the default values of arguments.
65
66\begin{verbatim}
67def find(self, name):
68 "Return list of any entries equal to 'name'"
69 L = filter(lambda x, name=name: x == name,
70 self.list_attribute)
71 return L
72\end{verbatim}
73
74The readability of Python code written in a strongly functional style
75suffers greatly as a result.
76
77The most significant change to Python 2.1 is that static scoping has
78been added to the language to fix this problem. As a first effect,
79the \code{name=name} default argument is now unnecessary in the above
80example. Put simply, when a given variable name is not assigned a
81value within a function (by an assignment, or the \keyword{def},
82\keyword{class}, or \keyword{import} statements), references to the
83variable will be looked up in the local namespace of the enclosing
84scope. A more detailed explanation of the rules, and a dissection of
85the implementation, can be found in the PEP.
86
87This change may cause some compatibility problems for code where the
88same variable name is used both at the module level and as a local
89variable within a function that contains further function definitions.
90This seems rather unlikely though, since such code would have been
91pretty confusing to read in the first place.
92
93One side effect of the change is that the \code{from \var{module}
94import *} and \keyword{exec} statements have been made illegal inside
95a function scope under certain conditions. The Python reference
96manual has said all along that \code{from \var{module} import *} is
97only legal at the top level of a module, but the CPython interpreter
98has never enforced this before. As part of the implementation of
99nested scopes, the compiler which turns Python source into bytecodes
100has to generate different code to access variables in a containing
101scope. \code{from \var{module} import *} and \keyword{exec} make it
102impossible for the compiler to figure this out, because they add names
103to the local namespace that are unknowable at compile time.
104Therefore, if a function contains function definitions or
105\keyword{lambda} expressions with free variables, the compiler will
106flag this by raising a \exception{SyntaxError} exception.
107
108To make the preceding explanation a bit clearer, here's an example:
109
110\begin{verbatim}
111x = 1
112def f():
113 # The next line is a syntax error
114 exec 'x=2'
115 def g():
116 return x
117\end{verbatim}
118
119Line 4 containing the \keyword{exec} statement is a syntax error,
120since \keyword{exec} would define a new local variable named \samp{x}
121whose value should be accessed by \function{g()}.
122
123This shouldn't be much of a limitation, since \keyword{exec} is rarely
124used in most Python code (and when it is used, it's often a sign of a
125poor design anyway).
126
127Compatibility concerns have led to nested scopes being introduced
128gradually; in Python 2.1, they aren't enabled by default, but can be
129turned on within a module by using a future statement as described in
130PEP 236. (See the following section for further discussion of PEP
131236.) In Python 2.2, nested scopes will become the default and there
132will be no way to turn them off, but users will have had all of 2.1's
133lifetime to fix any breakage resulting from their introduction.
134
135\begin{seealso}
136
137\seepep{227}{Statically Nested Scopes}{Written and implemented by
138Jeremy Hylton.}
139
140\end{seealso}
141
142
143%======================================================================
144\section{PEP 236: __future__ Directives}
145
146The reaction to nested scopes was widespread concern about the dangers
147of breaking code with the 2.1 release, and it was strong enough to
148make the Pythoneers take a more conservative approach. This approach
149consists of introducing a convention for enabling optional
150functionality in release N that will become compulsory in release N+1.
151
152The syntax uses a \code{from...import} statement using the reserved
153module name \module{__future__}. Nested scopes can be enabled by the
154following statement:
155
156\begin{verbatim}
157from __future__ import nested_scopes
158\end{verbatim}
159
160While it looks like a normal \keyword{import} statement, it's not;
161there are strict rules on where such a future statement can be put.
162They can only be at the top of a module, and must precede any Python
163code or regular \keyword{import} statements. This is because such
164statements can affect how the Python bytecode compiler parses code and
165generates bytecode, so they must precede any statement that will
166result in bytecodes being produced.
167
168\begin{seealso}
169
170\seepep{236}{Back to the \module{__future__}}{Written by Tim Peters,
171and primarily implemented by Jeremy Hylton.}
172
173\end{seealso}
174
175%======================================================================
176\section{PEP 207: Rich Comparisons}
177
178In earlier versions, Python's support for implementing comparisons on
179user-defined classes and extension types was quite simple. Classes
180could implement a \method{__cmp__} method that was given two instances
181of a class, and could only return 0 if they were equal or +1 or -1 if
182they weren't; the method couldn't raise an exception or return
183anything other than a Boolean value. Users of Numeric Python often
184found this model too weak and restrictive, because in the
185number-crunching programs that numeric Python is used for, it would be
186more useful to be able to perform elementwise comparisons of two
187matrices, returning a matrix containing the results of a given
188comparison for each element. If the two matrices are of different
189sizes, then the compare has to be able to raise an exception to signal
190the error.
191
192In Python 2.1, rich comparisons were added in order to support this
193need. Python classes can now individually overload each of the
194\code{<}, \code{<=}, \code{>}, \code{>=}, \code{==}, and \code{!=}
195operations. The new magic method names are:
196
197\begin{tableii}{c|l}{code}{Operation}{Method name}
198 \lineii{<}{\method{__lt__}} \lineii{<=}{\method{__le__}}
199 \lineii{>}{\method{__gt__}} \lineii{>=}{\method{__ge__}}
200 \lineii{==}{\method{__eq__}} \lineii{!=}{\method{__ne__}}
201 \end{tableii}
202
203(The magic methods are named after the corresponding Fortran operators
204\code{.LT.}. \code{.LE.}, \&c. Numeric programmers are almost
205certainly quite familiar with these names and will find them easy to
206remember.)
207
208Each of these magic methods is of the form \code{\var{method}(self,
209other)}, where \code{self} will be the object on the left-hand side of
210the operator, while \code{other} will be the object on the right-hand
211side. For example, the expression \code{A < B} will cause
212\code{A.__lt__(B)} to be called.
213
214Each of these magic methods can return anything at all: a Boolean, a
215matrix, a list, or any other Python object. Alternatively they can
216raise an exception if the comparison is impossible, inconsistent, or
217otherwise meaningless.
218
219The built-in \function{cmp(A,B)} function can use the rich comparison