blob: 337332a5c5188280dac36adc9c319084330cf8fb [file] [log] [blame]
Fred Drake2db76802004-12-01 05:05:47 +00001\documentclass{howto}
2\usepackage{distutils}
3% $Id$
4
Andrew M. Kuchling952f1962006-04-18 12:38:19 +00005% Describe the pkgutil module
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00006% Fix XXX comments
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00007% Count up the patches and bugs
Fred Drake2db76802004-12-01 05:05:47 +00008
9\title{What's New in Python 2.5}
Andrew M. Kuchling99714cf2006-04-27 12:23:07 +000010\release{0.2}
Andrew M. Kuchling92e24952004-12-03 13:54:09 +000011\author{A.M. Kuchling}
12\authoraddress{\email{amk@amk.ca}}
Fred Drake2db76802004-12-01 05:05:47 +000013
14\begin{document}
15\maketitle
16\tableofcontents
17
18This article explains the new features in Python 2.5. No release date
Andrew M. Kuchling5eefdca2006-02-08 11:36:09 +000019for Python 2.5 has been set; it will probably be released in the
Andrew M. Kuchlingd96a6ac2006-04-04 19:17:34 +000020autumn of 2006. \pep{356} describes the planned release schedule.
Fred Drake2db76802004-12-01 05:05:47 +000021
Andrew M. Kuchling0d660c02006-04-17 14:01:36 +000022Comments, suggestions, and error reports are welcome; please e-mail them
23to the author or open a bug in the Python bug tracker.
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +000024
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000025% XXX Compare with previous release in 2 - 3 sentences here.
Fred Drake2db76802004-12-01 05:05:47 +000026
27This article doesn't attempt to provide a complete specification of
28the new features, but instead provides a convenient overview. For
29full details, you should refer to the documentation for Python 2.5.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000030% XXX add hyperlink when the documentation becomes available online.
Fred Drake2db76802004-12-01 05:05:47 +000031If you want to understand the complete implementation and design
32rationale, refer to the PEP for a particular new feature.
33
34
35%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +000036\section{PEP 243: Uploading Modules to PyPI\label{pep-243}}
Andrew M. Kuchling6a67e4e2006-04-12 13:03:35 +000037
38PEP 243 describes an HTTP-based protocol for submitting software
39packages to a central archive. The Python package index at
40\url{http://cheeseshop.python.org} now supports package uploads, and
41the new \command{upload} Distutils command will upload a package to the
42repository.
43
44Before a package can be uploaded, you must be able to build a
45distribution using the \command{sdist} Distutils command. Once that
46works, you can run \code{python setup.py upload} to add your package
47to the PyPI archive. Optionally you can GPG-sign the package by
George Yoshida297bf822006-04-17 15:44:59 +000048supplying the \longprogramopt{sign} and
49\longprogramopt{identity} options.
Andrew M. Kuchling6a67e4e2006-04-12 13:03:35 +000050
51\begin{seealso}
52
53\seepep{243}{Module Repository Upload Mechanism}{PEP written by
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +000054Sean Reifschneider; implemented by Martin von~L\"owis
Andrew M. Kuchling6a67e4e2006-04-12 13:03:35 +000055and Richard Jones. Note that the PEP doesn't exactly
56describe what's implemented in PyPI.}
57
58\end{seealso}
59
60
61%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +000062\section{PEP 308: Conditional Expressions\label{pep-308}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000063
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000064For a long time, people have been requesting a way to write
65conditional expressions, expressions that return value A or value B
66depending on whether a Boolean value is true or false. A conditional
67expression lets you write a single assignment statement that has the
68same effect as the following:
69
70\begin{verbatim}
71if condition:
72 x = true_value
73else:
74 x = false_value
75\end{verbatim}
76
77There have been endless tedious discussions of syntax on both
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +000078python-dev and comp.lang.python. A vote was even held that found the
79majority of voters wanted conditional expressions in some form,
80but there was no syntax that was preferred by a clear majority.
81Candidates included C's \code{cond ? true_v : false_v},
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000082\code{if cond then true_v else false_v}, and 16 other variations.
83
84GvR eventually chose a surprising syntax:
85
86\begin{verbatim}
87x = true_value if condition else false_value
88\end{verbatim}
89
Andrew M. Kuchling38f85072006-04-02 01:46:32 +000090Evaluation is still lazy as in existing Boolean expressions, so the
91order of evaluation jumps around a bit. The \var{condition}
92expression in the middle is evaluated first, and the \var{true_value}
93expression is evaluated only if the condition was true. Similarly,
94the \var{false_value} expression is only evaluated when the condition
95is false.
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000096
97This syntax may seem strange and backwards; why does the condition go
98in the \emph{middle} of the expression, and not in the front as in C's
99\code{c ? x : y}? The decision was checked by applying the new syntax
100to the modules in the standard library and seeing how the resulting
101code read. In many cases where a conditional expression is used, one
102value seems to be the 'common case' and one value is an 'exceptional
103case', used only on rarer occasions when the condition isn't met. The
104conditional syntax makes this pattern a bit more obvious:
105
106\begin{verbatim}
107contents = ((doc + '\n') if doc else '')
108\end{verbatim}
109
110I read the above statement as meaning ``here \var{contents} is
Andrew M. Kuchlingd0fcc022006-03-09 13:57:28 +0000111usually assigned a value of \code{doc+'\e n'}; sometimes
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +0000112\var{doc} is empty, in which special case an empty string is returned.''
113I doubt I will use conditional expressions very often where there
114isn't a clear common and uncommon case.
115
116There was some discussion of whether the language should require
117surrounding conditional expressions with parentheses. The decision
118was made to \emph{not} require parentheses in the Python language's
119grammar, but as a matter of style I think you should always use them.
120Consider these two statements:
121
122\begin{verbatim}
123# First version -- no parens
124level = 1 if logging else 0
125
126# Second version -- with parens
127level = (1 if logging else 0)
128\end{verbatim}
129
130In the first version, I think a reader's eye might group the statement
131into 'level = 1', 'if logging', 'else 0', and think that the condition
132decides whether the assignment to \var{level} is performed. The
133second version reads better, in my opinion, because it makes it clear
134that the assignment is always performed and the choice is being made
135between two values.
136
137Another reason for including the brackets: a few odd combinations of
138list comprehensions and lambdas could look like incorrect conditional
139expressions. See \pep{308} for some examples. If you put parentheses
140around your conditional expressions, you won't run into this case.
141
142
143\begin{seealso}
144
145\seepep{308}{Conditional Expressions}{PEP written by
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000146Guido van~Rossum and Raymond D. Hettinger; implemented by Thomas
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +0000147Wouters.}
148
149\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000150
151
152%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000153\section{PEP 309: Partial Function Application\label{pep-309}}
Fred Drake2db76802004-12-01 05:05:47 +0000154
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000155The \module{functional} module is intended to contain tools for
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000156functional-style programming. Currently it only contains a
157\class{partial()} function, but new functions will probably be added
158in future versions of Python.
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000159
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000160For programs written in a functional style, it can be useful to
161construct variants of existing functions that have some of the
162parameters filled in. Consider a Python function \code{f(a, b, c)};
163you could create a new function \code{g(b, c)} that was equivalent to
164\code{f(1, b, c)}. This is called ``partial function application'',
165and is provided by the \class{partial} class in the new
166\module{functional} module.
167
168The constructor for \class{partial} takes the arguments
169\code{(\var{function}, \var{arg1}, \var{arg2}, ...
170\var{kwarg1}=\var{value1}, \var{kwarg2}=\var{value2})}. The resulting
171object is callable, so you can just call it to invoke \var{function}
172with the filled-in arguments.
173
174Here's a small but realistic example:
175
176\begin{verbatim}
177import functional
178
179def log (message, subsystem):
180 "Write the contents of 'message' to the specified subsystem."
181 print '%s: %s' % (subsystem, message)
182 ...
183
184server_log = functional.partial(log, subsystem='server')
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000185server_log('Unable to open socket')
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000186\end{verbatim}
187
Andrew M. Kuchling6af7fe02005-08-02 17:20:36 +0000188Here's another example, from a program that uses PyGTk. Here a
189context-sensitive pop-up menu is being constructed dynamically. The
190callback provided for the menu option is a partially applied version
191of the \method{open_item()} method, where the first argument has been
192provided.
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000193
Andrew M. Kuchling6af7fe02005-08-02 17:20:36 +0000194\begin{verbatim}
195...
196class Application:
197 def open_item(self, path):
198 ...
199 def init (self):
200 open_func = functional.partial(self.open_item, item_path)
201 popup_menu.append( ("Open", open_func, 1) )
202\end{verbatim}
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000203
204
205\begin{seealso}
206
207\seepep{309}{Partial Function Application}{PEP proposed and written by
208Peter Harris; implemented by Hye-Shik Chang, with adaptations by
209Raymond Hettinger.}
210
211\end{seealso}
Fred Drake2db76802004-12-01 05:05:47 +0000212
213
214%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000215\section{PEP 314: Metadata for Python Software Packages v1.1\label{pep-314}}
Fred Drakedb7b0022005-03-20 22:19:47 +0000216
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000217Some simple dependency support was added to Distutils. The
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000218\function{setup()} function now has \code{requires}, \code{provides},
219and \code{obsoletes} keyword parameters. When you build a source
220distribution using the \code{sdist} command, the dependency
221information will be recorded in the \file{PKG-INFO} file.
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000222
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000223Another new keyword parameter is \code{download_url}, which should be
224set to a URL for the package's source code. This means it's now
225possible to look up an entry in the package index, determine the
226dependencies for a package, and download the required packages.
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000227
Andrew M. Kuchling61434b62006-04-13 11:51:07 +0000228\begin{verbatim}
229VERSION = '1.0'
230setup(name='PyPackage',
231 version=VERSION,
232 requires=['numarray', 'zlib (>=1.1.4)'],
233 obsoletes=['OldPackage']
234 download_url=('http://www.example.com/pypackage/dist/pkg-%s.tar.gz'
235 % VERSION),
236 )
237\end{verbatim}
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000238
239\begin{seealso}
240
241\seepep{314}{Metadata for Python Software Packages v1.1}{PEP proposed
242and written by A.M. Kuchling, Richard Jones, and Fred Drake;
243implemented by Richard Jones and Fred Drake.}
244
245\end{seealso}
Fred Drakedb7b0022005-03-20 22:19:47 +0000246
247
248%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000249\section{PEP 328: Absolute and Relative Imports\label{pep-328}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000250
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000251The simpler part of PEP 328 was implemented in Python 2.4: parentheses
252could now be used to enclose the names imported from a module using
253the \code{from ... import ...} statement, making it easier to import
254many different names.
255
256The more complicated part has been implemented in Python 2.5:
257importing a module can be specified to use absolute or
258package-relative imports. The plan is to move toward making absolute
259imports the default in future versions of Python.
260
261Let's say you have a package directory like this:
262\begin{verbatim}
263pkg/
264pkg/__init__.py
265pkg/main.py
266pkg/string.py
267\end{verbatim}
268
269This defines a package named \module{pkg} containing the
270\module{pkg.main} and \module{pkg.string} submodules.
271
272Consider the code in the \file{main.py} module. What happens if it
273executes the statement \code{import string}? In Python 2.4 and
274earlier, it will first look in the package's directory to perform a
275relative import, finds \file{pkg/string.py}, imports the contents of
276that file as the \module{pkg.string} module, and that module is bound
277to the name \samp{string} in the \module{pkg.main} module's namespace.
278
279That's fine if \module{pkg.string} was what you wanted. But what if
280you wanted Python's standard \module{string} module? There's no clean
281way to ignore \module{pkg.string} and look for the standard module;
282generally you had to look at the contents of \code{sys.modules}, which
283is slightly unclean.
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000284Holger Krekel's \module{py.std} package provides a tidier way to perform
285imports from the standard library, \code{import py ; py.std.string.join()},
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000286but that package isn't available on all Python installations.
287
288Reading code which relies on relative imports is also less clear,
289because a reader may be confused about which module, \module{string}
290or \module{pkg.string}, is intended to be used. Python users soon
291learned not to duplicate the names of standard library modules in the
292names of their packages' submodules, but you can't protect against
293having your submodule's name being used for a new module added in a
294future version of Python.
295
296In Python 2.5, you can switch \keyword{import}'s behaviour to
297absolute imports using a \code{from __future__ import absolute_import}
298directive. This absolute-import behaviour will become the default in
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000299a future version (probably Python 2.7). Once absolute imports
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000300are the default, \code{import string} will
301always find the standard library's version.
302It's suggested that users should begin using absolute imports as much
303as possible, so it's preferable to begin writing \code{from pkg import
304string} in your code.
305
306Relative imports are still possible by adding a leading period
307to the module name when using the \code{from ... import} form:
308
309\begin{verbatim}
310# Import names from pkg.string
311from .string import name1, name2
312# Import pkg.string
313from . import string
314\end{verbatim}
315
316This imports the \module{string} module relative to the current
317package, so in \module{pkg.main} this will import \var{name1} and
318\var{name2} from \module{pkg.string}. Additional leading periods
319perform the relative import starting from the parent of the current
320package. For example, code in the \module{A.B.C} module can do:
321
322\begin{verbatim}
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000323from . import D # Imports A.B.D
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000324from .. import E # Imports A.E
325from ..F import G # Imports A.F.G
326\end{verbatim}
327
328Leading periods cannot be used with the \code{import \var{modname}}
329form of the import statement, only the \code{from ... import} form.
330
331\begin{seealso}
332
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000333\seepep{328}{Imports: Multi-Line and Absolute/Relative}
334{PEP written by Aahz; implemented by Thomas Wouters.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000335
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000336\seeurl{http://codespeak.net/py/current/doc/index.html}
337{The py library by Holger Krekel, which contains the \module{py.std} package.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000338
339\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000340
341
342%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000343\section{PEP 338: Executing Modules as Scripts\label{pep-338}}
Andrew M. Kuchling21d3a7c2006-03-15 11:53:09 +0000344
Andrew M. Kuchlingb182db42006-03-17 21:48:46 +0000345The \programopt{-m} switch added in Python 2.4 to execute a module as
346a script gained a few more abilities. Instead of being implemented in
347C code inside the Python interpreter, the switch now uses an
348implementation in a new module, \module{runpy}.
349
350The \module{runpy} module implements a more sophisticated import
351mechanism so that it's now possible to run modules in a package such
352as \module{pychecker.checker}. The module also supports alternative
Andrew M. Kuchling5d4cf5e2006-04-13 13:02:42 +0000353import mechanisms such as the \module{zipimport} module. This means
Andrew M. Kuchlingb182db42006-03-17 21:48:46 +0000354you can add a .zip archive's path to \code{sys.path} and then use the
355\programopt{-m} switch to execute code from the archive.
356
357
358\begin{seealso}
359
360\seepep{338}{Executing modules as scripts}{PEP written and
361implemented by Nick Coghlan.}
362
363\end{seealso}
Andrew M. Kuchling21d3a7c2006-03-15 11:53:09 +0000364
365
366%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000367\section{PEP 341: Unified try/except/finally\label{pep-341}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000368
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000369Until Python 2.5, the \keyword{try} statement came in two
370flavours. You could use a \keyword{finally} block to ensure that code
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +0000371is always executed, or one or more \keyword{except} blocks to catch
372specific exceptions. You couldn't combine both \keyword{except} blocks and a
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000373\keyword{finally} block, because generating the right bytecode for the
374combined version was complicated and it wasn't clear what the
375semantics of the combined should be.
376
377GvR spent some time working with Java, which does support the
378equivalent of combining \keyword{except} blocks and a
379\keyword{finally} block, and this clarified what the statement should
380mean. In Python 2.5, you can now write:
381
382\begin{verbatim}
383try:
384 block-1 ...
385except Exception1:
386 handler-1 ...
387except Exception2:
388 handler-2 ...
389else:
390 else-block
391finally:
392 final-block
393\end{verbatim}
394
395The code in \var{block-1} is executed. If the code raises an
396exception, the handlers are tried in order: \var{handler-1},
397\var{handler-2}, ... If no exception is raised, the \var{else-block}
398is executed. No matter what happened previously, the
399\var{final-block} is executed once the code block is complete and any
400raised exceptions handled. Even if there's an error in an exception
401handler or the \var{else-block} and a new exception is raised, the
402\var{final-block} is still executed.
403
404\begin{seealso}
405
406\seepep{341}{Unifying try-except and try-finally}{PEP written by Georg Brandl;
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000407implementation by Thomas Lee.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000408
409\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000410
411
412%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000413\section{PEP 342: New Generator Features\label{pep-342}}
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000414
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000415Python 2.5 adds a simple way to pass values \emph{into} a generator.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000416As introduced in Python 2.3, generators only produce output; once a
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000417generator's code is invoked to create an iterator, there's no way to
418pass any new information into the function when its execution is
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000419resumed. Sometimes the ability to pass in some information would be
420useful. Hackish solutions to this include making the generator's code
421look at a global variable and then changing the global variable's
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000422value, or passing in some mutable object that callers then modify.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000423
424To refresh your memory of basic generators, here's a simple example:
425
426\begin{verbatim}
427def counter (maximum):
428 i = 0
429 while i < maximum:
430 yield i
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000431 i += 1
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000432\end{verbatim}
433
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000434When you call \code{counter(10)}, the result is an iterator that
435returns the values from 0 up to 9. On encountering the
436\keyword{yield} statement, the iterator returns the provided value and
437suspends the function's execution, preserving the local variables.
438Execution resumes on the following call to the iterator's
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000439\method{next()} method, picking up after the \keyword{yield} statement.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000440
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000441In Python 2.3, \keyword{yield} was a statement; it didn't return any
442value. In 2.5, \keyword{yield} is now an expression, returning a
443value that can be assigned to a variable or otherwise operated on:
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000444
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000445\begin{verbatim}
446val = (yield i)
447\end{verbatim}
448
449I recommend that you always put parentheses around a \keyword{yield}
450expression when you're doing something with the returned value, as in
451the above example. The parentheses aren't always necessary, but it's
452easier to always add them instead of having to remember when they're
Andrew M. Kuchling3b675d22006-04-20 13:43:21 +0000453needed.
454
455(\pep{342} explains the exact rules, which are that a
456\keyword{yield}-expression must always be parenthesized except when it
457occurs at the top-level expression on the right-hand side of an
458assignment. This means you can write \code{val = yield i} but have to
459use parentheses when there's an operation, as in \code{val = (yield i)
460+ 12}.)
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000461
462Values are sent into a generator by calling its
463\method{send(\var{value})} method. The generator's code is then
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000464resumed and the \keyword{yield} expression returns the specified
465\var{value}. If the regular \method{next()} method is called, the
466\keyword{yield} returns \constant{None}.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000467
468Here's the previous example, modified to allow changing the value of
469the internal counter.
470
471\begin{verbatim}
472def counter (maximum):
473 i = 0
474 while i < maximum:
475 val = (yield i)
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000476 # If value provided, change counter
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000477 if val is not None:
478 i = val
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000479 else:
480 i += 1
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000481\end{verbatim}
482
483And here's an example of changing the counter:
484
485\begin{verbatim}
486>>> it = counter(10)
487>>> print it.next()
4880
489>>> print it.next()
4901
491>>> print it.send(8)
4928
493>>> print it.next()
4949
495>>> print it.next()
496Traceback (most recent call last):
497 File ``t.py'', line 15, in ?
498 print it.next()
499StopIteration
Andrew M. Kuchlingc2033702005-08-29 13:30:12 +0000500\end{verbatim}
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000501
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000502Because \keyword{yield} will often be returning \constant{None}, you
503should always check for this case. Don't just use its value in
504expressions unless you're sure that the \method{send()} method
505will be the only method used resume your generator function.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000506
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000507In addition to \method{send()}, there are two other new methods on
508generators:
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000509
510\begin{itemize}
511
512 \item \method{throw(\var{type}, \var{value}=None,
513 \var{traceback}=None)} is used to raise an exception inside the
514 generator; the exception is raised by the \keyword{yield} expression
515 where the generator's execution is paused.
516
517 \item \method{close()} raises a new \exception{GeneratorExit}
518 exception inside the generator to terminate the iteration.
519 On receiving this
520 exception, the generator's code must either raise
521 \exception{GeneratorExit} or \exception{StopIteration}; catching the
522 exception and doing anything else is illegal and will trigger
523 a \exception{RuntimeError}. \method{close()} will also be called by
524 Python's garbage collection when the generator is garbage-collected.
525
526 If you need to run cleanup code in case of a \exception{GeneratorExit},
527 I suggest using a \code{try: ... finally:} suite instead of
528 catching \exception{GeneratorExit}.
529
530\end{itemize}
531
532The cumulative effect of these changes is to turn generators from
533one-way producers of information into both producers and consumers.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000534
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000535Generators also become \emph{coroutines}, a more generalized form of
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000536subroutines. Subroutines are entered at one point and exited at
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000537another point (the top of the function, and a \keyword{return
538statement}), but coroutines can be entered, exited, and resumed at
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000539many different points (the \keyword{yield} statements). We'll have to
540figure out patterns for using coroutines effectively in Python.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000541
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000542The addition of the \method{close()} method has one side effect that
543isn't obvious. \method{close()} is called when a generator is
544garbage-collected, so this means the generator's code gets one last
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +0000545chance to run before the generator is destroyed. This last chance
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000546means that \code{try...finally} statements in generators can now be
547guaranteed to work; the \keyword{finally} clause will now always get a
548chance to run. The syntactic restriction that you couldn't mix
549\keyword{yield} statements with a \code{try...finally} suite has
550therefore been removed. This seems like a minor bit of language
551trivia, but using generators and \code{try...finally} is actually
552necessary in order to implement the \keyword{with} statement
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000553described by PEP 343. I'll look at this new statement in the following
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000554section.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000555
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +0000556Another even more esoteric effect of this change: previously, the
557\member{gi_frame} attribute of a generator was always a frame object.
558It's now possible for \member{gi_frame} to be \code{None}
559once the generator has been exhausted.
560
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000561\begin{seealso}
562
563\seepep{342}{Coroutines via Enhanced Generators}{PEP written by
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000564Guido van~Rossum and Phillip J. Eby;
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000565implemented by Phillip J. Eby. Includes examples of
566some fancier uses of generators as coroutines.}
567
568\seeurl{http://en.wikipedia.org/wiki/Coroutine}{The Wikipedia entry for
569coroutines.}
570
Neal Norwitz09179882006-03-04 23:31:45 +0000571\seeurl{http://www.sidhe.org/\~{}dan/blog/archives/000178.html}{An
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000572explanation of coroutines from a Perl point of view, written by Dan
573Sugalski.}
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000574
575\end{seealso}
576
577
578%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000579\section{PEP 343: The 'with' statement\label{pep-343}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000580
Andrew M. Kuchling0a7ed8c2006-04-24 14:30:47 +0000581The '\keyword{with}' statement clarifies code that previously would
582use \code{try...finally} blocks to ensure that clean-up code is
583executed. In this section, I'll discuss the statement as it will
584commonly be used. In the next section, I'll examine the
585implementation details and show how to write objects for use with this
586statement.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000587
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +0000588The '\keyword{with}' statement is a new control-flow structure whose
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000589basic structure is:
590
591\begin{verbatim}
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000592with expression [as variable]:
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000593 with-block
594\end{verbatim}
595
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000596The expression is evaluated, and it should result in an object that
597supports the context management protocol. This object may return a
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000598value that can optionally be bound to the name \var{variable}. (Note
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000599carefully that \var{variable} is \emph{not} assigned the result of
600\var{expression}.) The object can then run set-up code
601before \var{with-block} is executed and some clean-up code
602is executed after the block is done, even if the block raised an exception.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000603
604To enable the statement in Python 2.5, you need
605to add the following directive to your module:
606
607\begin{verbatim}
608from __future__ import with_statement
609\end{verbatim}
610
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000611The statement will always be enabled in Python 2.6.
612
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000613Some standard Python objects now support the context management
614protocol and can be used with the '\keyword{with}' statement. File
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000615objects are one example:
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000616
617\begin{verbatim}
618with open('/etc/passwd', 'r') as f:
619 for line in f:
620 print line
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000621 ... more processing code ...
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000622\end{verbatim}
623
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000624After this statement has executed, the file object in \var{f} will
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +0000625have been automatically closed, even if the 'for' loop
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000626raised an exception part-way through the block.
627
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000628The \module{threading} module's locks and condition variables
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +0000629also support the '\keyword{with}' statement:
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000630
631\begin{verbatim}
632lock = threading.Lock()
633with lock:
634 # Critical section of code
635 ...
636\end{verbatim}
637
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000638The lock is acquired before the block is executed and always released once
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000639the block is complete.
640
641The \module{decimal} module's contexts, which encapsulate the desired
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000642precision and rounding characteristics for computations, also work.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000643
644\begin{verbatim}
645import decimal
646
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000647# Displays with default precision of 28 digits
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000648v1 = decimal.Decimal('578')
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000649print v1.sqrt()
650
651with decimal.Context(prec=16):
652 # All code in this block uses a precision of 16 digits.
653 # The original context is restored on exiting the block.
654 print v1.sqrt()
655\end{verbatim}
656
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000657\subsection{Writing Context Managers\label{context-managers}}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000658
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +0000659Under the hood, the '\keyword{with}' statement is fairly complicated.
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000660Most people will only use '\keyword{with}' in company with existing
Andrew M. Kuchling0a7ed8c2006-04-24 14:30:47 +0000661objects and don't need to know these details, so you can skip the rest
662of this section if you like. Authors of new objects will need to
663understand the details of the underlying implementation and should
664keep reading.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000665
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000666A high-level explanation of the context management protocol is:
667
668\begin{itemize}
669\item The expression is evaluated and should result in an object
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000670with a \method{__context__()} method (called a ``context manager'').
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000671
Andrew M. Kuchling0a7ed8c2006-04-24 14:30:47 +0000672\item The context specifier's \method{__context__()} method is called,
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000673and must return another object (called a ``with-statement context object'') that has
Andrew M. Kuchling0a7ed8c2006-04-24 14:30:47 +0000674\method{__enter__()} and \method{__exit__()} methods.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000675
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000676\item The context object's \method{__enter__()} method is called. The value
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000677returned is assigned to \var{VAR}. If no \code{'as \var{VAR}'} clause
678is present, the value is simply discarded.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000679
680\item The code in \var{BLOCK} is executed.
681
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000682\item If \var{BLOCK} raises an exception, the
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000683\method{__exit__(\var{type}, \var{value}, \var{traceback})} is called
684with the exception's information, the same values returned by
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000685\function{sys.exc_info()}. The method's return value controls whether
686the exception is re-raised: any false value re-raises the exception,
687and \code{True} will result in suppressing it. You'll only rarely
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000688want to suppress the exception, because if you do
689the author of the code containing the
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000690'\keyword{with}' statement will never realize anything went wrong.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000691
692\item If \var{BLOCK} didn't raise an exception,
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000693the \method{__exit__()} method is still called,
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000694but \var{type}, \var{value}, and \var{traceback} are all \code{None}.
695
696\end{itemize}
697
698Let's think through an example. I won't present detailed code but
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000699will only sketch the methods necessary for a database that supports
700transactions.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000701
702(For people unfamiliar with database terminology: a set of changes to
703the database are grouped into a transaction. Transactions can be
704either committed, meaning that all the changes are written into the
705database, or rolled back, meaning that the changes are all discarded
706and the database is unchanged. See any database textbook for more
707information.)
708% XXX find a shorter reference?
709
710Let's assume there's an object representing a database connection.
711Our goal will be to let the user write code like this:
712
713\begin{verbatim}
714db_connection = DatabaseConnection()
715with db_connection as cursor:
716 cursor.execute('insert into ...')
717 cursor.execute('delete from ...')
718 # ... more operations ...
719\end{verbatim}
720
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000721The transaction should be committed if the code in the block
722runs flawlessly or rolled back if there's an exception.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000723
724First, the \class{DatabaseConnection} needs a \method{__context__()}
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000725method. Sometimes an object can simply return \code{self}; the
726\module{threading} module's lock objects do this, for example. For
727our database example, though, we need to create a new object; I'll
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000728call this class \class{DatabaseContext}. Our \method{__context__()}
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000729method must therefore look like this:
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000730
731\begin{verbatim}
732class DatabaseConnection:
733 ...
734 def __context__ (self):
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000735 return DatabaseContext(self)
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000736
737 # Database interface
738 def cursor (self):
739 "Returns a cursor object and starts a new transaction"
740 def commit (self):
741 "Commits current transaction"
742 def rollback (self):
743 "Rolls back current transaction"
744\end{verbatim}
745
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000746Instances of \class{DatabaseContext} need the connection object so that
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000747the connection object's \method{commit()} or \method{rollback()}
748methods can be called:
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000749
750\begin{verbatim}
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000751class DatabaseContext:
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000752 def __init__ (self, connection):
753 self.connection = connection
754\end{verbatim}
755
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000756The \method {__enter__()} method is pretty easy, having only to start
757a new transaction. For this application the resulting cursor object
758would be a useful result, so the method will return it. The user can
759then add \code{as cursor} to their '\keyword{with}' statement to bind
760the cursor to a variable name.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000761
762\begin{verbatim}
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000763class DatabaseContext:
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000764 ...
765 def __enter__ (self):
766 # Code to start a new transaction
767 cursor = self.connection.cursor()
768 return cursor
769\end{verbatim}
770
771The \method{__exit__()} method is the most complicated because it's
772where most of the work has to be done. The method has to check if an
773exception occurred. If there was no exception, the transaction is
774committed. The transaction is rolled back if there was an exception.
Andrew M. Kuchling0a7ed8c2006-04-24 14:30:47 +0000775
776In the code below, execution will just fall off the end of the
777function, returning the default value of \code{None}. \code{None} is
778false, so the exception will be re-raised automatically. If you
779wished, you could be more explicit and add a \keyword{return}
780statement at the marked location.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000781
782\begin{verbatim}
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000783class DatabaseContext:
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000784 ...
785 def __exit__ (self, type, value, tb):
786 if tb is None:
787 # No exception, so commit
788 self.connection.commit()
789 else:
790 # Exception occurred, so rollback.
791 self.connection.rollback()
792 # return False
793\end{verbatim}
794
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000795
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000796\subsection{The contextlib module\label{module-contextlib}}
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000797
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000798The new \module{contextlib} module provides some functions and a
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000799decorator that are useful for writing objects for use with the
800'\keyword{with}' statement.
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000801
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000802The decorator is called \function{contextfactory}, and lets you write
803a single generator function instead of defining a new class. The generator
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000804should yield exactly one value. The code up to the \keyword{yield}
805will be executed as the \method{__enter__()} method, and the value
806yielded will be the method's return value that will get bound to the
807variable in the '\keyword{with}' statement's \keyword{as} clause, if
808any. The code after the \keyword{yield} will be executed in the
809\method{__exit__()} method. Any exception raised in the block will be
810raised by the \keyword{yield} statement.
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000811
812Our database example from the previous section could be written
813using this decorator as:
814
815\begin{verbatim}
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000816from contextlib import contextfactory
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000817
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000818@contextfactory
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000819def db_transaction (connection):
820 cursor = connection.cursor()
821 try:
822 yield cursor
823 except:
824 connection.rollback()
825 raise
826 else:
827 connection.commit()
828
829db = DatabaseConnection()
830with db_transaction(db) as cursor:
831 ...
832\end{verbatim}
833
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000834You can also use this decorator to write the \method{__context__()}
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000835method for a class:
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000836
837\begin{verbatim}
838class DatabaseConnection:
839
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000840 @contextfactory
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000841 def __context__ (self):
842 cursor = self.cursor()
843 try:
844 yield cursor
845 except:
846 self.rollback()
847 raise
848 else:
849 self.commit()
850\end{verbatim}
851
852
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000853The \module{contextlib} module also has a \function{nested(\var{mgr1},
854\var{mgr2}, ...)} function that combines a number of contexts so you
855don't need to write nested '\keyword{with}' statements. In this
856example, the single '\keyword{with}' statement both starts a database
857transaction and acquires a thread lock:
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000858
859\begin{verbatim}
860lock = threading.Lock()
861with nested (db_transaction(db), lock) as (cursor, locked):
862 ...
863\end{verbatim}
864
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000865Finally, the \function{closing(\var{object})} function
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000866returns \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}
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +0000870import urllib, sys
871from contextlib import closing
872
873with closing(urllib.urlopen('http://www.yahoo.com')) as f:
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000874 for line in f:
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +0000875 sys.stdout.write(line)
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000876\end{verbatim}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000877
878\begin{seealso}
879
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000880\seepep{343}{The ``with'' statement}{PEP written by Guido van~Rossum
881and Nick Coghlan; implemented by Mike Bland, Guido van~Rossum, and
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +0000882Neal Norwitz. The PEP shows the code generated for a '\keyword{with}'
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000883statement, which can be helpful in learning how the statement works.}
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000884
885\seeurl{../lib/module-contextlib.html}{The documentation
886for the \module{contextlib} module.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000887
888\end{seealso}
889
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000890
891%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000892\section{PEP 352: Exceptions as New-Style Classes\label{pep-352}}
Andrew M. Kuchling8f4d2552006-03-08 01:50:20 +0000893
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000894Exception classes can now be new-style classes, not just classic
895classes, and the built-in \exception{Exception} class and all the
896standard built-in exceptions (\exception{NameError},
897\exception{ValueError}, etc.) are now new-style classes.
Andrew M. Kuchlingaeadf952006-03-09 19:06:05 +0000898
899The inheritance hierarchy for exceptions has been rearranged a bit.
900In 2.5, the inheritance relationships are:
901
902\begin{verbatim}
903BaseException # New in Python 2.5
904|- KeyboardInterrupt
905|- SystemExit
906|- Exception
907 |- (all other current built-in exceptions)
908\end{verbatim}
909
910This rearrangement was done because people often want to catch all
911exceptions that indicate program errors. \exception{KeyboardInterrupt} and
912\exception{SystemExit} aren't errors, though, and usually represent an explicit
913action such as the user hitting Control-C or code calling
914\function{sys.exit()}. A bare \code{except:} will catch all exceptions,
915so you commonly need to list \exception{KeyboardInterrupt} and
916\exception{SystemExit} in order to re-raise them. The usual pattern is:
917
918\begin{verbatim}
919try:
920 ...
921except (KeyboardInterrupt, SystemExit):
922 raise
923except:
924 # Log error...
925 # Continue running program...
926\end{verbatim}
927
928In Python 2.5, you can now write \code{except Exception} to achieve
929the same result, catching all the exceptions that usually indicate errors
930but leaving \exception{KeyboardInterrupt} and
931\exception{SystemExit} alone. As in previous versions,
932a bare \code{except:} still catches all exceptions.
933
934The goal for Python 3.0 is to require any class raised as an exception
935to derive from \exception{BaseException} or some descendant of
936\exception{BaseException}, and future releases in the
937Python 2.x series may begin to enforce this constraint. Therefore, I
938suggest you begin making all your exception classes derive from
939\exception{Exception} now. It's been suggested that the bare
940\code{except:} form should be removed in Python 3.0, but Guido van~Rossum
941hasn't decided whether to do this or not.
942
943Raising of strings as exceptions, as in the statement \code{raise
944"Error occurred"}, is deprecated in Python 2.5 and will trigger a
945warning. The aim is to be able to remove the string-exception feature
946in a few releases.
947
948
949\begin{seealso}
950
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000951\seepep{352}{Required Superclass for Exceptions}{PEP written by
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000952Brett Cannon and Guido van~Rossum; implemented by Brett Cannon.}
Andrew M. Kuchlingaeadf952006-03-09 19:06:05 +0000953
954\end{seealso}
Andrew M. Kuchling8f4d2552006-03-08 01:50:20 +0000955
956
957%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000958\section{PEP 353: Using ssize_t as the index type\label{pep-353}}
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000959
960A wide-ranging change to Python's C API, using a new
961\ctype{Py_ssize_t} type definition instead of \ctype{int},
962will permit the interpreter to handle more data on 64-bit platforms.
963This change doesn't affect Python's capacity on 32-bit platforms.
964
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000965Various pieces of the Python interpreter used C's \ctype{int} type to
966store sizes or counts; for example, the number of items in a list or
967tuple were stored in an \ctype{int}. The C compilers for most 64-bit
968platforms still define \ctype{int} as a 32-bit type, so that meant
969that lists could only hold up to \code{2**31 - 1} = 2147483647 items.
970(There are actually a few different programming models that 64-bit C
971compilers can use -- see
972\url{http://www.unix.org/version2/whatsnew/lp64_wp.html} for a
973discussion -- but the most commonly available model leaves \ctype{int}
974as 32 bits.)
975
976A limit of 2147483647 items doesn't really matter on a 32-bit platform
977because you'll run out of memory before hitting the length limit.
978Each list item requires space for a pointer, which is 4 bytes, plus
979space for a \ctype{PyObject} representing the item. 2147483647*4 is
980already more bytes than a 32-bit address space can contain.
981
982It's possible to address that much memory on a 64-bit platform,
983however. The pointers for a list that size would only require 16GiB
984of space, so it's not unreasonable that Python programmers might
985construct lists that large. Therefore, the Python interpreter had to
986be changed to use some type other than \ctype{int}, and this will be a
98764-bit type on 64-bit platforms. The change will cause
988incompatibilities on 64-bit machines, so it was deemed worth making
989the transition now, while the number of 64-bit users is still
990relatively small. (In 5 or 10 years, we may \emph{all} be on 64-bit
991machines, and the transition would be more painful then.)
992
993This change most strongly affects authors of C extension modules.
994Python strings and container types such as lists and tuples
995now use \ctype{Py_ssize_t} to store their size.
996Functions such as \cfunction{PyList_Size()}
997now return \ctype{Py_ssize_t}. Code in extension modules
998may therefore need to have some variables changed to
999\ctype{Py_ssize_t}.
1000
1001The \cfunction{PyArg_ParseTuple()} and \cfunction{Py_BuildValue()} functions
1002have a new conversion code, \samp{n}, for \ctype{Py_ssize_t}.
Andrew M. Kuchlinga4d651f2006-04-06 13:24:58 +00001003\cfunction{PyArg_ParseTuple()}'s \samp{s\#} and \samp{t\#} still output
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00001004\ctype{int} by default, but you can define the macro
1005\csimplemacro{PY_SSIZE_T_CLEAN} before including \file{Python.h}
1006to make them return \ctype{Py_ssize_t}.
1007
1008\pep{353} has a section on conversion guidelines that
1009extension authors should read to learn about supporting 64-bit
1010platforms.
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +00001011
1012\begin{seealso}
1013
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001014\seepep{353}{Using ssize_t as the index type}{PEP written and implemented by Martin von~L\"owis.}
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +00001015
1016\end{seealso}
1017
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00001018
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +00001019%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +00001020\section{PEP 357: The '__index__' method\label{pep-357}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +00001021
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001022The NumPy developers had a problem that could only be solved by adding
1023a new special method, \method{__index__}. When using slice notation,
Fred Drake1c0e3282006-04-02 03:30:06 +00001024as in \code{[\var{start}:\var{stop}:\var{step}]}, the values of the
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001025\var{start}, \var{stop}, and \var{step} indexes must all be either
1026integers or long integers. NumPy defines a variety of specialized
1027integer types corresponding to unsigned and signed integers of 8, 16,
102832, and 64 bits, but there was no way to signal that these types could
1029be used as slice indexes.
1030
1031Slicing can't just use the existing \method{__int__} method because
1032that method is also used to implement coercion to integers. If
1033slicing used \method{__int__}, floating-point numbers would also
1034become legal slice indexes and that's clearly an undesirable
1035behaviour.
1036
1037Instead, a new special method called \method{__index__} was added. It
1038takes no arguments and returns an integer giving the slice index to
1039use. For example:
1040
1041\begin{verbatim}
1042class C:
1043 def __index__ (self):
1044 return self.value
1045\end{verbatim}
1046
1047The return value must be either a Python integer or long integer.
1048The interpreter will check that the type returned is correct, and
1049raises a \exception{TypeError} if this requirement isn't met.
1050
1051A corresponding \member{nb_index} slot was added to the C-level
1052\ctype{PyNumberMethods} structure to let C extensions implement this
1053protocol. \cfunction{PyNumber_Index(\var{obj})} can be used in
1054extension code to call the \method{__index__} function and retrieve
1055its result.
1056
1057\begin{seealso}
1058
1059\seepep{357}{Allowing Any Object to be Used for Slicing}{PEP written
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +00001060and implemented by Travis Oliphant.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001061
1062\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +00001063
1064
1065%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001066\section{Other Language Changes\label{other-lang}}
Fred Drake2db76802004-12-01 05:05:47 +00001067
1068Here are all of the changes that Python 2.5 makes to the core Python
1069language.
1070
1071\begin{itemize}
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001072
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001073\item The \class{dict} type has a new hook for letting subclasses
1074provide a default value when a key isn't contained in the dictionary.
1075When a key isn't found, the dictionary's
1076\method{__missing__(\var{key})}
1077method will be called. This hook is used to implement
1078the new \class{defaultdict} class in the \module{collections}
1079module. The following example defines a dictionary
1080that returns zero for any missing key:
1081
1082\begin{verbatim}
1083class zerodict (dict):
1084 def __missing__ (self, key):
1085 return 0
1086
1087d = zerodict({1:1, 2:2})
1088print d[1], d[2] # Prints 1, 2
1089print d[3], d[4] # Prints 0, 0
1090\end{verbatim}
1091
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001092\item The \function{min()} and \function{max()} built-in functions
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001093gained a \code{key} keyword parameter analogous to the \code{key}
1094argument for \method{sort()}. This parameter supplies a function that
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001095takes a single argument and is called for every value in the list;
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001096\function{min()}/\function{max()} will return the element with the
1097smallest/largest return value from this function.
1098For example, to find the longest string in a list, you can do:
1099
1100\begin{verbatim}
1101L = ['medium', 'longest', 'short']
1102# Prints 'longest'
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001103print max(L, key=len)
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001104# Prints 'short', because lexicographically 'short' has the largest value
1105print max(L)
1106\end{verbatim}
1107
1108(Contributed by Steven Bethard and Raymond Hettinger.)
Fred Drake2db76802004-12-01 05:05:47 +00001109
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001110\item Two new built-in functions, \function{any()} and
1111\function{all()}, evaluate whether an iterator contains any true or
1112false values. \function{any()} returns \constant{True} if any value
1113returned by the iterator is true; otherwise it will return
1114\constant{False}. \function{all()} returns \constant{True} only if
1115all of the values returned by the iterator evaluate as being true.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001116(Suggested by GvR, and implemented by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001117
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001118\item ASCII is now the default encoding for modules. It's now
1119a syntax error if a module contains string literals with 8-bit
1120characters but doesn't have an encoding declaration. In Python 2.4
1121this triggered a warning, not a syntax error. See \pep{263}
1122for how to declare a module's encoding; for example, you might add
1123a line like this near the top of the source file:
1124
1125\begin{verbatim}
1126# -*- coding: latin1 -*-
1127\end{verbatim}
1128
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001129\item The list of base classes in a class definition can now be empty.
1130As an example, this is now legal:
1131
1132\begin{verbatim}
1133class C():
1134 pass
1135\end{verbatim}
1136(Implemented by Brett Cannon.)
1137
Fred Drake2db76802004-12-01 05:05:47 +00001138\end{itemize}
1139
1140
1141%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001142\subsection{Interactive Interpreter Changes\label{interactive}}
Andrew M. Kuchlingda376042006-03-17 15:56:41 +00001143
1144In the interactive interpreter, \code{quit} and \code{exit}
1145have long been strings so that new users get a somewhat helpful message
1146when they try to quit:
1147
1148\begin{verbatim}
1149>>> quit
1150'Use Ctrl-D (i.e. EOF) to exit.'
1151\end{verbatim}
1152
1153In Python 2.5, \code{quit} and \code{exit} are now objects that still
1154produce string representations of themselves, but are also callable.
1155Newbies who try \code{quit()} or \code{exit()} will now exit the
1156interpreter as they expect. (Implemented by Georg Brandl.)
1157
1158
1159%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001160\subsection{Optimizations\label{opts}}
Fred Drake2db76802004-12-01 05:05:47 +00001161
1162\begin{itemize}
1163
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001164\item When they were introduced
1165in Python 2.4, the built-in \class{set} and \class{frozenset} types
1166were built on top of Python's dictionary type.
1167In 2.5 the internal data structure has been customized for implementing sets,
1168and as a result sets will use a third less memory and are somewhat faster.
1169(Implemented by Raymond Hettinger.)
Fred Drake2db76802004-12-01 05:05:47 +00001170
Andrew M. Kuchling45bb98e2006-04-16 19:53:27 +00001171\item The performance of some Unicode operations, such as
1172character map decoding, has been improved.
1173% Patch 1313939
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001174
1175\item The code generator's peephole optimizer now performs
1176simple constant folding in expressions. If you write something like
1177\code{a = 2+3}, the code generator will do the arithmetic and produce
1178code corresponding to \code{a = 5}.
1179
Fred Drake2db76802004-12-01 05:05:47 +00001180\end{itemize}
1181
1182The net result of the 2.5 optimizations is that Python 2.5 runs the
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +00001183pystone benchmark around XXX\% faster than Python 2.4.
Fred Drake2db76802004-12-01 05:05:47 +00001184
1185
1186%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001187\section{New, Improved, and Removed Modules\label{modules}}
Fred Drake2db76802004-12-01 05:05:47 +00001188
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +00001189The standard library received many enhancements and bug fixes in
1190Python 2.5. Here's a partial list of the most notable changes, sorted
1191alphabetically by module name. Consult the \file{Misc/NEWS} file in
1192the source tree for a more complete list of changes, or look through
1193the SVN logs for all the details.
Fred Drake2db76802004-12-01 05:05:47 +00001194
1195\begin{itemize}
1196
Andrew M. Kuchling6fc69762006-04-13 12:37:21 +00001197\item The \module{audioop} module now supports the a-LAW encoding,
1198and the code for u-LAW encoding has been improved. (Contributed by
1199Lars Immisch.)
1200
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001201\item The \module{codecs} module gained support for incremental
1202codecs. The \function{codec.lookup()} function now
1203returns a \class{CodecInfo} instance instead of a tuple.
1204\class{CodecInfo} instances behave like a 4-tuple to preserve backward
1205compatibility but also have the attributes \member{encode},
1206\member{decode}, \member{incrementalencoder}, \member{incrementaldecoder},
1207\member{streamwriter}, and \member{streamreader}. Incremental codecs
1208can receive input and produce output in multiple chunks; the output is
1209the same as if the entire input was fed to the non-incremental codec.
1210See the \module{codecs} module documentation for details.
1211(Designed and implemented by Walter D\"orwald.)
1212% Patch 1436130
1213
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001214\item The \module{collections} module gained a new type,
1215\class{defaultdict}, that subclasses the standard \class{dict}
1216type. The new type mostly behaves like a dictionary but constructs a
1217default value when a key isn't present, automatically adding it to the
1218dictionary for the requested key value.
1219
1220The first argument to \class{defaultdict}'s constructor is a factory
1221function that gets called whenever a key is requested but not found.
1222This factory function receives no arguments, so you can use built-in
1223type constructors such as \function{list()} or \function{int()}. For
1224example,
1225you can make an index of words based on their initial letter like this:
1226
1227\begin{verbatim}
1228words = """Nel mezzo del cammin di nostra vita
1229mi ritrovai per una selva oscura
1230che la diritta via era smarrita""".lower().split()
1231
1232index = defaultdict(list)
1233
1234for w in words:
1235 init_letter = w[0]
1236 index[init_letter].append(w)
1237\end{verbatim}
1238
1239Printing \code{index} results in the following output:
1240
1241\begin{verbatim}
1242defaultdict(<type 'list'>, {'c': ['cammin', 'che'], 'e': ['era'],
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001243 'd': ['del', 'di', 'diritta'], 'm': ['mezzo', 'mi'],
1244 'l': ['la'], 'o': ['oscura'], 'n': ['nel', 'nostra'],
1245 'p': ['per'], 's': ['selva', 'smarrita'],
1246 'r': ['ritrovai'], 'u': ['una'], 'v': ['vita', 'via']}
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001247\end{verbatim}
1248
1249The \class{deque} double-ended queue type supplied by the
1250\module{collections} module now has a \method{remove(\var{value})}
1251method that removes the first occurrence of \var{value} in the queue,
1252raising \exception{ValueError} if the value isn't found.
1253
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001254\item New module: The \module{contextlib} module contains helper functions for use
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001255with the new '\keyword{with}' statement. See
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001256section~\ref{module-contextlib} for more about this module.
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +00001257
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001258\item New module: The \module{cProfile} module is a C implementation of
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001259the existing \module{profile} module that has much lower overhead.
1260The module's interface is the same as \module{profile}: you run
1261\code{cProfile.run('main()')} to profile a function, can save profile
1262data to a file, etc. It's not yet known if the Hotshot profiler,
1263which is also written in C but doesn't match the \module{profile}
1264module's interface, will continue to be maintained in future versions
1265of Python. (Contributed by Armin Rigo.)
1266
Andrew M. Kuchling0a7ed8c2006-04-24 14:30:47 +00001267Also, the \module{pstats} module for analyzing the data measured by
1268the profiler now supports directing the output to any file object
Andrew M. Kuchlinge78eeb12006-04-21 13:26:42 +00001269by supplying a \var{stream} argument to the \class{Stats} constructor.
1270(Contributed by Skip Montanaro.)
1271
Andrew M. Kuchling952f1962006-04-18 12:38:19 +00001272\item The \module{csv} module, which parses files in
1273comma-separated value format, received several enhancements and a
1274number of bugfixes. You can now set the maximum size in bytes of a
1275field by calling the \method{csv.field_size_limit(\var{new_limit})}
1276function; omitting the \var{new_limit} argument will return the
1277currently-set limit. The \class{reader} class now has a
1278\member{line_num} attribute that counts the number of physical lines
1279read from the source; records can span multiple physical lines, so
1280\member{line_num} is not the same as the number of records read.
1281(Contributed by Skip Montanaro and Andrew McNamara.)
1282
Andrew M. Kuchling67191312006-04-19 12:55:39 +00001283\item The \class{datetime} class in the \module{datetime}
1284module now has a \method{strptime(\var{string}, \var{format})}
1285method for parsing date strings, contributed by Josh Spoerri.
1286It uses the same format characters as \function{time.strptime()} and
1287\function{time.strftime()}:
1288
1289\begin{verbatim}
1290from datetime import datetime
1291
1292ts = datetime.strptime('10:13:15 2006-03-07',
1293 '%H:%M:%S %Y-%m-%d')
1294\end{verbatim}
1295
Andrew M. Kuchlingb33842a2006-04-25 12:31:38 +00001296\item The \module{doctest} module gained a \code{SKIP} option that
1297keeps an example from being executed at all. This is intended for
1298code snippets that are usage examples intended for the reader and
1299aren't actually test cases.
1300
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001301\item The \module{fileinput} module was made more flexible.
1302Unicode filenames are now supported, and a \var{mode} parameter that
1303defaults to \code{"r"} was added to the
1304\function{input()} function to allow opening files in binary or
1305universal-newline mode. Another new parameter, \var{openhook},
1306lets you use a function other than \function{open()}
1307to open the input files. Once you're iterating over
1308the set of files, the \class{FileInput} object's new
1309\method{fileno()} returns the file descriptor for the currently opened file.
1310(Contributed by Georg Brandl.)
1311
Andrew M. Kuchlingda376042006-03-17 15:56:41 +00001312\item In the \module{gc} module, the new \function{get_count()} function
1313returns a 3-tuple containing the current collection counts for the
1314three GC generations. This is accounting information for the garbage
1315collector; when these counts reach a specified threshold, a garbage
1316collection sweep will be made. The existing \function{gc.collect()}
1317function now takes an optional \var{generation} argument of 0, 1, or 2
1318to specify which generation to collect.
1319
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001320\item The \function{nsmallest()} and
1321\function{nlargest()} functions in the \module{heapq} module
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001322now support a \code{key} keyword parameter similar to the one
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001323provided by the \function{min()}/\function{max()} functions
1324and the \method{sort()} methods. For example:
1325Example:
1326
1327\begin{verbatim}
1328>>> import heapq
1329>>> L = ["short", 'medium', 'longest', 'longer still']
1330>>> heapq.nsmallest(2, L) # Return two lowest elements, lexicographically
1331['longer still', 'longest']
1332>>> heapq.nsmallest(2, L, key=len) # Return two shortest elements
1333['short', 'medium']
1334\end{verbatim}
1335
1336(Contributed by Raymond Hettinger.)
1337
Andrew M. Kuchling511a3a82005-03-20 19:52:18 +00001338\item The \function{itertools.islice()} function now accepts
1339\code{None} for the start and step arguments. This makes it more
1340compatible with the attributes of slice objects, so that you can now write
1341the following:
1342
1343\begin{verbatim}
1344s = slice(5) # Create slice object
1345itertools.islice(iterable, s.start, s.stop, s.step)
1346\end{verbatim}
1347
1348(Contributed by Raymond Hettinger.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001349
Andrew M. Kuchlingd4c21772006-04-23 21:51:10 +00001350\item The \module{mailbox} module underwent a massive rewrite to add
1351the capability to modify mailboxes in addition to reading them. A new
1352set of classes that include \class{mbox}, \class{MH}, and
1353\class{Maildir} are used to read mailboxes, and have an
1354\method{add(\var{message})} method to add messages,
1355\method{remove(\var{key})} to remove messages, and
1356\method{lock()}/\method{unlock()} to lock/unlock the mailbox. The
1357following example converts a maildir-format mailbox into an mbox-format one:
1358
1359\begin{verbatim}
1360import mailbox
1361
1362# 'factory=None' uses email.Message.Message as the class representing
1363# individual messages.
1364src = mailbox.Maildir('maildir', factory=None)
1365dest = mailbox.mbox('/tmp/mbox')
1366
1367for msg in src:
1368 dest.add(msg)
1369\end{verbatim}
1370
1371(Contributed by Gregory K. Johnson. Funding was provided by Google's
13722005 Summer of Code.)
1373
Andrew M. Kuchling75ba2442006-04-14 10:29:55 +00001374\item The \module{nis} module now supports accessing domains other
1375than the system default domain by supplying a \var{domain} argument to
1376the \function{nis.match()} and \function{nis.maps()} functions.
1377(Contributed by Ben Bell.)
1378
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001379\item The \module{operator} module's \function{itemgetter()}
1380and \function{attrgetter()} functions now support multiple fields.
1381A call such as \code{operator.attrgetter('a', 'b')}
1382will return a function
1383that retrieves the \member{a} and \member{b} attributes. Combining
1384this new feature with the \method{sort()} method's \code{key} parameter
1385lets you easily sort lists using multiple fields.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001386(Contributed by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001387
Andrew M. Kuchlingd4c21772006-04-23 21:51:10 +00001388\item The \module{optparse} module was updated to version 1.5.1 of the
1389Optik library. The \class{OptionParser} class gained an
1390\member{epilog} attribute, a string that will be printed after the
1391help message, and a \method{destroy()} method to break reference
1392cycles created by the object. (Contributed by Greg Ward.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001393
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +00001394\item The \module{os} module underwent several changes. The
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001395\member{stat_float_times} variable now defaults to true, meaning that
1396\function{os.stat()} will now return time values as floats. (This
1397doesn't necessarily mean that \function{os.stat()} will return times
1398that are precise to fractions of a second; not all systems support
1399such precision.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001400
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001401Constants named \member{os.SEEK_SET}, \member{os.SEEK_CUR}, and
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001402\member{os.SEEK_END} have been added; these are the parameters to the
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001403\function{os.lseek()} function. Two new constants for locking are
1404\member{os.O_SHLOCK} and \member{os.O_EXLOCK}.
1405
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001406Two new functions, \function{wait3()} and \function{wait4()}, were
1407added. They're similar the \function{waitpid()} function which waits
1408for a child process to exit and returns a tuple of the process ID and
1409its exit status, but \function{wait3()} and \function{wait4()} return
1410additional information. \function{wait3()} doesn't take a process ID
1411as input, so it waits for any child process to exit and returns a
14123-tuple of \var{process-id}, \var{exit-status}, \var{resource-usage}
1413as returned from the \function{resource.getrusage()} function.
1414\function{wait4(\var{pid})} does take a process ID.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001415(Contributed by Chad J. Schroeder.)
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001416
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001417On FreeBSD, the \function{os.stat()} function now returns
1418times with nanosecond resolution, and the returned object
1419now has \member{st_gen} and \member{st_birthtime}.
1420The \member{st_flags} member is also available, if the platform supports it.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001421(Contributed by Antti Louko and Diego Petten\`o.)
1422% (Patch 1180695, 1212117)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001423
Andrew M. Kuchlingb33842a2006-04-25 12:31:38 +00001424\item The Python debugger provided by the \module{pdb} module
1425can now store lists of commands to execute when a breakpoint is
George Yoshida3bbbc492006-04-25 14:09:58 +00001426reached and execution stops. Once breakpoint \#1 has been created,
Andrew M. Kuchlingb33842a2006-04-25 12:31:38 +00001427enter \samp{commands 1} and enter a series of commands to be executed,
1428finishing the list with \samp{end}. The command list can include
1429commands that resume execution, such as \samp{continue} or
1430\samp{next}. (Contributed by Gr\'egoire Dooms.)
1431% Patch 790710
1432
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001433\item The \module{pickle} and \module{cPickle} modules no
1434longer accept a return value of \code{None} from the
1435\method{__reduce__()} method; the method must return a tuple of
1436arguments instead. The ability to return \code{None} was deprecated
1437in Python 2.4, so this completes the removal of the feature.
1438
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001439\item The old \module{regex} and \module{regsub} modules, which have been
1440deprecated ever since Python 2.0, have finally been deleted.
Andrew M. Kuchlingf4b06602006-03-17 15:39:52 +00001441Other deleted modules: \module{statcache}, \module{tzparse},
1442\module{whrandom}.
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001443
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001444\item Also deleted: the \file{lib-old} directory,
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001445which includes ancient modules such as \module{dircmp} and
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001446\module{ni}, was removed. \file{lib-old} wasn't on the default
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001447\code{sys.path}, so unless your programs explicitly added the directory to
1448\code{sys.path}, this removal shouldn't affect your code.
1449
Andrew M. Kuchling4678dc82006-01-15 16:11:28 +00001450\item The \module{socket} module now supports \constant{AF_NETLINK}
1451sockets on Linux, thanks to a patch from Philippe Biondi.
1452Netlink sockets are a Linux-specific mechanism for communications
1453between a user-space process and kernel code; an introductory
1454article about them is at \url{http://www.linuxjournal.com/article/7356}.
1455In Python code, netlink addresses are represented as a tuple of 2 integers,
1456\code{(\var{pid}, \var{group_mask})}.
1457
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001458Socket objects also gained accessor methods \method{getfamily()},
1459\method{gettype()}, and \method{getproto()} methods to retrieve the
1460family, type, and protocol values for the socket.
1461
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001462\item New module: the \module{spwd} module provides functions for
1463accessing the shadow password database on systems that support
1464shadow passwords.
Fred Drake2db76802004-12-01 05:05:47 +00001465
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001466\item The Python developers switched from CVS to Subversion during the 2.5
1467development process. Information about the exact build version is
1468available as the \code{sys.subversion} variable, a 3-tuple
1469of \code{(\var{interpreter-name}, \var{branch-name}, \var{revision-range})}.
1470For example, at the time of writing
1471my copy of 2.5 was reporting \code{('CPython', 'trunk', '45313:45315')}.
1472
1473This information is also available to C extensions via the
1474\cfunction{Py_GetBuildInfo()} function that returns a
1475string of build information like this:
1476\code{"trunk:45355:45356M, Apr 13 2006, 07:42:19"}.
1477(Contributed by Barry Warsaw.)
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001478
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001479\item The \class{TarFile} class in the \module{tarfile} module now has
Georg Brandl08c02db2005-07-22 18:39:19 +00001480an \method{extractall()} method that extracts all members from the
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001481archive into the current working directory. It's also possible to set
1482a different directory as the extraction target, and to unpack only a
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001483subset of the archive's members.
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001484
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001485A tarfile's compression can be autodetected by
1486using the mode \code{'r|*'}.
1487% patch 918101
1488(Contributed by Lars Gust\"abel.)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001489
Andrew M. Kuchlingf688cc52006-03-10 18:50:08 +00001490\item The \module{unicodedata} module has been updated to use version 4.1.0
1491of the Unicode character database. Version 3.2.0 is required
1492by some specifications, so it's still available as
1493\member{unicodedata.db_3_2_0}.
1494
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001495\item The \module{webbrowser} module received a number of
1496enhancements.
1497It's now usable as a script with \code{python -m webbrowser}, taking a
1498URL as the argument; there are a number of switches
1499to control the behaviour (\programopt{-n} for a new browser window,
1500\programopt{-t} for a new tab). New module-level functions,
1501\function{open_new()} and \function{open_new_tab()}, were added
1502to support this. The module's \function{open()} function supports an
1503additional feature, an \var{autoraise} parameter that signals whether
1504to raise the open window when possible. A number of additional
1505browsers were added to the supported list such as Firefox, Opera,
1506Konqueror, and elinks. (Contributed by Oleg Broytmann and George
1507Brandl.)
1508% Patch #754022
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001509
Fredrik Lundh7e0aef02005-12-12 18:54:55 +00001510
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001511\item The \module{xmlrpclib} module now supports returning
1512 \class{datetime} objects for the XML-RPC date type. Supply
1513 \code{use_datetime=True} to the \function{loads()} function
1514 or the \class{Unmarshaller} class to enable this feature.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001515 (Contributed by Skip Montanaro.)
1516% Patch 1120353
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001517
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001518
Fred Drake114b8ca2005-03-21 05:47:11 +00001519\end{itemize}
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001520
Fred Drake2db76802004-12-01 05:05:47 +00001521
1522
1523%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001524\subsection{The ctypes package\label{module-ctypes}}
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001525
1526The \module{ctypes} package, written by Thomas Heller, has been added
1527to the standard library. \module{ctypes} lets you call arbitrary functions
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001528in shared libraries or DLLs. Long-time users may remember the \module{dl} module, which
1529provides functions for loading shared libraries and calling functions in them. The \module{ctypes} package is much fancier.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001530
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001531To load a shared library or DLL, you must create an instance of the
1532\class{CDLL} class and provide the name or path of the shared library
1533or DLL. Once that's done, you can call arbitrary functions
1534by accessing them as attributes of the \class{CDLL} object.
1535
1536\begin{verbatim}
1537import ctypes
1538
1539libc = ctypes.CDLL('libc.so.6')
1540result = libc.printf("Line of output\n")
1541\end{verbatim}
1542
1543Type constructors for the various C types are provided: \function{c_int},
1544\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
1545to change the wrapped value. Python integers and strings will be automatically
1546converted to the corresponding C types, but for other types you
1547must call the correct type constructor. (And I mean \emph{must};
1548getting it wrong will often result in the interpreter crashing
1549with a segmentation fault.)
1550
1551You 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
1552supposed to be immutable; breaking this rule will cause puzzling bugs. When you need a modifiable memory area,
Neal Norwitz5f5a69b2006-04-13 03:41:04 +00001553use \function{create_string_buffer()}:
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001554
1555\begin{verbatim}
1556s = "this is a string"
1557buf = ctypes.create_string_buffer(s)
1558libc.strfry(buf)
1559\end{verbatim}
1560
1561C functions are assumed to return integers, but you can set
1562the \member{restype} attribute of the function object to
1563change this:
1564
1565\begin{verbatim}
1566>>> libc.atof('2.71828')
1567-1783957616
1568>>> libc.atof.restype = ctypes.c_double
1569>>> libc.atof('2.71828')
15702.71828
1571\end{verbatim}
1572
1573\module{ctypes} also provides a wrapper for Python's C API
1574as the \code{ctypes.pythonapi} object. This object does \emph{not}
1575release the global interpreter lock before calling a function, because the lock must be held when calling into the interpreter's code.
1576There's a \class{py_object()} type constructor that will create a
1577\ctype{PyObject *} pointer. A simple usage:
1578
1579\begin{verbatim}
1580import ctypes
1581
1582d = {}
1583ctypes.pythonapi.PyObject_SetItem(ctypes.py_object(d),
1584 ctypes.py_object("abc"), ctypes.py_object(1))
1585# d is now {'abc', 1}.
1586\end{verbatim}
1587
1588Don't forget to use \class{py_object()}; if it's omitted you end
1589up with a segmentation fault.
1590
1591\module{ctypes} has been around for a while, but people still write
1592and distribution hand-coded extension modules because you can't rely on \module{ctypes} being present.
1593Perhaps developers will begin to write
1594Python wrappers atop a library accessed through \module{ctypes} instead
1595of extension modules, now that \module{ctypes} is included with core Python.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001596
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001597\begin{seealso}
1598
1599\seeurl{http://starship.python.net/crew/theller/ctypes/}
1600{The ctypes web page, with a tutorial, reference, and FAQ.}
1601
1602\end{seealso}
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001603
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001604
1605%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001606\subsection{The ElementTree package\label{module-etree}}
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001607
1608A subset of Fredrik Lundh's ElementTree library for processing XML has
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001609been added to the standard library as \module{xmlcore.etree}. The
Georg Brandlce27a062006-04-11 06:27:12 +00001610available modules are
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001611\module{ElementTree}, \module{ElementPath}, and
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00001612\module{ElementInclude} from ElementTree 1.2.6.
1613The \module{cElementTree} accelerator module is also included.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001614
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001615The rest of this section will provide a brief overview of using
1616ElementTree. Full documentation for ElementTree is available at
1617\url{http://effbot.org/zone/element-index.htm}.
1618
1619ElementTree represents an XML document as a tree of element nodes.
1620The text content of the document is stored as the \member{.text}
1621and \member{.tail} attributes of
1622(This is one of the major differences between ElementTree and
1623the Document Object Model; in the DOM there are many different
1624types of node, including \class{TextNode}.)
1625
1626The most commonly used parsing function is \function{parse()}, that
1627takes either a string (assumed to contain a filename) or a file-like
1628object and returns an \class{ElementTree} instance:
1629
1630\begin{verbatim}
1631from xmlcore.etree import ElementTree as ET
1632
1633tree = ET.parse('ex-1.xml')
1634
1635feed = urllib.urlopen(
1636 'http://planet.python.org/rss10.xml')
1637tree = ET.parse(feed)
1638\end{verbatim}
1639
1640Once you have an \class{ElementTree} instance, you
1641can call its \method{getroot()} method to get the root \class{Element} node.
1642
1643There's also an \function{XML()} function that takes a string literal
1644and returns an \class{Element} node (not an \class{ElementTree}).
1645This function provides a tidy way to incorporate XML fragments,
1646approaching the convenience of an XML literal:
1647
1648\begin{verbatim}
1649svg = et.XML("""<svg width="10px" version="1.0">
1650 </svg>""")
1651svg.set('height', '320px')
1652svg.append(elem1)
1653\end{verbatim}
1654
1655Each XML element supports some dictionary-like and some list-like
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001656access methods. Dictionary-like operations are used to access attribute
1657values, and list-like operations are used to access child nodes.
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001658
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001659\begin{tableii}{c|l}{code}{Operation}{Result}
1660 \lineii{elem[n]}{Returns n'th child element.}
1661 \lineii{elem[m:n]}{Returns list of m'th through n'th child elements.}
1662 \lineii{len(elem)}{Returns number of child elements.}
1663 \lineii{elem.getchildren()}{Returns list of child elements.}
1664 \lineii{elem.append(elem2)}{Adds \var{elem2} as a child.}
1665 \lineii{elem.insert(index, elem2)}{Inserts \var{elem2} at the specified location.}
1666 \lineii{del elem[n]}{Deletes n'th child element.}
1667 \lineii{elem.keys()}{Returns list of attribute names.}
1668 \lineii{elem.get(name)}{Returns value of attribute \var{name}.}
1669 \lineii{elem.set(name, value)}{Sets new value for attribute \var{name}.}
1670 \lineii{elem.attrib}{Retrieves the dictionary containing attributes.}
1671 \lineii{del elem.attrib[name]}{Deletes attribute \var{name}.}
1672\end{tableii}
1673
1674Comments and processing instructions are also represented as
1675\class{Element} nodes. To check if a node is a comment or processing
1676instructions:
1677
1678\begin{verbatim}
1679if elem.tag is ET.Comment:
1680 ...
1681elif elem.tag is ET.ProcessingInstruction:
1682 ...
1683\end{verbatim}
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001684
1685To generate XML output, you should call the
1686\method{ElementTree.write()} method. Like \function{parse()},
1687it can take either a string or a file-like object:
1688
1689\begin{verbatim}
1690# Encoding is US-ASCII
1691tree.write('output.xml')
1692
1693# Encoding is UTF-8
1694f = open('output.xml', 'w')
1695tree.write(f, 'utf-8')
1696\end{verbatim}
1697
1698(Caution: the default encoding used for output is ASCII, which isn't
1699very useful for general XML work, raising an exception if there are
1700any characters with values greater than 127. You should always
1701specify a different encoding such as UTF-8 that can handle any Unicode
1702character.)
1703
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001704This section is only a partial description of the ElementTree interfaces.
1705Please read the package's official documentation for more details.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001706
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001707\begin{seealso}
1708
1709\seeurl{http://effbot.org/zone/element-index.htm}
1710{Official documentation for ElementTree.}
1711
1712
1713\end{seealso}
1714
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001715
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001716%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001717\subsection{The hashlib package\label{module-hashlib}}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001718
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001719A new \module{hashlib} module, written by Gregory P. Smith,
1720has been added to replace the
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001721\module{md5} and \module{sha} modules. \module{hashlib} adds support
1722for additional secure hashes (SHA-224, SHA-256, SHA-384, and SHA-512).
1723When available, the module uses OpenSSL for fast platform optimized
1724implementations of algorithms.
1725
1726The old \module{md5} and \module{sha} modules still exist as wrappers
1727around hashlib to preserve backwards compatibility. The new module's
1728interface is very close to that of the old modules, but not identical.
1729The most significant difference is that the constructor functions
1730for creating new hashing objects are named differently.
1731
1732\begin{verbatim}
1733# Old versions
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001734h = md5.md5()
1735h = md5.new()
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001736
1737# New version
1738h = hashlib.md5()
1739
1740# Old versions
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001741h = sha.sha()
1742h = sha.new()
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001743
1744# New version
1745h = hashlib.sha1()
1746
1747# Hash that weren't previously available
1748h = hashlib.sha224()
1749h = hashlib.sha256()
1750h = hashlib.sha384()
1751h = hashlib.sha512()
1752
1753# Alternative form
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001754h = hashlib.new('md5') # Provide algorithm as a string
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001755\end{verbatim}
1756
1757Once a hash object has been created, its methods are the same as before:
1758\method{update(\var{string})} hashes the specified string into the
1759current digest state, \method{digest()} and \method{hexdigest()}
1760return the digest value as a binary string or a string of hex digits,
1761and \method{copy()} returns a new hashing object with the same digest state.
1762
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001763
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001764%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001765\subsection{The sqlite3 package\label{module-sqlite}}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001766
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001767The pysqlite module (\url{http://www.pysqlite.org}), a wrapper for the
1768SQLite embedded database, has been added to the standard library under
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001769the package name \module{sqlite3}.
1770
1771SQLite is a C library that provides a SQL-language database that
1772stores data in disk files without requiring a separate server process.
1773pysqlite was written by Gerhard H\"aring and provides a SQL interface
1774compliant with the DB-API 2.0 specification described by
1775\pep{249}. This means that it should be possible to write the first
1776version of your applications using SQLite for data storage. If
1777switching to a larger database such as PostgreSQL or Oracle is
1778later necessary, the switch should be relatively easy.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001779
1780If you're compiling the Python source yourself, note that the source
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001781tree doesn't include the SQLite code, only the wrapper module.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001782You'll need to have the SQLite libraries and headers installed before
1783compiling Python, and the build process will compile the module when
1784the necessary headers are available.
1785
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001786To use the module, you must first create a \class{Connection} object
1787that represents the database. Here the data will be stored in the
1788\file{/tmp/example} file:
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001789
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001790\begin{verbatim}
1791conn = sqlite3.connect('/tmp/example')
1792\end{verbatim}
1793
1794You can also supply the special name \samp{:memory:} to create
1795a database in RAM.
1796
1797Once you have a \class{Connection}, you can create a \class{Cursor}
1798object and call its \method{execute()} method to perform SQL commands:
1799
1800\begin{verbatim}
1801c = conn.cursor()
1802
1803# Create table
1804c.execute('''create table stocks
1805(date timestamp, trans varchar, symbol varchar,
1806 qty decimal, price decimal)''')
1807
1808# Insert a row of data
1809c.execute("""insert into stocks
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001810 values ('2006-01-05','BUY','RHAT',100,35.14)""")
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001811\end{verbatim}
1812
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001813Usually your SQL operations will need to use values from Python
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001814variables. You shouldn't assemble your query using Python's string
1815operations because doing so is insecure; it makes your program
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001816vulnerable to an SQL injection attack.
1817
1818Instead, use SQLite's parameter substitution. Put \samp{?} as a
1819placeholder wherever you want to use a value, and then provide a tuple
1820of values as the second argument to the cursor's \method{execute()}
1821method. For example:
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001822
1823\begin{verbatim}
1824# Never do this -- insecure!
1825symbol = 'IBM'
1826c.execute("... where symbol = '%s'" % symbol)
1827
1828# Do this instead
1829t = (symbol,)
Andrew M. Kuchling7e5abb92006-04-26 12:21:06 +00001830c.execute('select * from stocks where symbol=?', t)
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001831
1832# Larger example
1833for t in (('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001834 ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
1835 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
1836 ):
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001837 c.execute('insert into stocks values (?,?,?,?,?)', t)
1838\end{verbatim}
1839
1840To retrieve data after executing a SELECT statement, you can either
1841treat the cursor as an iterator, call the cursor's \method{fetchone()}
1842method to retrieve a single matching row,
1843or call \method{fetchall()} to get a list of the matching rows.
1844
1845This example uses the iterator form:
1846
1847\begin{verbatim}
1848>>> c = conn.cursor()
1849>>> c.execute('select * from stocks order by price')
1850>>> for row in c:
1851... print row
1852...
1853(u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001)
1854(u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
1855(u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
1856(u'2006-04-05', u'BUY', u'MSOFT', 1000, 72.0)
1857>>>
1858\end{verbatim}
1859
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001860For more information about the SQL dialect supported by SQLite, see
1861\url{http://www.sqlite.org}.
1862
1863\begin{seealso}
1864
1865\seeurl{http://www.pysqlite.org}
1866{The pysqlite web page.}
1867
1868\seeurl{http://www.sqlite.org}
1869{The SQLite web page; the documentation describes the syntax and the
1870available data types for the supported SQL dialect.}
1871
1872\seepep{249}{Database API Specification 2.0}{PEP written by
1873Marc-Andr\'e Lemburg.}
1874
1875\end{seealso}
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001876
Fred Drake2db76802004-12-01 05:05:47 +00001877
1878% ======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001879\section{Build and C API Changes\label{build-api}}
Fred Drake2db76802004-12-01 05:05:47 +00001880
1881Changes to Python's build process and to the C API include:
1882
1883\begin{itemize}
1884
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00001885\item The largest change to the C API came from \pep{353},
1886which modifies the interpreter to use a \ctype{Py_ssize_t} type
1887definition instead of \ctype{int}. See the earlier
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +00001888section~\ref{pep-353} for a discussion of this change.
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00001889
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001890\item The design of the bytecode compiler has changed a great deal, to
1891no longer generate bytecode by traversing the parse tree. Instead
Andrew M. Kuchlingdb85ed52005-10-23 21:52:59 +00001892the parse tree is converted to an abstract syntax tree (or AST), and it is
1893the abstract syntax tree that's traversed to produce the bytecode.
1894
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00001895It's possible for Python code to obtain AST objects by using the
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001896\function{compile()} built-in and specifying \code{_ast.PyCF_ONLY_AST}
1897as the value of the
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00001898\var{flags} parameter:
1899
1900\begin{verbatim}
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001901from _ast import PyCF_ONLY_AST
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00001902ast = compile("""a=0
1903for i in range(10):
1904 a += i
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001905""", "<string>", 'exec', PyCF_ONLY_AST)
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00001906
1907assignment = ast.body[0]
1908for_loop = ast.body[1]
1909\end{verbatim}
1910
Andrew M. Kuchlingdb85ed52005-10-23 21:52:59 +00001911No documentation has been written for the AST code yet. To start
1912learning about it, read the definition of the various AST nodes in
1913\file{Parser/Python.asdl}. A Python script reads this file and
1914generates a set of C structure definitions in
1915\file{Include/Python-ast.h}. The \cfunction{PyParser_ASTFromString()}
1916and \cfunction{PyParser_ASTFromFile()}, defined in
1917\file{Include/pythonrun.h}, take Python source as input and return the
1918root of an AST representing the contents. This AST can then be turned
1919into a code object by \cfunction{PyAST_Compile()}. For more
1920information, read the source code, and then ask questions on
1921python-dev.
1922
1923% List of names taken from Jeremy's python-dev post at
1924% http://mail.python.org/pipermail/python-dev/2005-October/057500.html
1925The AST code was developed under Jeremy Hylton's management, and
1926implemented by (in alphabetical order) Brett Cannon, Nick Coghlan,
1927Grant Edwards, John Ehresman, Kurt Kaiser, Neal Norwitz, Tim Peters,
1928Armin Rigo, and Neil Schemenauer, plus the participants in a number of
1929AST sprints at conferences such as PyCon.
1930
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001931\item The built-in set types now have an official C API. Call
1932\cfunction{PySet_New()} and \cfunction{PyFrozenSet_New()} to create a
1933new set, \cfunction{PySet_Add()} and \cfunction{PySet_Discard()} to
1934add and remove elements, and \cfunction{PySet_Contains} and
1935\cfunction{PySet_Size} to examine the set's state.
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001936(Contributed by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001937
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001938\item C code can now obtain information about the exact revision
1939of the Python interpreter by calling the
1940\cfunction{Py_GetBuildInfo()} function that returns a
1941string of build information like this:
1942\code{"trunk:45355:45356M, Apr 13 2006, 07:42:19"}.
1943(Contributed by Barry Warsaw.)
1944
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001945\item The CPython interpreter is still written in C, but
1946the code can now be compiled with a {\Cpp} compiler without errors.
1947(Implemented by Anthony Baxter, Martin von~L\"owis, Skip Montanaro.)
1948
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001949\item The \cfunction{PyRange_New()} function was removed. It was
1950never documented, never used in the core code, and had dangerously lax
1951error checking.
Fred Drake2db76802004-12-01 05:05:47 +00001952
1953\end{itemize}
1954
1955
1956%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001957\subsection{Port-Specific Changes\label{ports}}
Fred Drake2db76802004-12-01 05:05:47 +00001958
Andrew M. Kuchling6fc69762006-04-13 12:37:21 +00001959\begin{itemize}
1960
1961\item MacOS X (10.3 and higher): dynamic loading of modules
1962now uses the \cfunction{dlopen()} function instead of MacOS-specific
1963functions.
1964
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001965\item Windows: \file{.dll} is no longer supported as a filename extension for
1966extension modules. \file{.pyd} is now the only filename extension that will
1967be searched for.
1968
Andrew M. Kuchling6fc69762006-04-13 12:37:21 +00001969\end{itemize}
Fred Drake2db76802004-12-01 05:05:47 +00001970
1971
1972%======================================================================
1973\section{Other Changes and Fixes \label{section-other}}
1974
1975As usual, there were a bunch of other improvements and bugfixes
Andrew M. Kuchlingf688cc52006-03-10 18:50:08 +00001976scattered throughout the source tree. A search through the SVN change
Fred Drake2db76802004-12-01 05:05:47 +00001977logs finds there were XXX patches applied and YYY bugs fixed between
Andrew M. Kuchling92e24952004-12-03 13:54:09 +00001978Python 2.4 and 2.5. Both figures are likely to be underestimates.
Fred Drake2db76802004-12-01 05:05:47 +00001979
1980Some of the more notable changes are:
1981
1982\begin{itemize}
1983
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001984\item Evan Jones's patch to obmalloc, first described in a talk
1985at PyCon DC 2005, was applied. Python 2.4 allocated small objects in
1986256K-sized arenas, but never freed arenas. With this patch, Python
1987will free arenas when they're empty. The net effect is that on some
1988platforms, when you allocate many objects, Python's memory usage may
1989actually drop when you delete them, and the memory may be returned to
1990the operating system. (Implemented by Evan Jones, and reworked by Tim
1991Peters.)
Fred Drake2db76802004-12-01 05:05:47 +00001992
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00001993Note that this change means extension modules need to be more careful
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +00001994with how they allocate memory. Python's API has many different
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00001995functions for allocating memory that are grouped into families. For
1996example, \cfunction{PyMem_Malloc()}, \cfunction{PyMem_Realloc()}, and
1997\cfunction{PyMem_Free()} are one family that allocates raw memory,
1998while \cfunction{PyObject_Malloc()}, \cfunction{PyObject_Realloc()},
1999and \cfunction{PyObject_Free()} are another family that's supposed to
2000be used for creating Python objects.
2001
2002Previously these different families all reduced to the platform's
2003\cfunction{malloc()} and \cfunction{free()} functions. This meant
2004it didn't matter if you got things wrong and allocated memory with the
2005\cfunction{PyMem} function but freed it with the \cfunction{PyObject}
2006function. With the obmalloc change, these families now do different
2007things, and mismatches will probably result in a segfault. You should
2008carefully test your C extension modules with Python 2.5.
2009
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00002010\item Coverity, a company that markets a source code analysis tool
2011 called Prevent, provided the results of their examination of the Python
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +00002012 source code. The analysis found about 60 bugs that
2013 were quickly fixed. Many of the bugs were refcounting problems, often
2014 occurring in error-handling code. See
2015 \url{http://scan.coverity.com} for the statistics.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00002016
Fred Drake2db76802004-12-01 05:05:47 +00002017\end{itemize}
2018
2019
2020%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00002021\section{Porting to Python 2.5\label{porting}}
Fred Drake2db76802004-12-01 05:05:47 +00002022
2023This section lists previously described changes that may require
2024changes to your code:
2025
2026\begin{itemize}
2027
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00002028\item ASCII is now the default encoding for modules. It's now
2029a syntax error if a module contains string literals with 8-bit
2030characters but doesn't have an encoding declaration. In Python 2.4
2031this triggered a warning, not a syntax error.
2032
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +00002033\item Previously, the \member{gi_frame} attribute of a generator
2034was always a frame object. Because of the \pep{342} changes
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +00002035described in section~\ref{pep-342}, it's now possible
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +00002036for \member{gi_frame} to be \code{None}.
2037
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00002038
2039\item Library: The \module{pickle} and \module{cPickle} modules no
2040longer accept a return value of \code{None} from the
2041\method{__reduce__()} method; the method must return a tuple of
2042arguments instead. The modules also no longer accept the deprecated
2043\var{bin} keyword parameter.
2044
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00002045\item C API: Many functions now use \ctype{Py_ssize_t}
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00002046instead of \ctype{int} to allow processing more data on 64-bit
2047machines. Extension code may need to make the same change to avoid
2048warnings and to support 64-bit machines. See the earlier
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +00002049section~\ref{pep-353} for a discussion of this change.
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00002050
2051\item C API:
2052The obmalloc changes mean that
2053you must be careful to not mix usage
2054of the \cfunction{PyMem_*()} and \cfunction{PyObject_*()}
2055families of functions. Memory allocated with
2056one family's \cfunction{*_Malloc()} must be
2057freed with the corresponding family's \cfunction{*_Free()} function.
2058
Fred Drake2db76802004-12-01 05:05:47 +00002059\end{itemize}
2060
2061
2062%======================================================================
2063\section{Acknowledgements \label{acks}}
2064
2065The author would like to thank the following people for offering
2066suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00002067article: Phillip J. Eby, Kent Johnson, Martin von~L\"owis, Gustavo
Andrew M. Kuchling7e5abb92006-04-26 12:21:06 +00002068Niemeyer, James Pryor, Mike Rovner, Thomas Wouters.
Fred Drake2db76802004-12-01 05:05:47 +00002069
2070\end{document}