blob: 750162f773b5386f376bfe9f315fee54e917fd7f [file] [log] [blame]
Fred Drake2db76802004-12-01 05:05:47 +00001\documentclass{howto}
2\usepackage{distutils}
3% $Id$
4
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005% The easy_install stuff
6% Describe the pkgutil module
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007% Fix XXX comments
8% Count up the patches and bugs
Fred Drake2db76802004-12-01 05:05:47 +00009
10\title{What's New in Python 2.5}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011\release{0.1}
Andrew M. Kuchling92e24952004-12-03 13:54:09 +000012\author{A.M. Kuchling}
13\authoraddress{\email{amk@amk.ca}}
Fred Drake2db76802004-12-01 05:05:47 +000014
15\begin{document}
16\maketitle
17\tableofcontents
18
19This article explains the new features in Python 2.5. No release date
Andrew M. Kuchling5eefdca2006-02-08 11:36:09 +000020for Python 2.5 has been set; it will probably be released in the
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000021autumn of 2006. \pep{356} describes the planned release schedule.
22
23Comments, suggestions, and error reports are welcome; please e-mail them
24to the author or open a bug in the Python bug tracker.
Fred Drake2db76802004-12-01 05:05:47 +000025
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000026% XXX Compare with previous release in 2 - 3 sentences here.
Fred Drake2db76802004-12-01 05:05:47 +000027
28This article doesn't attempt to provide a complete specification of
29the new features, but instead provides a convenient overview. For
30full details, you should refer to the documentation for Python 2.5.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000031% XXX add hyperlink when the documentation becomes available online.
Fred Drake2db76802004-12-01 05:05:47 +000032If you want to understand the complete implementation and design
33rationale, refer to the PEP for a particular new feature.
34
35
36%======================================================================
Thomas Woutersd4ec0c32006-04-21 16:44:05 +000037\section{PEP 243: Uploading Modules to PyPI\label{pep-243}}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000038
39PEP 243 describes an HTTP-based protocol for submitting software
40packages to a central archive. The Python package index at
41\url{http://cheeseshop.python.org} now supports package uploads, and
42the new \command{upload} Distutils command will upload a package to the
43repository.
44
45Before a package can be uploaded, you must be able to build a
46distribution using the \command{sdist} Distutils command. Once that
47works, you can run \code{python setup.py upload} to add your package
48to the PyPI archive. Optionally you can GPG-sign the package by
49supplying the \longprogramopt{sign} and
50\longprogramopt{identity} options.
51
52\begin{seealso}
53
54\seepep{243}{Module Repository Upload Mechanism}{PEP written by
55Sean Reifschneider; implemented by Martin von~L\"owis
56and Richard Jones. Note that the PEP doesn't exactly
57describe what's implemented in PyPI.}
58
59\end{seealso}
60
61
62%======================================================================
Thomas Woutersd4ec0c32006-04-21 16:44:05 +000063\section{PEP 308: Conditional Expressions\label{pep-308}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000064
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000065For a long time, people have been requesting a way to write
66conditional expressions, expressions that return value A or value B
67depending on whether a Boolean value is true or false. A conditional
68expression lets you write a single assignment statement that has the
69same effect as the following:
70
71\begin{verbatim}
72if condition:
73 x = true_value
74else:
75 x = false_value
76\end{verbatim}
77
78There have been endless tedious discussions of syntax on both
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000079python-dev and comp.lang.python. A vote was even held that found the
80majority of voters wanted conditional expressions in some form,
81but there was no syntax that was preferred by a clear majority.
82Candidates included C's \code{cond ? true_v : false_v},
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000083\code{if cond then true_v else false_v}, and 16 other variations.
84
85GvR eventually chose a surprising syntax:
86
87\begin{verbatim}
88x = true_value if condition else false_value
89\end{verbatim}
90
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000091Evaluation is still lazy as in existing Boolean expressions, so the
92order of evaluation jumps around a bit. The \var{condition}
93expression in the middle is evaluated first, and the \var{true_value}
94expression is evaluated only if the condition was true. Similarly,
95the \var{false_value} expression is only evaluated when the condition
96is false.
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000097
98This syntax may seem strange and backwards; why does the condition go
99in the \emph{middle} of the expression, and not in the front as in C's
100\code{c ? x : y}? The decision was checked by applying the new syntax
101to the modules in the standard library and seeing how the resulting
102code read. In many cases where a conditional expression is used, one
103value seems to be the 'common case' and one value is an 'exceptional
104case', used only on rarer occasions when the condition isn't met. The
105conditional syntax makes this pattern a bit more obvious:
106
107\begin{verbatim}
108contents = ((doc + '\n') if doc else '')
109\end{verbatim}
110
111I read the above statement as meaning ``here \var{contents} is
Andrew M. Kuchlingd0fcc022006-03-09 13:57:28 +0000112usually assigned a value of \code{doc+'\e n'}; sometimes
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +0000113\var{doc} is empty, in which special case an empty string is returned.''
114I doubt I will use conditional expressions very often where there
115isn't a clear common and uncommon case.
116
117There was some discussion of whether the language should require
118surrounding conditional expressions with parentheses. The decision
119was made to \emph{not} require parentheses in the Python language's
120grammar, but as a matter of style I think you should always use them.
121Consider these two statements:
122
123\begin{verbatim}
124# First version -- no parens
125level = 1 if logging else 0
126
127# Second version -- with parens
128level = (1 if logging else 0)
129\end{verbatim}
130
131In the first version, I think a reader's eye might group the statement
132into 'level = 1', 'if logging', 'else 0', and think that the condition
133decides whether the assignment to \var{level} is performed. The
134second version reads better, in my opinion, because it makes it clear
135that the assignment is always performed and the choice is being made
136between two values.
137
138Another reason for including the brackets: a few odd combinations of
139list comprehensions and lambdas could look like incorrect conditional
140expressions. See \pep{308} for some examples. If you put parentheses
141around your conditional expressions, you won't run into this case.
142
143
144\begin{seealso}
145
146\seepep{308}{Conditional Expressions}{PEP written by
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000147Guido van~Rossum and Raymond D. Hettinger; implemented by Thomas
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +0000148Wouters.}
149
150\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000151
152
153%======================================================================
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000154\section{PEP 309: Partial Function Application\label{pep-309}}
Fred Drake2db76802004-12-01 05:05:47 +0000155
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000156The \module{functional} module is intended to contain tools for
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000157functional-style programming. Currently it only contains a
158\class{partial()} function, but new functions will probably be added
159in future versions of Python.
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000160
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000161For programs written in a functional style, it can be useful to
162construct variants of existing functions that have some of the
163parameters filled in. Consider a Python function \code{f(a, b, c)};
164you could create a new function \code{g(b, c)} that was equivalent to
165\code{f(1, b, c)}. This is called ``partial function application'',
166and is provided by the \class{partial} class in the new
167\module{functional} module.
168
169The constructor for \class{partial} takes the arguments
170\code{(\var{function}, \var{arg1}, \var{arg2}, ...
171\var{kwarg1}=\var{value1}, \var{kwarg2}=\var{value2})}. The resulting
172object is callable, so you can just call it to invoke \var{function}
173with the filled-in arguments.
174
175Here's a small but realistic example:
176
177\begin{verbatim}
178import functional
179
180def log (message, subsystem):
181 "Write the contents of 'message' to the specified subsystem."
182 print '%s: %s' % (subsystem, message)
183 ...
184
185server_log = functional.partial(log, subsystem='server')
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000186server_log('Unable to open socket')
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000187\end{verbatim}
188
Andrew M. Kuchling6af7fe02005-08-02 17:20:36 +0000189Here's another example, from a program that uses PyGTk. Here a
190context-sensitive pop-up menu is being constructed dynamically. The
191callback provided for the menu option is a partially applied version
192of the \method{open_item()} method, where the first argument has been
193provided.
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000194
Andrew M. Kuchling6af7fe02005-08-02 17:20:36 +0000195\begin{verbatim}
196...
197class Application:
198 def open_item(self, path):
199 ...
200 def init (self):
201 open_func = functional.partial(self.open_item, item_path)
202 popup_menu.append( ("Open", open_func, 1) )
203\end{verbatim}
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000204
205
206\begin{seealso}
207
208\seepep{309}{Partial Function Application}{PEP proposed and written by
209Peter Harris; implemented by Hye-Shik Chang, with adaptations by
210Raymond Hettinger.}
211
212\end{seealso}
Fred Drake2db76802004-12-01 05:05:47 +0000213
214
215%======================================================================
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000216\section{PEP 314: Metadata for Python Software Packages v1.1\label{pep-314}}
Fred Drakedb7b0022005-03-20 22:19:47 +0000217
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000218Some simple dependency support was added to Distutils. The
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000219\function{setup()} function now has \code{requires}, \code{provides},
220and \code{obsoletes} keyword parameters. When you build a source
221distribution using the \code{sdist} command, the dependency
222information will be recorded in the \file{PKG-INFO} file.
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000223
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000224Another new keyword parameter is \code{download_url}, which should be
225set to a URL for the package's source code. This means it's now
226possible to look up an entry in the package index, determine the
227dependencies for a package, and download the required packages.
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000228
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000229\begin{verbatim}
230VERSION = '1.0'
231setup(name='PyPackage',
232 version=VERSION,
233 requires=['numarray', 'zlib (>=1.1.4)'],
234 obsoletes=['OldPackage']
235 download_url=('http://www.example.com/pypackage/dist/pkg-%s.tar.gz'
236 % VERSION),
237 )
238\end{verbatim}
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000239
240\begin{seealso}
241
242\seepep{314}{Metadata for Python Software Packages v1.1}{PEP proposed
243and written by A.M. Kuchling, Richard Jones, and Fred Drake;
244implemented by Richard Jones and Fred Drake.}
245
246\end{seealso}
Fred Drakedb7b0022005-03-20 22:19:47 +0000247
248
249%======================================================================
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000250\section{PEP 328: Absolute and Relative Imports\label{pep-328}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000251
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000252The simpler part of PEP 328 was implemented in Python 2.4: parentheses
253could now be used to enclose the names imported from a module using
254the \code{from ... import ...} statement, making it easier to import
255many different names.
256
257The more complicated part has been implemented in Python 2.5:
258importing a module can be specified to use absolute or
259package-relative imports. The plan is to move toward making absolute
260imports the default in future versions of Python.
261
262Let's say you have a package directory like this:
263\begin{verbatim}
264pkg/
265pkg/__init__.py
266pkg/main.py
267pkg/string.py
268\end{verbatim}
269
270This defines a package named \module{pkg} containing the
271\module{pkg.main} and \module{pkg.string} submodules.
272
273Consider the code in the \file{main.py} module. What happens if it
274executes the statement \code{import string}? In Python 2.4 and
275earlier, it will first look in the package's directory to perform a
276relative import, finds \file{pkg/string.py}, imports the contents of
277that file as the \module{pkg.string} module, and that module is bound
278to the name \samp{string} in the \module{pkg.main} module's namespace.
279
280That's fine if \module{pkg.string} was what you wanted. But what if
281you wanted Python's standard \module{string} module? There's no clean
282way to ignore \module{pkg.string} and look for the standard module;
283generally you had to look at the contents of \code{sys.modules}, which
284is slightly unclean.
285Holger Krekel's \module{py.std} package provides a tidier way to perform
286imports from the standard library, \code{import py ; py.std.string.join()},
287but that package isn't available on all Python installations.
288
289Reading code which relies on relative imports is also less clear,
290because a reader may be confused about which module, \module{string}
291or \module{pkg.string}, is intended to be used. Python users soon
292learned not to duplicate the names of standard library modules in the
293names of their packages' submodules, but you can't protect against
294having your submodule's name being used for a new module added in a
295future version of Python.
296
297In Python 2.5, you can switch \keyword{import}'s behaviour to
298absolute imports using a \code{from __future__ import absolute_import}
299directive. This absolute-import behaviour will become the default in
300a future version (probably Python 2.7). Once absolute imports
301are the default, \code{import string} will
302always find the standard library's version.
303It's suggested that users should begin using absolute imports as much
304as possible, so it's preferable to begin writing \code{from pkg import
305string} in your code.
306
307Relative imports are still possible by adding a leading period
308to the module name when using the \code{from ... import} form:
309
310\begin{verbatim}
311# Import names from pkg.string
312from .string import name1, name2
313# Import pkg.string
314from . import string
315\end{verbatim}
316
317This imports the \module{string} module relative to the current
318package, so in \module{pkg.main} this will import \var{name1} and
319\var{name2} from \module{pkg.string}. Additional leading periods
320perform the relative import starting from the parent of the current
321package. For example, code in the \module{A.B.C} module can do:
322
323\begin{verbatim}
324from . import D # Imports A.B.D
325from .. import E # Imports A.E
326from ..F import G # Imports A.F.G
327\end{verbatim}
328
329Leading periods cannot be used with the \code{import \var{modname}}
330form of the import statement, only the \code{from ... import} form.
331
332\begin{seealso}
333
334\seepep{328}{Imports: Multi-Line and Absolute/Relative}
335{PEP written by Aahz; implemented by Thomas Wouters.}
336
337\seeurl{http://codespeak.net/py/current/doc/index.html}
338{The py library by Holger Krekel, which contains the \module{py.std} package.}
339
340\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000341
342
343%======================================================================
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000344\section{PEP 338: Executing Modules as Scripts\label{pep-338}}
Thomas Woutersa9773292006-04-21 09:43:23 +0000345
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000346The \programopt{-m} switch added in Python 2.4 to execute a module as
347a script gained a few more abilities. Instead of being implemented in
348C code inside the Python interpreter, the switch now uses an
349implementation in a new module, \module{runpy}.
350
351The \module{runpy} module implements a more sophisticated import
352mechanism so that it's now possible to run modules in a package such
353as \module{pychecker.checker}. The module also supports alternative
354import mechanisms such as the \module{zipimport} module. This means
355you can add a .zip archive's path to \code{sys.path} and then use the
356\programopt{-m} switch to execute code from the archive.
357
358
359\begin{seealso}
360
361\seepep{338}{Executing modules as scripts}{PEP written and
362implemented by Nick Coghlan.}
363
364\end{seealso}
Thomas Woutersa9773292006-04-21 09:43:23 +0000365
366
367%======================================================================
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000368\section{PEP 341: Unified try/except/finally\label{pep-341}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000369
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000370Until Python 2.5, the \keyword{try} statement came in two
371flavours. You could use a \keyword{finally} block to ensure that code
372is always executed, or one or more \keyword{except} blocks to catch
373specific exceptions. You couldn't combine both \keyword{except} blocks and a
374\keyword{finally} block, because generating the right bytecode for the
375combined version was complicated and it wasn't clear what the
376semantics of the combined should be.
377
378GvR spent some time working with Java, which does support the
379equivalent of combining \keyword{except} blocks and a
380\keyword{finally} block, and this clarified what the statement should
381mean. In Python 2.5, you can now write:
382
383\begin{verbatim}
384try:
385 block-1 ...
386except Exception1:
387 handler-1 ...
388except Exception2:
389 handler-2 ...
390else:
391 else-block
392finally:
393 final-block
394\end{verbatim}
395
396The code in \var{block-1} is executed. If the code raises an
397exception, the handlers are tried in order: \var{handler-1},
398\var{handler-2}, ... If no exception is raised, the \var{else-block}
399is executed. No matter what happened previously, the
400\var{final-block} is executed once the code block is complete and any
401raised exceptions handled. Even if there's an error in an exception
402handler or the \var{else-block} and a new exception is raised, the
403\var{final-block} is still executed.
404
405\begin{seealso}
406
407\seepep{341}{Unifying try-except and try-finally}{PEP written by Georg Brandl;
408implementation by Thomas Lee.}
409
410\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000411
412
413%======================================================================
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000414\section{PEP 342: New Generator Features\label{pep-342}}
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000415
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000416Python 2.5 adds a simple way to pass values \emph{into} a generator.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000417As introduced in Python 2.3, generators only produce output; once a
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000418generator's code is invoked to create an iterator, there's no way to
419pass any new information into the function when its execution is
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000420resumed. Sometimes the ability to pass in some information would be
421useful. Hackish solutions to this include making the generator's code
422look at a global variable and then changing the global variable's
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000423value, or passing in some mutable object that callers then modify.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000424
425To refresh your memory of basic generators, here's a simple example:
426
427\begin{verbatim}
428def counter (maximum):
429 i = 0
430 while i < maximum:
431 yield i
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000432 i += 1
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000433\end{verbatim}
434
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000435When you call \code{counter(10)}, the result is an iterator that
436returns the values from 0 up to 9. On encountering the
437\keyword{yield} statement, the iterator returns the provided value and
438suspends the function's execution, preserving the local variables.
439Execution resumes on the following call to the iterator's
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000440\method{next()} method, picking up after the \keyword{yield} statement.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000441
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000442In Python 2.3, \keyword{yield} was a statement; it didn't return any
443value. In 2.5, \keyword{yield} is now an expression, returning a
444value that can be assigned to a variable or otherwise operated on:
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000445
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000446\begin{verbatim}
447val = (yield i)
448\end{verbatim}
449
450I recommend that you always put parentheses around a \keyword{yield}
451expression when you're doing something with the returned value, as in
452the above example. The parentheses aren't always necessary, but it's
453easier to always add them instead of having to remember when they're
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000454needed.
455
456(\pep{342} explains the exact rules, which are that a
457\keyword{yield}-expression must always be parenthesized except when it
458occurs at the top-level expression on the right-hand side of an
459assignment. This means you can write \code{val = yield i} but have to
460use parentheses when there's an operation, as in \code{val = (yield i)
461+ 12}.)
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000462
463Values are sent into a generator by calling its
464\method{send(\var{value})} method. The generator's code is then
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000465resumed and the \keyword{yield} expression returns the specified
466\var{value}. If the regular \method{next()} method is called, the
467\keyword{yield} returns \constant{None}.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000468
469Here's the previous example, modified to allow changing the value of
470the internal counter.
471
472\begin{verbatim}
473def counter (maximum):
474 i = 0
475 while i < maximum:
476 val = (yield i)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000477 # If value provided, change counter
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000478 if val is not None:
479 i = val
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000480 else:
481 i += 1
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000482\end{verbatim}
483
484And here's an example of changing the counter:
485
486\begin{verbatim}
487>>> it = counter(10)
488>>> print it.next()
4890
490>>> print it.next()
4911
492>>> print it.send(8)
4938
494>>> print it.next()
4959
496>>> print it.next()
497Traceback (most recent call last):
498 File ``t.py'', line 15, in ?
499 print it.next()
500StopIteration
Andrew M. Kuchlingc2033702005-08-29 13:30:12 +0000501\end{verbatim}
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000502
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000503Because \keyword{yield} will often be returning \constant{None}, you
504should always check for this case. Don't just use its value in
505expressions unless you're sure that the \method{send()} method
506will be the only method used resume your generator function.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000507
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000508In addition to \method{send()}, there are two other new methods on
509generators:
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000510
511\begin{itemize}
512
513 \item \method{throw(\var{type}, \var{value}=None,
514 \var{traceback}=None)} is used to raise an exception inside the
515 generator; the exception is raised by the \keyword{yield} expression
516 where the generator's execution is paused.
517
518 \item \method{close()} raises a new \exception{GeneratorExit}
519 exception inside the generator to terminate the iteration.
520 On receiving this
521 exception, the generator's code must either raise
522 \exception{GeneratorExit} or \exception{StopIteration}; catching the
523 exception and doing anything else is illegal and will trigger
524 a \exception{RuntimeError}. \method{close()} will also be called by
525 Python's garbage collection when the generator is garbage-collected.
526
527 If you need to run cleanup code in case of a \exception{GeneratorExit},
528 I suggest using a \code{try: ... finally:} suite instead of
529 catching \exception{GeneratorExit}.
530
531\end{itemize}
532
533The cumulative effect of these changes is to turn generators from
534one-way producers of information into both producers and consumers.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000535
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000536Generators also become \emph{coroutines}, a more generalized form of
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000537subroutines. Subroutines are entered at one point and exited at
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000538another point (the top of the function, and a \keyword{return
539statement}), but coroutines can be entered, exited, and resumed at
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000540many different points (the \keyword{yield} statements). We'll have to
541figure out patterns for using coroutines effectively in Python.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000542
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000543The addition of the \method{close()} method has one side effect that
544isn't obvious. \method{close()} is called when a generator is
545garbage-collected, so this means the generator's code gets one last
546chance to run before the generator is destroyed. This last chance
547means that \code{try...finally} statements in generators can now be
548guaranteed to work; the \keyword{finally} clause will now always get a
549chance to run. The syntactic restriction that you couldn't mix
550\keyword{yield} statements with a \code{try...finally} suite has
551therefore been removed. This seems like a minor bit of language
552trivia, but using generators and \code{try...finally} is actually
553necessary in order to implement the \keyword{with} statement
554described by PEP 343. I'll look at this new statement in the following
555section.
556
557Another even more esoteric effect of this change: previously, the
558\member{gi_frame} attribute of a generator was always a frame object.
559It's now possible for \member{gi_frame} to be \code{None}
560once the generator has been exhausted.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000561
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000562\begin{seealso}
563
564\seepep{342}{Coroutines via Enhanced Generators}{PEP written by
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000565Guido van~Rossum and Phillip J. Eby;
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000566implemented by Phillip J. Eby. Includes examples of
567some fancier uses of generators as coroutines.}
568
569\seeurl{http://en.wikipedia.org/wiki/Coroutine}{The Wikipedia entry for
570coroutines.}
571
Neal Norwitz09179882006-03-04 23:31:45 +0000572\seeurl{http://www.sidhe.org/\~{}dan/blog/archives/000178.html}{An
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000573explanation of coroutines from a Perl point of view, written by Dan
574Sugalski.}
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000575
576\end{seealso}
577
578
579%======================================================================
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000580\section{PEP 343: The 'with' statement\label{pep-343}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000581
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000582The '\keyword{with}' statement allows a clearer version of code that
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000583uses \code{try...finally} blocks to ensure that clean-up code is
584executed.
585
586In this section, I'll discuss the statement as it will commonly be
587used. In the next section, I'll examine the implementation details
588and show how to write objects called ``context managers'' and
589``contexts'' for use with this statement.
590
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000591The '\keyword{with}' statement is a new control-flow structure whose
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000592basic structure is:
593
594\begin{verbatim}
595with expression [as variable]:
596 with-block
597\end{verbatim}
598
599The expression is evaluated, and it should result in a type of object
600that's called a context manager. The context manager can return a
601value that can optionally be bound to the name \var{variable}. (Note
602carefully: \var{variable} is \emph{not} assigned the result of
603\var{expression}.) One method of the context manager is run before
604\var{with-block} is executed, and another method is run after the
605block is done, even if the block raised an exception.
606
607To enable the statement in Python 2.5, you need
608to add the following directive to your module:
609
610\begin{verbatim}
611from __future__ import with_statement
612\end{verbatim}
613
614The statement will always be enabled in Python 2.6.
615
616Some standard Python objects can now behave as context managers. File
617objects are one example:
618
619\begin{verbatim}
620with open('/etc/passwd', 'r') as f:
621 for line in f:
622 print line
623 ... more processing code ...
624\end{verbatim}
625
626After this statement has executed, the file object in \var{f} will
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000627have been automatically closed, even if the 'for' loop
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000628raised an exception part-way through the block.
629
630The \module{threading} module's locks and condition variables
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000631also support the '\keyword{with}' statement:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000632
633\begin{verbatim}
634lock = threading.Lock()
635with lock:
636 # Critical section of code
637 ...
638\end{verbatim}
639
640The lock is acquired before the block is executed, and always released once
641the block is complete.
642
643The \module{decimal} module's contexts, which encapsulate the desired
644precision and rounding characteristics for computations, can also be
645used as context managers.
646
647\begin{verbatim}
648import decimal
649
650# Displays with default precision of 28 digits
651v1 = decimal.Decimal('578')
652print v1.sqrt()
653
654with decimal.Context(prec=16):
655 # All code in this block uses a precision of 16 digits.
656 # The original context is restored on exiting the block.
657 print v1.sqrt()
658\end{verbatim}
659
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000660\subsection{Writing Context Managers\label{context-managers}}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000661
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000662Under the hood, the '\keyword{with}' statement is fairly complicated.
663Most people will only use '\keyword{with}' in company with
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000664existing objects that are documented to work as context managers, and
665don't need to know these details, so you can skip the following section if
666you like. Authors of new context managers will need to understand the
667details of the underlying implementation.
668
669A high-level explanation of the context management protocol is:
670
671\begin{itemize}
672\item The expression is evaluated and should result in an object
673that's a context manager, meaning that it has a
674\method{__context__()} method.
675
676\item This object's \method{__context__()} method is called, and must
677return a context object.
678
679\item The context's \method{__enter__()} method is called.
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000680The value returned is assigned to \var{VAR}. If no \code{'as \var{VAR}'}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000681clause is present, the value is simply discarded.
682
683\item The code in \var{BLOCK} is executed.
684
685\item If \var{BLOCK} raises an exception, the context object's
686\method{__exit__(\var{type}, \var{value}, \var{traceback})} is called
687with the exception's information, the same values returned by
688\function{sys.exc_info()}. The method's return value
689controls whether the exception is re-raised: any false value
690re-raises the exception, and \code{True} will result in suppressing it.
691You'll only rarely want to suppress the exception; the
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000692author of the code containing the '\keyword{with}' statement will
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000693never realize anything went wrong.
694
695\item If \var{BLOCK} didn't raise an exception,
696the context object's \method{__exit__()} is still called,
697but \var{type}, \var{value}, and \var{traceback} are all \code{None}.
698
699\end{itemize}
700
701Let's think through an example. I won't present detailed code but
702will only sketch the necessary code. The example will be writing a
703context manager for a database that supports transactions.
704
705(For people unfamiliar with database terminology: a set of changes to
706the database are grouped into a transaction. Transactions can be
707either committed, meaning that all the changes are written into the
708database, or rolled back, meaning that the changes are all discarded
709and the database is unchanged. See any database textbook for more
710information.)
711% XXX find a shorter reference?
712
713Let's assume there's an object representing a database connection.
714Our goal will be to let the user write code like this:
715
716\begin{verbatim}
717db_connection = DatabaseConnection()
718with db_connection as cursor:
719 cursor.execute('insert into ...')
720 cursor.execute('delete from ...')
721 # ... more operations ...
722\end{verbatim}
723
724The transaction should either be committed if the code in the block
725runs flawlessly, or rolled back if there's an exception.
726
727First, the \class{DatabaseConnection} needs a \method{__context__()}
728method. Sometimes an object can be its own context manager and can
729simply return \code{self}; the \module{threading} module's lock objects
730can do this. For our database example, though, we need to
731create a new object; I'll call this class \class{DatabaseContext}.
732Our \method{__context__()} must therefore look like this:
733
734\begin{verbatim}
735class DatabaseConnection:
736 ...
737 def __context__ (self):
738 return DatabaseContext(self)
739
740 # Database interface
741 def cursor (self):
742 "Returns a cursor object and starts a new transaction"
743 def commit (self):
744 "Commits current transaction"
745 def rollback (self):
746 "Rolls back current transaction"
747\end{verbatim}
748
749The context needs the connection object so that the connection
750object's \method{commit()} or \method{rollback()} methods can be
751called:
752
753\begin{verbatim}
754class DatabaseContext:
755 def __init__ (self, connection):
756 self.connection = connection
757\end{verbatim}
758
759The \method {__enter__()} method is pretty easy, having only
760to start a new transaction. In this example,
761the resulting cursor object would be a useful result,
762so the method will return it. The user can
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000763then add \code{as cursor} to their '\keyword{with}' statement
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000764to bind the cursor to a variable name.
765
766\begin{verbatim}
767class DatabaseContext:
768 ...
769 def __enter__ (self):
770 # Code to start a new transaction
771 cursor = self.connection.cursor()
772 return cursor
773\end{verbatim}
774
775The \method{__exit__()} method is the most complicated because it's
776where most of the work has to be done. The method has to check if an
777exception occurred. If there was no exception, the transaction is
778committed. The transaction is rolled back if there was an exception.
779Here the code will just fall off the end of the function, returning
780the default value of \code{None}. \code{None} is false, so the exception
781will be re-raised automatically. If you wished, you could be more explicit
782and add a \keyword{return} at the marked location.
783
784\begin{verbatim}
785class DatabaseContext:
786 ...
787 def __exit__ (self, type, value, tb):
788 if tb is None:
789 # No exception, so commit
790 self.connection.commit()
791 else:
792 # Exception occurred, so rollback.
793 self.connection.rollback()
794 # return False
795\end{verbatim}
796
797
798\subsection{The contextlib module\label{module-contextlib}}
799
800The new \module{contextlib} module provides some functions and a
801decorator that are useful for writing context managers.
802
803The decorator is called \function{contextmanager}, and lets you write
804a simple context manager as a generator. The generator should yield
805exactly one value. The code up to the \keyword{yield} will be
806executed as the \method{__enter__()} method, and the value yielded
807will be the method's return value that will get bound to the variable
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000808in the '\keyword{with}' statement's \keyword{as} clause, if any. The
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000809code after the \keyword{yield} will be executed in the
810\method{__exit__()} method. Any exception raised in the block
811will be raised by the \keyword{yield} statement.
812
813Our database example from the previous section could be written
814using this decorator as:
815
816\begin{verbatim}
817from contextlib import contextmanager
818
819@contextmanager
820def db_transaction (connection):
821 cursor = connection.cursor()
822 try:
823 yield cursor
824 except:
825 connection.rollback()
826 raise
827 else:
828 connection.commit()
829
830db = DatabaseConnection()
831with db_transaction(db) as cursor:
832 ...
833\end{verbatim}
834
835You can also use this decorator to write the \method{__context__()} method
836for a class without creating a new class for the context:
837
838\begin{verbatim}
839class DatabaseConnection:
840
841 @contextmanager
842 def __context__ (self):
843 cursor = self.cursor()
844 try:
845 yield cursor
846 except:
847 self.rollback()
848 raise
849 else:
850 self.commit()
851\end{verbatim}
852
853
854There's a \function{nested(\var{mgr1}, \var{mgr2}, ...)} manager that
855combines a number of context managers so you don't need to write
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000856nested '\keyword{with}' statements. This example statement does two
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000857things, starting a database transaction and acquiring a thread lock:
858
859\begin{verbatim}
860lock = threading.Lock()
861with nested (db_transaction(db), lock) as (cursor, locked):
862 ...
863\end{verbatim}
864
865Finally, the \function{closing(\var{object})} context manager
866returns \var{object} so that it can be bound to a variable,
867and calls \code{\var{object}.close()} at the end of the block.
868
869\begin{verbatim}
870import urllib, sys
871from contextlib import closing
872
873with closing(urllib.urlopen('http://www.yahoo.com')) as f:
874 for line in f:
875 sys.stdout.write(line)
876\end{verbatim}
877
878\begin{seealso}
879
880\seepep{343}{The ``with'' statement}{PEP written by Guido van~Rossum
881and Nick Coghlan; implemented by Mike Bland, Guido van~Rossum, and
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000882Neal Norwitz. The PEP shows the code generated for a '\keyword{with}'
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000883statement, which can be helpful in learning how context managers
884work.}
885
886\seeurl{../lib/module-contextlib.html}{The documentation
887for the \module{contextlib} module.}
888
889\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000890
891
892%======================================================================
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000893\section{PEP 352: Exceptions as New-Style Classes\label{pep-352}}
Andrew M. Kuchling8f4d2552006-03-08 01:50:20 +0000894
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000895Exception classes can now be new-style classes, not just classic
896classes, and the built-in \exception{Exception} class and all the
897standard built-in exceptions (\exception{NameError},
898\exception{ValueError}, etc.) are now new-style classes.
Andrew M. Kuchlingaeadf952006-03-09 19:06:05 +0000899
900The inheritance hierarchy for exceptions has been rearranged a bit.
901In 2.5, the inheritance relationships are:
902
903\begin{verbatim}
904BaseException # New in Python 2.5
905|- KeyboardInterrupt
906|- SystemExit
907|- Exception
908 |- (all other current built-in exceptions)
909\end{verbatim}
910
911This rearrangement was done because people often want to catch all
912exceptions that indicate program errors. \exception{KeyboardInterrupt} and
913\exception{SystemExit} aren't errors, though, and usually represent an explicit
914action such as the user hitting Control-C or code calling
915\function{sys.exit()}. A bare \code{except:} will catch all exceptions,
916so you commonly need to list \exception{KeyboardInterrupt} and
917\exception{SystemExit} in order to re-raise them. The usual pattern is:
918
919\begin{verbatim}
920try:
921 ...
922except (KeyboardInterrupt, SystemExit):
923 raise
924except:
925 # Log error...
926 # Continue running program...
927\end{verbatim}
928
929In Python 2.5, you can now write \code{except Exception} to achieve
930the same result, catching all the exceptions that usually indicate errors
931but leaving \exception{KeyboardInterrupt} and
932\exception{SystemExit} alone. As in previous versions,
933a bare \code{except:} still catches all exceptions.
934
935The goal for Python 3.0 is to require any class raised as an exception
936to derive from \exception{BaseException} or some descendant of
937\exception{BaseException}, and future releases in the
938Python 2.x series may begin to enforce this constraint. Therefore, I
939suggest you begin making all your exception classes derive from
940\exception{Exception} now. It's been suggested that the bare
941\code{except:} form should be removed in Python 3.0, but Guido van~Rossum
942hasn't decided whether to do this or not.
943
944Raising of strings as exceptions, as in the statement \code{raise
945"Error occurred"}, is deprecated in Python 2.5 and will trigger a
946warning. The aim is to be able to remove the string-exception feature
947in a few releases.
948
949
950\begin{seealso}
951
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000952\seepep{352}{Required Superclass for Exceptions}{PEP written by
953Brett Cannon and Guido van~Rossum; implemented by Brett Cannon.}
954
955\end{seealso}
956
957
958%======================================================================
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000959\section{PEP 353: Using ssize_t as the index type\label{pep-353}}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000960
961A wide-ranging change to Python's C API, using a new
962\ctype{Py_ssize_t} type definition instead of \ctype{int},
963will permit the interpreter to handle more data on 64-bit platforms.
964This change doesn't affect Python's capacity on 32-bit platforms.
965
966Various pieces of the Python interpreter used C's \ctype{int} type to
967store sizes or counts; for example, the number of items in a list or
968tuple were stored in an \ctype{int}. The C compilers for most 64-bit
969platforms still define \ctype{int} as a 32-bit type, so that meant
970that lists could only hold up to \code{2**31 - 1} = 2147483647 items.
971(There are actually a few different programming models that 64-bit C
972compilers can use -- see
973\url{http://www.unix.org/version2/whatsnew/lp64_wp.html} for a
974discussion -- but the most commonly available model leaves \ctype{int}
975as 32 bits.)
976
977A limit of 2147483647 items doesn't really matter on a 32-bit platform
978because you'll run out of memory before hitting the length limit.
979Each list item requires space for a pointer, which is 4 bytes, plus
980space for a \ctype{PyObject} representing the item. 2147483647*4 is
981already more bytes than a 32-bit address space can contain.
982
983It's possible to address that much memory on a 64-bit platform,
984however. The pointers for a list that size would only require 16GiB
985of space, so it's not unreasonable that Python programmers might
986construct lists that large. Therefore, the Python interpreter had to
987be changed to use some type other than \ctype{int}, and this will be a
98864-bit type on 64-bit platforms. The change will cause
989incompatibilities on 64-bit machines, so it was deemed worth making
990the transition now, while the number of 64-bit users is still
991relatively small. (In 5 or 10 years, we may \emph{all} be on 64-bit
992machines, and the transition would be more painful then.)
993
994This change most strongly affects authors of C extension modules.
995Python strings and container types such as lists and tuples
996now use \ctype{Py_ssize_t} to store their size.
997Functions such as \cfunction{PyList_Size()}
998now return \ctype{Py_ssize_t}. Code in extension modules
999may therefore need to have some variables changed to
1000\ctype{Py_ssize_t}.
1001
1002The \cfunction{PyArg_ParseTuple()} and \cfunction{Py_BuildValue()} functions
1003have a new conversion code, \samp{n}, for \ctype{Py_ssize_t}.
1004\cfunction{PyArg_ParseTuple()}'s \samp{s\#} and \samp{t\#} still output
1005\ctype{int} by default, but you can define the macro
1006\csimplemacro{PY_SSIZE_T_CLEAN} before including \file{Python.h}
1007to make them return \ctype{Py_ssize_t}.
1008
1009\pep{353} has a section on conversion guidelines that
1010extension authors should read to learn about supporting 64-bit
1011platforms.
1012
1013\begin{seealso}
1014
1015\seepep{353}{Using ssize_t as the index type}{PEP written and implemented by Martin von~L\"owis.}
Andrew M. Kuchlingaeadf952006-03-09 19:06:05 +00001016
1017\end{seealso}
Andrew M. Kuchling8f4d2552006-03-08 01:50:20 +00001018
1019
1020%======================================================================
Thomas Woutersd4ec0c32006-04-21 16:44:05 +00001021\section{PEP 357: The '__index__' method\label{pep-357}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +00001022
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001023The NumPy developers had a problem that could only be solved by adding
1024a new special method, \method{__index__}. When using slice notation,
1025as in \code{[\var{start}:\var{stop}:\var{step}]}, the values of the
1026\var{start}, \var{stop}, and \var{step} indexes must all be either
1027integers or long integers. NumPy defines a variety of specialized
1028integer types corresponding to unsigned and signed integers of 8, 16,
102932, and 64 bits, but there was no way to signal that these types could
1030be used as slice indexes.
1031
1032Slicing can't just use the existing \method{__int__} method because
1033that method is also used to implement coercion to integers. If
1034slicing used \method{__int__}, floating-point numbers would also
1035become legal slice indexes and that's clearly an undesirable
1036behaviour.
1037
1038Instead, a new special method called \method{__index__} was added. It
1039takes no arguments and returns an integer giving the slice index to
1040use. For example:
1041
1042\begin{verbatim}
1043class C:
1044 def __index__ (self):
1045 return self.value
1046\end{verbatim}
1047
1048The return value must be either a Python integer or long integer.
1049The interpreter will check that the type returned is correct, and
1050raises a \exception{TypeError} if this requirement isn't met.
1051
1052A corresponding \member{nb_index} slot was added to the C-level
1053\ctype{PyNumberMethods} structure to let C extensions implement this
1054protocol. \cfunction{PyNumber_Index(\var{obj})} can be used in
1055extension code to call the \method{__index__} function and retrieve
1056its result.
1057
1058\begin{seealso}
1059
1060\seepep{357}{Allowing Any Object to be Used for Slicing}{PEP written
1061and implemented by Travis Oliphant.}
1062
1063\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +00001064
1065
1066%======================================================================
Fred Drake2db76802004-12-01 05:05:47 +00001067\section{Other Language Changes}
1068
1069Here are all of the changes that Python 2.5 makes to the core Python
1070language.
1071
1072\begin{itemize}
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001073
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001074\item The \class{dict} type has a new hook for letting subclasses
1075provide a default value when a key isn't contained in the dictionary.
1076When a key isn't found, the dictionary's
1077\method{__missing__(\var{key})}
1078method will be called. This hook is used to implement
1079the new \class{defaultdict} class in the \module{collections}
1080module. The following example defines a dictionary
1081that returns zero for any missing key:
1082
1083\begin{verbatim}
1084class zerodict (dict):
1085 def __missing__ (self, key):
1086 return 0
1087
1088d = zerodict({1:1, 2:2})
1089print d[1], d[2] # Prints 1, 2
1090print d[3], d[4] # Prints 0, 0
1091\end{verbatim}
1092
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001093\item The \function{min()} and \function{max()} built-in functions
Thomas Woutersd4ec0c32006-04-21 16:44:05 +00001094gained a \code{key} keyword parameter analogous to the \code{key}
1095argument for \method{sort()}. This parameter supplies a function that
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001096takes a single argument and is called for every value in the list;
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001097\function{min()}/\function{max()} will return the element with the
1098smallest/largest return value from this function.
1099For example, to find the longest string in a list, you can do:
1100
1101\begin{verbatim}
1102L = ['medium', 'longest', 'short']
1103# Prints 'longest'
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001104print max(L, key=len)
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001105# Prints 'short', because lexicographically 'short' has the largest value
1106print max(L)
1107\end{verbatim}
1108
1109(Contributed by Steven Bethard and Raymond Hettinger.)
Fred Drake2db76802004-12-01 05:05:47 +00001110
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001111\item Two new built-in functions, \function{any()} and
1112\function{all()}, evaluate whether an iterator contains any true or
1113false values. \function{any()} returns \constant{True} if any value
1114returned by the iterator is true; otherwise it will return
1115\constant{False}. \function{all()} returns \constant{True} only if
1116all of the values returned by the iterator evaluate as being true.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001117(Suggested by GvR, and implemented by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001118
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001119\item ASCII is now the default encoding for modules. It's now
1120a syntax error if a module contains string literals with 8-bit
1121characters but doesn't have an encoding declaration. In Python 2.4
1122this triggered a warning, not a syntax error. See \pep{263}
1123for how to declare a module's encoding; for example, you might add
1124a line like this near the top of the source file:
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001125
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001126\begin{verbatim}
1127# -*- coding: latin1 -*-
1128\end{verbatim}
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001129
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001130\item The list of base classes in a class definition can now be empty.
1131As an example, this is now legal:
1132
1133\begin{verbatim}
1134class C():
1135 pass
1136\end{verbatim}
1137(Implemented by Brett Cannon.)
1138
Fred Drake2db76802004-12-01 05:05:47 +00001139\end{itemize}
1140
1141
1142%======================================================================
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001143\subsection{Interactive Interpreter Changes}
1144
1145In the interactive interpreter, \code{quit} and \code{exit}
1146have long been strings so that new users get a somewhat helpful message
1147when they try to quit:
1148
1149\begin{verbatim}
1150>>> quit
1151'Use Ctrl-D (i.e. EOF) to exit.'
1152\end{verbatim}
1153
1154In Python 2.5, \code{quit} and \code{exit} are now objects that still
1155produce string representations of themselves, but are also callable.
1156Newbies who try \code{quit()} or \code{exit()} will now exit the
1157interpreter as they expect. (Implemented by Georg Brandl.)
1158
1159
1160%======================================================================
Fred Drake2db76802004-12-01 05:05:47 +00001161\subsection{Optimizations}
1162
1163\begin{itemize}
1164
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001165\item When they were introduced
1166in Python 2.4, the built-in \class{set} and \class{frozenset} types
1167were built on top of Python's dictionary type.
1168In 2.5 the internal data structure has been customized for implementing sets,
1169and as a result sets will use a third less memory and are somewhat faster.
1170(Implemented by Raymond Hettinger.)
Fred Drake2db76802004-12-01 05:05:47 +00001171
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001172\item The performance of some Unicode operations, such as
1173character map decoding, has been improved.
1174% Patch 1313939
1175
1176\item The code generator's peephole optimizer now performs
1177simple constant folding in expressions. If you write something like
1178\code{a = 2+3}, the code generator will do the arithmetic and produce
1179code corresponding to \code{a = 5}.
1180
Fred Drake2db76802004-12-01 05:05:47 +00001181\end{itemize}
1182
1183The net result of the 2.5 optimizations is that Python 2.5 runs the
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001184pystone benchmark around XXX\% faster than Python 2.4.
Fred Drake2db76802004-12-01 05:05:47 +00001185
1186
1187%======================================================================
Thomas Woutersd4ec0c32006-04-21 16:44:05 +00001188\section{New, Improved, and Removed Modules}
Fred Drake2db76802004-12-01 05:05:47 +00001189
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001190The standard library received many enhancements and bug fixes in
1191Python 2.5. Here's a partial list of the most notable changes, sorted
1192alphabetically by module name. Consult the \file{Misc/NEWS} file in
1193the source tree for a more complete list of changes, or look through
1194the SVN logs for all the details.
Fred Drake2db76802004-12-01 05:05:47 +00001195
1196\begin{itemize}
1197
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001198\item The \module{audioop} module now supports the a-LAW encoding,
1199and the code for u-LAW encoding has been improved. (Contributed by
1200Lars Immisch.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001201
Thomas Woutersd4ec0c32006-04-21 16:44:05 +00001202\item The \module{codecs} module gained support for incremental
1203codecs. The \function{codec.lookup()} function now
1204returns a \class{CodecInfo} instance instead of a tuple.
1205\class{CodecInfo} instances behave like a 4-tuple to preserve backward
1206compatibility but also have the attributes \member{encode},
1207\member{decode}, \member{incrementalencoder}, \member{incrementaldecoder},
1208\member{streamwriter}, and \member{streamreader}. Incremental codecs
1209can receive input and produce output in multiple chunks; the output is
1210the same as if the entire input was fed to the non-incremental codec.
1211See the \module{codecs} module documentation for details.
1212(Designed and implemented by Walter D\"orwald.)
1213% Patch 1436130
1214
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001215\item The \module{collections} module gained a new type,
1216\class{defaultdict}, that subclasses the standard \class{dict}
1217type. The new type mostly behaves like a dictionary but constructs a
1218default value when a key isn't present, automatically adding it to the
1219dictionary for the requested key value.
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001220
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001221The first argument to \class{defaultdict}'s constructor is a factory
1222function that gets called whenever a key is requested but not found.
1223This factory function receives no arguments, so you can use built-in
1224type constructors such as \function{list()} or \function{int()}. For
1225example,
1226you can make an index of words based on their initial letter like this:
1227
1228\begin{verbatim}
1229words = """Nel mezzo del cammin di nostra vita
1230mi ritrovai per una selva oscura
1231che la diritta via era smarrita""".lower().split()
1232
1233index = defaultdict(list)
1234
1235for w in words:
1236 init_letter = w[0]
1237 index[init_letter].append(w)
1238\end{verbatim}
1239
1240Printing \code{index} results in the following output:
1241
1242\begin{verbatim}
1243defaultdict(<type 'list'>, {'c': ['cammin', 'che'], 'e': ['era'],
1244 'd': ['del', 'di', 'diritta'], 'm': ['mezzo', 'mi'],
1245 'l': ['la'], 'o': ['oscura'], 'n': ['nel', 'nostra'],
1246 'p': ['per'], 's': ['selva', 'smarrita'],
1247 'r': ['ritrovai'], 'u': ['una'], 'v': ['vita', 'via']}
1248\end{verbatim}
1249
1250The \class{deque} double-ended queue type supplied by the
1251\module{collections} module now has a \method{remove(\var{value})}
1252method that removes the first occurrence of \var{value} in the queue,
1253raising \exception{ValueError} if the value isn't found.
1254
1255\item New module: The \module{contextlib} module contains helper functions for use
Thomas Woutersd4ec0c32006-04-21 16:44:05 +00001256with the new '\keyword{with}' statement. See
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001257section~\ref{module-contextlib} for more about this module.
1258(Contributed by Phillip J. Eby.)
1259
1260\item New module: The \module{cProfile} module is a C implementation of
1261the existing \module{profile} module that has much lower overhead.
1262The module's interface is the same as \module{profile}: you run
1263\code{cProfile.run('main()')} to profile a function, can save profile
1264data to a file, etc. It's not yet known if the Hotshot profiler,
1265which is also written in C but doesn't match the \module{profile}
1266module's interface, will continue to be maintained in future versions
1267of Python. (Contributed by Armin Rigo.)
1268
Thomas Woutersd4ec0c32006-04-21 16:44:05 +00001269Also, the \module{pstats} module used to analyze the data measured by
1270the profiler now supports directing the output to any file stream
1271by supplying a \var{stream} argument to the \class{Stats} constructor.
1272(Contributed by Skip Montanaro.)
1273
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001274\item The \module{csv} module, which parses files in
1275comma-separated value format, received several enhancements and a
1276number of bugfixes. You can now set the maximum size in bytes of a
1277field by calling the \method{csv.field_size_limit(\var{new_limit})}
1278function; omitting the \var{new_limit} argument will return the
1279currently-set limit. The \class{reader} class now has a
1280\member{line_num} attribute that counts the number of physical lines
1281read from the source; records can span multiple physical lines, so
1282\member{line_num} is not the same as the number of records read.
1283(Contributed by Skip Montanaro and Andrew McNamara.)
1284
1285\item The \class{datetime} class in the \module{datetime}
1286module now has a \method{strptime(\var{string}, \var{format})}
1287method for parsing date strings, contributed by Josh Spoerri.
1288It uses the same format characters as \function{time.strptime()} and
1289\function{time.strftime()}:
1290
1291\begin{verbatim}
1292from datetime import datetime
1293
1294ts = datetime.strptime('10:13:15 2006-03-07',
1295 '%H:%M:%S %Y-%m-%d')
1296\end{verbatim}
1297
1298\item The \module{fileinput} module was made more flexible.
1299Unicode filenames are now supported, and a \var{mode} parameter that
1300defaults to \code{"r"} was added to the
1301\function{input()} function to allow opening files in binary or
1302universal-newline mode. Another new parameter, \var{openhook},
1303lets you use a function other than \function{open()}
1304to open the input files. Once you're iterating over
1305the set of files, the \class{FileInput} object's new
1306\method{fileno()} returns the file descriptor for the currently opened file.
1307(Contributed by Georg Brandl.)
1308
1309\item In the \module{gc} module, the new \function{get_count()} function
1310returns a 3-tuple containing the current collection counts for the
1311three GC generations. This is accounting information for the garbage
1312collector; when these counts reach a specified threshold, a garbage
1313collection sweep will be made. The existing \function{gc.collect()}
1314function now takes an optional \var{generation} argument of 0, 1, or 2
1315to specify which generation to collect.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001316
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001317\item The \function{nsmallest()} and
1318\function{nlargest()} functions in the \module{heapq} module
Thomas Woutersd4ec0c32006-04-21 16:44:05 +00001319now support a \code{key} keyword parameter similar to the one
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001320provided by the \function{min()}/\function{max()} functions
1321and the \method{sort()} methods. For example:
1322Example:
1323
1324\begin{verbatim}
1325>>> import heapq
1326>>> L = ["short", 'medium', 'longest', 'longer still']
1327>>> heapq.nsmallest(2, L) # Return two lowest elements, lexicographically
1328['longer still', 'longest']
1329>>> heapq.nsmallest(2, L, key=len) # Return two shortest elements
1330['short', 'medium']
1331\end{verbatim}
1332
1333(Contributed by Raymond Hettinger.)
1334
Andrew M. Kuchling511a3a82005-03-20 19:52:18 +00001335\item The \function{itertools.islice()} function now accepts
1336\code{None} for the start and step arguments. This makes it more
1337compatible with the attributes of slice objects, so that you can now write
1338the following:
1339
1340\begin{verbatim}
1341s = slice(5) # Create slice object
1342itertools.islice(iterable, s.start, s.stop, s.step)
1343\end{verbatim}
1344
1345(Contributed by Raymond Hettinger.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001346
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001347\item The \module{nis} module now supports accessing domains other
1348than the system default domain by supplying a \var{domain} argument to
1349the \function{nis.match()} and \function{nis.maps()} functions.
1350(Contributed by Ben Bell.)
1351
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001352\item The \module{operator} module's \function{itemgetter()}
1353and \function{attrgetter()} functions now support multiple fields.
1354A call such as \code{operator.attrgetter('a', 'b')}
1355will return a function
1356that retrieves the \member{a} and \member{b} attributes. Combining
1357this new feature with the \method{sort()} method's \code{key} parameter
1358lets you easily sort lists using multiple fields.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001359(Contributed by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001360
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001361
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001362\item The \module{os} module underwent several changes. The
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001363\member{stat_float_times} variable now defaults to true, meaning that
1364\function{os.stat()} will now return time values as floats. (This
1365doesn't necessarily mean that \function{os.stat()} will return times
1366that are precise to fractions of a second; not all systems support
1367such precision.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001368
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001369Constants named \member{os.SEEK_SET}, \member{os.SEEK_CUR}, and
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001370\member{os.SEEK_END} have been added; these are the parameters to the
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001371\function{os.lseek()} function. Two new constants for locking are
1372\member{os.O_SHLOCK} and \member{os.O_EXLOCK}.
1373
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001374Two new functions, \function{wait3()} and \function{wait4()}, were
1375added. They're similar the \function{waitpid()} function which waits
1376for a child process to exit and returns a tuple of the process ID and
1377its exit status, but \function{wait3()} and \function{wait4()} return
1378additional information. \function{wait3()} doesn't take a process ID
1379as input, so it waits for any child process to exit and returns a
13803-tuple of \var{process-id}, \var{exit-status}, \var{resource-usage}
1381as returned from the \function{resource.getrusage()} function.
1382\function{wait4(\var{pid})} does take a process ID.
1383(Contributed by Chad J. Schroeder.)
1384
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001385On FreeBSD, the \function{os.stat()} function now returns
1386times with nanosecond resolution, and the returned object
1387now has \member{st_gen} and \member{st_birthtime}.
1388The \member{st_flags} member is also available, if the platform supports it.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001389(Contributed by Antti Louko and Diego Petten\`o.)
1390% (Patch 1180695, 1212117)
1391
Thomas Woutersd4ec0c32006-04-21 16:44:05 +00001392\item The \module{pickle} and \module{cPickle} modules no
1393longer accept a return value of \code{None} from the
1394\method{__reduce__()} method; the method must return a tuple of
1395arguments instead. The ability to return \code{None} was deprecated
1396in Python 2.4, so this completes the removal of the feature.
1397
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001398\item The old \module{regex} and \module{regsub} modules, which have been
1399deprecated ever since Python 2.0, have finally been deleted.
1400Other deleted modules: \module{statcache}, \module{tzparse},
1401\module{whrandom}.
1402
Thomas Woutersd4ec0c32006-04-21 16:44:05 +00001403\item Also deleted: the \file{lib-old} directory,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001404which includes ancient modules such as \module{dircmp} and
Thomas Woutersd4ec0c32006-04-21 16:44:05 +00001405\module{ni}, was removed. \file{lib-old} wasn't on the default
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001406\code{sys.path}, so unless your programs explicitly added the directory to
1407\code{sys.path}, this removal shouldn't affect your code.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001408
Andrew M. Kuchling4678dc82006-01-15 16:11:28 +00001409\item The \module{socket} module now supports \constant{AF_NETLINK}
1410sockets on Linux, thanks to a patch from Philippe Biondi.
1411Netlink sockets are a Linux-specific mechanism for communications
1412between a user-space process and kernel code; an introductory
1413article about them is at \url{http://www.linuxjournal.com/article/7356}.
1414In Python code, netlink addresses are represented as a tuple of 2 integers,
1415\code{(\var{pid}, \var{group_mask})}.
1416
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001417Socket objects also gained accessor methods \method{getfamily()},
1418\method{gettype()}, and \method{getproto()} methods to retrieve the
1419family, type, and protocol values for the socket.
1420
1421\item New module: the \module{spwd} module provides functions for
1422accessing the shadow password database on systems that support
1423shadow passwords.
1424
1425\item The Python developers switched from CVS to Subversion during the 2.5
1426development process. Information about the exact build version is
1427available as the \code{sys.subversion} variable, a 3-tuple
1428of \code{(\var{interpreter-name}, \var{branch-name}, \var{revision-range})}.
1429For example, at the time of writing
1430my copy of 2.5 was reporting \code{('CPython', 'trunk', '45313:45315')}.
1431
1432This information is also available to C extensions via the
1433\cfunction{Py_GetBuildInfo()} function that returns a
1434string of build information like this:
1435\code{"trunk:45355:45356M, Apr 13 2006, 07:42:19"}.
1436(Contributed by Barry Warsaw.)
Fred Drake2db76802004-12-01 05:05:47 +00001437
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001438\item The \class{TarFile} class in the \module{tarfile} module now has
Georg Brandl08c02db2005-07-22 18:39:19 +00001439an \method{extractall()} method that extracts all members from the
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001440archive into the current working directory. It's also possible to set
1441a different directory as the extraction target, and to unpack only a
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001442subset of the archive's members.
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001443
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001444A tarfile's compression can be autodetected by
1445using the mode \code{'r|*'}.
1446% patch 918101
1447(Contributed by Lars Gust\"abel.)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001448
Andrew M. Kuchlingf688cc52006-03-10 18:50:08 +00001449\item The \module{unicodedata} module has been updated to use version 4.1.0
1450of the Unicode character database. Version 3.2.0 is required
1451by some specifications, so it's still available as
1452\member{unicodedata.db_3_2_0}.
1453
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001454\item The \module{webbrowser} module received a number of
1455enhancements.
1456It's now usable as a script with \code{python -m webbrowser}, taking a
1457URL as the argument; there are a number of switches
1458to control the behaviour (\programopt{-n} for a new browser window,
1459\programopt{-t} for a new tab). New module-level functions,
1460\function{open_new()} and \function{open_new_tab()}, were added
1461to support this. The module's \function{open()} function supports an
1462additional feature, an \var{autoraise} parameter that signals whether
1463to raise the open window when possible. A number of additional
1464browsers were added to the supported list such as Firefox, Opera,
1465Konqueror, and elinks. (Contributed by Oleg Broytmann and George
1466Brandl.)
1467% Patch #754022
1468
Fredrik Lundh7e0aef02005-12-12 18:54:55 +00001469
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001470\item The \module{xmlrpclib} module now supports returning
1471 \class{datetime} objects for the XML-RPC date type. Supply
1472 \code{use_datetime=True} to the \function{loads()} function
1473 or the \class{Unmarshaller} class to enable this feature.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001474 (Contributed by Skip Montanaro.)
1475% Patch 1120353
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001476
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001477
Fred Drake114b8ca2005-03-21 05:47:11 +00001478\end{itemize}
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001479
Fred Drake2db76802004-12-01 05:05:47 +00001480
1481
1482%======================================================================
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001483\subsection{The ctypes package}
Fred Drake2db76802004-12-01 05:05:47 +00001484
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001485The \module{ctypes} package, written by Thomas Heller, has been added
1486to the standard library. \module{ctypes} lets you call arbitrary functions
1487in shared libraries or DLLs. Long-time users may remember the \module{dl} module, which
1488provides functions for loading shared libraries and calling functions in them. The \module{ctypes} package is much fancier.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001489
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001490To load a shared library or DLL, you must create an instance of the
1491\class{CDLL} class and provide the name or path of the shared library
1492or DLL. Once that's done, you can call arbitrary functions
1493by accessing them as attributes of the \class{CDLL} object.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001494
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001495\begin{verbatim}
1496import ctypes
1497
1498libc = ctypes.CDLL('libc.so.6')
1499result = libc.printf("Line of output\n")
1500\end{verbatim}
1501
1502Type constructors for the various C types are provided: \function{c_int},
1503\function{c_float}, \function{c_double}, \function{c_char_p} (equivalent to \ctype{char *}), and so forth. Unlike Python's types, the C versions are all mutable; you can assign to their \member{value} attribute
1504to change the wrapped value. Python integers and strings will be automatically
1505converted to the corresponding C types, but for other types you
1506must call the correct type constructor. (And I mean \emph{must};
1507getting it wrong will often result in the interpreter crashing
1508with a segmentation fault.)
1509
1510You shouldn't use \function{c_char_p} with a Python string when the C function will be modifying the memory area, because Python strings are
1511supposed to be immutable; breaking this rule will cause puzzling bugs. When you need a modifiable memory area,
1512use \function{create_string_buffer()}:
1513
1514\begin{verbatim}
1515s = "this is a string"
1516buf = ctypes.create_string_buffer(s)
1517libc.strfry(buf)
1518\end{verbatim}
1519
1520C functions are assumed to return integers, but you can set
1521the \member{restype} attribute of the function object to
1522change this:
1523
1524\begin{verbatim}
1525>>> libc.atof('2.71828')
1526-1783957616
1527>>> libc.atof.restype = ctypes.c_double
1528>>> libc.atof('2.71828')
15292.71828
1530\end{verbatim}
1531
1532\module{ctypes} also provides a wrapper for Python's C API
1533as the \code{ctypes.pythonapi} object. This object does \emph{not}
1534release the global interpreter lock before calling a function, because the lock must be held when calling into the interpreter's code.
1535There's a \class{py_object()} type constructor that will create a
1536\ctype{PyObject *} pointer. A simple usage:
1537
1538\begin{verbatim}
1539import ctypes
1540
1541d = {}
1542ctypes.pythonapi.PyObject_SetItem(ctypes.py_object(d),
1543 ctypes.py_object("abc"), ctypes.py_object(1))
1544# d is now {'abc', 1}.
1545\end{verbatim}
1546
1547Don't forget to use \class{py_object()}; if it's omitted you end
1548up with a segmentation fault.
1549
1550\module{ctypes} has been around for a while, but people still write
1551and distribution hand-coded extension modules because you can't rely on \module{ctypes} being present.
1552Perhaps developers will begin to write
1553Python wrappers atop a library accessed through \module{ctypes} instead
1554of extension modules, now that \module{ctypes} is included with core Python.
1555
1556\begin{seealso}
1557
1558\seeurl{http://starship.python.net/crew/theller/ctypes/}
1559{The ctypes web page, with a tutorial, reference, and FAQ.}
1560
1561\end{seealso}
1562
1563
1564%======================================================================
1565\subsection{The ElementTree package}
1566
1567A subset of Fredrik Lundh's ElementTree library for processing XML has
1568been added to the standard library as \module{xmlcore.etree}. The
1569available modules are
1570\module{ElementTree}, \module{ElementPath}, and
1571\module{ElementInclude} from ElementTree 1.2.6.
1572The \module{cElementTree} accelerator module is also included.
1573
1574The rest of this section will provide a brief overview of using
1575ElementTree. Full documentation for ElementTree is available at
1576\url{http://effbot.org/zone/element-index.htm}.
1577
1578ElementTree represents an XML document as a tree of element nodes.
1579The text content of the document is stored as the \member{.text}
1580and \member{.tail} attributes of
1581(This is one of the major differences between ElementTree and
1582the Document Object Model; in the DOM there are many different
1583types of node, including \class{TextNode}.)
1584
1585The most commonly used parsing function is \function{parse()}, that
1586takes either a string (assumed to contain a filename) or a file-like
1587object and returns an \class{ElementTree} instance:
1588
1589\begin{verbatim}
1590from xmlcore.etree import ElementTree as ET
1591
1592tree = ET.parse('ex-1.xml')
1593
1594feed = urllib.urlopen(
1595 'http://planet.python.org/rss10.xml')
1596tree = ET.parse(feed)
1597\end{verbatim}
1598
1599Once you have an \class{ElementTree} instance, you
1600can call its \method{getroot()} method to get the root \class{Element} node.
1601
1602There's also an \function{XML()} function that takes a string literal
1603and returns an \class{Element} node (not an \class{ElementTree}).
1604This function provides a tidy way to incorporate XML fragments,
1605approaching the convenience of an XML literal:
1606
1607\begin{verbatim}
1608svg = et.XML("""<svg width="10px" version="1.0">
1609 </svg>""")
1610svg.set('height', '320px')
1611svg.append(elem1)
1612\end{verbatim}
1613
1614Each XML element supports some dictionary-like and some list-like
1615access methods. Dictionary-like operations are used to access attribute
1616values, and list-like operations are used to access child nodes.
1617
1618\begin{tableii}{c|l}{code}{Operation}{Result}
1619 \lineii{elem[n]}{Returns n'th child element.}
1620 \lineii{elem[m:n]}{Returns list of m'th through n'th child elements.}
1621 \lineii{len(elem)}{Returns number of child elements.}
1622 \lineii{elem.getchildren()}{Returns list of child elements.}
1623 \lineii{elem.append(elem2)}{Adds \var{elem2} as a child.}
1624 \lineii{elem.insert(index, elem2)}{Inserts \var{elem2} at the specified location.}
1625 \lineii{del elem[n]}{Deletes n'th child element.}
1626 \lineii{elem.keys()}{Returns list of attribute names.}
1627 \lineii{elem.get(name)}{Returns value of attribute \var{name}.}
1628 \lineii{elem.set(name, value)}{Sets new value for attribute \var{name}.}
1629 \lineii{elem.attrib}{Retrieves the dictionary containing attributes.}
1630 \lineii{del elem.attrib[name]}{Deletes attribute \var{name}.}
1631\end{tableii}
1632
1633Comments and processing instructions are also represented as
1634\class{Element} nodes. To check if a node is a comment or processing
1635instructions:
1636
1637\begin{verbatim}
1638if elem.tag is ET.Comment:
1639 ...
1640elif elem.tag is ET.ProcessingInstruction:
1641 ...
1642\end{verbatim}
1643
1644To generate XML output, you should call the
1645\method{ElementTree.write()} method. Like \function{parse()},
1646it can take either a string or a file-like object:
1647
1648\begin{verbatim}
1649# Encoding is US-ASCII
1650tree.write('output.xml')
1651
1652# Encoding is UTF-8
1653f = open('output.xml', 'w')
1654tree.write(f, 'utf-8')
1655\end{verbatim}
1656
1657(Caution: the default encoding used for output is ASCII, which isn't
1658very useful for general XML work, raising an exception if there are
1659any characters with values greater than 127. You should always
1660specify a different encoding such as UTF-8 that can handle any Unicode
1661character.)
1662
1663This section is only a partial description of the ElementTree interfaces.
1664Please read the package's official documentation for more details.
1665
1666\begin{seealso}
1667
1668\seeurl{http://effbot.org/zone/element-index.htm}
1669{Official documentation for ElementTree.}
1670
1671
1672\end{seealso}
1673
1674
1675%======================================================================
1676\subsection{The hashlib package}
1677
1678A new \module{hashlib} module, written by Gregory P. Smith,
1679has been added to replace the
1680\module{md5} and \module{sha} modules. \module{hashlib} adds support
1681for additional secure hashes (SHA-224, SHA-256, SHA-384, and SHA-512).
1682When available, the module uses OpenSSL for fast platform optimized
1683implementations of algorithms.
1684
1685The old \module{md5} and \module{sha} modules still exist as wrappers
1686around hashlib to preserve backwards compatibility. The new module's
1687interface is very close to that of the old modules, but not identical.
1688The most significant difference is that the constructor functions
1689for creating new hashing objects are named differently.
1690
1691\begin{verbatim}
1692# Old versions
1693h = md5.md5()
1694h = md5.new()
1695
1696# New version
1697h = hashlib.md5()
1698
1699# Old versions
1700h = sha.sha()
1701h = sha.new()
1702
1703# New version
1704h = hashlib.sha1()
1705
1706# Hash that weren't previously available
1707h = hashlib.sha224()
1708h = hashlib.sha256()
1709h = hashlib.sha384()
1710h = hashlib.sha512()
1711
1712# Alternative form
1713h = hashlib.new('md5') # Provide algorithm as a string
1714\end{verbatim}
1715
1716Once a hash object has been created, its methods are the same as before:
1717\method{update(\var{string})} hashes the specified string into the
1718current digest state, \method{digest()} and \method{hexdigest()}
1719return the digest value as a binary string or a string of hex digits,
1720and \method{copy()} returns a new hashing object with the same digest state.
1721
1722
1723%======================================================================
1724\subsection{The sqlite3 package}
1725
1726The pysqlite module (\url{http://www.pysqlite.org}), a wrapper for the
1727SQLite embedded database, has been added to the standard library under
1728the package name \module{sqlite3}.
1729
1730SQLite is a C library that provides a SQL-language database that
1731stores data in disk files without requiring a separate server process.
1732pysqlite was written by Gerhard H\"aring and provides a SQL interface
1733compliant with the DB-API 2.0 specification described by
1734\pep{249}. This means that it should be possible to write the first
1735version of your applications using SQLite for data storage. If
1736switching to a larger database such as PostgreSQL or Oracle is
1737later necessary, the switch should be relatively easy.
1738
1739If you're compiling the Python source yourself, note that the source
1740tree doesn't include the SQLite code, only the wrapper module.
1741You'll need to have the SQLite libraries and headers installed before
1742compiling Python, and the build process will compile the module when
1743the necessary headers are available.
1744
1745To use the module, you must first create a \class{Connection} object
1746that represents the database. Here the data will be stored in the
1747\file{/tmp/example} file:
1748
1749\begin{verbatim}
1750conn = sqlite3.connect('/tmp/example')
1751\end{verbatim}
1752
1753You can also supply the special name \samp{:memory:} to create
1754a database in RAM.
1755
1756Once you have a \class{Connection}, you can create a \class{Cursor}
1757object and call its \method{execute()} method to perform SQL commands:
1758
1759\begin{verbatim}
1760c = conn.cursor()
1761
1762# Create table
1763c.execute('''create table stocks
1764(date timestamp, trans varchar, symbol varchar,
1765 qty decimal, price decimal)''')
1766
1767# Insert a row of data
1768c.execute("""insert into stocks
1769 values ('2006-01-05','BUY','RHAT',100,35.14)""")
1770\end{verbatim}
1771
1772Usually your SQL operations will need to use values from Python
1773variables. You shouldn't assemble your query using Python's string
1774operations because doing so is insecure; it makes your program
1775vulnerable to an SQL injection attack.
1776
1777Instead, use SQLite's parameter substitution. Put \samp{?} as a
1778placeholder wherever you want to use a value, and then provide a tuple
1779of values as the second argument to the cursor's \method{execute()}
1780method. For example:
1781
1782\begin{verbatim}
1783# Never do this -- insecure!
1784symbol = 'IBM'
1785c.execute("... where symbol = '%s'" % symbol)
1786
1787# Do this instead
1788t = (symbol,)
1789c.execute('select * from stocks where symbol=?', ('IBM',))
1790
1791# Larger example
1792for t in (('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
1793 ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
1794 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
1795 ):
1796 c.execute('insert into stocks values (?,?,?,?,?)', t)
1797\end{verbatim}
1798
1799To retrieve data after executing a SELECT statement, you can either
1800treat the cursor as an iterator, call the cursor's \method{fetchone()}
1801method to retrieve a single matching row,
1802or call \method{fetchall()} to get a list of the matching rows.
1803
1804This example uses the iterator form:
1805
1806\begin{verbatim}
1807>>> c = conn.cursor()
1808>>> c.execute('select * from stocks order by price')
1809>>> for row in c:
1810... print row
1811...
1812(u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001)
1813(u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
1814(u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
1815(u'2006-04-05', u'BUY', u'MSOFT', 1000, 72.0)
1816>>>
1817\end{verbatim}
1818
1819For more information about the SQL dialect supported by SQLite, see
1820\url{http://www.sqlite.org}.
1821
1822\begin{seealso}
1823
1824\seeurl{http://www.pysqlite.org}
1825{The pysqlite web page.}
1826
1827\seeurl{http://www.sqlite.org}
1828{The SQLite web page; the documentation describes the syntax and the
1829available data types for the supported SQL dialect.}
1830
1831\seepep{249}{Database API Specification 2.0}{PEP written by
1832Marc-Andr\'e Lemburg.}
1833
1834\end{seealso}
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001835
Fred Drake2db76802004-12-01 05:05:47 +00001836
1837% ======================================================================
1838\section{Build and C API Changes}
1839
1840Changes to Python's build process and to the C API include:
1841
1842\begin{itemize}
1843
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001844\item The largest change to the C API came from \pep{353},
1845which modifies the interpreter to use a \ctype{Py_ssize_t} type
1846definition instead of \ctype{int}. See the earlier
Thomas Woutersd4ec0c32006-04-21 16:44:05 +00001847section~\ref{pep-353} for a discussion of this change.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001848
1849\item The design of the bytecode compiler has changed a great deal, to
1850no longer generate bytecode by traversing the parse tree. Instead
Andrew M. Kuchlingdb85ed52005-10-23 21:52:59 +00001851the parse tree is converted to an abstract syntax tree (or AST), and it is
1852the abstract syntax tree that's traversed to produce the bytecode.
1853
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001854It's possible for Python code to obtain AST objects by using the
1855\function{compile()} built-in and specifying \code{_ast.PyCF_ONLY_AST}
1856as the value of the
1857\var{flags} parameter:
1858
1859\begin{verbatim}
1860from _ast import PyCF_ONLY_AST
1861ast = compile("""a=0
1862for i in range(10):
1863 a += i
1864""", "<string>", 'exec', PyCF_ONLY_AST)
1865
1866assignment = ast.body[0]
1867for_loop = ast.body[1]
1868\end{verbatim}
1869
Andrew M. Kuchlingdb85ed52005-10-23 21:52:59 +00001870No documentation has been written for the AST code yet. To start
1871learning about it, read the definition of the various AST nodes in
1872\file{Parser/Python.asdl}. A Python script reads this file and
1873generates a set of C structure definitions in
1874\file{Include/Python-ast.h}. The \cfunction{PyParser_ASTFromString()}
1875and \cfunction{PyParser_ASTFromFile()}, defined in
1876\file{Include/pythonrun.h}, take Python source as input and return the
1877root of an AST representing the contents. This AST can then be turned
1878into a code object by \cfunction{PyAST_Compile()}. For more
1879information, read the source code, and then ask questions on
1880python-dev.
1881
1882% List of names taken from Jeremy's python-dev post at
1883% http://mail.python.org/pipermail/python-dev/2005-October/057500.html
1884The AST code was developed under Jeremy Hylton's management, and
1885implemented by (in alphabetical order) Brett Cannon, Nick Coghlan,
1886Grant Edwards, John Ehresman, Kurt Kaiser, Neal Norwitz, Tim Peters,
1887Armin Rigo, and Neil Schemenauer, plus the participants in a number of
1888AST sprints at conferences such as PyCon.
1889
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001890\item The built-in set types now have an official C API. Call
1891\cfunction{PySet_New()} and \cfunction{PyFrozenSet_New()} to create a
1892new set, \cfunction{PySet_Add()} and \cfunction{PySet_Discard()} to
1893add and remove elements, and \cfunction{PySet_Contains} and
1894\cfunction{PySet_Size} to examine the set's state.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001895(Contributed by Raymond Hettinger.)
1896
1897\item C code can now obtain information about the exact revision
1898of the Python interpreter by calling the
1899\cfunction{Py_GetBuildInfo()} function that returns a
1900string of build information like this:
1901\code{"trunk:45355:45356M, Apr 13 2006, 07:42:19"}.
1902(Contributed by Barry Warsaw.)
1903
1904\item The CPython interpreter is still written in C, but
1905the code can now be compiled with a {\Cpp} compiler without errors.
1906(Implemented by Anthony Baxter, Martin von~L\"owis, Skip Montanaro.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001907
1908\item The \cfunction{PyRange_New()} function was removed. It was
1909never documented, never used in the core code, and had dangerously lax
1910error checking.
Fred Drake2db76802004-12-01 05:05:47 +00001911
1912\end{itemize}
1913
1914
1915%======================================================================
1916\subsection{Port-Specific Changes}
1917
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001918\begin{itemize}
1919
1920\item MacOS X (10.3 and higher): dynamic loading of modules
1921now uses the \cfunction{dlopen()} function instead of MacOS-specific
1922functions.
1923
1924\item Windows: \file{.dll} is no longer supported as a filename extension for
1925extension modules. \file{.pyd} is now the only filename extension that will
1926be searched for.
1927
1928\end{itemize}
Fred Drake2db76802004-12-01 05:05:47 +00001929
1930
1931%======================================================================
1932\section{Other Changes and Fixes \label{section-other}}
1933
1934As usual, there were a bunch of other improvements and bugfixes
Andrew M. Kuchlingf688cc52006-03-10 18:50:08 +00001935scattered throughout the source tree. A search through the SVN change
Fred Drake2db76802004-12-01 05:05:47 +00001936logs finds there were XXX patches applied and YYY bugs fixed between
Andrew M. Kuchling92e24952004-12-03 13:54:09 +00001937Python 2.4 and 2.5. Both figures are likely to be underestimates.
Fred Drake2db76802004-12-01 05:05:47 +00001938
1939Some of the more notable changes are:
1940
1941\begin{itemize}
1942
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001943\item Evan Jones's patch to obmalloc, first described in a talk
1944at PyCon DC 2005, was applied. Python 2.4 allocated small objects in
1945256K-sized arenas, but never freed arenas. With this patch, Python
1946will free arenas when they're empty. The net effect is that on some
1947platforms, when you allocate many objects, Python's memory usage may
1948actually drop when you delete them, and the memory may be returned to
1949the operating system. (Implemented by Evan Jones, and reworked by Tim
1950Peters.)
1951
1952Note that this change means extension modules need to be more careful
1953with how they allocate memory. Python's API has many different
1954functions for allocating memory that are grouped into families. For
1955example, \cfunction{PyMem_Malloc()}, \cfunction{PyMem_Realloc()}, and
1956\cfunction{PyMem_Free()} are one family that allocates raw memory,
1957while \cfunction{PyObject_Malloc()}, \cfunction{PyObject_Realloc()},
1958and \cfunction{PyObject_Free()} are another family that's supposed to
1959be used for creating Python objects.
1960
1961Previously these different families all reduced to the platform's
1962\cfunction{malloc()} and \cfunction{free()} functions. This meant
1963it didn't matter if you got things wrong and allocated memory with the
1964\cfunction{PyMem} function but freed it with the \cfunction{PyObject}
1965function. With the obmalloc change, these families now do different
1966things, and mismatches will probably result in a segfault. You should
1967carefully test your C extension modules with Python 2.5.
1968
1969\item Coverity, a company that markets a source code analysis tool
1970 called Prevent, provided the results of their examination of the Python
1971 source code. The analysis found about 60 bugs that
1972 were quickly fixed. Many of the bugs were refcounting problems, often
1973 occurring in error-handling code. See
1974 \url{http://scan.coverity.com} for the statistics.
Fred Drake2db76802004-12-01 05:05:47 +00001975
1976\end{itemize}
1977
1978
1979%======================================================================
1980\section{Porting to Python 2.5}
1981
1982This section lists previously described changes that may require
1983changes to your code:
1984
1985\begin{itemize}
1986
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001987\item ASCII is now the default encoding for modules. It's now
1988a syntax error if a module contains string literals with 8-bit
1989characters but doesn't have an encoding declaration. In Python 2.4
1990this triggered a warning, not a syntax error.
Andrew M. Kuchling0c35db92005-03-20 20:06:49 +00001991
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001992\item Previously, the \member{gi_frame} attribute of a generator
1993was always a frame object. Because of the \pep{342} changes
Thomas Woutersd4ec0c32006-04-21 16:44:05 +00001994described in section~\ref{pep-342}, it's now possible
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001995for \member{gi_frame} to be \code{None}.
Andrew M. Kuchling0c35db92005-03-20 20:06:49 +00001996
Thomas Woutersd4ec0c32006-04-21 16:44:05 +00001997
1998\item Library: The \module{pickle} and \module{cPickle} modules no
1999longer accept a return value of \code{None} from the
2000\method{__reduce__()} method; the method must return a tuple of
2001arguments instead. The modules also no longer accept the deprecated
2002\var{bin} keyword parameter.
2003
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002004\item C API: Many functions now use \ctype{Py_ssize_t}
Thomas Woutersd4ec0c32006-04-21 16:44:05 +00002005instead of \ctype{int} to allow processing more data on 64-bit
2006machines. Extension code may need to make the same change to avoid
2007warnings and to support 64-bit machines. See the earlier
2008section~\ref{pep-353} for a discussion of this change.
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00002009
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002010\item C API:
2011The obmalloc changes mean that
2012you must be careful to not mix usage
2013of the \cfunction{PyMem_*()} and \cfunction{PyObject_*()}
2014families of functions. Memory allocated with
2015one family's \cfunction{*_Malloc()} must be
2016freed with the corresponding family's \cfunction{*_Free()} function.
Fred Drake2db76802004-12-01 05:05:47 +00002017
2018\end{itemize}
2019
2020
2021%======================================================================
2022\section{Acknowledgements \label{acks}}
2023
2024The author would like to thank the following people for offering
2025suggestions, corrections and assistance with various drafts of this
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002026article: Phillip J. Eby, Kent Johnson, Martin von~L\"owis, Gustavo
2027Niemeyer, Mike Rovner, Thomas Wouters.
Fred Drake2db76802004-12-01 05:05:47 +00002028
2029\end{document}