Andrew M. Kuchling | a8defaa | 2001-05-05 16:37:29 +0000 | [diff] [blame] | 1 | \documentclass{howto} |
| 2 | |
| 3 | % $Id$ |
| 4 | |
| 5 | \title{What's New in Python 2.2} |
Andrew M. Kuchling | 2cd712b | 2001-07-16 13:39:08 +0000 | [diff] [blame] | 6 | \release{0.02} |
Andrew M. Kuchling | a8defaa | 2001-05-05 16:37:29 +0000 | [diff] [blame] | 7 | \author{A.M. Kuchling} |
Andrew M. Kuchling | 7bf8277 | 2001-07-11 18:54:26 +0000 | [diff] [blame] | 8 | \authoraddress{\email{akuchlin@mems-exchange.org}} |
Andrew M. Kuchling | a8defaa | 2001-05-05 16:37:29 +0000 | [diff] [blame] | 9 | \begin{document} |
| 10 | \maketitle\tableofcontents |
| 11 | |
| 12 | \section{Introduction} |
| 13 | |
| 14 | {\large This document is a draft, and is subject to change until the |
| 15 | final version of Python 2.2 is released. Currently it's not up to |
| 16 | date at all. Please send any comments, bug reports, or questions, no |
Andrew M. Kuchling | 7bf8277 | 2001-07-11 18:54:26 +0000 | [diff] [blame] | 17 | matter how minor, to \email{akuchlin@mems-exchange.org}. } |
Andrew M. Kuchling | a8defaa | 2001-05-05 16:37:29 +0000 | [diff] [blame] | 18 | |
Andrew M. Kuchling | 7bf8277 | 2001-07-11 18:54:26 +0000 | [diff] [blame] | 19 | This article explains the new features in Python 2.2. Python 2.2 |
| 20 | includes some significant changes that go far toward cleaning up the |
| 21 | language's darkest corners, and some exciting new features. |
Andrew M. Kuchling | a8defaa | 2001-05-05 16:37:29 +0000 | [diff] [blame] | 22 | |
| 23 | This article doesn't attempt to provide a complete specification for |
| 24 | the new features, but instead provides a convenient overview of the |
| 25 | new features. For full details, you should refer to 2.2 documentation |
Fred Drake | 0d00254 | 2001-07-17 13:55:33 +0000 | [diff] [blame] | 26 | such as the |
| 27 | \citetitle[http://python.sourceforge.net/devel-docs/lib/lib.html]{Python |
| 28 | Library Reference} and the |
| 29 | \citetitle[http://python.sourceforge.net/devel-docs/ref/ref.html]{Python |
| 30 | Reference Manual}, or to the PEP for a particular new feature. |
| 31 | % These \citetitle marks should get the python.org URLs for the final |
| 32 | % release, just as soon as the docs are published there. |
Andrew M. Kuchling | a8defaa | 2001-05-05 16:37:29 +0000 | [diff] [blame] | 33 | |
| 34 | The final release of Python 2.2 is planned for October 2001. |
| 35 | |
| 36 | %====================================================================== |
Andrew M. Kuchling | 4dbf871 | 2001-07-16 02:17:14 +0000 | [diff] [blame] | 37 | % It looks like this set of changes will likely get into 2.2, |
| 38 | % so I need to read and digest the relevant PEPs. |
Andrew M. Kuchling | 7bf8277 | 2001-07-11 18:54:26 +0000 | [diff] [blame] | 39 | %\section{PEP 252: Type and Class Changes} |
Andrew M. Kuchling | a8defaa | 2001-05-05 16:37:29 +0000 | [diff] [blame] | 40 | |
Andrew M. Kuchling | 7bf8277 | 2001-07-11 18:54:26 +0000 | [diff] [blame] | 41 | %XXX |
Andrew M. Kuchling | a8defaa | 2001-05-05 16:37:29 +0000 | [diff] [blame] | 42 | |
Andrew M. Kuchling | 7bf8277 | 2001-07-11 18:54:26 +0000 | [diff] [blame] | 43 | %\begin{seealso} |
Andrew M. Kuchling | a8defaa | 2001-05-05 16:37:29 +0000 | [diff] [blame] | 44 | |
Andrew M. Kuchling | 7bf8277 | 2001-07-11 18:54:26 +0000 | [diff] [blame] | 45 | %\seepep{252}{Making Types Look More Like Classes}{Written and implemented |
| 46 | %by GvR.} |
Andrew M. Kuchling | a8defaa | 2001-05-05 16:37:29 +0000 | [diff] [blame] | 47 | |
Andrew M. Kuchling | 7bf8277 | 2001-07-11 18:54:26 +0000 | [diff] [blame] | 48 | %\end{seealso} |
Andrew M. Kuchling | a8defaa | 2001-05-05 16:37:29 +0000 | [diff] [blame] | 49 | |
| 50 | %====================================================================== |
Andrew M. Kuchling | 4dbf871 | 2001-07-16 02:17:14 +0000 | [diff] [blame] | 51 | \section{PEP 234: Iterators} |
| 52 | |
| 53 | A significant addition to 2.2 is an iteration interface at both the C |
| 54 | and Python levels. Objects can define how they can be looped over by |
| 55 | callers. |
| 56 | |
| 57 | In Python versions up to 2.1, the usual way to make \code{for item in |
| 58 | obj} work is to define a \method{__getitem__()} method that looks |
| 59 | something like this: |
| 60 | |
| 61 | \begin{verbatim} |
| 62 | def __getitem__(self, index): |
| 63 | return <next item> |
| 64 | \end{verbatim} |
| 65 | |
| 66 | \method{__getitem__()} is more properly used to define an indexing |
| 67 | operation on an object so that you can write \code{obj[5]} to retrieve |
| 68 | the fifth element. It's a bit misleading when you're using this only |
| 69 | to support \keyword{for} loops. Consider some file-like object that |
| 70 | wants to be looped over; the \var{index} parameter is essentially |
| 71 | meaningless, as the class probably assumes that a series of |
| 72 | \method{__getitem__()} calls will be made, with \var{index} |
| 73 | incrementing by one each time. In other words, the presence of the |
| 74 | \method{__getitem__()} method doesn't mean that \code{file[5]} will |
| 75 | work, though it really should. |
| 76 | |
| 77 | In Python 2.2, iteration can be implemented separately, and |
| 78 | \method{__getitem__()} methods can be limited to classes that really |
| 79 | do support random access. The basic idea of iterators is quite |
| 80 | simple. A new built-in function, \function{iter(obj)}, returns an |
| 81 | iterator for the object \var{obj}. (It can also take two arguments: |
Fred Drake | 0d00254 | 2001-07-17 13:55:33 +0000 | [diff] [blame] | 82 | \code{iter(\var{C}, \var{sentinel})} will call the callable \var{C}, |
| 83 | until it returns \var{sentinel}, which will signal that the iterator |
| 84 | is done. This form probably won't be used very often.) |
Andrew M. Kuchling | 4dbf871 | 2001-07-16 02:17:14 +0000 | [diff] [blame] | 85 | |
| 86 | Python classes can define an \method{__iter__()} method, which should |
| 87 | create and return a new iterator for the object; if the object is its |
| 88 | own iterator, this method can just return \code{self}. In particular, |
| 89 | iterators will usually be their own iterators. Extension types |
| 90 | implemented in C can implement a \code{tp_iter} function in order to |
Andrew M. Kuchling | 4cf52a9 | 2001-07-17 12:48:48 +0000 | [diff] [blame] | 91 | return an iterator, and extension types that want to behave as |
| 92 | iterators can define a \code{tp_iternext} function. |
Andrew M. Kuchling | 4dbf871 | 2001-07-16 02:17:14 +0000 | [diff] [blame] | 93 | |
| 94 | So what do iterators do? They have one required method, |
| 95 | \method{next()}, which takes no arguments and returns the next value. |
| 96 | When there are no more values to be returned, calling \method{next()} |
| 97 | should raise the \exception{StopIteration} exception. |
| 98 | |
| 99 | \begin{verbatim} |
| 100 | >>> L = [1,2,3] |
| 101 | >>> i = iter(L) |
| 102 | >>> print i |
| 103 | <iterator object at 0x8116870> |
| 104 | >>> i.next() |
| 105 | 1 |
| 106 | >>> i.next() |
| 107 | 2 |
| 108 | >>> i.next() |
| 109 | 3 |
| 110 | >>> i.next() |
| 111 | Traceback (most recent call last): |
| 112 | File "<stdin>", line 1, in ? |
| 113 | StopIteration |
| 114 | >>> |
| 115 | \end{verbatim} |
| 116 | |
| 117 | In 2.2, Python's \keyword{for} statement no longer expects a sequence; |
| 118 | it expects something for which \function{iter()} will return something. |
| 119 | For backward compatibility, and convenience, an iterator is |
| 120 | automatically constructed for sequences that don't implement |
| 121 | \method{__iter__()} or a \code{tp_iter} slot, so \code{for i in |
| 122 | [1,2,3]} will still work. Wherever the Python interpreter loops over |
| 123 | a sequence, it's been changed to use the iterator protocol. This |
| 124 | means you can do things like this: |
| 125 | |
| 126 | \begin{verbatim} |
| 127 | >>> i = iter(L) |
| 128 | >>> a,b,c = i |
| 129 | >>> a,b,c |
| 130 | (1, 2, 3) |
| 131 | >>> |
| 132 | \end{verbatim} |
| 133 | |
| 134 | Iterator support has been added to some of Python's basic types. The |
| 135 | \keyword{in} operator now works on dictionaries, so \code{\var{key} in |
| 136 | dict} is now equivalent to \code{dict.has_key(\var{key})}. |
Fred Drake | 0d00254 | 2001-07-17 13:55:33 +0000 | [diff] [blame] | 137 | Calling \function{iter()} on a dictionary will return an iterator |
Andrew M. Kuchling | 6ea9f0b | 2001-07-17 14:50:31 +0000 | [diff] [blame^] | 138 | which loops over its keys: |
Andrew M. Kuchling | 4dbf871 | 2001-07-16 02:17:14 +0000 | [diff] [blame] | 139 | |
| 140 | \begin{verbatim} |
| 141 | >>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6, |
| 142 | ... 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12} |
| 143 | >>> for key in m: print key, m[key] |
| 144 | ... |
| 145 | Mar 3 |
| 146 | Feb 2 |
| 147 | Aug 8 |
| 148 | Sep 9 |
| 149 | May 5 |
| 150 | Jun 6 |
| 151 | Jul 7 |
| 152 | Jan 1 |
| 153 | Apr 4 |
| 154 | Nov 11 |
| 155 | Dec 12 |
| 156 | Oct 10 |
| 157 | >>> |
| 158 | \end{verbatim} |
| 159 | |
| 160 | That's just the default behaviour. If you want to iterate over keys, |
| 161 | values, or key/value pairs, you can explicitly call the |
| 162 | \method{iterkeys()}, \method{itervalues()}, or \method{iteritems()} |
| 163 | methods to get an appropriate iterator. |
| 164 | |
| 165 | Files also provide an iterator, which calls its \method{readline()} |
| 166 | method until there are no more lines in the file. This means you can |
| 167 | now read each line of a file using code like this: |
| 168 | |
| 169 | \begin{verbatim} |
| 170 | for line in file: |
| 171 | # do something for each line |
| 172 | \end{verbatim} |
| 173 | |
| 174 | Note that you can only go forward in an iterator; there's no way to |
| 175 | get the previous element, reset the iterator, or make a copy of it. |
Fred Drake | 0d00254 | 2001-07-17 13:55:33 +0000 | [diff] [blame] | 176 | An iterator object could provide such additional capabilities, but the |
| 177 | iterator protocol only requires a \method{next()} method. |
Andrew M. Kuchling | 4dbf871 | 2001-07-16 02:17:14 +0000 | [diff] [blame] | 178 | |
| 179 | \begin{seealso} |
| 180 | |
| 181 | \seepep{234}{Iterators}{Written by Ka-Ping Yee and GvR; implemented |
| 182 | by the Python Labs crew, mostly by GvR and Tim Peters.} |
| 183 | |
| 184 | \end{seealso} |
| 185 | |
| 186 | %====================================================================== |
| 187 | \section{PEP 255: Simple Generators} |
| 188 | |
| 189 | Generators are another new feature, one that interacts with the |
| 190 | introduction of iterators. |
| 191 | |
| 192 | You're doubtless familiar with how function calls work in Python or |
| 193 | C. When you call a function, it gets a private area where its local |
| 194 | variables are created. When the function reaches a \keyword{return} |
| 195 | statement, the local variables are destroyed and the resulting value |
| 196 | is returned to the caller. A later call to the same function will get |
| 197 | a fresh new set of local variables. But, what if the local variables |
| 198 | weren't destroyed on exiting a function? What if you could later |
| 199 | resume the function where it left off? This is what generators |
| 200 | provide; they can be thought of as resumable functions. |
| 201 | |
| 202 | Here's the simplest example of a generator function: |
| 203 | |
| 204 | \begin{verbatim} |
| 205 | def generate_ints(N): |
| 206 | for i in range(N): |
| 207 | yield i |
| 208 | \end{verbatim} |
| 209 | |
| 210 | A new keyword, \keyword{yield}, was introduced for generators. Any |
| 211 | function containing a \keyword{yield} statement is a generator |
| 212 | function; this is detected by Python's bytecode compiler which |
Andrew M. Kuchling | 4cf52a9 | 2001-07-17 12:48:48 +0000 | [diff] [blame] | 213 | compiles the function specially. Because a new keyword was |
| 214 | introduced, generators must be explicitly enabled in a module by |
| 215 | including a \code{from __future__ import generators} statement near |
| 216 | the top of the module's source code. In Python 2.3 this statement |
| 217 | will become unnecessary. |
| 218 | |
| 219 | When you call a generator function, it doesn't return a single value; |
| 220 | instead it returns a generator object that supports the iterator |
| 221 | interface. On executing the \keyword{yield} statement, the generator |
| 222 | outputs the value of \code{i}, similar to a \keyword{return} |
| 223 | statement. The big difference between \keyword{yield} and a |
| 224 | \keyword{return} statement is that, on reaching a \keyword{yield} the |
| 225 | generator's state of execution is suspended and local variables are |
| 226 | preserved. On the next call to the generator's \code{.next()} method, |
| 227 | the function will resume executing immediately after the |
| 228 | \keyword{yield} statement. (For complicated reasons, the |
| 229 | \keyword{yield} statement isn't allowed inside the \keyword{try} block |
| 230 | of a \code{try...finally} statement; read PEP 255 for a full |
| 231 | explanation of the interaction between \keyword{yield} and |
Andrew M. Kuchling | 4dbf871 | 2001-07-16 02:17:14 +0000 | [diff] [blame] | 232 | exceptions.) |
| 233 | |
| 234 | Here's a sample usage of the \function{generate_ints} generator: |
| 235 | |
| 236 | \begin{verbatim} |
| 237 | >>> gen = generate_ints(3) |
| 238 | >>> gen |
| 239 | <generator object at 0x8117f90> |
| 240 | >>> gen.next() |
| 241 | 0 |
| 242 | >>> gen.next() |
| 243 | 1 |
| 244 | >>> gen.next() |
| 245 | 2 |
| 246 | >>> gen.next() |
| 247 | Traceback (most recent call last): |
| 248 | File "<stdin>", line 1, in ? |
| 249 | File "<stdin>", line 2, in generate_ints |
| 250 | StopIteration |
| 251 | >>> |
| 252 | \end{verbatim} |
| 253 | |
| 254 | You could equally write \code{for i in generate_ints(5)}, or |
| 255 | \code{a,b,c = generate_ints(3)}. |
| 256 | |
| 257 | Inside a generator function, the \keyword{return} statement can only |
Andrew M. Kuchling | 4cf52a9 | 2001-07-17 12:48:48 +0000 | [diff] [blame] | 258 | be used without a value, and signals the end of the procession of |
| 259 | values; afterwards the generator cannot return any further values. |
| 260 | \keyword{return} with a value, such as \code{return 5}, is a syntax |
| 261 | error inside a generator function. The end of the generator's results |
| 262 | can also be indicated by raising \exception{StopIteration} manually, |
| 263 | or by just letting the flow of execution fall off the bottom of the |
| 264 | function. |
Andrew M. Kuchling | 4dbf871 | 2001-07-16 02:17:14 +0000 | [diff] [blame] | 265 | |
| 266 | You could achieve the effect of generators manually by writing your |
Andrew M. Kuchling | 4cf52a9 | 2001-07-17 12:48:48 +0000 | [diff] [blame] | 267 | own class and storing all the local variables of the generator as |
Andrew M. Kuchling | 4dbf871 | 2001-07-16 02:17:14 +0000 | [diff] [blame] | 268 | instance variables. For example, returning a list of integers could |
| 269 | be done by setting \code{self.count} to 0, and having the |
| 270 | \method{next()} method increment \code{self.count} and return it. |
| 271 | because it would be easy to write a Python class. However, for a |
| 272 | moderately complicated generator, writing a corresponding class would |
| 273 | be much messier. \file{Lib/test/test_generators.py} contains a number |
| 274 | of more interesting examples. The simplest one implements an in-order |
| 275 | traversal of a tree using generators recursively. |
| 276 | |
| 277 | \begin{verbatim} |
| 278 | # A recursive generator that generates Tree leaves in in-order. |
| 279 | def inorder(t): |
| 280 | if t: |
| 281 | for x in inorder(t.left): |
| 282 | yield x |
| 283 | yield t.label |
| 284 | for x in inorder(t.right): |
| 285 | yield x |
| 286 | \end{verbatim} |
| 287 | |
| 288 | Two other examples in \file{Lib/test/test_generators.py} produce |
| 289 | solutions for the N-Queens problem (placing $N$ queens on an $NxN$ |
| 290 | chess board so that no queen threatens another) and the Knight's Tour |
| 291 | (a route that takes a knight to every square of an $NxN$ chessboard |
| 292 | without visiting any square twice). |
| 293 | |
| 294 | The idea of generators comes from other programming languages, |
| 295 | especially Icon (\url{http://www.cs.arizona.edu/icon/}), where the |
| 296 | idea of generators is central to the language. In Icon, every |
| 297 | expression and function call behaves like a generator. One example |
| 298 | from ``An Overview of the Icon Programming Language'' at |
| 299 | \url{http://www.cs.arizona.edu/icon/docs/ipd266.htm} gives an idea of |
| 300 | what this looks like: |
| 301 | |
| 302 | \begin{verbatim} |
| 303 | sentence := "Store it in the neighboring harbor" |
| 304 | if (i := find("or", sentence)) > 5 then write(i) |
| 305 | \end{verbatim} |
| 306 | |
| 307 | The \function{find()} function returns the indexes at which the |
| 308 | substring ``or'' is found: 3, 23, 33. In the \keyword{if} statement, |
| 309 | \code{i} is first assigned a value of 3, but 3 is less than 5, so the |
| 310 | comparison fails, and Icon retries it with the second value of 23. 23 |
| 311 | is greater than 5, so the comparison now succeeds, and the code prints |
| 312 | the value 23 to the screen. |
| 313 | |
| 314 | Python doesn't go nearly as far as Icon in adopting generators as a |
| 315 | central concept. Generators are considered a new part of the core |
| 316 | Python language, but learning or using them isn't compulsory; if they |
| 317 | don't solve any problems that you have, feel free to ignore them. |
| 318 | This is different from Icon where the idea of generators is a basic |
| 319 | concept. One novel feature of Python's interface as compared to |
| 320 | Icon's is that a generator's state is represented as a concrete object |
| 321 | that can be passed around to other functions or stored in a data |
| 322 | structure. |
| 323 | |
| 324 | \begin{seealso} |
| 325 | |
Andrew M. Kuchling | 4cf52a9 | 2001-07-17 12:48:48 +0000 | [diff] [blame] | 326 | \seepep{255}{Simple Generators}{Written by Neil Schemenauer, Tim |
| 327 | Peters, Magnus Lie Hetland. Implemented mostly by Neil Schemenauer |
| 328 | and Tim Peters, with other fixes from the Python Labs crew.} |
Andrew M. Kuchling | 4dbf871 | 2001-07-16 02:17:14 +0000 | [diff] [blame] | 329 | |
| 330 | \end{seealso} |
| 331 | |
| 332 | %====================================================================== |
Andrew M. Kuchling | a43e703 | 2001-06-27 20:32:12 +0000 | [diff] [blame] | 333 | \section{Unicode Changes} |
| 334 | |
Andrew M. Kuchling | 2cd712b | 2001-07-16 13:39:08 +0000 | [diff] [blame] | 335 | Python's Unicode support has been enhanced a bit in 2.2. Unicode |
| 336 | strings are usually stored as UCS-2, as 16-bit unsigned integers. |
| 337 | Python 2.2 can also be compiled to use UCS-4, 32-bit unsigned integers |
Andrew M. Kuchling | ddeb135 | 2001-07-16 14:35:52 +0000 | [diff] [blame] | 338 | by supplying \longprogramopt{enable-unicode=ucs4} to the configure script. |
Andrew M. Kuchling | 2cd712b | 2001-07-16 13:39:08 +0000 | [diff] [blame] | 339 | |
| 340 | XXX explain surrogates? I have to figure out what the changes mean to users. |
| 341 | |
| 342 | Since their introduction, Unicode strings (XXX and regular strings in |
| 343 | 2.1?) have supported an \method{encode()} method to convert the |
| 344 | string to a selected encoding such as UTF-8 or Latin-1. A symmetric |
| 345 | \method{decode(\optional{\var{encoding}})} method has been added to |
| 346 | both 8-bit and Unicode strings in 2.2, which assumes that the string |
| 347 | is in the specified encoding and decodes it. This means that |
| 348 | \method{encode()} and \method{decode()} can be called on both types of |
| 349 | strings, and can be used for tasks not directly related to Unicode. |
| 350 | For example, codecs have been added for UUencoding, MIME's base-64 |
| 351 | encoding, and compression with the \module{zlib} module. |
| 352 | |
| 353 | \begin{verbatim} |
| 354 | >>> s = """Here is a lengthy piece of redundant, overly verbose, |
| 355 | ... and repetitive text. |
| 356 | ... """ |
| 357 | >>> data = s.encode('zlib') |
| 358 | >>> data |
| 359 | 'x\x9c\r\xc9\xc1\r\x80 \x10\x04\xc0?Ul...' |
| 360 | >>> data.decode('zlib') |
| 361 | 'Here is a lengthy piece of redundant, overly verbose,\nand repetitive text.\n' |
| 362 | >>> print s.encode('uu') |
| 363 | begin 666 <data> |
| 364 | M2&5R92!I<R!A(&QE;F=T:'D@<&EE8V4@;V8@<F5D=6YD86YT+"!O=F5R;'D@ |
| 365 | >=F5R8F]S92P*86YD(')E<&5T:71I=F4@=&5X="X* |
| 366 | |
| 367 | end |
| 368 | >>> "sheesh".encode('rot-13') |
| 369 | 'furrfu' |
| 370 | \end{verbatim} |
Andrew M. Kuchling | a43e703 | 2001-06-27 20:32:12 +0000 | [diff] [blame] | 371 | |
| 372 | References: http://mail.python.org/pipermail/i18n-sig/2001-June/001107.html |
| 373 | and following thread. |
| 374 | |
Andrew M. Kuchling | 4dbf871 | 2001-07-16 02:17:14 +0000 | [diff] [blame] | 375 | %====================================================================== |
| 376 | \section{PEP 227: Nested Scopes} |
| 377 | |
| 378 | In Python 2.1, statically nested scopes were added as an optional |
| 379 | feature, to be enabled by a \code{from __future__ import |
| 380 | nested_scopes} directive. In 2.2 nested scopes no longer need to be |
| 381 | specially enabled, but are always enabled. The rest of this section |
| 382 | is a copy of the description of nested scopes from my ``What's New in |
| 383 | Python 2.1'' document; if you read it when 2.1 came out, you can skip |
| 384 | the rest of this section. |
| 385 | |
| 386 | The largest change introduced in Python 2.1, and made complete in 2.2, |
| 387 | is to Python's scoping rules. In Python 2.0, at any given time there |
| 388 | are at most three namespaces used to look up variable names: local, |
| 389 | module-level, and the built-in namespace. This often surprised people |
| 390 | because it didn't match their intuitive expectations. For example, a |
| 391 | nested recursive function definition doesn't work: |
| 392 | |
| 393 | \begin{verbatim} |
| 394 | def f(): |
| 395 | ... |
| 396 | def g(value): |
| 397 | ... |
| 398 | return g(value-1) + 1 |
| 399 | ... |
| 400 | \end{verbatim} |
| 401 | |
| 402 | The function \function{g()} will always raise a \exception{NameError} |
| 403 | exception, because the binding of the name \samp{g} isn't in either |
| 404 | its local namespace or in the module-level namespace. This isn't much |
| 405 | of a problem in practice (how often do you recursively define interior |
| 406 | functions like this?), but this also made using the \keyword{lambda} |
| 407 | statement clumsier, and this was a problem in practice. In code which |
| 408 | uses \keyword{lambda} you can often find local variables being copied |
| 409 | by passing them as the default values of arguments. |
| 410 | |
| 411 | \begin{verbatim} |
| 412 | def find(self, name): |
| 413 | "Return list of any entries equal to 'name'" |
| 414 | L = filter(lambda x, name=name: x == name, |
| 415 | self.list_attribute) |
| 416 | return L |
| 417 | \end{verbatim} |
| 418 | |
| 419 | The readability of Python code written in a strongly functional style |
| 420 | suffers greatly as a result. |
| 421 | |
| 422 | The most significant change to Python 2.2 is that static scoping has |
| 423 | been added to the language to fix this problem. As a first effect, |
| 424 | the \code{name=name} default argument is now unnecessary in the above |
| 425 | example. Put simply, when a given variable name is not assigned a |
| 426 | value within a function (by an assignment, or the \keyword{def}, |
| 427 | \keyword{class}, or \keyword{import} statements), references to the |
| 428 | variable will be looked up in the local namespace of the enclosing |
| 429 | scope. A more detailed explanation of the rules, and a dissection of |
| 430 | the implementation, can be found in the PEP. |
| 431 | |
| 432 | This change may cause some compatibility problems for code where the |
| 433 | same variable name is used both at the module level and as a local |
| 434 | variable within a function that contains further function definitions. |
| 435 | This seems rather unlikely though, since such code would have been |
| 436 | pretty confusing to read in the first place. |
| 437 | |
| 438 | One side effect of the change is that the \code{from \var{module} |
| 439 | import *} and \keyword{exec} statements have been made illegal inside |
| 440 | a function scope under certain conditions. The Python reference |
| 441 | manual has said all along that \code{from \var{module} import *} is |
| 442 | only legal at the top level of a module, but the CPython interpreter |
| 443 | has never enforced this before. As part of the implementation of |
| 444 | nested scopes, the compiler which turns Python source into bytecodes |
| 445 | has to generate different code to access variables in a containing |
| 446 | scope. \code{from \var{module} import *} and \keyword{exec} make it |
| 447 | impossible for the compiler to figure this out, because they add names |
| 448 | to the local namespace that are unknowable at compile time. |
| 449 | Therefore, if a function contains function definitions or |
| 450 | \keyword{lambda} expressions with free variables, the compiler will |
| 451 | flag this by raising a \exception{SyntaxError} exception. |
| 452 | |
| 453 | To make the preceding explanation a bit clearer, here's an example: |
| 454 | |
| 455 | \begin{verbatim} |
| 456 | x = 1 |
| 457 | def f(): |
| 458 | # The next line is a syntax error |
| 459 | exec 'x=2' |
| 460 | def g(): |
| 461 | return x |
| 462 | \end{verbatim} |
| 463 | |
| 464 | Line 4 containing the \keyword{exec} statement is a syntax error, |
| 465 | since \keyword{exec} would define a new local variable named \samp{x} |
| 466 | whose value should be accessed by \function{g()}. |
| 467 | |
| 468 | This shouldn't be much of a limitation, since \keyword{exec} is rarely |
| 469 | used in most Python code (and when it is used, it's often a sign of a |
| 470 | poor design anyway). |
Andrew M. Kuchling | 4dbf871 | 2001-07-16 02:17:14 +0000 | [diff] [blame] | 471 | |
| 472 | \begin{seealso} |
| 473 | |
| 474 | \seepep{227}{Statically Nested Scopes}{Written and implemented by |
| 475 | Jeremy Hylton.} |
| 476 | |
| 477 | \end{seealso} |
| 478 | |
Andrew M. Kuchling | a43e703 | 2001-06-27 20:32:12 +0000 | [diff] [blame] | 479 | |
| 480 | %====================================================================== |
Andrew M. Kuchling | a8defaa | 2001-05-05 16:37:29 +0000 | [diff] [blame] | 481 | \section{New and Improved Modules} |
| 482 | |
| 483 | \begin{itemize} |
| 484 | |
Andrew M. Kuchling | 4dbf871 | 2001-07-16 02:17:14 +0000 | [diff] [blame] | 485 | \item The \module{xmlrpclib} module was contributed to the standard |
| 486 | library by Fredrik Lundh. It provides support for writing XML-RPC |
| 487 | clients; XML-RPC is a simple remote procedure call protocol built on |
| 488 | top of HTTP and XML. For example, the following snippet retrieves a |
| 489 | list of RSS channels from the O'Reilly Network, and then retrieves a |
| 490 | list of the recent headlines for one channel: |
| 491 | |
| 492 | \begin{verbatim} |
| 493 | import xmlrpclib |
| 494 | s = xmlrpclib.Server( |
| 495 | 'http://www.oreillynet.com/meerkat/xml-rpc/server.php') |
| 496 | channels = s.meerkat.getChannels() |
| 497 | # channels is a list of dictionaries, like this: |
| 498 | # [{'id': 4, 'title': 'Freshmeat Daily News'} |
| 499 | # {'id': 190, 'title': '32Bits Online'}, |
| 500 | # {'id': 4549, 'title': '3DGamers'}, ... ] |
| 501 | |
| 502 | # Get the items for one channel |
| 503 | items = s.meerkat.getItems( {'channel': 4} ) |
| 504 | |
| 505 | # 'items' is another list of dictionaries, like this: |
| 506 | # [{'link': 'http://freshmeat.net/releases/52719/', |
| 507 | # 'description': 'A utility which converts HTML to XSL FO.', |
| 508 | # 'title': 'html2fo 0.3 (Default)'}, ... ] |
| 509 | \end{verbatim} |
| 510 | |
Fred Drake | 0d00254 | 2001-07-17 13:55:33 +0000 | [diff] [blame] | 511 | See \url{http://www.xmlrpc.com/} for more information about XML-RPC. |
Andrew M. Kuchling | 4dbf871 | 2001-07-16 02:17:14 +0000 | [diff] [blame] | 512 | |
| 513 | \item The \module{socket} module can be compiled to support IPv6; |
Andrew M. Kuchling | ddeb135 | 2001-07-16 14:35:52 +0000 | [diff] [blame] | 514 | specify the \longprogramopt{enable-ipv6} option to Python's configure |
Andrew M. Kuchling | 4dbf871 | 2001-07-16 02:17:14 +0000 | [diff] [blame] | 515 | script. (Contributed by Jun-ichiro ``itojun'' Hagino.) |
| 516 | |
| 517 | \item Two new format characters were added to the \module{struct} |
| 518 | module for 64-bit integers on platforms that support the C |
| 519 | \ctype{long long} type. \samp{q} is for a signed 64-bit integer, |
| 520 | and \samp{Q} is for an unsigned one. The value is returned in |
| 521 | Python's long integer type. (Contributed by Tim Peters.) |
| 522 | |
| 523 | \item In the interpreter's interactive mode, there's a new built-in |
| 524 | function \function{help()}, that uses the \module{pydoc} module |
| 525 | introduced in Python 2.1 to provide interactive. |
| 526 | \code{help(\var{object})} displays any available help text about |
| 527 | \var{object}. \code{help()} with no argument puts you in an online |
| 528 | help utility, where you can enter the names of functions, classes, |
| 529 | or modules to read their help text. |
| 530 | (Contributed by Guido van Rossum, using Ka-Ping Yee's \module{pydoc} module.) |
| 531 | |
| 532 | \item Various bugfixes and performance improvements have been made |
Andrew M. Kuchling | 4cf52a9 | 2001-07-17 12:48:48 +0000 | [diff] [blame] | 533 | to the SRE engine underlying the \module{re} module. For example, |
| 534 | \function{re.sub()} will now use \function{string.replace()} |
| 535 | automatically when the pattern and its replacement are both just |
| 536 | literal strings without regex metacharacters. Another contributed |
| 537 | patch speeds up certain Unicode character ranges by a factor of |
| 538 | two. (SRE is maintained by Fredrik Lundh. The BIGCHARSET patch was |
| 539 | contributed by Martin von L\"owis.) |
Andrew M. Kuchling | 4dbf871 | 2001-07-16 02:17:14 +0000 | [diff] [blame] | 540 | |
| 541 | \item The \module{imaplib} module now has support for the IMAP |
Andrew M. Kuchling | 4cf52a9 | 2001-07-17 12:48:48 +0000 | [diff] [blame] | 542 | NAMESPACE extension defined in \rfc{2342}. (Contributed by Michel |
| 543 | Pelletier.) |
Andrew M. Kuchling | 4dbf871 | 2001-07-16 02:17:14 +0000 | [diff] [blame] | 544 | |
Fred Drake | 0d00254 | 2001-07-17 13:55:33 +0000 | [diff] [blame] | 545 | \item The \module{rfc822} module's parsing of email addresses is |
Andrew M. Kuchling | 4cf52a9 | 2001-07-17 12:48:48 +0000 | [diff] [blame] | 546 | now compliant with \rfc{2822}, an update to \rfc{822}. The module's |
| 547 | name is \emph{not} going to be changed to \samp{rfc2822}. |
| 548 | (Contributed by Barry Warsaw.) |
| 549 | |
Andrew M. Kuchling | a8defaa | 2001-05-05 16:37:29 +0000 | [diff] [blame] | 550 | \end{itemize} |
| 551 | |
| 552 | |
| 553 | %====================================================================== |
| 554 | \section{Other Changes and Fixes} |
| 555 | |
Andrew M. Kuchling | 4dbf871 | 2001-07-16 02:17:14 +0000 | [diff] [blame] | 556 | As usual there were a bunch of other improvements and bugfixes |
| 557 | scattered throughout the source tree. A search through the CVS change |
| 558 | logs finds there were XXX patches applied, and XXX bugs fixed; both |
| 559 | figures are likely to be underestimates. Some of the more notable |
| 560 | changes are: |
Andrew M. Kuchling | a8defaa | 2001-05-05 16:37:29 +0000 | [diff] [blame] | 561 | |
| 562 | \begin{itemize} |
| 563 | |
Andrew M. Kuchling | 2cd712b | 2001-07-16 13:39:08 +0000 | [diff] [blame] | 564 | \item Keyword arguments passed to builtin functions that don't take them |
| 565 | now cause a \exception{TypeError} exception to be raised, with the |
| 566 | message "\var{function} takes no keyword arguments". |
| 567 | |
Fred Drake | 0d00254 | 2001-07-17 13:55:33 +0000 | [diff] [blame] | 568 | \item The code for the Mac OS port for Python, maintained by Jack |
Andrew M. Kuchling | 2cd712b | 2001-07-16 13:39:08 +0000 | [diff] [blame] | 569 | Jansen, is now kept in the main Python CVS tree. |
| 570 | |
| 571 | \item The new license introduced with Python 1.6 wasn't |
| 572 | GPL-compatible. This is fixed by some minor textual changes to the |
| 573 | 2.2 license, so Python can now be embedded inside a GPLed program |
| 574 | again. The license changes were also applied to the Python 2.0.1 |
| 575 | and 2.1.1 releases. |
| 576 | |
Andrew M. Kuchling | 4cf52a9 | 2001-07-17 12:48:48 +0000 | [diff] [blame] | 577 | \item Profiling and tracing functions can now be implemented in C, |
| 578 | which can operate at much higher speeds than Python-based functions |
| 579 | and should reduce the overhead of enabling profiling and tracing, so |
| 580 | it will be of interest to authors of development environments for |
| 581 | Python. Two new C functions were added to Python's API, |
| 582 | \cfunction{PyEval_SetProfile()} and \cfunction{PyEval_SetTrace()}. |
| 583 | The existing \function{sys.setprofile()} and |
| 584 | \function{sys.settrace()} functions still exist, and have simply |
Fred Drake | 0d00254 | 2001-07-17 13:55:33 +0000 | [diff] [blame] | 585 | been changed to use the new C-level interface. (Contributed by Fred |
| 586 | L. Drake, Jr.) |
Andrew M. Kuchling | 2cd712b | 2001-07-16 13:39:08 +0000 | [diff] [blame] | 587 | |
| 588 | \item The \file{Tools/scripts/ftpmirror.py} script |
| 589 | now parses a \file{.netrc} file, if you have one. |
Andrew M. Kuchling | 4cf52a9 | 2001-07-17 12:48:48 +0000 | [diff] [blame] | 590 | (Contributed by Mike Romberg.) |
Andrew M. Kuchling | 2cd712b | 2001-07-16 13:39:08 +0000 | [diff] [blame] | 591 | |
Andrew M. Kuchling | 4cf52a9 | 2001-07-17 12:48:48 +0000 | [diff] [blame] | 592 | \item Some features of the object returned by the |
| 593 | \function{xrange()} function are now deprecated, and trigger |
| 594 | warnings when they're accessed; they'll disappear in Python 2.3. |
| 595 | \class{xrange} objects tried to pretend they were full sequence |
| 596 | types by supporting slicing, sequence multiplication, and the |
| 597 | \keyword{in} operator, but these features were rarely used and |
| 598 | therefore buggy. The \method{tolist()} method and the |
| 599 | \member{start}, \member{stop}, and \member{step} attributes are also |
| 600 | being deprecated. At the C level, the fourth argument to the |
| 601 | \cfunction{PyRange_New()} function, \samp{repeat}, has also been |
| 602 | deprecated. |
| 603 | |
| 604 | \item On Windows, Python can now be compiled with Borland C thanks |
| 605 | to a number of patches contribued by Stephen Hansen. |
Andrew M. Kuchling | 2cd712b | 2001-07-16 13:39:08 +0000 | [diff] [blame] | 606 | |
Andrew M. Kuchling | a8defaa | 2001-05-05 16:37:29 +0000 | [diff] [blame] | 607 | \item XXX C API: Reorganization of object calling |
| 608 | |
Fred Drake | 0d00254 | 2001-07-17 13:55:33 +0000 | [diff] [blame] | 609 | The \cfunction{call_object()} function, originally in \file{ceval.c}, |
| 610 | begins a new life as the official API \cfunction{PyObject_Call()}. It |
| 611 | is also much simplified: all it does is call the \member{tp_call} |
| 612 | slot, or raise an exception if that's \NULL. |
Andrew M. Kuchling | 3b923fc | 2001-05-19 19:35:46 +0000 | [diff] [blame] | 613 | |
Andrew M. Kuchling | a8defaa | 2001-05-05 16:37:29 +0000 | [diff] [blame] | 614 | %The subsidiary functions (call_eval_code2(), call_cfunction(), |
| 615 | %call_instance(), and call_method()) have all been moved to the file |
| 616 | %implementing their particular object type, renamed according to the |
| 617 | %local convention, and added to the type's tp_call slot. Note that |
| 618 | %call_eval_code2() became function_call(); the tp_slot for class |
| 619 | %objects now simply points to PyInstance_New(), which already has the |
| 620 | %correct signature. |
| 621 | |
| 622 | %Because of these moves, there are some more new APIs that expose |
| 623 | %helpers in ceval.c that are now needed outside: PyEval_GetFuncName(), |
| 624 | %PyEval_GetFuncDesc(), PyEval_EvalCodeEx() (formerly get_func_name(), |
| 625 | %get_func_desc(), and eval_code2(). |
| 626 | |
Andrew M. Kuchling | 4cf52a9 | 2001-07-17 12:48:48 +0000 | [diff] [blame] | 627 | \item XXX Add support for Windows using "mbcs" as the default |
| 628 | Unicode encoding when dealing with the file system. As discussed on |
| 629 | python-dev and in patch 410465. |
Andrew M. Kuchling | 2cd712b | 2001-07-16 13:39:08 +0000 | [diff] [blame] | 630 | |
Fred Drake | 0d00254 | 2001-07-17 13:55:33 +0000 | [diff] [blame] | 631 | \item XXX Lots of patches to dictionaries; measure performance |
| 632 | improvement, if any. |
Andrew M. Kuchling | 2cd712b | 2001-07-16 13:39:08 +0000 | [diff] [blame] | 633 | |
Andrew M. Kuchling | a8defaa | 2001-05-05 16:37:29 +0000 | [diff] [blame] | 634 | \end{itemize} |
| 635 | |
| 636 | |
| 637 | |
| 638 | %====================================================================== |
| 639 | \section{Acknowledgements} |
| 640 | |
| 641 | The author would like to thank the following people for offering |
Andrew M. Kuchling | 6ea9f0b | 2001-07-17 14:50:31 +0000 | [diff] [blame^] | 642 | suggestions and corrections to various drafts of this article: Fred |
| 643 | L. Drake, Tim Peters, Neil Schemenauer. |
Andrew M. Kuchling | a8defaa | 2001-05-05 16:37:29 +0000 | [diff] [blame] | 644 | |
| 645 | \end{document} |