blob: 261f65a4c4bc95b3b68fd24d8e3416ecbce2dff9 [file] [log] [blame]
Fred Drake2db76802004-12-01 05:05:47 +00001\documentclass{howto}
2\usepackage{distutils}
3% $Id$
4
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00005% Fix XXX comments
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00006% Count up the patches and bugs
Fred Drake2db76802004-12-01 05:05:47 +00007
8\title{What's New in Python 2.5}
Andrew M. Kuchling99714cf2006-04-27 12:23:07 +00009\release{0.2}
Andrew M. Kuchling92e24952004-12-03 13:54:09 +000010\author{A.M. Kuchling}
11\authoraddress{\email{amk@amk.ca}}
Fred Drake2db76802004-12-01 05:05:47 +000012
13\begin{document}
14\maketitle
15\tableofcontents
16
17This article explains the new features in Python 2.5. No release date
Andrew M. Kuchling5eefdca2006-02-08 11:36:09 +000018for Python 2.5 has been set; it will probably be released in the
Andrew M. Kuchlingd96a6ac2006-04-04 19:17:34 +000019autumn of 2006. \pep{356} describes the planned release schedule.
Fred Drake2db76802004-12-01 05:05:47 +000020
Andrew M. Kuchling0d660c02006-04-17 14:01:36 +000021Comments, suggestions, and error reports are welcome; please e-mail them
22to the author or open a bug in the Python bug tracker.
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +000023
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000024% XXX Compare with previous release in 2 - 3 sentences here.
Fred Drake2db76802004-12-01 05:05:47 +000025
26This article doesn't attempt to provide a complete specification of
27the new features, but instead provides a convenient overview. For
28full details, you should refer to the documentation for Python 2.5.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000029% XXX add hyperlink when the documentation becomes available online.
Fred Drake2db76802004-12-01 05:05:47 +000030If you want to understand the complete implementation and design
31rationale, refer to the PEP for a particular new feature.
32
33
34%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +000035\section{PEP 243: Uploading Modules to PyPI\label{pep-243}}
Andrew M. Kuchling6a67e4e2006-04-12 13:03:35 +000036
37PEP 243 describes an HTTP-based protocol for submitting software
38packages to a central archive. The Python package index at
39\url{http://cheeseshop.python.org} now supports package uploads, and
40the new \command{upload} Distutils command will upload a package to the
41repository.
42
43Before a package can be uploaded, you must be able to build a
44distribution using the \command{sdist} Distutils command. Once that
45works, you can run \code{python setup.py upload} to add your package
46to the PyPI archive. Optionally you can GPG-sign the package by
George Yoshida297bf822006-04-17 15:44:59 +000047supplying the \longprogramopt{sign} and
48\longprogramopt{identity} options.
Andrew M. Kuchling6a67e4e2006-04-12 13:03:35 +000049
50\begin{seealso}
51
52\seepep{243}{Module Repository Upload Mechanism}{PEP written by
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +000053Sean Reifschneider; implemented by Martin von~L\"owis
Andrew M. Kuchling6a67e4e2006-04-12 13:03:35 +000054and Richard Jones. Note that the PEP doesn't exactly
55describe what's implemented in PyPI.}
56
57\end{seealso}
58
59
60%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +000061\section{PEP 308: Conditional Expressions\label{pep-308}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000062
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000063For a long time, people have been requesting a way to write
64conditional expressions, expressions that return value A or value B
65depending on whether a Boolean value is true or false. A conditional
66expression lets you write a single assignment statement that has the
67same effect as the following:
68
69\begin{verbatim}
70if condition:
71 x = true_value
72else:
73 x = false_value
74\end{verbatim}
75
76There have been endless tedious discussions of syntax on both
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +000077python-dev and comp.lang.python. A vote was even held that found the
78majority of voters wanted conditional expressions in some form,
79but there was no syntax that was preferred by a clear majority.
80Candidates included C's \code{cond ? true_v : false_v},
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000081\code{if cond then true_v else false_v}, and 16 other variations.
82
83GvR eventually chose a surprising syntax:
84
85\begin{verbatim}
86x = true_value if condition else false_value
87\end{verbatim}
88
Andrew M. Kuchling38f85072006-04-02 01:46:32 +000089Evaluation is still lazy as in existing Boolean expressions, so the
90order of evaluation jumps around a bit. The \var{condition}
91expression in the middle is evaluated first, and the \var{true_value}
92expression is evaluated only if the condition was true. Similarly,
93the \var{false_value} expression is only evaluated when the condition
94is false.
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000095
96This syntax may seem strange and backwards; why does the condition go
97in the \emph{middle} of the expression, and not in the front as in C's
98\code{c ? x : y}? The decision was checked by applying the new syntax
99to the modules in the standard library and seeing how the resulting
100code read. In many cases where a conditional expression is used, one
101value seems to be the 'common case' and one value is an 'exceptional
102case', used only on rarer occasions when the condition isn't met. The
103conditional syntax makes this pattern a bit more obvious:
104
105\begin{verbatim}
106contents = ((doc + '\n') if doc else '')
107\end{verbatim}
108
109I read the above statement as meaning ``here \var{contents} is
Andrew M. Kuchlingd0fcc022006-03-09 13:57:28 +0000110usually assigned a value of \code{doc+'\e n'}; sometimes
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +0000111\var{doc} is empty, in which special case an empty string is returned.''
112I doubt I will use conditional expressions very often where there
113isn't a clear common and uncommon case.
114
115There was some discussion of whether the language should require
116surrounding conditional expressions with parentheses. The decision
117was made to \emph{not} require parentheses in the Python language's
118grammar, but as a matter of style I think you should always use them.
119Consider these two statements:
120
121\begin{verbatim}
122# First version -- no parens
123level = 1 if logging else 0
124
125# Second version -- with parens
126level = (1 if logging else 0)
127\end{verbatim}
128
129In the first version, I think a reader's eye might group the statement
130into 'level = 1', 'if logging', 'else 0', and think that the condition
131decides whether the assignment to \var{level} is performed. The
132second version reads better, in my opinion, because it makes it clear
133that the assignment is always performed and the choice is being made
134between two values.
135
136Another reason for including the brackets: a few odd combinations of
137list comprehensions and lambdas could look like incorrect conditional
138expressions. See \pep{308} for some examples. If you put parentheses
139around your conditional expressions, you won't run into this case.
140
141
142\begin{seealso}
143
144\seepep{308}{Conditional Expressions}{PEP written by
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000145Guido van~Rossum and Raymond D. Hettinger; implemented by Thomas
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +0000146Wouters.}
147
148\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000149
150
151%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000152\section{PEP 309: Partial Function Application\label{pep-309}}
Fred Drake2db76802004-12-01 05:05:47 +0000153
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000154The \module{functional} module is intended to contain tools for
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000155functional-style programming. Currently it only contains a
156\class{partial()} function, but new functions will probably be added
157in future versions of Python.
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000158
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000159For programs written in a functional style, it can be useful to
160construct variants of existing functions that have some of the
161parameters filled in. Consider a Python function \code{f(a, b, c)};
162you could create a new function \code{g(b, c)} that was equivalent to
163\code{f(1, b, c)}. This is called ``partial function application'',
164and is provided by the \class{partial} class in the new
165\module{functional} module.
166
167The constructor for \class{partial} takes the arguments
168\code{(\var{function}, \var{arg1}, \var{arg2}, ...
169\var{kwarg1}=\var{value1}, \var{kwarg2}=\var{value2})}. The resulting
170object is callable, so you can just call it to invoke \var{function}
171with the filled-in arguments.
172
173Here's a small but realistic example:
174
175\begin{verbatim}
176import functional
177
178def log (message, subsystem):
179 "Write the contents of 'message' to the specified subsystem."
180 print '%s: %s' % (subsystem, message)
181 ...
182
183server_log = functional.partial(log, subsystem='server')
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000184server_log('Unable to open socket')
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000185\end{verbatim}
186
Andrew M. Kuchling6af7fe02005-08-02 17:20:36 +0000187Here's another example, from a program that uses PyGTk. Here a
188context-sensitive pop-up menu is being constructed dynamically. The
189callback provided for the menu option is a partially applied version
190of the \method{open_item()} method, where the first argument has been
191provided.
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000192
Andrew M. Kuchling6af7fe02005-08-02 17:20:36 +0000193\begin{verbatim}
194...
195class Application:
196 def open_item(self, path):
197 ...
198 def init (self):
199 open_func = functional.partial(self.open_item, item_path)
200 popup_menu.append( ("Open", open_func, 1) )
201\end{verbatim}
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000202
203
204\begin{seealso}
205
206\seepep{309}{Partial Function Application}{PEP proposed and written by
207Peter Harris; implemented by Hye-Shik Chang, with adaptations by
208Raymond Hettinger.}
209
210\end{seealso}
Fred Drake2db76802004-12-01 05:05:47 +0000211
212
213%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000214\section{PEP 314: Metadata for Python Software Packages v1.1\label{pep-314}}
Fred Drakedb7b0022005-03-20 22:19:47 +0000215
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000216Some simple dependency support was added to Distutils. The
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000217\function{setup()} function now has \code{requires}, \code{provides},
218and \code{obsoletes} keyword parameters. When you build a source
219distribution using the \code{sdist} command, the dependency
220information will be recorded in the \file{PKG-INFO} file.
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000221
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000222Another new keyword parameter is \code{download_url}, which should be
223set to a URL for the package's source code. This means it's now
224possible to look up an entry in the package index, determine the
225dependencies for a package, and download the required packages.
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000226
Andrew M. Kuchling61434b62006-04-13 11:51:07 +0000227\begin{verbatim}
228VERSION = '1.0'
229setup(name='PyPackage',
230 version=VERSION,
231 requires=['numarray', 'zlib (>=1.1.4)'],
232 obsoletes=['OldPackage']
233 download_url=('http://www.example.com/pypackage/dist/pkg-%s.tar.gz'
234 % VERSION),
235 )
236\end{verbatim}
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000237
238\begin{seealso}
239
240\seepep{314}{Metadata for Python Software Packages v1.1}{PEP proposed
241and written by A.M. Kuchling, Richard Jones, and Fred Drake;
242implemented by Richard Jones and Fred Drake.}
243
244\end{seealso}
Fred Drakedb7b0022005-03-20 22:19:47 +0000245
246
247%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000248\section{PEP 328: Absolute and Relative Imports\label{pep-328}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000249
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000250The simpler part of PEP 328 was implemented in Python 2.4: parentheses
251could now be used to enclose the names imported from a module using
252the \code{from ... import ...} statement, making it easier to import
253many different names.
254
255The more complicated part has been implemented in Python 2.5:
256importing a module can be specified to use absolute or
257package-relative imports. The plan is to move toward making absolute
258imports the default in future versions of Python.
259
260Let's say you have a package directory like this:
261\begin{verbatim}
262pkg/
263pkg/__init__.py
264pkg/main.py
265pkg/string.py
266\end{verbatim}
267
268This defines a package named \module{pkg} containing the
269\module{pkg.main} and \module{pkg.string} submodules.
270
271Consider the code in the \file{main.py} module. What happens if it
272executes the statement \code{import string}? In Python 2.4 and
273earlier, it will first look in the package's directory to perform a
274relative import, finds \file{pkg/string.py}, imports the contents of
275that file as the \module{pkg.string} module, and that module is bound
276to the name \samp{string} in the \module{pkg.main} module's namespace.
277
278That's fine if \module{pkg.string} was what you wanted. But what if
279you wanted Python's standard \module{string} module? There's no clean
280way to ignore \module{pkg.string} and look for the standard module;
281generally you had to look at the contents of \code{sys.modules}, which
282is slightly unclean.
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000283Holger Krekel's \module{py.std} package provides a tidier way to perform
284imports from the standard library, \code{import py ; py.std.string.join()},
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000285but that package isn't available on all Python installations.
286
287Reading code which relies on relative imports is also less clear,
288because a reader may be confused about which module, \module{string}
289or \module{pkg.string}, is intended to be used. Python users soon
290learned not to duplicate the names of standard library modules in the
291names of their packages' submodules, but you can't protect against
292having your submodule's name being used for a new module added in a
293future version of Python.
294
295In Python 2.5, you can switch \keyword{import}'s behaviour to
296absolute imports using a \code{from __future__ import absolute_import}
297directive. This absolute-import behaviour will become the default in
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000298a future version (probably Python 2.7). Once absolute imports
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000299are the default, \code{import string} will
300always find the standard library's version.
301It's suggested that users should begin using absolute imports as much
302as possible, so it's preferable to begin writing \code{from pkg import
303string} in your code.
304
305Relative imports are still possible by adding a leading period
306to the module name when using the \code{from ... import} form:
307
308\begin{verbatim}
309# Import names from pkg.string
310from .string import name1, name2
311# Import pkg.string
312from . import string
313\end{verbatim}
314
315This imports the \module{string} module relative to the current
316package, so in \module{pkg.main} this will import \var{name1} and
317\var{name2} from \module{pkg.string}. Additional leading periods
318perform the relative import starting from the parent of the current
319package. For example, code in the \module{A.B.C} module can do:
320
321\begin{verbatim}
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000322from . import D # Imports A.B.D
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000323from .. import E # Imports A.E
324from ..F import G # Imports A.F.G
325\end{verbatim}
326
327Leading periods cannot be used with the \code{import \var{modname}}
328form of the import statement, only the \code{from ... import} form.
329
330\begin{seealso}
331
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000332\seepep{328}{Imports: Multi-Line and Absolute/Relative}
333{PEP written by Aahz; implemented by Thomas Wouters.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000334
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000335\seeurl{http://codespeak.net/py/current/doc/index.html}
336{The py library by Holger Krekel, which contains the \module{py.std} package.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000337
338\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000339
340
341%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000342\section{PEP 338: Executing Modules as Scripts\label{pep-338}}
Andrew M. Kuchling21d3a7c2006-03-15 11:53:09 +0000343
Andrew M. Kuchlingb182db42006-03-17 21:48:46 +0000344The \programopt{-m} switch added in Python 2.4 to execute a module as
345a script gained a few more abilities. Instead of being implemented in
346C code inside the Python interpreter, the switch now uses an
347implementation in a new module, \module{runpy}.
348
349The \module{runpy} module implements a more sophisticated import
350mechanism so that it's now possible to run modules in a package such
351as \module{pychecker.checker}. The module also supports alternative
Andrew M. Kuchling5d4cf5e2006-04-13 13:02:42 +0000352import mechanisms such as the \module{zipimport} module. This means
Andrew M. Kuchlingb182db42006-03-17 21:48:46 +0000353you can add a .zip archive's path to \code{sys.path} and then use the
354\programopt{-m} switch to execute code from the archive.
355
356
357\begin{seealso}
358
359\seepep{338}{Executing modules as scripts}{PEP written and
360implemented by Nick Coghlan.}
361
362\end{seealso}
Andrew M. Kuchling21d3a7c2006-03-15 11:53:09 +0000363
364
365%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000366\section{PEP 341: Unified try/except/finally\label{pep-341}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000367
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000368Until Python 2.5, the \keyword{try} statement came in two
369flavours. You could use a \keyword{finally} block to ensure that code
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +0000370is always executed, or one or more \keyword{except} blocks to catch
371specific exceptions. You couldn't combine both \keyword{except} blocks and a
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000372\keyword{finally} block, because generating the right bytecode for the
373combined version was complicated and it wasn't clear what the
374semantics of the combined should be.
375
376GvR spent some time working with Java, which does support the
377equivalent of combining \keyword{except} blocks and a
378\keyword{finally} block, and this clarified what the statement should
379mean. In Python 2.5, you can now write:
380
381\begin{verbatim}
382try:
383 block-1 ...
384except Exception1:
385 handler-1 ...
386except Exception2:
387 handler-2 ...
388else:
389 else-block
390finally:
391 final-block
392\end{verbatim}
393
394The code in \var{block-1} is executed. If the code raises an
Andrew M. Kuchling356af462006-05-10 17:19:04 +0000395exception, the various \keyword{except} blocks are tested: if the
396exception is of class \class{Exception1}, \var{handler-1} is executed;
397otherwise if it's of class \class{Exception2}, \var{handler-2} is
398executed, and so forth. If no exception is raised, the
399\var{else-block} is executed.
400
401No matter what happened previously, the \var{final-block} is executed
402once the code block is complete and any raised exceptions handled.
403Even if there's an error in an exception handler or the
404\var{else-block} and a new exception is raised, the
405code in the \var{final-block} is still run.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000406
407\begin{seealso}
408
409\seepep{341}{Unifying try-except and try-finally}{PEP written by Georg Brandl;
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000410implementation by Thomas Lee.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000411
412\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000413
414
415%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000416\section{PEP 342: New Generator Features\label{pep-342}}
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000417
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000418Python 2.5 adds a simple way to pass values \emph{into} a generator.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000419As introduced in Python 2.3, generators only produce output; once a
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000420generator's code is invoked to create an iterator, there's no way to
421pass any new information into the function when its execution is
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000422resumed. Sometimes the ability to pass in some information would be
423useful. Hackish solutions to this include making the generator's code
424look at a global variable and then changing the global variable's
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000425value, or passing in some mutable object that callers then modify.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000426
427To refresh your memory of basic generators, here's a simple example:
428
429\begin{verbatim}
430def counter (maximum):
431 i = 0
432 while i < maximum:
433 yield i
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000434 i += 1
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000435\end{verbatim}
436
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000437When you call \code{counter(10)}, the result is an iterator that
438returns the values from 0 up to 9. On encountering the
439\keyword{yield} statement, the iterator returns the provided value and
440suspends the function's execution, preserving the local variables.
441Execution resumes on the following call to the iterator's
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000442\method{next()} method, picking up after the \keyword{yield} statement.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000443
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000444In Python 2.3, \keyword{yield} was a statement; it didn't return any
445value. In 2.5, \keyword{yield} is now an expression, returning a
446value that can be assigned to a variable or otherwise operated on:
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000447
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000448\begin{verbatim}
449val = (yield i)
450\end{verbatim}
451
452I recommend that you always put parentheses around a \keyword{yield}
453expression when you're doing something with the returned value, as in
454the above example. The parentheses aren't always necessary, but it's
455easier to always add them instead of having to remember when they're
Andrew M. Kuchling3b675d22006-04-20 13:43:21 +0000456needed.
457
458(\pep{342} explains the exact rules, which are that a
459\keyword{yield}-expression must always be parenthesized except when it
460occurs at the top-level expression on the right-hand side of an
461assignment. This means you can write \code{val = yield i} but have to
462use parentheses when there's an operation, as in \code{val = (yield i)
463+ 12}.)
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000464
465Values are sent into a generator by calling its
466\method{send(\var{value})} method. The generator's code is then
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000467resumed and the \keyword{yield} expression returns the specified
468\var{value}. If the regular \method{next()} method is called, the
469\keyword{yield} returns \constant{None}.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000470
471Here's the previous example, modified to allow changing the value of
472the internal counter.
473
474\begin{verbatim}
475def counter (maximum):
476 i = 0
477 while i < maximum:
478 val = (yield i)
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000479 # If value provided, change counter
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000480 if val is not None:
481 i = val
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000482 else:
483 i += 1
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000484\end{verbatim}
485
486And here's an example of changing the counter:
487
488\begin{verbatim}
489>>> it = counter(10)
490>>> print it.next()
4910
492>>> print it.next()
4931
494>>> print it.send(8)
4958
496>>> print it.next()
4979
498>>> print it.next()
499Traceback (most recent call last):
500 File ``t.py'', line 15, in ?
501 print it.next()
502StopIteration
Andrew M. Kuchlingc2033702005-08-29 13:30:12 +0000503\end{verbatim}
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000504
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000505Because \keyword{yield} will often be returning \constant{None}, you
506should always check for this case. Don't just use its value in
507expressions unless you're sure that the \method{send()} method
508will be the only method used resume your generator function.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000509
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000510In addition to \method{send()}, there are two other new methods on
511generators:
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000512
513\begin{itemize}
514
515 \item \method{throw(\var{type}, \var{value}=None,
516 \var{traceback}=None)} is used to raise an exception inside the
517 generator; the exception is raised by the \keyword{yield} expression
518 where the generator's execution is paused.
519
520 \item \method{close()} raises a new \exception{GeneratorExit}
521 exception inside the generator to terminate the iteration.
522 On receiving this
523 exception, the generator's code must either raise
524 \exception{GeneratorExit} or \exception{StopIteration}; catching the
525 exception and doing anything else is illegal and will trigger
526 a \exception{RuntimeError}. \method{close()} will also be called by
527 Python's garbage collection when the generator is garbage-collected.
528
529 If you need to run cleanup code in case of a \exception{GeneratorExit},
530 I suggest using a \code{try: ... finally:} suite instead of
531 catching \exception{GeneratorExit}.
532
533\end{itemize}
534
535The cumulative effect of these changes is to turn generators from
536one-way producers of information into both producers and consumers.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000537
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000538Generators also become \emph{coroutines}, a more generalized form of
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000539subroutines. Subroutines are entered at one point and exited at
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000540another point (the top of the function, and a \keyword{return
541statement}), but coroutines can be entered, exited, and resumed at
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000542many different points (the \keyword{yield} statements). We'll have to
543figure out patterns for using coroutines effectively in Python.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000544
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000545The addition of the \method{close()} method has one side effect that
546isn't obvious. \method{close()} is called when a generator is
547garbage-collected, so this means the generator's code gets one last
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +0000548chance to run before the generator is destroyed. This last chance
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000549means that \code{try...finally} statements in generators can now be
550guaranteed to work; the \keyword{finally} clause will now always get a
551chance to run. The syntactic restriction that you couldn't mix
552\keyword{yield} statements with a \code{try...finally} suite has
553therefore been removed. This seems like a minor bit of language
554trivia, but using generators and \code{try...finally} is actually
555necessary in order to implement the \keyword{with} statement
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000556described by PEP 343. I'll look at this new statement in the following
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000557section.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000558
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +0000559Another even more esoteric effect of this change: previously, the
560\member{gi_frame} attribute of a generator was always a frame object.
561It's now possible for \member{gi_frame} to be \code{None}
562once the generator has been exhausted.
563
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000564\begin{seealso}
565
566\seepep{342}{Coroutines via Enhanced Generators}{PEP written by
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000567Guido van~Rossum and Phillip J. Eby;
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000568implemented by Phillip J. Eby. Includes examples of
569some fancier uses of generators as coroutines.}
570
571\seeurl{http://en.wikipedia.org/wiki/Coroutine}{The Wikipedia entry for
572coroutines.}
573
Neal Norwitz09179882006-03-04 23:31:45 +0000574\seeurl{http://www.sidhe.org/\~{}dan/blog/archives/000178.html}{An
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000575explanation of coroutines from a Perl point of view, written by Dan
576Sugalski.}
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000577
578\end{seealso}
579
580
581%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000582\section{PEP 343: The 'with' statement\label{pep-343}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000583
Andrew M. Kuchling0a7ed8c2006-04-24 14:30:47 +0000584The '\keyword{with}' statement clarifies code that previously would
585use \code{try...finally} blocks to ensure that clean-up code is
586executed. In this section, I'll discuss the statement as it will
587commonly be used. In the next section, I'll examine the
588implementation details and show how to write objects for use with this
589statement.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000590
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +0000591The '\keyword{with}' statement is a new control-flow structure whose
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000592basic structure is:
593
594\begin{verbatim}
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000595with expression [as variable]:
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000596 with-block
597\end{verbatim}
598
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000599The expression is evaluated, and it should result in an object that
600supports the context management protocol. This object may return a
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000601value that can optionally be bound to the name \var{variable}. (Note
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000602carefully that \var{variable} is \emph{not} assigned the result of
603\var{expression}.) The object can then run set-up code
604before \var{with-block} is executed and some clean-up code
605is executed after the block is done, even if the block raised an exception.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000606
607To enable the statement in Python 2.5, you need
608to add the following directive to your module:
609
610\begin{verbatim}
611from __future__ import with_statement
612\end{verbatim}
613
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000614The statement will always be enabled in Python 2.6.
615
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000616Some standard Python objects now support the context management
617protocol and can be used with the '\keyword{with}' statement. File
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000618objects are one example:
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000619
620\begin{verbatim}
621with open('/etc/passwd', 'r') as f:
622 for line in f:
623 print line
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000624 ... more processing code ...
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000625\end{verbatim}
626
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000627After this statement has executed, the file object in \var{f} will
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +0000628have been automatically closed, even if the 'for' loop
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000629raised an exception part-way through the block.
630
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000631The \module{threading} module's locks and condition variables
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +0000632also support the '\keyword{with}' statement:
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000633
634\begin{verbatim}
635lock = threading.Lock()
636with lock:
637 # Critical section of code
638 ...
639\end{verbatim}
640
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000641The lock is acquired before the block is executed and always released once
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000642the block is complete.
643
644The \module{decimal} module's contexts, which encapsulate the desired
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000645precision and rounding characteristics for computations, provide a
646\method{context_manager()} method for getting a context manager:
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000647
648\begin{verbatim}
649import decimal
650
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000651# Displays with default precision of 28 digits
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000652v1 = decimal.Decimal('578')
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000653print v1.sqrt()
654
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000655ctx = decimal.Context(prec=16)
656with ctx.context_manager():
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000657 # All code in this block uses a precision of 16 digits.
658 # The original context is restored on exiting the block.
659 print v1.sqrt()
660\end{verbatim}
661
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000662\subsection{Writing Context Managers\label{context-managers}}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000663
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +0000664Under the hood, the '\keyword{with}' statement is fairly complicated.
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000665Most people will only use '\keyword{with}' in company with existing
Andrew M. Kuchling0a7ed8c2006-04-24 14:30:47 +0000666objects and don't need to know these details, so you can skip the rest
667of this section if you like. Authors of new objects will need to
668understand the details of the underlying implementation and should
669keep reading.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000670
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000671A high-level explanation of the context management protocol is:
672
673\begin{itemize}
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000674
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000675\item The expression is evaluated and should result in an object
676called a ``context manager''. The context manager must have
Andrew M. Kuchling0a7ed8c2006-04-24 14:30:47 +0000677\method{__enter__()} and \method{__exit__()} methods.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000678
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000679\item The context manager's \method{__enter__()} method is called. The value
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000680returned is assigned to \var{VAR}. If no \code{'as \var{VAR}'} clause
681is present, the value is simply discarded.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000682
683\item The code in \var{BLOCK} is executed.
684
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000685\item If \var{BLOCK} raises an exception, the
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000686\method{__exit__(\var{type}, \var{value}, \var{traceback})} is called
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000687with the exception details, the same values returned by
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000688\function{sys.exc_info()}. The method's return value controls whether
689the exception is re-raised: any false value re-raises the exception,
690and \code{True} will result in suppressing it. You'll only rarely
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000691want to suppress the exception, because if you do
692the author of the code containing the
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000693'\keyword{with}' statement will never realize anything went wrong.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000694
695\item If \var{BLOCK} didn't raise an exception,
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000696the \method{__exit__()} method is still called,
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000697but \var{type}, \var{value}, and \var{traceback} are all \code{None}.
698
699\end{itemize}
700
701Let's think through an example. I won't present detailed code but
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000702will only sketch the methods necessary for a database that supports
703transactions.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000704
705(For people unfamiliar with database terminology: a set of changes to
706the database are grouped into a transaction. Transactions can be
707either committed, meaning that all the changes are written into the
708database, or rolled back, meaning that the changes are all discarded
709and the database is unchanged. See any database textbook for more
710information.)
711% XXX find a shorter reference?
712
713Let's assume there's an object representing a database connection.
714Our goal will be to let the user write code like this:
715
716\begin{verbatim}
717db_connection = DatabaseConnection()
718with db_connection as cursor:
719 cursor.execute('insert into ...')
720 cursor.execute('delete from ...')
721 # ... more operations ...
722\end{verbatim}
723
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000724The transaction should be committed if the code in the block
725runs flawlessly or rolled back if there's an exception.
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000726Here's the basic interface
727for \class{DatabaseConnection} that I'll assume:
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000728
729\begin{verbatim}
730class DatabaseConnection:
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000731 # Database interface
732 def cursor (self):
733 "Returns a cursor object and starts a new transaction"
734 def commit (self):
735 "Commits current transaction"
736 def rollback (self):
737 "Rolls back current transaction"
738\end{verbatim}
739
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000740The \method {__enter__()} method is pretty easy, having only to start
741a new transaction. For this application the resulting cursor object
742would be a useful result, so the method will return it. The user can
743then add \code{as cursor} to their '\keyword{with}' statement to bind
744the cursor to a variable name.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000745
746\begin{verbatim}
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000747class DatabaseConnection:
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000748 ...
749 def __enter__ (self):
750 # Code to start a new transaction
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000751 cursor = self.cursor()
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000752 return cursor
753\end{verbatim}
754
755The \method{__exit__()} method is the most complicated because it's
756where most of the work has to be done. The method has to check if an
757exception occurred. If there was no exception, the transaction is
758committed. The transaction is rolled back if there was an exception.
Andrew M. Kuchling0a7ed8c2006-04-24 14:30:47 +0000759
760In the code below, execution will just fall off the end of the
761function, returning the default value of \code{None}. \code{None} is
762false, so the exception will be re-raised automatically. If you
763wished, you could be more explicit and add a \keyword{return}
764statement at the marked location.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000765
766\begin{verbatim}
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000767class DatabaseConnection:
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000768 ...
769 def __exit__ (self, type, value, tb):
770 if tb is None:
771 # No exception, so commit
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000772 self.commit()
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000773 else:
774 # Exception occurred, so rollback.
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000775 self.rollback()
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000776 # return False
777\end{verbatim}
778
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000779
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000780\subsection{The contextlib module\label{module-contextlib}}
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000781
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000782The new \module{contextlib} module provides some functions and a
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000783decorator that are useful for writing objects for use with the
784'\keyword{with}' statement.
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000785
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000786The decorator is called \function{contextfactory}, and lets you write
787a single generator function instead of defining a new class. The generator
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000788should yield exactly one value. The code up to the \keyword{yield}
789will be executed as the \method{__enter__()} method, and the value
790yielded will be the method's return value that will get bound to the
791variable in the '\keyword{with}' statement's \keyword{as} clause, if
792any. The code after the \keyword{yield} will be executed in the
793\method{__exit__()} method. Any exception raised in the block will be
794raised by the \keyword{yield} statement.
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000795
796Our database example from the previous section could be written
797using this decorator as:
798
799\begin{verbatim}
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000800from contextlib import contextfactory
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000801
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000802@contextfactory
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000803def db_transaction (connection):
804 cursor = connection.cursor()
805 try:
806 yield cursor
807 except:
808 connection.rollback()
809 raise
810 else:
811 connection.commit()
812
813db = DatabaseConnection()
814with db_transaction(db) as cursor:
815 ...
816\end{verbatim}
817
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000818The \module{contextlib} module also has a \function{nested(\var{mgr1},
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000819\var{mgr2}, ...)} function that combines a number of context managers so you
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000820don't need to write nested '\keyword{with}' statements. In this
821example, the single '\keyword{with}' statement both starts a database
822transaction and acquires a thread lock:
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000823
824\begin{verbatim}
825lock = threading.Lock()
826with nested (db_transaction(db), lock) as (cursor, locked):
827 ...
828\end{verbatim}
829
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000830Finally, the \function{closing(\var{object})} function
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000831returns \var{object} so that it can be bound to a variable,
832and calls \code{\var{object}.close()} at the end of the block.
833
834\begin{verbatim}
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +0000835import urllib, sys
836from contextlib import closing
837
838with closing(urllib.urlopen('http://www.yahoo.com')) as f:
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000839 for line in f:
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +0000840 sys.stdout.write(line)
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000841\end{verbatim}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000842
843\begin{seealso}
844
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000845\seepep{343}{The ``with'' statement}{PEP written by Guido van~Rossum
846and Nick Coghlan; implemented by Mike Bland, Guido van~Rossum, and
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +0000847Neal Norwitz. The PEP shows the code generated for a '\keyword{with}'
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000848statement, which can be helpful in learning how the statement works.}
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000849
850\seeurl{../lib/module-contextlib.html}{The documentation
851for the \module{contextlib} module.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000852
853\end{seealso}
854
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000855
856%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000857\section{PEP 352: Exceptions as New-Style Classes\label{pep-352}}
Andrew M. Kuchling8f4d2552006-03-08 01:50:20 +0000858
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000859Exception classes can now be new-style classes, not just classic
860classes, and the built-in \exception{Exception} class and all the
861standard built-in exceptions (\exception{NameError},
862\exception{ValueError}, etc.) are now new-style classes.
Andrew M. Kuchlingaeadf952006-03-09 19:06:05 +0000863
864The inheritance hierarchy for exceptions has been rearranged a bit.
865In 2.5, the inheritance relationships are:
866
867\begin{verbatim}
868BaseException # New in Python 2.5
869|- KeyboardInterrupt
870|- SystemExit
871|- Exception
872 |- (all other current built-in exceptions)
873\end{verbatim}
874
875This rearrangement was done because people often want to catch all
876exceptions that indicate program errors. \exception{KeyboardInterrupt} and
877\exception{SystemExit} aren't errors, though, and usually represent an explicit
878action such as the user hitting Control-C or code calling
879\function{sys.exit()}. A bare \code{except:} will catch all exceptions,
880so you commonly need to list \exception{KeyboardInterrupt} and
881\exception{SystemExit} in order to re-raise them. The usual pattern is:
882
883\begin{verbatim}
884try:
885 ...
886except (KeyboardInterrupt, SystemExit):
887 raise
888except:
889 # Log error...
890 # Continue running program...
891\end{verbatim}
892
893In Python 2.5, you can now write \code{except Exception} to achieve
894the same result, catching all the exceptions that usually indicate errors
895but leaving \exception{KeyboardInterrupt} and
896\exception{SystemExit} alone. As in previous versions,
897a bare \code{except:} still catches all exceptions.
898
899The goal for Python 3.0 is to require any class raised as an exception
900to derive from \exception{BaseException} or some descendant of
901\exception{BaseException}, and future releases in the
902Python 2.x series may begin to enforce this constraint. Therefore, I
903suggest you begin making all your exception classes derive from
904\exception{Exception} now. It's been suggested that the bare
905\code{except:} form should be removed in Python 3.0, but Guido van~Rossum
906hasn't decided whether to do this or not.
907
908Raising of strings as exceptions, as in the statement \code{raise
909"Error occurred"}, is deprecated in Python 2.5 and will trigger a
910warning. The aim is to be able to remove the string-exception feature
911in a few releases.
912
913
914\begin{seealso}
915
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000916\seepep{352}{Required Superclass for Exceptions}{PEP written by
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000917Brett Cannon and Guido van~Rossum; implemented by Brett Cannon.}
Andrew M. Kuchlingaeadf952006-03-09 19:06:05 +0000918
919\end{seealso}
Andrew M. Kuchling8f4d2552006-03-08 01:50:20 +0000920
921
922%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000923\section{PEP 353: Using ssize_t as the index type\label{pep-353}}
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000924
925A wide-ranging change to Python's C API, using a new
926\ctype{Py_ssize_t} type definition instead of \ctype{int},
927will permit the interpreter to handle more data on 64-bit platforms.
928This change doesn't affect Python's capacity on 32-bit platforms.
929
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000930Various pieces of the Python interpreter used C's \ctype{int} type to
931store sizes or counts; for example, the number of items in a list or
932tuple were stored in an \ctype{int}. The C compilers for most 64-bit
933platforms still define \ctype{int} as a 32-bit type, so that meant
934that lists could only hold up to \code{2**31 - 1} = 2147483647 items.
935(There are actually a few different programming models that 64-bit C
936compilers can use -- see
937\url{http://www.unix.org/version2/whatsnew/lp64_wp.html} for a
938discussion -- but the most commonly available model leaves \ctype{int}
939as 32 bits.)
940
941A limit of 2147483647 items doesn't really matter on a 32-bit platform
942because you'll run out of memory before hitting the length limit.
943Each list item requires space for a pointer, which is 4 bytes, plus
944space for a \ctype{PyObject} representing the item. 2147483647*4 is
945already more bytes than a 32-bit address space can contain.
946
947It's possible to address that much memory on a 64-bit platform,
948however. The pointers for a list that size would only require 16GiB
949of space, so it's not unreasonable that Python programmers might
950construct lists that large. Therefore, the Python interpreter had to
951be changed to use some type other than \ctype{int}, and this will be a
95264-bit type on 64-bit platforms. The change will cause
953incompatibilities on 64-bit machines, so it was deemed worth making
954the transition now, while the number of 64-bit users is still
955relatively small. (In 5 or 10 years, we may \emph{all} be on 64-bit
956machines, and the transition would be more painful then.)
957
958This change most strongly affects authors of C extension modules.
959Python strings and container types such as lists and tuples
960now use \ctype{Py_ssize_t} to store their size.
961Functions such as \cfunction{PyList_Size()}
962now return \ctype{Py_ssize_t}. Code in extension modules
963may therefore need to have some variables changed to
964\ctype{Py_ssize_t}.
965
966The \cfunction{PyArg_ParseTuple()} and \cfunction{Py_BuildValue()} functions
967have a new conversion code, \samp{n}, for \ctype{Py_ssize_t}.
Andrew M. Kuchlinga4d651f2006-04-06 13:24:58 +0000968\cfunction{PyArg_ParseTuple()}'s \samp{s\#} and \samp{t\#} still output
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000969\ctype{int} by default, but you can define the macro
970\csimplemacro{PY_SSIZE_T_CLEAN} before including \file{Python.h}
971to make them return \ctype{Py_ssize_t}.
972
973\pep{353} has a section on conversion guidelines that
974extension authors should read to learn about supporting 64-bit
975platforms.
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000976
977\begin{seealso}
978
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +0000979\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 +0000980
981\end{seealso}
982
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000983
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000984%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000985\section{PEP 357: The '__index__' method\label{pep-357}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000986
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000987The NumPy developers had a problem that could only be solved by adding
988a new special method, \method{__index__}. When using slice notation,
Fred Drake1c0e3282006-04-02 03:30:06 +0000989as in \code{[\var{start}:\var{stop}:\var{step}]}, the values of the
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000990\var{start}, \var{stop}, and \var{step} indexes must all be either
991integers or long integers. NumPy defines a variety of specialized
992integer types corresponding to unsigned and signed integers of 8, 16,
99332, and 64 bits, but there was no way to signal that these types could
994be used as slice indexes.
995
996Slicing can't just use the existing \method{__int__} method because
997that method is also used to implement coercion to integers. If
998slicing used \method{__int__}, floating-point numbers would also
999become legal slice indexes and that's clearly an undesirable
1000behaviour.
1001
1002Instead, a new special method called \method{__index__} was added. It
1003takes no arguments and returns an integer giving the slice index to
1004use. For example:
1005
1006\begin{verbatim}
1007class C:
1008 def __index__ (self):
1009 return self.value
1010\end{verbatim}
1011
1012The return value must be either a Python integer or long integer.
1013The interpreter will check that the type returned is correct, and
1014raises a \exception{TypeError} if this requirement isn't met.
1015
1016A corresponding \member{nb_index} slot was added to the C-level
1017\ctype{PyNumberMethods} structure to let C extensions implement this
1018protocol. \cfunction{PyNumber_Index(\var{obj})} can be used in
1019extension code to call the \method{__index__} function and retrieve
1020its result.
1021
1022\begin{seealso}
1023
1024\seepep{357}{Allowing Any Object to be Used for Slicing}{PEP written
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +00001025and implemented by Travis Oliphant.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001026
1027\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +00001028
1029
1030%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001031\section{Other Language Changes\label{other-lang}}
Fred Drake2db76802004-12-01 05:05:47 +00001032
1033Here are all of the changes that Python 2.5 makes to the core Python
1034language.
1035
1036\begin{itemize}
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001037
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001038\item The \class{dict} type has a new hook for letting subclasses
1039provide a default value when a key isn't contained in the dictionary.
1040When a key isn't found, the dictionary's
1041\method{__missing__(\var{key})}
1042method will be called. This hook is used to implement
1043the new \class{defaultdict} class in the \module{collections}
1044module. The following example defines a dictionary
1045that returns zero for any missing key:
1046
1047\begin{verbatim}
1048class zerodict (dict):
1049 def __missing__ (self, key):
1050 return 0
1051
1052d = zerodict({1:1, 2:2})
1053print d[1], d[2] # Prints 1, 2
1054print d[3], d[4] # Prints 0, 0
1055\end{verbatim}
1056
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001057\item The \function{min()} and \function{max()} built-in functions
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001058gained a \code{key} keyword parameter analogous to the \code{key}
1059argument for \method{sort()}. This parameter supplies a function that
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001060takes a single argument and is called for every value in the list;
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001061\function{min()}/\function{max()} will return the element with the
1062smallest/largest return value from this function.
1063For example, to find the longest string in a list, you can do:
1064
1065\begin{verbatim}
1066L = ['medium', 'longest', 'short']
1067# Prints 'longest'
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001068print max(L, key=len)
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001069# Prints 'short', because lexicographically 'short' has the largest value
1070print max(L)
1071\end{verbatim}
1072
1073(Contributed by Steven Bethard and Raymond Hettinger.)
Fred Drake2db76802004-12-01 05:05:47 +00001074
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001075\item Two new built-in functions, \function{any()} and
1076\function{all()}, evaluate whether an iterator contains any true or
1077false values. \function{any()} returns \constant{True} if any value
1078returned by the iterator is true; otherwise it will return
1079\constant{False}. \function{all()} returns \constant{True} only if
1080all of the values returned by the iterator evaluate as being true.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001081(Suggested by GvR, and implemented by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001082
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001083\item ASCII is now the default encoding for modules. It's now
1084a syntax error if a module contains string literals with 8-bit
1085characters but doesn't have an encoding declaration. In Python 2.4
1086this triggered a warning, not a syntax error. See \pep{263}
1087for how to declare a module's encoding; for example, you might add
1088a line like this near the top of the source file:
1089
1090\begin{verbatim}
1091# -*- coding: latin1 -*-
1092\end{verbatim}
1093
Andrew M. Kuchlingc9236112006-04-30 01:07:09 +00001094\item One error that Python programmers sometimes make is forgetting
1095to include an \file{__init__.py} module in a package directory.
1096Debugging this mistake can be confusing, and usually requires running
1097Python with the \programopt{-v} switch to log all the paths searched.
1098In Python 2.5, a new \exception{ImportWarning} warning is raised when
1099an import would have picked up a directory as a package but no
1100\file{__init__.py} was found. (Implemented by Thomas Wouters.)
1101
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001102\item The list of base classes in a class definition can now be empty.
1103As an example, this is now legal:
1104
1105\begin{verbatim}
1106class C():
1107 pass
1108\end{verbatim}
1109(Implemented by Brett Cannon.)
1110
Fred Drake2db76802004-12-01 05:05:47 +00001111\end{itemize}
1112
1113
1114%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001115\subsection{Interactive Interpreter Changes\label{interactive}}
Andrew M. Kuchlingda376042006-03-17 15:56:41 +00001116
1117In the interactive interpreter, \code{quit} and \code{exit}
1118have long been strings so that new users get a somewhat helpful message
1119when they try to quit:
1120
1121\begin{verbatim}
1122>>> quit
1123'Use Ctrl-D (i.e. EOF) to exit.'
1124\end{verbatim}
1125
1126In Python 2.5, \code{quit} and \code{exit} are now objects that still
1127produce string representations of themselves, but are also callable.
1128Newbies who try \code{quit()} or \code{exit()} will now exit the
1129interpreter as they expect. (Implemented by Georg Brandl.)
1130
1131
1132%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001133\subsection{Optimizations\label{opts}}
Fred Drake2db76802004-12-01 05:05:47 +00001134
1135\begin{itemize}
1136
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001137\item When they were introduced
1138in Python 2.4, the built-in \class{set} and \class{frozenset} types
1139were built on top of Python's dictionary type.
1140In 2.5 the internal data structure has been customized for implementing sets,
1141and as a result sets will use a third less memory and are somewhat faster.
1142(Implemented by Raymond Hettinger.)
Fred Drake2db76802004-12-01 05:05:47 +00001143
Andrew M. Kuchling45bb98e2006-04-16 19:53:27 +00001144\item The performance of some Unicode operations, such as
1145character map decoding, has been improved.
1146% Patch 1313939
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001147
1148\item The code generator's peephole optimizer now performs
1149simple constant folding in expressions. If you write something like
1150\code{a = 2+3}, the code generator will do the arithmetic and produce
1151code corresponding to \code{a = 5}.
1152
Fred Drake2db76802004-12-01 05:05:47 +00001153\end{itemize}
1154
1155The net result of the 2.5 optimizations is that Python 2.5 runs the
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +00001156pystone benchmark around XXX\% faster than Python 2.4.
Fred Drake2db76802004-12-01 05:05:47 +00001157
1158
1159%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001160\section{New, Improved, and Removed Modules\label{modules}}
Fred Drake2db76802004-12-01 05:05:47 +00001161
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +00001162The standard library received many enhancements and bug fixes in
1163Python 2.5. Here's a partial list of the most notable changes, sorted
1164alphabetically by module name. Consult the \file{Misc/NEWS} file in
1165the source tree for a more complete list of changes, or look through
1166the SVN logs for all the details.
Fred Drake2db76802004-12-01 05:05:47 +00001167
1168\begin{itemize}
1169
Andrew M. Kuchling6fc69762006-04-13 12:37:21 +00001170\item The \module{audioop} module now supports the a-LAW encoding,
1171and the code for u-LAW encoding has been improved. (Contributed by
1172Lars Immisch.)
1173
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001174\item The \module{codecs} module gained support for incremental
1175codecs. The \function{codec.lookup()} function now
1176returns a \class{CodecInfo} instance instead of a tuple.
1177\class{CodecInfo} instances behave like a 4-tuple to preserve backward
1178compatibility but also have the attributes \member{encode},
1179\member{decode}, \member{incrementalencoder}, \member{incrementaldecoder},
1180\member{streamwriter}, and \member{streamreader}. Incremental codecs
1181can receive input and produce output in multiple chunks; the output is
1182the same as if the entire input was fed to the non-incremental codec.
1183See the \module{codecs} module documentation for details.
1184(Designed and implemented by Walter D\"orwald.)
1185% Patch 1436130
1186
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001187\item The \module{collections} module gained a new type,
1188\class{defaultdict}, that subclasses the standard \class{dict}
1189type. The new type mostly behaves like a dictionary but constructs a
1190default value when a key isn't present, automatically adding it to the
1191dictionary for the requested key value.
1192
1193The first argument to \class{defaultdict}'s constructor is a factory
1194function that gets called whenever a key is requested but not found.
1195This factory function receives no arguments, so you can use built-in
1196type constructors such as \function{list()} or \function{int()}. For
1197example,
1198you can make an index of words based on their initial letter like this:
1199
1200\begin{verbatim}
1201words = """Nel mezzo del cammin di nostra vita
1202mi ritrovai per una selva oscura
1203che la diritta via era smarrita""".lower().split()
1204
1205index = defaultdict(list)
1206
1207for w in words:
1208 init_letter = w[0]
1209 index[init_letter].append(w)
1210\end{verbatim}
1211
1212Printing \code{index} results in the following output:
1213
1214\begin{verbatim}
1215defaultdict(<type 'list'>, {'c': ['cammin', 'che'], 'e': ['era'],
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001216 'd': ['del', 'di', 'diritta'], 'm': ['mezzo', 'mi'],
1217 'l': ['la'], 'o': ['oscura'], 'n': ['nel', 'nostra'],
1218 'p': ['per'], 's': ['selva', 'smarrita'],
1219 'r': ['ritrovai'], 'u': ['una'], 'v': ['vita', 'via']}
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001220\end{verbatim}
1221
1222The \class{deque} double-ended queue type supplied by the
1223\module{collections} module now has a \method{remove(\var{value})}
1224method that removes the first occurrence of \var{value} in the queue,
1225raising \exception{ValueError} if the value isn't found.
1226
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001227\item New module: The \module{contextlib} module contains helper functions for use
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001228with the new '\keyword{with}' statement. See
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001229section~\ref{module-contextlib} for more about this module.
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +00001230
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001231\item New module: The \module{cProfile} module is a C implementation of
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001232the existing \module{profile} module that has much lower overhead.
1233The module's interface is the same as \module{profile}: you run
1234\code{cProfile.run('main()')} to profile a function, can save profile
1235data to a file, etc. It's not yet known if the Hotshot profiler,
1236which is also written in C but doesn't match the \module{profile}
1237module's interface, will continue to be maintained in future versions
1238of Python. (Contributed by Armin Rigo.)
1239
Andrew M. Kuchling0a7ed8c2006-04-24 14:30:47 +00001240Also, the \module{pstats} module for analyzing the data measured by
1241the profiler now supports directing the output to any file object
Andrew M. Kuchlinge78eeb12006-04-21 13:26:42 +00001242by supplying a \var{stream} argument to the \class{Stats} constructor.
1243(Contributed by Skip Montanaro.)
1244
Andrew M. Kuchling952f1962006-04-18 12:38:19 +00001245\item The \module{csv} module, which parses files in
1246comma-separated value format, received several enhancements and a
1247number of bugfixes. You can now set the maximum size in bytes of a
1248field by calling the \method{csv.field_size_limit(\var{new_limit})}
1249function; omitting the \var{new_limit} argument will return the
1250currently-set limit. The \class{reader} class now has a
1251\member{line_num} attribute that counts the number of physical lines
1252read from the source; records can span multiple physical lines, so
1253\member{line_num} is not the same as the number of records read.
1254(Contributed by Skip Montanaro and Andrew McNamara.)
1255
Andrew M. Kuchling67191312006-04-19 12:55:39 +00001256\item The \class{datetime} class in the \module{datetime}
1257module now has a \method{strptime(\var{string}, \var{format})}
1258method for parsing date strings, contributed by Josh Spoerri.
1259It uses the same format characters as \function{time.strptime()} and
1260\function{time.strftime()}:
1261
1262\begin{verbatim}
1263from datetime import datetime
1264
1265ts = datetime.strptime('10:13:15 2006-03-07',
1266 '%H:%M:%S %Y-%m-%d')
1267\end{verbatim}
1268
Andrew M. Kuchlingb33842a2006-04-25 12:31:38 +00001269\item The \module{doctest} module gained a \code{SKIP} option that
1270keeps an example from being executed at all. This is intended for
1271code snippets that are usage examples intended for the reader and
1272aren't actually test cases.
1273
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001274\item The \module{fileinput} module was made more flexible.
1275Unicode filenames are now supported, and a \var{mode} parameter that
1276defaults to \code{"r"} was added to the
1277\function{input()} function to allow opening files in binary or
1278universal-newline mode. Another new parameter, \var{openhook},
1279lets you use a function other than \function{open()}
1280to open the input files. Once you're iterating over
1281the set of files, the \class{FileInput} object's new
1282\method{fileno()} returns the file descriptor for the currently opened file.
1283(Contributed by Georg Brandl.)
1284
Andrew M. Kuchlingda376042006-03-17 15:56:41 +00001285\item In the \module{gc} module, the new \function{get_count()} function
1286returns a 3-tuple containing the current collection counts for the
1287three GC generations. This is accounting information for the garbage
1288collector; when these counts reach a specified threshold, a garbage
1289collection sweep will be made. The existing \function{gc.collect()}
1290function now takes an optional \var{generation} argument of 0, 1, or 2
1291to specify which generation to collect.
1292
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001293\item The \function{nsmallest()} and
1294\function{nlargest()} functions in the \module{heapq} module
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001295now support a \code{key} keyword parameter similar to the one
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001296provided by the \function{min()}/\function{max()} functions
1297and the \method{sort()} methods. For example:
1298Example:
1299
1300\begin{verbatim}
1301>>> import heapq
1302>>> L = ["short", 'medium', 'longest', 'longer still']
1303>>> heapq.nsmallest(2, L) # Return two lowest elements, lexicographically
1304['longer still', 'longest']
1305>>> heapq.nsmallest(2, L, key=len) # Return two shortest elements
1306['short', 'medium']
1307\end{verbatim}
1308
1309(Contributed by Raymond Hettinger.)
1310
Andrew M. Kuchling511a3a82005-03-20 19:52:18 +00001311\item The \function{itertools.islice()} function now accepts
1312\code{None} for the start and step arguments. This makes it more
1313compatible with the attributes of slice objects, so that you can now write
1314the following:
1315
1316\begin{verbatim}
1317s = slice(5) # Create slice object
1318itertools.islice(iterable, s.start, s.stop, s.step)
1319\end{verbatim}
1320
1321(Contributed by Raymond Hettinger.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001322
Andrew M. Kuchlingd4c21772006-04-23 21:51:10 +00001323\item The \module{mailbox} module underwent a massive rewrite to add
1324the capability to modify mailboxes in addition to reading them. A new
1325set of classes that include \class{mbox}, \class{MH}, and
1326\class{Maildir} are used to read mailboxes, and have an
1327\method{add(\var{message})} method to add messages,
1328\method{remove(\var{key})} to remove messages, and
1329\method{lock()}/\method{unlock()} to lock/unlock the mailbox. The
1330following example converts a maildir-format mailbox into an mbox-format one:
1331
1332\begin{verbatim}
1333import mailbox
1334
1335# 'factory=None' uses email.Message.Message as the class representing
1336# individual messages.
1337src = mailbox.Maildir('maildir', factory=None)
1338dest = mailbox.mbox('/tmp/mbox')
1339
1340for msg in src:
1341 dest.add(msg)
1342\end{verbatim}
1343
1344(Contributed by Gregory K. Johnson. Funding was provided by Google's
13452005 Summer of Code.)
1346
Andrew M. Kuchling68494882006-05-01 16:32:49 +00001347\item New module: the \module{msilib} module allows creating
1348Microsoft Installer \file{.msi} files and CAB files. Some support
1349for reading the \file{.msi} database is also included.
1350(Contributed by Martin von~L\"owis.)
1351
Andrew M. Kuchling75ba2442006-04-14 10:29:55 +00001352\item The \module{nis} module now supports accessing domains other
1353than the system default domain by supplying a \var{domain} argument to
1354the \function{nis.match()} and \function{nis.maps()} functions.
1355(Contributed by Ben Bell.)
1356
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001357\item The \module{operator} module's \function{itemgetter()}
1358and \function{attrgetter()} functions now support multiple fields.
1359A call such as \code{operator.attrgetter('a', 'b')}
1360will return a function
1361that retrieves the \member{a} and \member{b} attributes. Combining
1362this new feature with the \method{sort()} method's \code{key} parameter
1363lets you easily sort lists using multiple fields.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001364(Contributed by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001365
Andrew M. Kuchlingd4c21772006-04-23 21:51:10 +00001366\item The \module{optparse} module was updated to version 1.5.1 of the
1367Optik library. The \class{OptionParser} class gained an
1368\member{epilog} attribute, a string that will be printed after the
1369help message, and a \method{destroy()} method to break reference
1370cycles created by the object. (Contributed by Greg Ward.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001371
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +00001372\item The \module{os} module underwent several changes. The
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001373\member{stat_float_times} variable now defaults to true, meaning that
1374\function{os.stat()} will now return time values as floats. (This
1375doesn't necessarily mean that \function{os.stat()} will return times
1376that are precise to fractions of a second; not all systems support
1377such precision.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001378
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001379Constants named \member{os.SEEK_SET}, \member{os.SEEK_CUR}, and
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001380\member{os.SEEK_END} have been added; these are the parameters to the
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001381\function{os.lseek()} function. Two new constants for locking are
1382\member{os.O_SHLOCK} and \member{os.O_EXLOCK}.
1383
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001384Two new functions, \function{wait3()} and \function{wait4()}, were
1385added. They're similar the \function{waitpid()} function which waits
1386for a child process to exit and returns a tuple of the process ID and
1387its exit status, but \function{wait3()} and \function{wait4()} return
1388additional information. \function{wait3()} doesn't take a process ID
1389as input, so it waits for any child process to exit and returns a
13903-tuple of \var{process-id}, \var{exit-status}, \var{resource-usage}
1391as returned from the \function{resource.getrusage()} function.
1392\function{wait4(\var{pid})} does take a process ID.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001393(Contributed by Chad J. Schroeder.)
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001394
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001395On FreeBSD, the \function{os.stat()} function now returns
1396times with nanosecond resolution, and the returned object
1397now has \member{st_gen} and \member{st_birthtime}.
1398The \member{st_flags} member is also available, if the platform supports it.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001399(Contributed by Antti Louko and Diego Petten\`o.)
1400% (Patch 1180695, 1212117)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001401
Andrew M. Kuchlingb33842a2006-04-25 12:31:38 +00001402\item The Python debugger provided by the \module{pdb} module
1403can now store lists of commands to execute when a breakpoint is
George Yoshida3bbbc492006-04-25 14:09:58 +00001404reached and execution stops. Once breakpoint \#1 has been created,
Andrew M. Kuchlingb33842a2006-04-25 12:31:38 +00001405enter \samp{commands 1} and enter a series of commands to be executed,
1406finishing the list with \samp{end}. The command list can include
1407commands that resume execution, such as \samp{continue} or
1408\samp{next}. (Contributed by Gr\'egoire Dooms.)
1409% Patch 790710
1410
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001411\item The \module{pickle} and \module{cPickle} modules no
1412longer accept a return value of \code{None} from the
1413\method{__reduce__()} method; the method must return a tuple of
1414arguments instead. The ability to return \code{None} was deprecated
1415in Python 2.4, so this completes the removal of the feature.
1416
Andrew M. Kuchlingaa013da2006-04-29 12:10:43 +00001417\item The \module{pkgutil} module, containing various utility
1418functions for finding packages, was enhanced to support PEP 302's
1419import hooks and now also works for packages stored in ZIP-format archives.
1420(Contributed by Phillip J. Eby.)
1421
Andrew M. Kuchlingc9236112006-04-30 01:07:09 +00001422\item The pybench benchmark suite by Marc-Andr\'e~Lemburg is now
1423included in the \file{Tools/pybench} directory. The pybench suite is
1424an improvement on the commonly used \file{pystone.py} program because
1425pybench provides a more detailed measurement of the interpreter's
1426performance. It times particular operations such as function calls,
1427tuple slicing, method lookups, and numeric operations, instead of
1428performing many different operations and reducing the result to a
1429single number as \file{pystone.py} does.
1430
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001431\item The old \module{regex} and \module{regsub} modules, which have been
1432deprecated ever since Python 2.0, have finally been deleted.
Andrew M. Kuchlingf4b06602006-03-17 15:39:52 +00001433Other deleted modules: \module{statcache}, \module{tzparse},
1434\module{whrandom}.
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001435
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001436\item Also deleted: the \file{lib-old} directory,
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001437which includes ancient modules such as \module{dircmp} and
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001438\module{ni}, was removed. \file{lib-old} wasn't on the default
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001439\code{sys.path}, so unless your programs explicitly added the directory to
1440\code{sys.path}, this removal shouldn't affect your code.
1441
Andrew M. Kuchling09612282006-04-30 21:19:49 +00001442\item The \module{rlcompleter} module is no longer
1443dependent on importing the \module{readline} module and
1444therefore now works on non-{\UNIX} platforms.
1445(Patch from Robert Kiendl.)
1446% Patch #1472854
1447
Andrew M. Kuchling4678dc82006-01-15 16:11:28 +00001448\item The \module{socket} module now supports \constant{AF_NETLINK}
1449sockets on Linux, thanks to a patch from Philippe Biondi.
1450Netlink sockets are a Linux-specific mechanism for communications
1451between a user-space process and kernel code; an introductory
1452article about them is at \url{http://www.linuxjournal.com/article/7356}.
1453In Python code, netlink addresses are represented as a tuple of 2 integers,
1454\code{(\var{pid}, \var{group_mask})}.
1455
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001456Socket objects also gained accessor methods \method{getfamily()},
1457\method{gettype()}, and \method{getproto()} methods to retrieve the
1458family, type, and protocol values for the socket.
1459
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001460\item New module: the \module{spwd} module provides functions for
1461accessing the shadow password database on systems that support
1462shadow passwords.
Fred Drake2db76802004-12-01 05:05:47 +00001463
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001464\item The Python developers switched from CVS to Subversion during the 2.5
1465development process. Information about the exact build version is
1466available as the \code{sys.subversion} variable, a 3-tuple
1467of \code{(\var{interpreter-name}, \var{branch-name}, \var{revision-range})}.
1468For example, at the time of writing
1469my copy of 2.5 was reporting \code{('CPython', 'trunk', '45313:45315')}.
1470
1471This information is also available to C extensions via the
1472\cfunction{Py_GetBuildInfo()} function that returns a
1473string of build information like this:
1474\code{"trunk:45355:45356M, Apr 13 2006, 07:42:19"}.
1475(Contributed by Barry Warsaw.)
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001476
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001477\item The \class{TarFile} class in the \module{tarfile} module now has
Georg Brandl08c02db2005-07-22 18:39:19 +00001478an \method{extractall()} method that extracts all members from the
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001479archive into the current working directory. It's also possible to set
1480a different directory as the extraction target, and to unpack only a
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001481subset of the archive's members.
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001482
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001483A tarfile's compression can be autodetected by
1484using the mode \code{'r|*'}.
1485% patch 918101
1486(Contributed by Lars Gust\"abel.)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001487
Andrew M. Kuchlingf688cc52006-03-10 18:50:08 +00001488\item The \module{unicodedata} module has been updated to use version 4.1.0
1489of the Unicode character database. Version 3.2.0 is required
1490by some specifications, so it's still available as
1491\member{unicodedata.db_3_2_0}.
1492
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001493\item The \module{webbrowser} module received a number of
1494enhancements.
1495It's now usable as a script with \code{python -m webbrowser}, taking a
1496URL as the argument; there are a number of switches
1497to control the behaviour (\programopt{-n} for a new browser window,
1498\programopt{-t} for a new tab). New module-level functions,
1499\function{open_new()} and \function{open_new_tab()}, were added
1500to support this. The module's \function{open()} function supports an
1501additional feature, an \var{autoraise} parameter that signals whether
1502to raise the open window when possible. A number of additional
1503browsers were added to the supported list such as Firefox, Opera,
1504Konqueror, and elinks. (Contributed by Oleg Broytmann and George
1505Brandl.)
1506% Patch #754022
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001507
Fredrik Lundh7e0aef02005-12-12 18:54:55 +00001508
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001509\item The \module{xmlrpclib} module now supports returning
1510 \class{datetime} objects for the XML-RPC date type. Supply
1511 \code{use_datetime=True} to the \function{loads()} function
1512 or the \class{Unmarshaller} class to enable this feature.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001513 (Contributed by Skip Montanaro.)
1514% Patch 1120353
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001515
Andrew M. Kuchlingd779b352006-05-16 16:11:54 +00001516\item The \module{zlib} module's \class{Compress} and \class{Decompress}
1517objects now support a \method{copy()} method that makes a copy of the
1518object's internal state and returns a new
1519\class{Compress} or \class{Decompress} object.
1520(Contributed by Chris AtLee.)
1521% Patch 1435422
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001522
Fred Drake114b8ca2005-03-21 05:47:11 +00001523\end{itemize}
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001524
Fred Drake2db76802004-12-01 05:05:47 +00001525
1526
1527%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001528\subsection{The ctypes package\label{module-ctypes}}
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001529
1530The \module{ctypes} package, written by Thomas Heller, has been added
1531to the standard library. \module{ctypes} lets you call arbitrary functions
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001532in shared libraries or DLLs. Long-time users may remember the \module{dl} module, which
1533provides 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 +00001534
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001535To load a shared library or DLL, you must create an instance of the
1536\class{CDLL} class and provide the name or path of the shared library
1537or DLL. Once that's done, you can call arbitrary functions
1538by accessing them as attributes of the \class{CDLL} object.
1539
1540\begin{verbatim}
1541import ctypes
1542
1543libc = ctypes.CDLL('libc.so.6')
1544result = libc.printf("Line of output\n")
1545\end{verbatim}
1546
1547Type constructors for the various C types are provided: \function{c_int},
1548\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
1549to change the wrapped value. Python integers and strings will be automatically
1550converted to the corresponding C types, but for other types you
1551must call the correct type constructor. (And I mean \emph{must};
1552getting it wrong will often result in the interpreter crashing
1553with a segmentation fault.)
1554
1555You 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
1556supposed to be immutable; breaking this rule will cause puzzling bugs. When you need a modifiable memory area,
Neal Norwitz5f5a69b2006-04-13 03:41:04 +00001557use \function{create_string_buffer()}:
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001558
1559\begin{verbatim}
1560s = "this is a string"
1561buf = ctypes.create_string_buffer(s)
1562libc.strfry(buf)
1563\end{verbatim}
1564
1565C functions are assumed to return integers, but you can set
1566the \member{restype} attribute of the function object to
1567change this:
1568
1569\begin{verbatim}
1570>>> libc.atof('2.71828')
1571-1783957616
1572>>> libc.atof.restype = ctypes.c_double
1573>>> libc.atof('2.71828')
15742.71828
1575\end{verbatim}
1576
1577\module{ctypes} also provides a wrapper for Python's C API
1578as the \code{ctypes.pythonapi} object. This object does \emph{not}
1579release the global interpreter lock before calling a function, because the lock must be held when calling into the interpreter's code.
1580There's a \class{py_object()} type constructor that will create a
1581\ctype{PyObject *} pointer. A simple usage:
1582
1583\begin{verbatim}
1584import ctypes
1585
1586d = {}
1587ctypes.pythonapi.PyObject_SetItem(ctypes.py_object(d),
1588 ctypes.py_object("abc"), ctypes.py_object(1))
1589# d is now {'abc', 1}.
1590\end{verbatim}
1591
1592Don't forget to use \class{py_object()}; if it's omitted you end
1593up with a segmentation fault.
1594
1595\module{ctypes} has been around for a while, but people still write
1596and distribution hand-coded extension modules because you can't rely on \module{ctypes} being present.
1597Perhaps developers will begin to write
1598Python wrappers atop a library accessed through \module{ctypes} instead
1599of extension modules, now that \module{ctypes} is included with core Python.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001600
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001601\begin{seealso}
1602
1603\seeurl{http://starship.python.net/crew/theller/ctypes/}
1604{The ctypes web page, with a tutorial, reference, and FAQ.}
1605
1606\end{seealso}
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001607
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001608
1609%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001610\subsection{The ElementTree package\label{module-etree}}
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001611
1612A subset of Fredrik Lundh's ElementTree library for processing XML has
Andrew M. Kuchlinge3c958c2006-05-01 12:45:02 +00001613been added to the standard library as \module{xml.etree}. The
Georg Brandlce27a062006-04-11 06:27:12 +00001614available modules are
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001615\module{ElementTree}, \module{ElementPath}, and
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00001616\module{ElementInclude} from ElementTree 1.2.6.
1617The \module{cElementTree} accelerator module is also included.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001618
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001619The rest of this section will provide a brief overview of using
1620ElementTree. Full documentation for ElementTree is available at
1621\url{http://effbot.org/zone/element-index.htm}.
1622
1623ElementTree represents an XML document as a tree of element nodes.
1624The text content of the document is stored as the \member{.text}
1625and \member{.tail} attributes of
1626(This is one of the major differences between ElementTree and
1627the Document Object Model; in the DOM there are many different
1628types of node, including \class{TextNode}.)
1629
1630The most commonly used parsing function is \function{parse()}, that
1631takes either a string (assumed to contain a filename) or a file-like
1632object and returns an \class{ElementTree} instance:
1633
1634\begin{verbatim}
Andrew M. Kuchlinge3c958c2006-05-01 12:45:02 +00001635from xml.etree import ElementTree as ET
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001636
1637tree = ET.parse('ex-1.xml')
1638
1639feed = urllib.urlopen(
1640 'http://planet.python.org/rss10.xml')
1641tree = ET.parse(feed)
1642\end{verbatim}
1643
1644Once you have an \class{ElementTree} instance, you
1645can call its \method{getroot()} method to get the root \class{Element} node.
1646
1647There's also an \function{XML()} function that takes a string literal
1648and returns an \class{Element} node (not an \class{ElementTree}).
1649This function provides a tidy way to incorporate XML fragments,
1650approaching the convenience of an XML literal:
1651
1652\begin{verbatim}
Andrew M. Kuchlinge3c958c2006-05-01 12:45:02 +00001653svg = ET.XML("""<svg width="10px" version="1.0">
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001654 </svg>""")
1655svg.set('height', '320px')
1656svg.append(elem1)
1657\end{verbatim}
1658
1659Each XML element supports some dictionary-like and some list-like
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001660access methods. Dictionary-like operations are used to access attribute
1661values, and list-like operations are used to access child nodes.
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001662
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001663\begin{tableii}{c|l}{code}{Operation}{Result}
1664 \lineii{elem[n]}{Returns n'th child element.}
1665 \lineii{elem[m:n]}{Returns list of m'th through n'th child elements.}
1666 \lineii{len(elem)}{Returns number of child elements.}
Andrew M. Kuchlinge3c958c2006-05-01 12:45:02 +00001667 \lineii{list(elem)}{Returns list of child elements.}
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001668 \lineii{elem.append(elem2)}{Adds \var{elem2} as a child.}
1669 \lineii{elem.insert(index, elem2)}{Inserts \var{elem2} at the specified location.}
1670 \lineii{del elem[n]}{Deletes n'th child element.}
1671 \lineii{elem.keys()}{Returns list of attribute names.}
1672 \lineii{elem.get(name)}{Returns value of attribute \var{name}.}
1673 \lineii{elem.set(name, value)}{Sets new value for attribute \var{name}.}
1674 \lineii{elem.attrib}{Retrieves the dictionary containing attributes.}
1675 \lineii{del elem.attrib[name]}{Deletes attribute \var{name}.}
1676\end{tableii}
1677
1678Comments and processing instructions are also represented as
1679\class{Element} nodes. To check if a node is a comment or processing
1680instructions:
1681
1682\begin{verbatim}
1683if elem.tag is ET.Comment:
1684 ...
1685elif elem.tag is ET.ProcessingInstruction:
1686 ...
1687\end{verbatim}
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001688
1689To generate XML output, you should call the
1690\method{ElementTree.write()} method. Like \function{parse()},
1691it can take either a string or a file-like object:
1692
1693\begin{verbatim}
1694# Encoding is US-ASCII
1695tree.write('output.xml')
1696
1697# Encoding is UTF-8
1698f = open('output.xml', 'w')
Andrew M. Kuchlinga8837012006-05-02 11:30:03 +00001699tree.write(f, encoding='utf-8')
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001700\end{verbatim}
1701
Andrew M. Kuchlinga8837012006-05-02 11:30:03 +00001702(Caution: the default encoding used for output is ASCII. For general
1703XML work, where an element's name may contain arbitrary Unicode
1704characters, ASCII isn't a very useful encoding because it will raise
1705an exception if an element's name contains any characters with values
1706greater than 127. Therefore, it's best to specify a different
1707encoding such as UTF-8 that can handle any Unicode character.)
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001708
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001709This section is only a partial description of the ElementTree interfaces.
1710Please read the package's official documentation for more details.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001711
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001712\begin{seealso}
1713
1714\seeurl{http://effbot.org/zone/element-index.htm}
1715{Official documentation for ElementTree.}
1716
1717
1718\end{seealso}
1719
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001720
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001721%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001722\subsection{The hashlib package\label{module-hashlib}}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001723
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001724A new \module{hashlib} module, written by Gregory P. Smith,
1725has been added to replace the
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001726\module{md5} and \module{sha} modules. \module{hashlib} adds support
1727for additional secure hashes (SHA-224, SHA-256, SHA-384, and SHA-512).
1728When available, the module uses OpenSSL for fast platform optimized
1729implementations of algorithms.
1730
1731The old \module{md5} and \module{sha} modules still exist as wrappers
1732around hashlib to preserve backwards compatibility. The new module's
1733interface is very close to that of the old modules, but not identical.
1734The most significant difference is that the constructor functions
1735for creating new hashing objects are named differently.
1736
1737\begin{verbatim}
1738# Old versions
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001739h = md5.md5()
1740h = md5.new()
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001741
1742# New version
1743h = hashlib.md5()
1744
1745# Old versions
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001746h = sha.sha()
1747h = sha.new()
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001748
1749# New version
1750h = hashlib.sha1()
1751
1752# Hash that weren't previously available
1753h = hashlib.sha224()
1754h = hashlib.sha256()
1755h = hashlib.sha384()
1756h = hashlib.sha512()
1757
1758# Alternative form
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001759h = hashlib.new('md5') # Provide algorithm as a string
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001760\end{verbatim}
1761
1762Once a hash object has been created, its methods are the same as before:
1763\method{update(\var{string})} hashes the specified string into the
1764current digest state, \method{digest()} and \method{hexdigest()}
1765return the digest value as a binary string or a string of hex digits,
1766and \method{copy()} returns a new hashing object with the same digest state.
1767
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001768
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001769%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001770\subsection{The sqlite3 package\label{module-sqlite}}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001771
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001772The pysqlite module (\url{http://www.pysqlite.org}), a wrapper for the
1773SQLite embedded database, has been added to the standard library under
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001774the package name \module{sqlite3}.
1775
1776SQLite is a C library that provides a SQL-language database that
1777stores data in disk files without requiring a separate server process.
1778pysqlite was written by Gerhard H\"aring and provides a SQL interface
1779compliant with the DB-API 2.0 specification described by
1780\pep{249}. This means that it should be possible to write the first
1781version of your applications using SQLite for data storage. If
1782switching to a larger database such as PostgreSQL or Oracle is
1783later necessary, the switch should be relatively easy.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001784
1785If you're compiling the Python source yourself, note that the source
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001786tree doesn't include the SQLite code, only the wrapper module.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001787You'll need to have the SQLite libraries and headers installed before
1788compiling Python, and the build process will compile the module when
1789the necessary headers are available.
1790
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001791To use the module, you must first create a \class{Connection} object
1792that represents the database. Here the data will be stored in the
1793\file{/tmp/example} file:
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001794
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001795\begin{verbatim}
1796conn = sqlite3.connect('/tmp/example')
1797\end{verbatim}
1798
1799You can also supply the special name \samp{:memory:} to create
1800a database in RAM.
1801
1802Once you have a \class{Connection}, you can create a \class{Cursor}
1803object and call its \method{execute()} method to perform SQL commands:
1804
1805\begin{verbatim}
1806c = conn.cursor()
1807
1808# Create table
1809c.execute('''create table stocks
1810(date timestamp, trans varchar, symbol varchar,
1811 qty decimal, price decimal)''')
1812
1813# Insert a row of data
1814c.execute("""insert into stocks
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001815 values ('2006-01-05','BUY','RHAT',100,35.14)""")
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001816\end{verbatim}
1817
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001818Usually your SQL operations will need to use values from Python
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001819variables. You shouldn't assemble your query using Python's string
1820operations because doing so is insecure; it makes your program
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001821vulnerable to an SQL injection attack.
1822
1823Instead, use SQLite's parameter substitution. Put \samp{?} as a
1824placeholder wherever you want to use a value, and then provide a tuple
1825of values as the second argument to the cursor's \method{execute()}
1826method. For example:
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001827
1828\begin{verbatim}
1829# Never do this -- insecure!
1830symbol = 'IBM'
1831c.execute("... where symbol = '%s'" % symbol)
1832
1833# Do this instead
1834t = (symbol,)
Andrew M. Kuchling7e5abb92006-04-26 12:21:06 +00001835c.execute('select * from stocks where symbol=?', t)
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001836
1837# Larger example
1838for t in (('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001839 ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
1840 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
1841 ):
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001842 c.execute('insert into stocks values (?,?,?,?,?)', t)
1843\end{verbatim}
1844
1845To retrieve data after executing a SELECT statement, you can either
1846treat the cursor as an iterator, call the cursor's \method{fetchone()}
1847method to retrieve a single matching row,
1848or call \method{fetchall()} to get a list of the matching rows.
1849
1850This example uses the iterator form:
1851
1852\begin{verbatim}
1853>>> c = conn.cursor()
1854>>> c.execute('select * from stocks order by price')
1855>>> for row in c:
1856... print row
1857...
1858(u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001)
1859(u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
1860(u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
1861(u'2006-04-05', u'BUY', u'MSOFT', 1000, 72.0)
1862>>>
1863\end{verbatim}
1864
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001865For more information about the SQL dialect supported by SQLite, see
1866\url{http://www.sqlite.org}.
1867
1868\begin{seealso}
1869
1870\seeurl{http://www.pysqlite.org}
1871{The pysqlite web page.}
1872
1873\seeurl{http://www.sqlite.org}
1874{The SQLite web page; the documentation describes the syntax and the
1875available data types for the supported SQL dialect.}
1876
1877\seepep{249}{Database API Specification 2.0}{PEP written by
1878Marc-Andr\'e Lemburg.}
1879
1880\end{seealso}
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001881
Fred Drake2db76802004-12-01 05:05:47 +00001882
1883% ======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001884\section{Build and C API Changes\label{build-api}}
Fred Drake2db76802004-12-01 05:05:47 +00001885
1886Changes to Python's build process and to the C API include:
1887
1888\begin{itemize}
1889
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00001890\item The largest change to the C API came from \pep{353},
1891which modifies the interpreter to use a \ctype{Py_ssize_t} type
1892definition instead of \ctype{int}. See the earlier
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +00001893section~\ref{pep-353} for a discussion of this change.
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00001894
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001895\item The design of the bytecode compiler has changed a great deal, to
1896no longer generate bytecode by traversing the parse tree. Instead
Andrew M. Kuchlingdb85ed52005-10-23 21:52:59 +00001897the parse tree is converted to an abstract syntax tree (or AST), and it is
1898the abstract syntax tree that's traversed to produce the bytecode.
1899
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00001900It's possible for Python code to obtain AST objects by using the
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001901\function{compile()} built-in and specifying \code{_ast.PyCF_ONLY_AST}
1902as the value of the
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00001903\var{flags} parameter:
1904
1905\begin{verbatim}
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001906from _ast import PyCF_ONLY_AST
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00001907ast = compile("""a=0
1908for i in range(10):
1909 a += i
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001910""", "<string>", 'exec', PyCF_ONLY_AST)
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00001911
1912assignment = ast.body[0]
1913for_loop = ast.body[1]
1914\end{verbatim}
1915
Andrew M. Kuchlingdb85ed52005-10-23 21:52:59 +00001916No documentation has been written for the AST code yet. To start
1917learning about it, read the definition of the various AST nodes in
1918\file{Parser/Python.asdl}. A Python script reads this file and
1919generates a set of C structure definitions in
1920\file{Include/Python-ast.h}. The \cfunction{PyParser_ASTFromString()}
1921and \cfunction{PyParser_ASTFromFile()}, defined in
1922\file{Include/pythonrun.h}, take Python source as input and return the
1923root of an AST representing the contents. This AST can then be turned
1924into a code object by \cfunction{PyAST_Compile()}. For more
1925information, read the source code, and then ask questions on
1926python-dev.
1927
1928% List of names taken from Jeremy's python-dev post at
1929% http://mail.python.org/pipermail/python-dev/2005-October/057500.html
1930The AST code was developed under Jeremy Hylton's management, and
1931implemented by (in alphabetical order) Brett Cannon, Nick Coghlan,
1932Grant Edwards, John Ehresman, Kurt Kaiser, Neal Norwitz, Tim Peters,
1933Armin Rigo, and Neil Schemenauer, plus the participants in a number of
1934AST sprints at conferences such as PyCon.
1935
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001936\item The built-in set types now have an official C API. Call
1937\cfunction{PySet_New()} and \cfunction{PyFrozenSet_New()} to create a
1938new set, \cfunction{PySet_Add()} and \cfunction{PySet_Discard()} to
1939add and remove elements, and \cfunction{PySet_Contains} and
1940\cfunction{PySet_Size} to examine the set's state.
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001941(Contributed by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001942
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001943\item C code can now obtain information about the exact revision
1944of the Python interpreter by calling the
1945\cfunction{Py_GetBuildInfo()} function that returns a
1946string of build information like this:
1947\code{"trunk:45355:45356M, Apr 13 2006, 07:42:19"}.
1948(Contributed by Barry Warsaw.)
1949
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001950\item The CPython interpreter is still written in C, but
1951the code can now be compiled with a {\Cpp} compiler without errors.
1952(Implemented by Anthony Baxter, Martin von~L\"owis, Skip Montanaro.)
1953
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001954\item The \cfunction{PyRange_New()} function was removed. It was
1955never documented, never used in the core code, and had dangerously lax
1956error checking.
Fred Drake2db76802004-12-01 05:05:47 +00001957
1958\end{itemize}
1959
1960
1961%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001962\subsection{Port-Specific Changes\label{ports}}
Fred Drake2db76802004-12-01 05:05:47 +00001963
Andrew M. Kuchling6fc69762006-04-13 12:37:21 +00001964\begin{itemize}
1965
1966\item MacOS X (10.3 and higher): dynamic loading of modules
1967now uses the \cfunction{dlopen()} function instead of MacOS-specific
1968functions.
1969
Andrew M. Kuchlingb37bcb52006-04-29 11:53:15 +00001970\item MacOS X: a \longprogramopt{enable-universalsdk} switch was added
1971to the \program{configure} script that compiles the interpreter as a
1972universal binary able to run on both PowerPC and Intel processors.
1973(Contributed by Ronald Oussoren.)
1974
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001975\item Windows: \file{.dll} is no longer supported as a filename extension for
1976extension modules. \file{.pyd} is now the only filename extension that will
1977be searched for.
1978
Andrew M. Kuchling6fc69762006-04-13 12:37:21 +00001979\end{itemize}
Fred Drake2db76802004-12-01 05:05:47 +00001980
1981
1982%======================================================================
1983\section{Other Changes and Fixes \label{section-other}}
1984
1985As usual, there were a bunch of other improvements and bugfixes
Andrew M. Kuchlingf688cc52006-03-10 18:50:08 +00001986scattered throughout the source tree. A search through the SVN change
Fred Drake2db76802004-12-01 05:05:47 +00001987logs finds there were XXX patches applied and YYY bugs fixed between
Andrew M. Kuchling92e24952004-12-03 13:54:09 +00001988Python 2.4 and 2.5. Both figures are likely to be underestimates.
Fred Drake2db76802004-12-01 05:05:47 +00001989
1990Some of the more notable changes are:
1991
1992\begin{itemize}
1993
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001994\item Evan Jones's patch to obmalloc, first described in a talk
1995at PyCon DC 2005, was applied. Python 2.4 allocated small objects in
1996256K-sized arenas, but never freed arenas. With this patch, Python
1997will free arenas when they're empty. The net effect is that on some
1998platforms, when you allocate many objects, Python's memory usage may
1999actually drop when you delete them, and the memory may be returned to
2000the operating system. (Implemented by Evan Jones, and reworked by Tim
2001Peters.)
Fred Drake2db76802004-12-01 05:05:47 +00002002
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00002003Note that this change means extension modules need to be more careful
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +00002004with how they allocate memory. Python's API has many different
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00002005functions for allocating memory that are grouped into families. For
2006example, \cfunction{PyMem_Malloc()}, \cfunction{PyMem_Realloc()}, and
2007\cfunction{PyMem_Free()} are one family that allocates raw memory,
2008while \cfunction{PyObject_Malloc()}, \cfunction{PyObject_Realloc()},
2009and \cfunction{PyObject_Free()} are another family that's supposed to
2010be used for creating Python objects.
2011
2012Previously these different families all reduced to the platform's
2013\cfunction{malloc()} and \cfunction{free()} functions. This meant
2014it didn't matter if you got things wrong and allocated memory with the
2015\cfunction{PyMem} function but freed it with the \cfunction{PyObject}
2016function. With the obmalloc change, these families now do different
2017things, and mismatches will probably result in a segfault. You should
2018carefully test your C extension modules with Python 2.5.
2019
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00002020\item Coverity, a company that markets a source code analysis tool
2021 called Prevent, provided the results of their examination of the Python
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +00002022 source code. The analysis found about 60 bugs that
2023 were quickly fixed. Many of the bugs were refcounting problems, often
2024 occurring in error-handling code. See
2025 \url{http://scan.coverity.com} for the statistics.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00002026
Fred Drake2db76802004-12-01 05:05:47 +00002027\end{itemize}
2028
2029
2030%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00002031\section{Porting to Python 2.5\label{porting}}
Fred Drake2db76802004-12-01 05:05:47 +00002032
2033This section lists previously described changes that may require
2034changes to your code:
2035
2036\begin{itemize}
2037
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00002038\item ASCII is now the default encoding for modules. It's now
2039a syntax error if a module contains string literals with 8-bit
2040characters but doesn't have an encoding declaration. In Python 2.4
2041this triggered a warning, not a syntax error.
2042
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +00002043\item Previously, the \member{gi_frame} attribute of a generator
2044was always a frame object. Because of the \pep{342} changes
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +00002045described in section~\ref{pep-342}, it's now possible
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +00002046for \member{gi_frame} to be \code{None}.
2047
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00002048
2049\item Library: The \module{pickle} and \module{cPickle} modules no
2050longer accept a return value of \code{None} from the
2051\method{__reduce__()} method; the method must return a tuple of
2052arguments instead. The modules also no longer accept the deprecated
2053\var{bin} keyword parameter.
2054
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00002055\item C API: Many functions now use \ctype{Py_ssize_t}
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00002056instead of \ctype{int} to allow processing more data on 64-bit
2057machines. Extension code may need to make the same change to avoid
2058warnings and to support 64-bit machines. See the earlier
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +00002059section~\ref{pep-353} for a discussion of this change.
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00002060
2061\item C API:
2062The obmalloc changes mean that
2063you must be careful to not mix usage
2064of the \cfunction{PyMem_*()} and \cfunction{PyObject_*()}
2065families of functions. Memory allocated with
2066one family's \cfunction{*_Malloc()} must be
2067freed with the corresponding family's \cfunction{*_Free()} function.
2068
Fred Drake2db76802004-12-01 05:05:47 +00002069\end{itemize}
2070
2071
2072%======================================================================
2073\section{Acknowledgements \label{acks}}
2074
2075The author would like to thank the following people for offering
2076suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchlinge3c958c2006-05-01 12:45:02 +00002077article: Phillip J. Eby, Kent Johnson, Martin von~L\"owis, Fredrik Lundh,
Andrew M. Kuchling356af462006-05-10 17:19:04 +00002078Gustavo Niemeyer, James Pryor, Mike Rovner, Scott Weikart, Thomas Wouters.
Fred Drake2db76802004-12-01 05:05:47 +00002079
2080\end{document}