blob: 2744103a1a6f9ccd0ad9d8be78ce1ee073f9dde1 [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 308: Conditional Expressions\label{pep-308}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000036
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000037For a long time, people have been requesting a way to write
38conditional expressions, expressions that return value A or value B
39depending on whether a Boolean value is true or false. A conditional
40expression lets you write a single assignment statement that has the
41same effect as the following:
42
43\begin{verbatim}
44if condition:
45 x = true_value
46else:
47 x = false_value
48\end{verbatim}
49
50There have been endless tedious discussions of syntax on both
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +000051python-dev and comp.lang.python. A vote was even held that found the
52majority of voters wanted conditional expressions in some form,
53but there was no syntax that was preferred by a clear majority.
54Candidates included C's \code{cond ? true_v : false_v},
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000055\code{if cond then true_v else false_v}, and 16 other variations.
56
57GvR eventually chose a surprising syntax:
58
59\begin{verbatim}
60x = true_value if condition else false_value
61\end{verbatim}
62
Andrew M. Kuchling38f85072006-04-02 01:46:32 +000063Evaluation is still lazy as in existing Boolean expressions, so the
64order of evaluation jumps around a bit. The \var{condition}
65expression in the middle is evaluated first, and the \var{true_value}
66expression is evaluated only if the condition was true. Similarly,
67the \var{false_value} expression is only evaluated when the condition
68is false.
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000069
70This syntax may seem strange and backwards; why does the condition go
71in the \emph{middle} of the expression, and not in the front as in C's
72\code{c ? x : y}? The decision was checked by applying the new syntax
73to the modules in the standard library and seeing how the resulting
74code read. In many cases where a conditional expression is used, one
75value seems to be the 'common case' and one value is an 'exceptional
76case', used only on rarer occasions when the condition isn't met. The
77conditional syntax makes this pattern a bit more obvious:
78
79\begin{verbatim}
80contents = ((doc + '\n') if doc else '')
81\end{verbatim}
82
83I read the above statement as meaning ``here \var{contents} is
Andrew M. Kuchlingd0fcc022006-03-09 13:57:28 +000084usually assigned a value of \code{doc+'\e n'}; sometimes
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000085\var{doc} is empty, in which special case an empty string is returned.''
86I doubt I will use conditional expressions very often where there
87isn't a clear common and uncommon case.
88
89There was some discussion of whether the language should require
90surrounding conditional expressions with parentheses. The decision
91was made to \emph{not} require parentheses in the Python language's
92grammar, but as a matter of style I think you should always use them.
93Consider these two statements:
94
95\begin{verbatim}
96# First version -- no parens
97level = 1 if logging else 0
98
99# Second version -- with parens
100level = (1 if logging else 0)
101\end{verbatim}
102
103In the first version, I think a reader's eye might group the statement
104into 'level = 1', 'if logging', 'else 0', and think that the condition
105decides whether the assignment to \var{level} is performed. The
106second version reads better, in my opinion, because it makes it clear
107that the assignment is always performed and the choice is being made
108between two values.
109
110Another reason for including the brackets: a few odd combinations of
111list comprehensions and lambdas could look like incorrect conditional
112expressions. See \pep{308} for some examples. If you put parentheses
113around your conditional expressions, you won't run into this case.
114
115
116\begin{seealso}
117
118\seepep{308}{Conditional Expressions}{PEP written by
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000119Guido van~Rossum and Raymond D. Hettinger; implemented by Thomas
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +0000120Wouters.}
121
122\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000123
124
125%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000126\section{PEP 309: Partial Function Application\label{pep-309}}
Fred Drake2db76802004-12-01 05:05:47 +0000127
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000128The \module{functional} module is intended to contain tools for
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000129functional-style programming. Currently it only contains a
130\class{partial()} function, but new functions will probably be added
131in future versions of Python.
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000132
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000133For programs written in a functional style, it can be useful to
134construct variants of existing functions that have some of the
135parameters filled in. Consider a Python function \code{f(a, b, c)};
136you could create a new function \code{g(b, c)} that was equivalent to
137\code{f(1, b, c)}. This is called ``partial function application'',
138and is provided by the \class{partial} class in the new
139\module{functional} module.
140
141The constructor for \class{partial} takes the arguments
142\code{(\var{function}, \var{arg1}, \var{arg2}, ...
143\var{kwarg1}=\var{value1}, \var{kwarg2}=\var{value2})}. The resulting
144object is callable, so you can just call it to invoke \var{function}
145with the filled-in arguments.
146
147Here's a small but realistic example:
148
149\begin{verbatim}
150import functional
151
152def log (message, subsystem):
153 "Write the contents of 'message' to the specified subsystem."
154 print '%s: %s' % (subsystem, message)
155 ...
156
157server_log = functional.partial(log, subsystem='server')
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000158server_log('Unable to open socket')
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000159\end{verbatim}
160
Andrew M. Kuchling6af7fe02005-08-02 17:20:36 +0000161Here's another example, from a program that uses PyGTk. Here a
162context-sensitive pop-up menu is being constructed dynamically. The
163callback provided for the menu option is a partially applied version
164of the \method{open_item()} method, where the first argument has been
165provided.
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000166
Andrew M. Kuchling6af7fe02005-08-02 17:20:36 +0000167\begin{verbatim}
168...
169class Application:
170 def open_item(self, path):
171 ...
172 def init (self):
173 open_func = functional.partial(self.open_item, item_path)
174 popup_menu.append( ("Open", open_func, 1) )
175\end{verbatim}
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000176
177
178\begin{seealso}
179
180\seepep{309}{Partial Function Application}{PEP proposed and written by
181Peter Harris; implemented by Hye-Shik Chang, with adaptations by
182Raymond Hettinger.}
183
184\end{seealso}
Fred Drake2db76802004-12-01 05:05:47 +0000185
186
187%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000188\section{PEP 314: Metadata for Python Software Packages v1.1\label{pep-314}}
Fred Drakedb7b0022005-03-20 22:19:47 +0000189
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000190Some simple dependency support was added to Distutils. The
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000191\function{setup()} function now has \code{requires}, \code{provides},
192and \code{obsoletes} keyword parameters. When you build a source
193distribution using the \code{sdist} command, the dependency
194information will be recorded in the \file{PKG-INFO} file.
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000195
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000196Another new keyword parameter is \code{download_url}, which should be
197set to a URL for the package's source code. This means it's now
198possible to look up an entry in the package index, determine the
199dependencies for a package, and download the required packages.
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000200
Andrew M. Kuchling61434b62006-04-13 11:51:07 +0000201\begin{verbatim}
202VERSION = '1.0'
203setup(name='PyPackage',
204 version=VERSION,
205 requires=['numarray', 'zlib (>=1.1.4)'],
206 obsoletes=['OldPackage']
207 download_url=('http://www.example.com/pypackage/dist/pkg-%s.tar.gz'
208 % VERSION),
209 )
210\end{verbatim}
Andrew M. Kuchlingc0a0dec2006-05-16 16:27:31 +0000211
212Another new enhancement to the Python package index at
213\url{http://cheeseshop.python.org} is storing source and binary
214archives for a package. The new \command{upload} Distutils command
215will upload a package to the repository.
216
217Before a package can be uploaded, you must be able to build a
218distribution using the \command{sdist} Distutils command. Once that
219works, you can run \code{python setup.py upload} to add your package
220to the PyPI archive. Optionally you can GPG-sign the package by
221supplying the \longprogramopt{sign} and
222\longprogramopt{identity} options.
223
224Package uploading was implemented by Martin von~L\"owis and Richard Jones.
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000225
226\begin{seealso}
227
228\seepep{314}{Metadata for Python Software Packages v1.1}{PEP proposed
229and written by A.M. Kuchling, Richard Jones, and Fred Drake;
230implemented by Richard Jones and Fred Drake.}
231
232\end{seealso}
Fred Drakedb7b0022005-03-20 22:19:47 +0000233
234
235%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000236\section{PEP 328: Absolute and Relative Imports\label{pep-328}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000237
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000238The simpler part of PEP 328 was implemented in Python 2.4: parentheses
239could now be used to enclose the names imported from a module using
240the \code{from ... import ...} statement, making it easier to import
241many different names.
242
243The more complicated part has been implemented in Python 2.5:
244importing a module can be specified to use absolute or
245package-relative imports. The plan is to move toward making absolute
246imports the default in future versions of Python.
247
248Let's say you have a package directory like this:
249\begin{verbatim}
250pkg/
251pkg/__init__.py
252pkg/main.py
253pkg/string.py
254\end{verbatim}
255
256This defines a package named \module{pkg} containing the
257\module{pkg.main} and \module{pkg.string} submodules.
258
259Consider the code in the \file{main.py} module. What happens if it
260executes the statement \code{import string}? In Python 2.4 and
261earlier, it will first look in the package's directory to perform a
262relative import, finds \file{pkg/string.py}, imports the contents of
263that file as the \module{pkg.string} module, and that module is bound
264to the name \samp{string} in the \module{pkg.main} module's namespace.
265
266That's fine if \module{pkg.string} was what you wanted. But what if
267you wanted Python's standard \module{string} module? There's no clean
268way to ignore \module{pkg.string} and look for the standard module;
269generally you had to look at the contents of \code{sys.modules}, which
270is slightly unclean.
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000271Holger Krekel's \module{py.std} package provides a tidier way to perform
272imports from the standard library, \code{import py ; py.std.string.join()},
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000273but that package isn't available on all Python installations.
274
275Reading code which relies on relative imports is also less clear,
276because a reader may be confused about which module, \module{string}
277or \module{pkg.string}, is intended to be used. Python users soon
278learned not to duplicate the names of standard library modules in the
279names of their packages' submodules, but you can't protect against
280having your submodule's name being used for a new module added in a
281future version of Python.
282
283In Python 2.5, you can switch \keyword{import}'s behaviour to
284absolute imports using a \code{from __future__ import absolute_import}
285directive. This absolute-import behaviour will become the default in
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000286a future version (probably Python 2.7). Once absolute imports
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000287are the default, \code{import string} will
288always find the standard library's version.
289It's suggested that users should begin using absolute imports as much
290as possible, so it's preferable to begin writing \code{from pkg import
291string} in your code.
292
293Relative imports are still possible by adding a leading period
294to the module name when using the \code{from ... import} form:
295
296\begin{verbatim}
297# Import names from pkg.string
298from .string import name1, name2
299# Import pkg.string
300from . import string
301\end{verbatim}
302
303This imports the \module{string} module relative to the current
304package, so in \module{pkg.main} this will import \var{name1} and
305\var{name2} from \module{pkg.string}. Additional leading periods
306perform the relative import starting from the parent of the current
307package. For example, code in the \module{A.B.C} module can do:
308
309\begin{verbatim}
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000310from . import D # Imports A.B.D
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000311from .. import E # Imports A.E
312from ..F import G # Imports A.F.G
313\end{verbatim}
314
315Leading periods cannot be used with the \code{import \var{modname}}
316form of the import statement, only the \code{from ... import} form.
317
318\begin{seealso}
319
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000320\seepep{328}{Imports: Multi-Line and Absolute/Relative}
321{PEP written by Aahz; implemented by Thomas Wouters.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000322
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000323\seeurl{http://codespeak.net/py/current/doc/index.html}
324{The py library by Holger Krekel, which contains the \module{py.std} package.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000325
326\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000327
328
329%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000330\section{PEP 338: Executing Modules as Scripts\label{pep-338}}
Andrew M. Kuchling21d3a7c2006-03-15 11:53:09 +0000331
Andrew M. Kuchlingb182db42006-03-17 21:48:46 +0000332The \programopt{-m} switch added in Python 2.4 to execute a module as
333a script gained a few more abilities. Instead of being implemented in
334C code inside the Python interpreter, the switch now uses an
335implementation in a new module, \module{runpy}.
336
337The \module{runpy} module implements a more sophisticated import
338mechanism so that it's now possible to run modules in a package such
339as \module{pychecker.checker}. The module also supports alternative
Andrew M. Kuchling5d4cf5e2006-04-13 13:02:42 +0000340import mechanisms such as the \module{zipimport} module. This means
Andrew M. Kuchlingb182db42006-03-17 21:48:46 +0000341you can add a .zip archive's path to \code{sys.path} and then use the
342\programopt{-m} switch to execute code from the archive.
343
344
345\begin{seealso}
346
347\seepep{338}{Executing modules as scripts}{PEP written and
348implemented by Nick Coghlan.}
349
350\end{seealso}
Andrew M. Kuchling21d3a7c2006-03-15 11:53:09 +0000351
352
353%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000354\section{PEP 341: Unified try/except/finally\label{pep-341}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000355
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000356Until Python 2.5, the \keyword{try} statement came in two
357flavours. You could use a \keyword{finally} block to ensure that code
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +0000358is always executed, or one or more \keyword{except} blocks to catch
359specific exceptions. You couldn't combine both \keyword{except} blocks and a
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000360\keyword{finally} block, because generating the right bytecode for the
361combined version was complicated and it wasn't clear what the
362semantics of the combined should be.
363
364GvR spent some time working with Java, which does support the
365equivalent of combining \keyword{except} blocks and a
366\keyword{finally} block, and this clarified what the statement should
367mean. In Python 2.5, you can now write:
368
369\begin{verbatim}
370try:
371 block-1 ...
372except Exception1:
373 handler-1 ...
374except Exception2:
375 handler-2 ...
376else:
377 else-block
378finally:
379 final-block
380\end{verbatim}
381
382The code in \var{block-1} is executed. If the code raises an
Andrew M. Kuchling356af462006-05-10 17:19:04 +0000383exception, the various \keyword{except} blocks are tested: if the
384exception is of class \class{Exception1}, \var{handler-1} is executed;
385otherwise if it's of class \class{Exception2}, \var{handler-2} is
386executed, and so forth. If no exception is raised, the
387\var{else-block} is executed.
388
389No matter what happened previously, the \var{final-block} is executed
390once the code block is complete and any raised exceptions handled.
391Even if there's an error in an exception handler or the
392\var{else-block} and a new exception is raised, the
393code in the \var{final-block} is still run.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000394
395\begin{seealso}
396
397\seepep{341}{Unifying try-except and try-finally}{PEP written by Georg Brandl;
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000398implementation by Thomas Lee.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000399
400\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000401
402
403%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000404\section{PEP 342: New Generator Features\label{pep-342}}
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000405
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000406Python 2.5 adds a simple way to pass values \emph{into} a generator.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000407As introduced in Python 2.3, generators only produce output; once a
Andrew M. Kuchling1e9f5742006-05-20 19:25:16 +0000408generator's code was invoked to create an iterator, there was no way to
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000409pass any new information into the function when its execution is
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000410resumed. Sometimes the ability to pass in some information would be
411useful. Hackish solutions to this include making the generator's code
412look at a global variable and then changing the global variable's
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000413value, or passing in some mutable object that callers then modify.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000414
415To refresh your memory of basic generators, here's a simple example:
416
417\begin{verbatim}
418def counter (maximum):
419 i = 0
420 while i < maximum:
421 yield i
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000422 i += 1
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000423\end{verbatim}
424
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000425When you call \code{counter(10)}, the result is an iterator that
426returns the values from 0 up to 9. On encountering the
427\keyword{yield} statement, the iterator returns the provided value and
428suspends the function's execution, preserving the local variables.
429Execution resumes on the following call to the iterator's
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000430\method{next()} method, picking up after the \keyword{yield} statement.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000431
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000432In Python 2.3, \keyword{yield} was a statement; it didn't return any
433value. In 2.5, \keyword{yield} is now an expression, returning a
434value that can be assigned to a variable or otherwise operated on:
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000435
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000436\begin{verbatim}
437val = (yield i)
438\end{verbatim}
439
440I recommend that you always put parentheses around a \keyword{yield}
441expression when you're doing something with the returned value, as in
442the above example. The parentheses aren't always necessary, but it's
443easier to always add them instead of having to remember when they're
Andrew M. Kuchling3b675d22006-04-20 13:43:21 +0000444needed.
445
446(\pep{342} explains the exact rules, which are that a
447\keyword{yield}-expression must always be parenthesized except when it
448occurs at the top-level expression on the right-hand side of an
449assignment. This means you can write \code{val = yield i} but have to
450use parentheses when there's an operation, as in \code{val = (yield i)
451+ 12}.)
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000452
453Values are sent into a generator by calling its
454\method{send(\var{value})} method. The generator's code is then
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000455resumed and the \keyword{yield} expression returns the specified
456\var{value}. If the regular \method{next()} method is called, the
457\keyword{yield} returns \constant{None}.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000458
459Here's the previous example, modified to allow changing the value of
460the internal counter.
461
462\begin{verbatim}
463def counter (maximum):
464 i = 0
465 while i < maximum:
466 val = (yield i)
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000467 # If value provided, change counter
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000468 if val is not None:
469 i = val
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000470 else:
471 i += 1
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000472\end{verbatim}
473
474And here's an example of changing the counter:
475
476\begin{verbatim}
477>>> it = counter(10)
478>>> print it.next()
4790
480>>> print it.next()
4811
482>>> print it.send(8)
4838
484>>> print it.next()
4859
486>>> print it.next()
487Traceback (most recent call last):
488 File ``t.py'', line 15, in ?
489 print it.next()
490StopIteration
Andrew M. Kuchlingc2033702005-08-29 13:30:12 +0000491\end{verbatim}
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000492
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000493Because \keyword{yield} will often be returning \constant{None}, you
494should always check for this case. Don't just use its value in
495expressions unless you're sure that the \method{send()} method
496will be the only method used resume your generator function.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000497
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000498In addition to \method{send()}, there are two other new methods on
499generators:
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000500
501\begin{itemize}
502
503 \item \method{throw(\var{type}, \var{value}=None,
504 \var{traceback}=None)} is used to raise an exception inside the
505 generator; the exception is raised by the \keyword{yield} expression
506 where the generator's execution is paused.
507
508 \item \method{close()} raises a new \exception{GeneratorExit}
509 exception inside the generator to terminate the iteration.
510 On receiving this
511 exception, the generator's code must either raise
512 \exception{GeneratorExit} or \exception{StopIteration}; catching the
513 exception and doing anything else is illegal and will trigger
514 a \exception{RuntimeError}. \method{close()} will also be called by
515 Python's garbage collection when the generator is garbage-collected.
516
517 If you need to run cleanup code in case of a \exception{GeneratorExit},
518 I suggest using a \code{try: ... finally:} suite instead of
519 catching \exception{GeneratorExit}.
520
521\end{itemize}
522
523The cumulative effect of these changes is to turn generators from
524one-way producers of information into both producers and consumers.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000525
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000526Generators also become \emph{coroutines}, a more generalized form of
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000527subroutines. Subroutines are entered at one point and exited at
Andrew M. Kuchling1e9f5742006-05-20 19:25:16 +0000528another point (the top of the function, and a \keyword{return}
529statement), but coroutines can be entered, exited, and resumed at
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000530many different points (the \keyword{yield} statements). We'll have to
531figure out patterns for using coroutines effectively in Python.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000532
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000533The addition of the \method{close()} method has one side effect that
534isn't obvious. \method{close()} is called when a generator is
535garbage-collected, so this means the generator's code gets one last
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +0000536chance to run before the generator is destroyed. This last chance
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000537means that \code{try...finally} statements in generators can now be
538guaranteed to work; the \keyword{finally} clause will now always get a
539chance to run. The syntactic restriction that you couldn't mix
540\keyword{yield} statements with a \code{try...finally} suite has
541therefore been removed. This seems like a minor bit of language
542trivia, but using generators and \code{try...finally} is actually
543necessary in order to implement the \keyword{with} statement
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000544described by PEP 343. I'll look at this new statement in the following
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000545section.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000546
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +0000547Another even more esoteric effect of this change: previously, the
548\member{gi_frame} attribute of a generator was always a frame object.
549It's now possible for \member{gi_frame} to be \code{None}
550once the generator has been exhausted.
551
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000552\begin{seealso}
553
554\seepep{342}{Coroutines via Enhanced Generators}{PEP written by
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000555Guido van~Rossum and Phillip J. Eby;
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000556implemented by Phillip J. Eby. Includes examples of
557some fancier uses of generators as coroutines.}
558
559\seeurl{http://en.wikipedia.org/wiki/Coroutine}{The Wikipedia entry for
560coroutines.}
561
Neal Norwitz09179882006-03-04 23:31:45 +0000562\seeurl{http://www.sidhe.org/\~{}dan/blog/archives/000178.html}{An
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000563explanation of coroutines from a Perl point of view, written by Dan
564Sugalski.}
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000565
566\end{seealso}
567
568
569%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000570\section{PEP 343: The 'with' statement\label{pep-343}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000571
Andrew M. Kuchling0a7ed8c2006-04-24 14:30:47 +0000572The '\keyword{with}' statement clarifies code that previously would
573use \code{try...finally} blocks to ensure that clean-up code is
574executed. In this section, I'll discuss the statement as it will
575commonly be used. In the next section, I'll examine the
576implementation details and show how to write objects for use with this
577statement.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000578
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +0000579The '\keyword{with}' statement is a new control-flow structure whose
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000580basic structure is:
581
582\begin{verbatim}
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000583with expression [as variable]:
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000584 with-block
585\end{verbatim}
586
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000587The expression is evaluated, and it should result in an object that
588supports the context management protocol. This object may return a
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000589value that can optionally be bound to the name \var{variable}. (Note
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000590carefully that \var{variable} is \emph{not} assigned the result of
591\var{expression}.) The object can then run set-up code
592before \var{with-block} is executed and some clean-up code
593is executed after the block is done, even if the block raised an exception.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000594
595To enable the statement in Python 2.5, you need
596to add the following directive to your module:
597
598\begin{verbatim}
599from __future__ import with_statement
600\end{verbatim}
601
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000602The statement will always be enabled in Python 2.6.
603
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000604Some standard Python objects now support the context management
605protocol and can be used with the '\keyword{with}' statement. File
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000606objects are one example:
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000607
608\begin{verbatim}
609with open('/etc/passwd', 'r') as f:
610 for line in f:
611 print line
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000612 ... more processing code ...
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000613\end{verbatim}
614
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000615After this statement has executed, the file object in \var{f} will
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +0000616have been automatically closed, even if the 'for' loop
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000617raised an exception part-way through the block.
618
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000619The \module{threading} module's locks and condition variables
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +0000620also support the '\keyword{with}' statement:
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000621
622\begin{verbatim}
623lock = threading.Lock()
624with lock:
625 # Critical section of code
626 ...
627\end{verbatim}
628
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000629The lock is acquired before the block is executed and always released once
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000630the block is complete.
631
632The \module{decimal} module's contexts, which encapsulate the desired
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000633precision and rounding characteristics for computations, provide a
634\method{context_manager()} method for getting a context manager:
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000635
636\begin{verbatim}
637import decimal
638
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000639# Displays with default precision of 28 digits
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000640v1 = decimal.Decimal('578')
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000641print v1.sqrt()
642
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000643ctx = decimal.Context(prec=16)
644with ctx.context_manager():
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000645 # All code in this block uses a precision of 16 digits.
646 # The original context is restored on exiting the block.
647 print v1.sqrt()
648\end{verbatim}
649
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000650\subsection{Writing Context Managers\label{context-managers}}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000651
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +0000652Under the hood, the '\keyword{with}' statement is fairly complicated.
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000653Most people will only use '\keyword{with}' in company with existing
Andrew M. Kuchling0a7ed8c2006-04-24 14:30:47 +0000654objects and don't need to know these details, so you can skip the rest
655of this section if you like. Authors of new objects will need to
656understand the details of the underlying implementation and should
657keep reading.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000658
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000659A high-level explanation of the context management protocol is:
660
661\begin{itemize}
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000662
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000663\item The expression is evaluated and should result in an object
664called a ``context manager''. The context manager must have
Andrew M. Kuchling0a7ed8c2006-04-24 14:30:47 +0000665\method{__enter__()} and \method{__exit__()} methods.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000666
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000667\item The context manager's \method{__enter__()} method is called. The value
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000668returned is assigned to \var{VAR}. If no \code{'as \var{VAR}'} clause
669is present, the value is simply discarded.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000670
671\item The code in \var{BLOCK} is executed.
672
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000673\item If \var{BLOCK} raises an exception, the
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000674\method{__exit__(\var{type}, \var{value}, \var{traceback})} is called
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000675with the exception details, the same values returned by
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000676\function{sys.exc_info()}. The method's return value controls whether
677the exception is re-raised: any false value re-raises the exception,
678and \code{True} will result in suppressing it. You'll only rarely
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000679want to suppress the exception, because if you do
680the author of the code containing the
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000681'\keyword{with}' statement will never realize anything went wrong.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000682
683\item If \var{BLOCK} didn't raise an exception,
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000684the \method{__exit__()} method is still called,
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000685but \var{type}, \var{value}, and \var{traceback} are all \code{None}.
686
687\end{itemize}
688
689Let's think through an example. I won't present detailed code but
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000690will only sketch the methods necessary for a database that supports
691transactions.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000692
693(For people unfamiliar with database terminology: a set of changes to
694the database are grouped into a transaction. Transactions can be
695either committed, meaning that all the changes are written into the
696database, or rolled back, meaning that the changes are all discarded
697and the database is unchanged. See any database textbook for more
698information.)
699% XXX find a shorter reference?
700
701Let's assume there's an object representing a database connection.
702Our goal will be to let the user write code like this:
703
704\begin{verbatim}
705db_connection = DatabaseConnection()
706with db_connection as cursor:
707 cursor.execute('insert into ...')
708 cursor.execute('delete from ...')
709 # ... more operations ...
710\end{verbatim}
711
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000712The transaction should be committed if the code in the block
713runs flawlessly or rolled back if there's an exception.
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000714Here's the basic interface
715for \class{DatabaseConnection} that I'll assume:
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000716
717\begin{verbatim}
718class DatabaseConnection:
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000719 # Database interface
720 def cursor (self):
721 "Returns a cursor object and starts a new transaction"
722 def commit (self):
723 "Commits current transaction"
724 def rollback (self):
725 "Rolls back current transaction"
726\end{verbatim}
727
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000728The \method {__enter__()} method is pretty easy, having only to start
729a new transaction. For this application the resulting cursor object
730would be a useful result, so the method will return it. The user can
731then add \code{as cursor} to their '\keyword{with}' statement to bind
732the cursor to a variable name.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000733
734\begin{verbatim}
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000735class DatabaseConnection:
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000736 ...
737 def __enter__ (self):
738 # Code to start a new transaction
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000739 cursor = self.cursor()
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000740 return cursor
741\end{verbatim}
742
743The \method{__exit__()} method is the most complicated because it's
744where most of the work has to be done. The method has to check if an
745exception occurred. If there was no exception, the transaction is
746committed. The transaction is rolled back if there was an exception.
Andrew M. Kuchling0a7ed8c2006-04-24 14:30:47 +0000747
748In the code below, execution will just fall off the end of the
749function, returning the default value of \code{None}. \code{None} is
750false, so the exception will be re-raised automatically. If you
751wished, you could be more explicit and add a \keyword{return}
752statement at the marked location.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000753
754\begin{verbatim}
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000755class DatabaseConnection:
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000756 ...
757 def __exit__ (self, type, value, tb):
758 if tb is None:
759 # No exception, so commit
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000760 self.commit()
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000761 else:
762 # Exception occurred, so rollback.
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000763 self.rollback()
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000764 # return False
765\end{verbatim}
766
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000767
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000768\subsection{The contextlib module\label{module-contextlib}}
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000769
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000770The new \module{contextlib} module provides some functions and a
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000771decorator that are useful for writing objects for use with the
772'\keyword{with}' statement.
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000773
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000774The decorator is called \function{contextfactory}, and lets you write
775a single generator function instead of defining a new class. The generator
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000776should yield exactly one value. The code up to the \keyword{yield}
777will be executed as the \method{__enter__()} method, and the value
778yielded will be the method's return value that will get bound to the
779variable in the '\keyword{with}' statement's \keyword{as} clause, if
780any. The code after the \keyword{yield} will be executed in the
781\method{__exit__()} method. Any exception raised in the block will be
782raised by the \keyword{yield} statement.
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000783
784Our database example from the previous section could be written
785using this decorator as:
786
787\begin{verbatim}
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000788from contextlib import contextfactory
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000789
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000790@contextfactory
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000791def db_transaction (connection):
792 cursor = connection.cursor()
793 try:
794 yield cursor
795 except:
796 connection.rollback()
797 raise
798 else:
799 connection.commit()
800
801db = DatabaseConnection()
802with db_transaction(db) as cursor:
803 ...
804\end{verbatim}
805
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000806The \module{contextlib} module also has a \function{nested(\var{mgr1},
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000807\var{mgr2}, ...)} function that combines a number of context managers so you
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000808don't need to write nested '\keyword{with}' statements. In this
809example, the single '\keyword{with}' statement both starts a database
810transaction and acquires a thread lock:
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000811
812\begin{verbatim}
813lock = threading.Lock()
814with nested (db_transaction(db), lock) as (cursor, locked):
815 ...
816\end{verbatim}
817
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000818Finally, the \function{closing(\var{object})} function
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000819returns \var{object} so that it can be bound to a variable,
820and calls \code{\var{object}.close()} at the end of the block.
821
822\begin{verbatim}
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +0000823import urllib, sys
824from contextlib import closing
825
826with closing(urllib.urlopen('http://www.yahoo.com')) as f:
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000827 for line in f:
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +0000828 sys.stdout.write(line)
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000829\end{verbatim}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000830
831\begin{seealso}
832
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000833\seepep{343}{The ``with'' statement}{PEP written by Guido van~Rossum
834and Nick Coghlan; implemented by Mike Bland, Guido van~Rossum, and
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +0000835Neal Norwitz. The PEP shows the code generated for a '\keyword{with}'
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000836statement, which can be helpful in learning how the statement works.}
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000837
838\seeurl{../lib/module-contextlib.html}{The documentation
839for the \module{contextlib} module.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000840
841\end{seealso}
842
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000843
844%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000845\section{PEP 352: Exceptions as New-Style Classes\label{pep-352}}
Andrew M. Kuchling8f4d2552006-03-08 01:50:20 +0000846
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000847Exception classes can now be new-style classes, not just classic
848classes, and the built-in \exception{Exception} class and all the
849standard built-in exceptions (\exception{NameError},
850\exception{ValueError}, etc.) are now new-style classes.
Andrew M. Kuchlingaeadf952006-03-09 19:06:05 +0000851
852The inheritance hierarchy for exceptions has been rearranged a bit.
853In 2.5, the inheritance relationships are:
854
855\begin{verbatim}
856BaseException # New in Python 2.5
857|- KeyboardInterrupt
858|- SystemExit
859|- Exception
860 |- (all other current built-in exceptions)
861\end{verbatim}
862
863This rearrangement was done because people often want to catch all
864exceptions that indicate program errors. \exception{KeyboardInterrupt} and
865\exception{SystemExit} aren't errors, though, and usually represent an explicit
866action such as the user hitting Control-C or code calling
867\function{sys.exit()}. A bare \code{except:} will catch all exceptions,
868so you commonly need to list \exception{KeyboardInterrupt} and
869\exception{SystemExit} in order to re-raise them. The usual pattern is:
870
871\begin{verbatim}
872try:
873 ...
874except (KeyboardInterrupt, SystemExit):
875 raise
876except:
877 # Log error...
878 # Continue running program...
879\end{verbatim}
880
881In Python 2.5, you can now write \code{except Exception} to achieve
882the same result, catching all the exceptions that usually indicate errors
883but leaving \exception{KeyboardInterrupt} and
884\exception{SystemExit} alone. As in previous versions,
885a bare \code{except:} still catches all exceptions.
886
887The goal for Python 3.0 is to require any class raised as an exception
888to derive from \exception{BaseException} or some descendant of
889\exception{BaseException}, and future releases in the
890Python 2.x series may begin to enforce this constraint. Therefore, I
891suggest you begin making all your exception classes derive from
892\exception{Exception} now. It's been suggested that the bare
893\code{except:} form should be removed in Python 3.0, but Guido van~Rossum
894hasn't decided whether to do this or not.
895
896Raising of strings as exceptions, as in the statement \code{raise
897"Error occurred"}, is deprecated in Python 2.5 and will trigger a
898warning. The aim is to be able to remove the string-exception feature
899in a few releases.
900
901
902\begin{seealso}
903
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000904\seepep{352}{Required Superclass for Exceptions}{PEP written by
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000905Brett Cannon and Guido van~Rossum; implemented by Brett Cannon.}
Andrew M. Kuchlingaeadf952006-03-09 19:06:05 +0000906
907\end{seealso}
Andrew M. Kuchling8f4d2552006-03-08 01:50:20 +0000908
909
910%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000911\section{PEP 353: Using ssize_t as the index type\label{pep-353}}
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000912
913A wide-ranging change to Python's C API, using a new
914\ctype{Py_ssize_t} type definition instead of \ctype{int},
915will permit the interpreter to handle more data on 64-bit platforms.
916This change doesn't affect Python's capacity on 32-bit platforms.
917
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000918Various pieces of the Python interpreter used C's \ctype{int} type to
919store sizes or counts; for example, the number of items in a list or
920tuple were stored in an \ctype{int}. The C compilers for most 64-bit
921platforms still define \ctype{int} as a 32-bit type, so that meant
922that lists could only hold up to \code{2**31 - 1} = 2147483647 items.
923(There are actually a few different programming models that 64-bit C
924compilers can use -- see
925\url{http://www.unix.org/version2/whatsnew/lp64_wp.html} for a
926discussion -- but the most commonly available model leaves \ctype{int}
927as 32 bits.)
928
929A limit of 2147483647 items doesn't really matter on a 32-bit platform
930because you'll run out of memory before hitting the length limit.
931Each list item requires space for a pointer, which is 4 bytes, plus
932space for a \ctype{PyObject} representing the item. 2147483647*4 is
933already more bytes than a 32-bit address space can contain.
934
935It's possible to address that much memory on a 64-bit platform,
936however. The pointers for a list that size would only require 16GiB
937of space, so it's not unreasonable that Python programmers might
938construct lists that large. Therefore, the Python interpreter had to
939be changed to use some type other than \ctype{int}, and this will be a
94064-bit type on 64-bit platforms. The change will cause
941incompatibilities on 64-bit machines, so it was deemed worth making
942the transition now, while the number of 64-bit users is still
943relatively small. (In 5 or 10 years, we may \emph{all} be on 64-bit
944machines, and the transition would be more painful then.)
945
946This change most strongly affects authors of C extension modules.
947Python strings and container types such as lists and tuples
948now use \ctype{Py_ssize_t} to store their size.
949Functions such as \cfunction{PyList_Size()}
950now return \ctype{Py_ssize_t}. Code in extension modules
951may therefore need to have some variables changed to
952\ctype{Py_ssize_t}.
953
954The \cfunction{PyArg_ParseTuple()} and \cfunction{Py_BuildValue()} functions
955have a new conversion code, \samp{n}, for \ctype{Py_ssize_t}.
Andrew M. Kuchlinga4d651f2006-04-06 13:24:58 +0000956\cfunction{PyArg_ParseTuple()}'s \samp{s\#} and \samp{t\#} still output
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000957\ctype{int} by default, but you can define the macro
958\csimplemacro{PY_SSIZE_T_CLEAN} before including \file{Python.h}
959to make them return \ctype{Py_ssize_t}.
960
961\pep{353} has a section on conversion guidelines that
962extension authors should read to learn about supporting 64-bit
963platforms.
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000964
965\begin{seealso}
966
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +0000967\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 +0000968
969\end{seealso}
970
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000971
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000972%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000973\section{PEP 357: The '__index__' method\label{pep-357}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000974
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000975The NumPy developers had a problem that could only be solved by adding
976a new special method, \method{__index__}. When using slice notation,
Fred Drake1c0e3282006-04-02 03:30:06 +0000977as in \code{[\var{start}:\var{stop}:\var{step}]}, the values of the
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000978\var{start}, \var{stop}, and \var{step} indexes must all be either
979integers or long integers. NumPy defines a variety of specialized
980integer types corresponding to unsigned and signed integers of 8, 16,
98132, and 64 bits, but there was no way to signal that these types could
982be used as slice indexes.
983
984Slicing can't just use the existing \method{__int__} method because
985that method is also used to implement coercion to integers. If
986slicing used \method{__int__}, floating-point numbers would also
987become legal slice indexes and that's clearly an undesirable
988behaviour.
989
990Instead, a new special method called \method{__index__} was added. It
991takes no arguments and returns an integer giving the slice index to
992use. For example:
993
994\begin{verbatim}
995class C:
996 def __index__ (self):
997 return self.value
998\end{verbatim}
999
1000The return value must be either a Python integer or long integer.
1001The interpreter will check that the type returned is correct, and
1002raises a \exception{TypeError} if this requirement isn't met.
1003
1004A corresponding \member{nb_index} slot was added to the C-level
1005\ctype{PyNumberMethods} structure to let C extensions implement this
1006protocol. \cfunction{PyNumber_Index(\var{obj})} can be used in
1007extension code to call the \method{__index__} function and retrieve
1008its result.
1009
1010\begin{seealso}
1011
1012\seepep{357}{Allowing Any Object to be Used for Slicing}{PEP written
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +00001013and implemented by Travis Oliphant.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001014
1015\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +00001016
1017
1018%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001019\section{Other Language Changes\label{other-lang}}
Fred Drake2db76802004-12-01 05:05:47 +00001020
1021Here are all of the changes that Python 2.5 makes to the core Python
1022language.
1023
1024\begin{itemize}
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001025
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001026\item The \class{dict} type has a new hook for letting subclasses
1027provide a default value when a key isn't contained in the dictionary.
1028When a key isn't found, the dictionary's
1029\method{__missing__(\var{key})}
1030method will be called. This hook is used to implement
1031the new \class{defaultdict} class in the \module{collections}
1032module. The following example defines a dictionary
1033that returns zero for any missing key:
1034
1035\begin{verbatim}
1036class zerodict (dict):
1037 def __missing__ (self, key):
1038 return 0
1039
1040d = zerodict({1:1, 2:2})
1041print d[1], d[2] # Prints 1, 2
1042print d[3], d[4] # Prints 0, 0
1043\end{verbatim}
1044
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001045\item The \function{min()} and \function{max()} built-in functions
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001046gained a \code{key} keyword parameter analogous to the \code{key}
1047argument for \method{sort()}. This parameter supplies a function that
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001048takes a single argument and is called for every value in the list;
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001049\function{min()}/\function{max()} will return the element with the
1050smallest/largest return value from this function.
1051For example, to find the longest string in a list, you can do:
1052
1053\begin{verbatim}
1054L = ['medium', 'longest', 'short']
1055# Prints 'longest'
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001056print max(L, key=len)
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001057# Prints 'short', because lexicographically 'short' has the largest value
1058print max(L)
1059\end{verbatim}
1060
1061(Contributed by Steven Bethard and Raymond Hettinger.)
Fred Drake2db76802004-12-01 05:05:47 +00001062
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001063\item Two new built-in functions, \function{any()} and
1064\function{all()}, evaluate whether an iterator contains any true or
1065false values. \function{any()} returns \constant{True} if any value
1066returned by the iterator is true; otherwise it will return
1067\constant{False}. \function{all()} returns \constant{True} only if
1068all of the values returned by the iterator evaluate as being true.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001069(Suggested by GvR, and implemented by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001070
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001071\item ASCII is now the default encoding for modules. It's now
1072a syntax error if a module contains string literals with 8-bit
1073characters but doesn't have an encoding declaration. In Python 2.4
1074this triggered a warning, not a syntax error. See \pep{263}
1075for how to declare a module's encoding; for example, you might add
1076a line like this near the top of the source file:
1077
1078\begin{verbatim}
1079# -*- coding: latin1 -*-
1080\end{verbatim}
1081
Andrew M. Kuchlingc9236112006-04-30 01:07:09 +00001082\item One error that Python programmers sometimes make is forgetting
1083to include an \file{__init__.py} module in a package directory.
1084Debugging this mistake can be confusing, and usually requires running
1085Python with the \programopt{-v} switch to log all the paths searched.
1086In Python 2.5, a new \exception{ImportWarning} warning is raised when
1087an import would have picked up a directory as a package but no
1088\file{__init__.py} was found. (Implemented by Thomas Wouters.)
1089
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001090\item The list of base classes in a class definition can now be empty.
1091As an example, this is now legal:
1092
1093\begin{verbatim}
1094class C():
1095 pass
1096\end{verbatim}
1097(Implemented by Brett Cannon.)
1098
Fred Drake2db76802004-12-01 05:05:47 +00001099\end{itemize}
1100
1101
1102%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001103\subsection{Interactive Interpreter Changes\label{interactive}}
Andrew M. Kuchlingda376042006-03-17 15:56:41 +00001104
1105In the interactive interpreter, \code{quit} and \code{exit}
1106have long been strings so that new users get a somewhat helpful message
1107when they try to quit:
1108
1109\begin{verbatim}
1110>>> quit
1111'Use Ctrl-D (i.e. EOF) to exit.'
1112\end{verbatim}
1113
1114In Python 2.5, \code{quit} and \code{exit} are now objects that still
1115produce string representations of themselves, but are also callable.
1116Newbies who try \code{quit()} or \code{exit()} will now exit the
1117interpreter as they expect. (Implemented by Georg Brandl.)
1118
1119
1120%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001121\subsection{Optimizations\label{opts}}
Fred Drake2db76802004-12-01 05:05:47 +00001122
Andrew M. Kuchlingc6027232006-05-23 12:44:36 +00001123Several of the optimizations were developed at the NeedForSpeed
1124sprint, an event held in Reykjavik, Iceland, from May 21--28 2006.
1125The sprint focused on speed enhancements to the CPython implementation
1126and was funded by EWT LLC with local support from CCP Games. Those
1127optimizations added at this sprint are specially marked in the
1128following list.
1129
Fred Drake2db76802004-12-01 05:05:47 +00001130\begin{itemize}
1131
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001132\item When they were introduced
1133in Python 2.4, the built-in \class{set} and \class{frozenset} types
1134were built on top of Python's dictionary type.
1135In 2.5 the internal data structure has been customized for implementing sets,
1136and as a result sets will use a third less memory and are somewhat faster.
1137(Implemented by Raymond Hettinger.)
Fred Drake2db76802004-12-01 05:05:47 +00001138
Andrew M. Kuchling3e134a52006-05-23 12:49:35 +00001139\item The speed of some Unicode operations, such as
Andrew M. Kuchling150faff2006-05-23 19:29:38 +00001140finding substrings, string splitting, and character map decoding, has
1141been improved. (Substring search and splitting improvements were
1142added by Fredrik Lundh and Andrew Dalke at the NeedForSpeed
1143sprint. Character map decoding was improved by Walter D\"orwald.)
Andrew M. Kuchling45bb98e2006-04-16 19:53:27 +00001144% Patch 1313939
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001145
Andrew M. Kuchling70bd1992006-05-23 19:32:35 +00001146\item The \module{struct} module now compiles structure format
1147strings into an internal representation and caches this
1148representation, yielding a 20\% speedup. (Contributed by Bob Ippolito
1149at the NeedForSpeed sprint.)
1150
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001151\item The code generator's peephole optimizer now performs
1152simple constant folding in expressions. If you write something like
1153\code{a = 2+3}, the code generator will do the arithmetic and produce
1154code corresponding to \code{a = 5}.
1155
Andrew M. Kuchlingc6027232006-05-23 12:44:36 +00001156\item Function calls are now faster because code objects now keep
1157the most recently finished frame (a ``zombie frame'') in an internal
1158field of the code object, reusing it the next time the code object is
1159invoked. (Original patch by Michael Hudson, modified by Armin Rigo
1160and Richard Jones; committed at the NeedForSpeed sprint.)
1161% Patch 876206
1162
Andrew M. Kuchling150faff2006-05-23 19:29:38 +00001163Frame objects are also slightly smaller, which may improve cache locality
1164and reduce memory usage a bit. (Contributed by Neal Norwitz.)
1165% Patch 1337051
1166
Fred Drake2db76802004-12-01 05:05:47 +00001167\end{itemize}
1168
1169The net result of the 2.5 optimizations is that Python 2.5 runs the
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +00001170pystone benchmark around XXX\% faster than Python 2.4.
Fred Drake2db76802004-12-01 05:05:47 +00001171
1172
1173%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001174\section{New, Improved, and Removed Modules\label{modules}}
Fred Drake2db76802004-12-01 05:05:47 +00001175
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +00001176The standard library received many enhancements and bug fixes in
1177Python 2.5. Here's a partial list of the most notable changes, sorted
1178alphabetically by module name. Consult the \file{Misc/NEWS} file in
1179the source tree for a more complete list of changes, or look through
1180the SVN logs for all the details.
Fred Drake2db76802004-12-01 05:05:47 +00001181
1182\begin{itemize}
1183
Andrew M. Kuchling6fc69762006-04-13 12:37:21 +00001184\item The \module{audioop} module now supports the a-LAW encoding,
1185and the code for u-LAW encoding has been improved. (Contributed by
1186Lars Immisch.)
1187
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001188\item The \module{codecs} module gained support for incremental
1189codecs. The \function{codec.lookup()} function now
1190returns a \class{CodecInfo} instance instead of a tuple.
1191\class{CodecInfo} instances behave like a 4-tuple to preserve backward
1192compatibility but also have the attributes \member{encode},
1193\member{decode}, \member{incrementalencoder}, \member{incrementaldecoder},
1194\member{streamwriter}, and \member{streamreader}. Incremental codecs
1195can receive input and produce output in multiple chunks; the output is
1196the same as if the entire input was fed to the non-incremental codec.
1197See the \module{codecs} module documentation for details.
1198(Designed and implemented by Walter D\"orwald.)
1199% Patch 1436130
1200
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001201\item The \module{collections} module gained a new type,
1202\class{defaultdict}, that subclasses the standard \class{dict}
1203type. The new type mostly behaves like a dictionary but constructs a
1204default value when a key isn't present, automatically adding it to the
1205dictionary for the requested key value.
1206
1207The first argument to \class{defaultdict}'s constructor is a factory
1208function that gets called whenever a key is requested but not found.
1209This factory function receives no arguments, so you can use built-in
1210type constructors such as \function{list()} or \function{int()}. For
1211example,
1212you can make an index of words based on their initial letter like this:
1213
1214\begin{verbatim}
1215words = """Nel mezzo del cammin di nostra vita
1216mi ritrovai per una selva oscura
1217che la diritta via era smarrita""".lower().split()
1218
1219index = defaultdict(list)
1220
1221for w in words:
1222 init_letter = w[0]
1223 index[init_letter].append(w)
1224\end{verbatim}
1225
1226Printing \code{index} results in the following output:
1227
1228\begin{verbatim}
1229defaultdict(<type 'list'>, {'c': ['cammin', 'che'], 'e': ['era'],
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001230 'd': ['del', 'di', 'diritta'], 'm': ['mezzo', 'mi'],
1231 'l': ['la'], 'o': ['oscura'], 'n': ['nel', 'nostra'],
1232 'p': ['per'], 's': ['selva', 'smarrita'],
1233 'r': ['ritrovai'], 'u': ['una'], 'v': ['vita', 'via']}
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001234\end{verbatim}
1235
1236The \class{deque} double-ended queue type supplied by the
1237\module{collections} module now has a \method{remove(\var{value})}
1238method that removes the first occurrence of \var{value} in the queue,
1239raising \exception{ValueError} if the value isn't found.
1240
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001241\item New module: The \module{contextlib} module contains helper functions for use
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001242with the new '\keyword{with}' statement. See
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001243section~\ref{module-contextlib} for more about this module.
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +00001244
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001245\item New module: The \module{cProfile} module is a C implementation of
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001246the existing \module{profile} module that has much lower overhead.
1247The module's interface is the same as \module{profile}: you run
1248\code{cProfile.run('main()')} to profile a function, can save profile
1249data to a file, etc. It's not yet known if the Hotshot profiler,
1250which is also written in C but doesn't match the \module{profile}
1251module's interface, will continue to be maintained in future versions
1252of Python. (Contributed by Armin Rigo.)
1253
Andrew M. Kuchling0a7ed8c2006-04-24 14:30:47 +00001254Also, the \module{pstats} module for analyzing the data measured by
1255the profiler now supports directing the output to any file object
Andrew M. Kuchlinge78eeb12006-04-21 13:26:42 +00001256by supplying a \var{stream} argument to the \class{Stats} constructor.
1257(Contributed by Skip Montanaro.)
1258
Andrew M. Kuchling952f1962006-04-18 12:38:19 +00001259\item The \module{csv} module, which parses files in
1260comma-separated value format, received several enhancements and a
1261number of bugfixes. You can now set the maximum size in bytes of a
1262field by calling the \method{csv.field_size_limit(\var{new_limit})}
1263function; omitting the \var{new_limit} argument will return the
1264currently-set limit. The \class{reader} class now has a
1265\member{line_num} attribute that counts the number of physical lines
1266read from the source; records can span multiple physical lines, so
1267\member{line_num} is not the same as the number of records read.
1268(Contributed by Skip Montanaro and Andrew McNamara.)
1269
Andrew M. Kuchling67191312006-04-19 12:55:39 +00001270\item The \class{datetime} class in the \module{datetime}
1271module now has a \method{strptime(\var{string}, \var{format})}
1272method for parsing date strings, contributed by Josh Spoerri.
1273It uses the same format characters as \function{time.strptime()} and
1274\function{time.strftime()}:
1275
1276\begin{verbatim}
1277from datetime import datetime
1278
1279ts = datetime.strptime('10:13:15 2006-03-07',
1280 '%H:%M:%S %Y-%m-%d')
1281\end{verbatim}
1282
Andrew M. Kuchlingb33842a2006-04-25 12:31:38 +00001283\item The \module{doctest} module gained a \code{SKIP} option that
1284keeps an example from being executed at all. This is intended for
1285code snippets that are usage examples intended for the reader and
1286aren't actually test cases.
1287
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001288\item The \module{fileinput} module was made more flexible.
1289Unicode filenames are now supported, and a \var{mode} parameter that
1290defaults to \code{"r"} was added to the
1291\function{input()} function to allow opening files in binary or
1292universal-newline mode. Another new parameter, \var{openhook},
1293lets you use a function other than \function{open()}
1294to open the input files. Once you're iterating over
1295the set of files, the \class{FileInput} object's new
1296\method{fileno()} returns the file descriptor for the currently opened file.
1297(Contributed by Georg Brandl.)
1298
Andrew M. Kuchlingda376042006-03-17 15:56:41 +00001299\item In the \module{gc} module, the new \function{get_count()} function
1300returns a 3-tuple containing the current collection counts for the
1301three GC generations. This is accounting information for the garbage
1302collector; when these counts reach a specified threshold, a garbage
1303collection sweep will be made. The existing \function{gc.collect()}
1304function now takes an optional \var{generation} argument of 0, 1, or 2
1305to specify which generation to collect.
1306
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001307\item The \function{nsmallest()} and
1308\function{nlargest()} functions in the \module{heapq} module
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001309now support a \code{key} keyword parameter similar to the one
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001310provided by the \function{min()}/\function{max()} functions
1311and the \method{sort()} methods. For example:
1312Example:
1313
1314\begin{verbatim}
1315>>> import heapq
1316>>> L = ["short", 'medium', 'longest', 'longer still']
1317>>> heapq.nsmallest(2, L) # Return two lowest elements, lexicographically
1318['longer still', 'longest']
1319>>> heapq.nsmallest(2, L, key=len) # Return two shortest elements
1320['short', 'medium']
1321\end{verbatim}
1322
1323(Contributed by Raymond Hettinger.)
1324
Andrew M. Kuchling511a3a82005-03-20 19:52:18 +00001325\item The \function{itertools.islice()} function now accepts
1326\code{None} for the start and step arguments. This makes it more
1327compatible with the attributes of slice objects, so that you can now write
1328the following:
1329
1330\begin{verbatim}
1331s = slice(5) # Create slice object
1332itertools.islice(iterable, s.start, s.stop, s.step)
1333\end{verbatim}
1334
1335(Contributed by Raymond Hettinger.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001336
Andrew M. Kuchlingd4c21772006-04-23 21:51:10 +00001337\item The \module{mailbox} module underwent a massive rewrite to add
1338the capability to modify mailboxes in addition to reading them. A new
1339set of classes that include \class{mbox}, \class{MH}, and
1340\class{Maildir} are used to read mailboxes, and have an
1341\method{add(\var{message})} method to add messages,
1342\method{remove(\var{key})} to remove messages, and
1343\method{lock()}/\method{unlock()} to lock/unlock the mailbox. The
1344following example converts a maildir-format mailbox into an mbox-format one:
1345
1346\begin{verbatim}
1347import mailbox
1348
1349# 'factory=None' uses email.Message.Message as the class representing
1350# individual messages.
1351src = mailbox.Maildir('maildir', factory=None)
1352dest = mailbox.mbox('/tmp/mbox')
1353
1354for msg in src:
1355 dest.add(msg)
1356\end{verbatim}
1357
1358(Contributed by Gregory K. Johnson. Funding was provided by Google's
13592005 Summer of Code.)
1360
Andrew M. Kuchling68494882006-05-01 16:32:49 +00001361\item New module: the \module{msilib} module allows creating
1362Microsoft Installer \file{.msi} files and CAB files. Some support
1363for reading the \file{.msi} database is also included.
1364(Contributed by Martin von~L\"owis.)
1365
Andrew M. Kuchling75ba2442006-04-14 10:29:55 +00001366\item The \module{nis} module now supports accessing domains other
1367than the system default domain by supplying a \var{domain} argument to
1368the \function{nis.match()} and \function{nis.maps()} functions.
1369(Contributed by Ben Bell.)
1370
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001371\item The \module{operator} module's \function{itemgetter()}
1372and \function{attrgetter()} functions now support multiple fields.
1373A call such as \code{operator.attrgetter('a', 'b')}
1374will return a function
1375that retrieves the \member{a} and \member{b} attributes. Combining
1376this new feature with the \method{sort()} method's \code{key} parameter
1377lets you easily sort lists using multiple fields.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001378(Contributed by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001379
Andrew M. Kuchlingd4c21772006-04-23 21:51:10 +00001380\item The \module{optparse} module was updated to version 1.5.1 of the
1381Optik library. The \class{OptionParser} class gained an
1382\member{epilog} attribute, a string that will be printed after the
1383help message, and a \method{destroy()} method to break reference
1384cycles created by the object. (Contributed by Greg Ward.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001385
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +00001386\item The \module{os} module underwent several changes. The
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001387\member{stat_float_times} variable now defaults to true, meaning that
1388\function{os.stat()} will now return time values as floats. (This
1389doesn't necessarily mean that \function{os.stat()} will return times
1390that are precise to fractions of a second; not all systems support
1391such precision.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001392
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001393Constants named \member{os.SEEK_SET}, \member{os.SEEK_CUR}, and
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001394\member{os.SEEK_END} have been added; these are the parameters to the
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001395\function{os.lseek()} function. Two new constants for locking are
1396\member{os.O_SHLOCK} and \member{os.O_EXLOCK}.
1397
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001398Two new functions, \function{wait3()} and \function{wait4()}, were
1399added. They're similar the \function{waitpid()} function which waits
1400for a child process to exit and returns a tuple of the process ID and
1401its exit status, but \function{wait3()} and \function{wait4()} return
1402additional information. \function{wait3()} doesn't take a process ID
1403as input, so it waits for any child process to exit and returns a
14043-tuple of \var{process-id}, \var{exit-status}, \var{resource-usage}
1405as returned from the \function{resource.getrusage()} function.
1406\function{wait4(\var{pid})} does take a process ID.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001407(Contributed by Chad J. Schroeder.)
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001408
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001409On FreeBSD, the \function{os.stat()} function now returns
1410times with nanosecond resolution, and the returned object
1411now has \member{st_gen} and \member{st_birthtime}.
1412The \member{st_flags} member is also available, if the platform supports it.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001413(Contributed by Antti Louko and Diego Petten\`o.)
1414% (Patch 1180695, 1212117)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001415
Andrew M. Kuchlingb33842a2006-04-25 12:31:38 +00001416\item The Python debugger provided by the \module{pdb} module
1417can now store lists of commands to execute when a breakpoint is
George Yoshida3bbbc492006-04-25 14:09:58 +00001418reached and execution stops. Once breakpoint \#1 has been created,
Andrew M. Kuchlingb33842a2006-04-25 12:31:38 +00001419enter \samp{commands 1} and enter a series of commands to be executed,
1420finishing the list with \samp{end}. The command list can include
1421commands that resume execution, such as \samp{continue} or
1422\samp{next}. (Contributed by Gr\'egoire Dooms.)
1423% Patch 790710
1424
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001425\item The \module{pickle} and \module{cPickle} modules no
1426longer accept a return value of \code{None} from the
1427\method{__reduce__()} method; the method must return a tuple of
1428arguments instead. The ability to return \code{None} was deprecated
1429in Python 2.4, so this completes the removal of the feature.
1430
Andrew M. Kuchlingaa013da2006-04-29 12:10:43 +00001431\item The \module{pkgutil} module, containing various utility
1432functions for finding packages, was enhanced to support PEP 302's
1433import hooks and now also works for packages stored in ZIP-format archives.
1434(Contributed by Phillip J. Eby.)
1435
Andrew M. Kuchlingc9236112006-04-30 01:07:09 +00001436\item The pybench benchmark suite by Marc-Andr\'e~Lemburg is now
1437included in the \file{Tools/pybench} directory. The pybench suite is
1438an improvement on the commonly used \file{pystone.py} program because
1439pybench provides a more detailed measurement of the interpreter's
Andrew M. Kuchling3e134a52006-05-23 12:49:35 +00001440speed. It times particular operations such as function calls,
Andrew M. Kuchlingc9236112006-04-30 01:07:09 +00001441tuple slicing, method lookups, and numeric operations, instead of
1442performing many different operations and reducing the result to a
1443single number as \file{pystone.py} does.
1444
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001445\item The old \module{regex} and \module{regsub} modules, which have been
1446deprecated ever since Python 2.0, have finally been deleted.
Andrew M. Kuchlingf4b06602006-03-17 15:39:52 +00001447Other deleted modules: \module{statcache}, \module{tzparse},
1448\module{whrandom}.
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001449
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001450\item Also deleted: the \file{lib-old} directory,
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001451which includes ancient modules such as \module{dircmp} and
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001452\module{ni}, was removed. \file{lib-old} wasn't on the default
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001453\code{sys.path}, so unless your programs explicitly added the directory to
1454\code{sys.path}, this removal shouldn't affect your code.
1455
Andrew M. Kuchling09612282006-04-30 21:19:49 +00001456\item The \module{rlcompleter} module is no longer
1457dependent on importing the \module{readline} module and
1458therefore now works on non-{\UNIX} platforms.
1459(Patch from Robert Kiendl.)
1460% Patch #1472854
1461
Andrew M. Kuchling4678dc82006-01-15 16:11:28 +00001462\item The \module{socket} module now supports \constant{AF_NETLINK}
1463sockets on Linux, thanks to a patch from Philippe Biondi.
1464Netlink sockets are a Linux-specific mechanism for communications
1465between a user-space process and kernel code; an introductory
1466article about them is at \url{http://www.linuxjournal.com/article/7356}.
1467In Python code, netlink addresses are represented as a tuple of 2 integers,
1468\code{(\var{pid}, \var{group_mask})}.
1469
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001470Socket objects also gained accessor methods \method{getfamily()},
1471\method{gettype()}, and \method{getproto()} methods to retrieve the
1472family, type, and protocol values for the socket.
1473
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001474\item New module: the \module{spwd} module provides functions for
1475accessing the shadow password database on systems that support
1476shadow passwords.
Fred Drake2db76802004-12-01 05:05:47 +00001477
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001478\item The Python developers switched from CVS to Subversion during the 2.5
1479development process. Information about the exact build version is
1480available as the \code{sys.subversion} variable, a 3-tuple
1481of \code{(\var{interpreter-name}, \var{branch-name}, \var{revision-range})}.
1482For example, at the time of writing
1483my copy of 2.5 was reporting \code{('CPython', 'trunk', '45313:45315')}.
1484
1485This information is also available to C extensions via the
1486\cfunction{Py_GetBuildInfo()} function that returns a
1487string of build information like this:
1488\code{"trunk:45355:45356M, Apr 13 2006, 07:42:19"}.
1489(Contributed by Barry Warsaw.)
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001490
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001491\item The \class{TarFile} class in the \module{tarfile} module now has
Georg Brandl08c02db2005-07-22 18:39:19 +00001492an \method{extractall()} method that extracts all members from the
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001493archive into the current working directory. It's also possible to set
1494a different directory as the extraction target, and to unpack only a
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001495subset of the archive's members.
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001496
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001497A tarfile's compression can be autodetected by
1498using the mode \code{'r|*'}.
1499% patch 918101
1500(Contributed by Lars Gust\"abel.)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001501
Andrew M. Kuchlingf688cc52006-03-10 18:50:08 +00001502\item The \module{unicodedata} module has been updated to use version 4.1.0
1503of the Unicode character database. Version 3.2.0 is required
1504by some specifications, so it's still available as
1505\member{unicodedata.db_3_2_0}.
1506
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001507\item The \module{webbrowser} module received a number of
1508enhancements.
1509It's now usable as a script with \code{python -m webbrowser}, taking a
1510URL as the argument; there are a number of switches
1511to control the behaviour (\programopt{-n} for a new browser window,
1512\programopt{-t} for a new tab). New module-level functions,
1513\function{open_new()} and \function{open_new_tab()}, were added
1514to support this. The module's \function{open()} function supports an
1515additional feature, an \var{autoraise} parameter that signals whether
1516to raise the open window when possible. A number of additional
1517browsers were added to the supported list such as Firefox, Opera,
1518Konqueror, and elinks. (Contributed by Oleg Broytmann and George
1519Brandl.)
1520% Patch #754022
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001521
Fredrik Lundh7e0aef02005-12-12 18:54:55 +00001522
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001523\item The \module{xmlrpclib} module now supports returning
1524 \class{datetime} objects for the XML-RPC date type. Supply
1525 \code{use_datetime=True} to the \function{loads()} function
1526 or the \class{Unmarshaller} class to enable this feature.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001527 (Contributed by Skip Montanaro.)
1528% Patch 1120353
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001529
Andrew M. Kuchlingd779b352006-05-16 16:11:54 +00001530\item The \module{zlib} module's \class{Compress} and \class{Decompress}
1531objects now support a \method{copy()} method that makes a copy of the
1532object's internal state and returns a new
1533\class{Compress} or \class{Decompress} object.
1534(Contributed by Chris AtLee.)
1535% Patch 1435422
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001536
Fred Drake114b8ca2005-03-21 05:47:11 +00001537\end{itemize}
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001538
Fred Drake2db76802004-12-01 05:05:47 +00001539
1540
1541%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001542\subsection{The ctypes package\label{module-ctypes}}
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001543
1544The \module{ctypes} package, written by Thomas Heller, has been added
1545to the standard library. \module{ctypes} lets you call arbitrary functions
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001546in shared libraries or DLLs. Long-time users may remember the \module{dl} module, which
1547provides 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 +00001548
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001549To load a shared library or DLL, you must create an instance of the
1550\class{CDLL} class and provide the name or path of the shared library
1551or DLL. Once that's done, you can call arbitrary functions
1552by accessing them as attributes of the \class{CDLL} object.
1553
1554\begin{verbatim}
1555import ctypes
1556
1557libc = ctypes.CDLL('libc.so.6')
1558result = libc.printf("Line of output\n")
1559\end{verbatim}
1560
1561Type constructors for the various C types are provided: \function{c_int},
1562\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
1563to change the wrapped value. Python integers and strings will be automatically
1564converted to the corresponding C types, but for other types you
1565must call the correct type constructor. (And I mean \emph{must};
1566getting it wrong will often result in the interpreter crashing
1567with a segmentation fault.)
1568
1569You 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
1570supposed to be immutable; breaking this rule will cause puzzling bugs. When you need a modifiable memory area,
Neal Norwitz5f5a69b2006-04-13 03:41:04 +00001571use \function{create_string_buffer()}:
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001572
1573\begin{verbatim}
1574s = "this is a string"
1575buf = ctypes.create_string_buffer(s)
1576libc.strfry(buf)
1577\end{verbatim}
1578
1579C functions are assumed to return integers, but you can set
1580the \member{restype} attribute of the function object to
1581change this:
1582
1583\begin{verbatim}
1584>>> libc.atof('2.71828')
1585-1783957616
1586>>> libc.atof.restype = ctypes.c_double
1587>>> libc.atof('2.71828')
15882.71828
1589\end{verbatim}
1590
1591\module{ctypes} also provides a wrapper for Python's C API
1592as the \code{ctypes.pythonapi} object. This object does \emph{not}
1593release the global interpreter lock before calling a function, because the lock must be held when calling into the interpreter's code.
1594There's a \class{py_object()} type constructor that will create a
1595\ctype{PyObject *} pointer. A simple usage:
1596
1597\begin{verbatim}
1598import ctypes
1599
1600d = {}
1601ctypes.pythonapi.PyObject_SetItem(ctypes.py_object(d),
1602 ctypes.py_object("abc"), ctypes.py_object(1))
1603# d is now {'abc', 1}.
1604\end{verbatim}
1605
1606Don't forget to use \class{py_object()}; if it's omitted you end
1607up with a segmentation fault.
1608
1609\module{ctypes} has been around for a while, but people still write
1610and distribution hand-coded extension modules because you can't rely on \module{ctypes} being present.
1611Perhaps developers will begin to write
1612Python wrappers atop a library accessed through \module{ctypes} instead
1613of extension modules, now that \module{ctypes} is included with core Python.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001614
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001615\begin{seealso}
1616
1617\seeurl{http://starship.python.net/crew/theller/ctypes/}
1618{The ctypes web page, with a tutorial, reference, and FAQ.}
1619
1620\end{seealso}
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001621
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001622
1623%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001624\subsection{The ElementTree package\label{module-etree}}
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001625
1626A subset of Fredrik Lundh's ElementTree library for processing XML has
Andrew M. Kuchlinge3c958c2006-05-01 12:45:02 +00001627been added to the standard library as \module{xml.etree}. The
Georg Brandlce27a062006-04-11 06:27:12 +00001628available modules are
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001629\module{ElementTree}, \module{ElementPath}, and
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00001630\module{ElementInclude} from ElementTree 1.2.6.
1631The \module{cElementTree} accelerator module is also included.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001632
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001633The rest of this section will provide a brief overview of using
1634ElementTree. Full documentation for ElementTree is available at
1635\url{http://effbot.org/zone/element-index.htm}.
1636
1637ElementTree represents an XML document as a tree of element nodes.
1638The text content of the document is stored as the \member{.text}
1639and \member{.tail} attributes of
1640(This is one of the major differences between ElementTree and
1641the Document Object Model; in the DOM there are many different
1642types of node, including \class{TextNode}.)
1643
1644The most commonly used parsing function is \function{parse()}, that
1645takes either a string (assumed to contain a filename) or a file-like
1646object and returns an \class{ElementTree} instance:
1647
1648\begin{verbatim}
Andrew M. Kuchlinge3c958c2006-05-01 12:45:02 +00001649from xml.etree import ElementTree as ET
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001650
1651tree = ET.parse('ex-1.xml')
1652
1653feed = urllib.urlopen(
1654 'http://planet.python.org/rss10.xml')
1655tree = ET.parse(feed)
1656\end{verbatim}
1657
1658Once you have an \class{ElementTree} instance, you
1659can call its \method{getroot()} method to get the root \class{Element} node.
1660
1661There's also an \function{XML()} function that takes a string literal
1662and returns an \class{Element} node (not an \class{ElementTree}).
1663This function provides a tidy way to incorporate XML fragments,
1664approaching the convenience of an XML literal:
1665
1666\begin{verbatim}
Andrew M. Kuchlinge3c958c2006-05-01 12:45:02 +00001667svg = ET.XML("""<svg width="10px" version="1.0">
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001668 </svg>""")
1669svg.set('height', '320px')
1670svg.append(elem1)
1671\end{verbatim}
1672
1673Each XML element supports some dictionary-like and some list-like
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001674access methods. Dictionary-like operations are used to access attribute
1675values, and list-like operations are used to access child nodes.
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001676
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001677\begin{tableii}{c|l}{code}{Operation}{Result}
1678 \lineii{elem[n]}{Returns n'th child element.}
1679 \lineii{elem[m:n]}{Returns list of m'th through n'th child elements.}
1680 \lineii{len(elem)}{Returns number of child elements.}
Andrew M. Kuchlinge3c958c2006-05-01 12:45:02 +00001681 \lineii{list(elem)}{Returns list of child elements.}
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001682 \lineii{elem.append(elem2)}{Adds \var{elem2} as a child.}
1683 \lineii{elem.insert(index, elem2)}{Inserts \var{elem2} at the specified location.}
1684 \lineii{del elem[n]}{Deletes n'th child element.}
1685 \lineii{elem.keys()}{Returns list of attribute names.}
1686 \lineii{elem.get(name)}{Returns value of attribute \var{name}.}
1687 \lineii{elem.set(name, value)}{Sets new value for attribute \var{name}.}
1688 \lineii{elem.attrib}{Retrieves the dictionary containing attributes.}
1689 \lineii{del elem.attrib[name]}{Deletes attribute \var{name}.}
1690\end{tableii}
1691
1692Comments and processing instructions are also represented as
1693\class{Element} nodes. To check if a node is a comment or processing
1694instructions:
1695
1696\begin{verbatim}
1697if elem.tag is ET.Comment:
1698 ...
1699elif elem.tag is ET.ProcessingInstruction:
1700 ...
1701\end{verbatim}
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001702
1703To generate XML output, you should call the
1704\method{ElementTree.write()} method. Like \function{parse()},
1705it can take either a string or a file-like object:
1706
1707\begin{verbatim}
1708# Encoding is US-ASCII
1709tree.write('output.xml')
1710
1711# Encoding is UTF-8
1712f = open('output.xml', 'w')
Andrew M. Kuchlinga8837012006-05-02 11:30:03 +00001713tree.write(f, encoding='utf-8')
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001714\end{verbatim}
1715
Andrew M. Kuchlinga8837012006-05-02 11:30:03 +00001716(Caution: the default encoding used for output is ASCII. For general
1717XML work, where an element's name may contain arbitrary Unicode
1718characters, ASCII isn't a very useful encoding because it will raise
1719an exception if an element's name contains any characters with values
1720greater than 127. Therefore, it's best to specify a different
1721encoding such as UTF-8 that can handle any Unicode character.)
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001722
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001723This section is only a partial description of the ElementTree interfaces.
1724Please read the package's official documentation for more details.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001725
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001726\begin{seealso}
1727
1728\seeurl{http://effbot.org/zone/element-index.htm}
1729{Official documentation for ElementTree.}
1730
1731
1732\end{seealso}
1733
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001734
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001735%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001736\subsection{The hashlib package\label{module-hashlib}}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001737
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001738A new \module{hashlib} module, written by Gregory P. Smith,
1739has been added to replace the
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001740\module{md5} and \module{sha} modules. \module{hashlib} adds support
1741for additional secure hashes (SHA-224, SHA-256, SHA-384, and SHA-512).
1742When available, the module uses OpenSSL for fast platform optimized
1743implementations of algorithms.
1744
1745The old \module{md5} and \module{sha} modules still exist as wrappers
1746around hashlib to preserve backwards compatibility. The new module's
1747interface is very close to that of the old modules, but not identical.
1748The most significant difference is that the constructor functions
1749for creating new hashing objects are named differently.
1750
1751\begin{verbatim}
1752# Old versions
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001753h = md5.md5()
1754h = md5.new()
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001755
1756# New version
1757h = hashlib.md5()
1758
1759# Old versions
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001760h = sha.sha()
1761h = sha.new()
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001762
1763# New version
1764h = hashlib.sha1()
1765
1766# Hash that weren't previously available
1767h = hashlib.sha224()
1768h = hashlib.sha256()
1769h = hashlib.sha384()
1770h = hashlib.sha512()
1771
1772# Alternative form
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001773h = hashlib.new('md5') # Provide algorithm as a string
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001774\end{verbatim}
1775
1776Once a hash object has been created, its methods are the same as before:
1777\method{update(\var{string})} hashes the specified string into the
1778current digest state, \method{digest()} and \method{hexdigest()}
1779return the digest value as a binary string or a string of hex digits,
1780and \method{copy()} returns a new hashing object with the same digest state.
1781
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001782
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001783%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001784\subsection{The sqlite3 package\label{module-sqlite}}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001785
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001786The pysqlite module (\url{http://www.pysqlite.org}), a wrapper for the
1787SQLite embedded database, has been added to the standard library under
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001788the package name \module{sqlite3}.
1789
1790SQLite is a C library that provides a SQL-language database that
1791stores data in disk files without requiring a separate server process.
1792pysqlite was written by Gerhard H\"aring and provides a SQL interface
1793compliant with the DB-API 2.0 specification described by
1794\pep{249}. This means that it should be possible to write the first
1795version of your applications using SQLite for data storage. If
1796switching to a larger database such as PostgreSQL or Oracle is
1797later necessary, the switch should be relatively easy.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001798
1799If you're compiling the Python source yourself, note that the source
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001800tree doesn't include the SQLite code, only the wrapper module.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001801You'll need to have the SQLite libraries and headers installed before
1802compiling Python, and the build process will compile the module when
1803the necessary headers are available.
1804
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001805To use the module, you must first create a \class{Connection} object
1806that represents the database. Here the data will be stored in the
1807\file{/tmp/example} file:
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001808
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001809\begin{verbatim}
1810conn = sqlite3.connect('/tmp/example')
1811\end{verbatim}
1812
1813You can also supply the special name \samp{:memory:} to create
1814a database in RAM.
1815
1816Once you have a \class{Connection}, you can create a \class{Cursor}
1817object and call its \method{execute()} method to perform SQL commands:
1818
1819\begin{verbatim}
1820c = conn.cursor()
1821
1822# Create table
1823c.execute('''create table stocks
1824(date timestamp, trans varchar, symbol varchar,
1825 qty decimal, price decimal)''')
1826
1827# Insert a row of data
1828c.execute("""insert into stocks
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001829 values ('2006-01-05','BUY','RHAT',100,35.14)""")
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001830\end{verbatim}
1831
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001832Usually your SQL operations will need to use values from Python
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001833variables. You shouldn't assemble your query using Python's string
1834operations because doing so is insecure; it makes your program
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001835vulnerable to an SQL injection attack.
1836
1837Instead, use SQLite's parameter substitution. Put \samp{?} as a
1838placeholder wherever you want to use a value, and then provide a tuple
1839of values as the second argument to the cursor's \method{execute()}
1840method. For example:
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001841
1842\begin{verbatim}
1843# Never do this -- insecure!
1844symbol = 'IBM'
1845c.execute("... where symbol = '%s'" % symbol)
1846
1847# Do this instead
1848t = (symbol,)
Andrew M. Kuchling7e5abb92006-04-26 12:21:06 +00001849c.execute('select * from stocks where symbol=?', t)
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001850
1851# Larger example
1852for t in (('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001853 ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
1854 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
1855 ):
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001856 c.execute('insert into stocks values (?,?,?,?,?)', t)
1857\end{verbatim}
1858
1859To retrieve data after executing a SELECT statement, you can either
1860treat the cursor as an iterator, call the cursor's \method{fetchone()}
1861method to retrieve a single matching row,
1862or call \method{fetchall()} to get a list of the matching rows.
1863
1864This example uses the iterator form:
1865
1866\begin{verbatim}
1867>>> c = conn.cursor()
1868>>> c.execute('select * from stocks order by price')
1869>>> for row in c:
1870... print row
1871...
1872(u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001)
1873(u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
1874(u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
1875(u'2006-04-05', u'BUY', u'MSOFT', 1000, 72.0)
1876>>>
1877\end{verbatim}
1878
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001879For more information about the SQL dialect supported by SQLite, see
1880\url{http://www.sqlite.org}.
1881
1882\begin{seealso}
1883
1884\seeurl{http://www.pysqlite.org}
1885{The pysqlite web page.}
1886
1887\seeurl{http://www.sqlite.org}
1888{The SQLite web page; the documentation describes the syntax and the
1889available data types for the supported SQL dialect.}
1890
1891\seepep{249}{Database API Specification 2.0}{PEP written by
1892Marc-Andr\'e Lemburg.}
1893
1894\end{seealso}
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001895
Fred Drake2db76802004-12-01 05:05:47 +00001896
1897% ======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001898\section{Build and C API Changes\label{build-api}}
Fred Drake2db76802004-12-01 05:05:47 +00001899
1900Changes to Python's build process and to the C API include:
1901
1902\begin{itemize}
1903
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00001904\item The largest change to the C API came from \pep{353},
1905which modifies the interpreter to use a \ctype{Py_ssize_t} type
1906definition instead of \ctype{int}. See the earlier
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +00001907section~\ref{pep-353} for a discussion of this change.
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00001908
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001909\item The design of the bytecode compiler has changed a great deal, to
1910no longer generate bytecode by traversing the parse tree. Instead
Andrew M. Kuchlingdb85ed52005-10-23 21:52:59 +00001911the parse tree is converted to an abstract syntax tree (or AST), and it is
1912the abstract syntax tree that's traversed to produce the bytecode.
1913
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00001914It's possible for Python code to obtain AST objects by using the
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001915\function{compile()} built-in and specifying \code{_ast.PyCF_ONLY_AST}
1916as the value of the
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00001917\var{flags} parameter:
1918
1919\begin{verbatim}
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001920from _ast import PyCF_ONLY_AST
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00001921ast = compile("""a=0
1922for i in range(10):
1923 a += i
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001924""", "<string>", 'exec', PyCF_ONLY_AST)
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00001925
1926assignment = ast.body[0]
1927for_loop = ast.body[1]
1928\end{verbatim}
1929
Andrew M. Kuchlingdb85ed52005-10-23 21:52:59 +00001930No documentation has been written for the AST code yet. To start
1931learning about it, read the definition of the various AST nodes in
1932\file{Parser/Python.asdl}. A Python script reads this file and
1933generates a set of C structure definitions in
1934\file{Include/Python-ast.h}. The \cfunction{PyParser_ASTFromString()}
1935and \cfunction{PyParser_ASTFromFile()}, defined in
1936\file{Include/pythonrun.h}, take Python source as input and return the
1937root of an AST representing the contents. This AST can then be turned
1938into a code object by \cfunction{PyAST_Compile()}. For more
1939information, read the source code, and then ask questions on
1940python-dev.
1941
1942% List of names taken from Jeremy's python-dev post at
1943% http://mail.python.org/pipermail/python-dev/2005-October/057500.html
1944The AST code was developed under Jeremy Hylton's management, and
1945implemented by (in alphabetical order) Brett Cannon, Nick Coghlan,
1946Grant Edwards, John Ehresman, Kurt Kaiser, Neal Norwitz, Tim Peters,
1947Armin Rigo, and Neil Schemenauer, plus the participants in a number of
1948AST sprints at conferences such as PyCon.
1949
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001950\item The built-in set types now have an official C API. Call
1951\cfunction{PySet_New()} and \cfunction{PyFrozenSet_New()} to create a
1952new set, \cfunction{PySet_Add()} and \cfunction{PySet_Discard()} to
1953add and remove elements, and \cfunction{PySet_Contains} and
1954\cfunction{PySet_Size} to examine the set's state.
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001955(Contributed by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001956
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001957\item C code can now obtain information about the exact revision
1958of the Python interpreter by calling the
1959\cfunction{Py_GetBuildInfo()} function that returns a
1960string of build information like this:
1961\code{"trunk:45355:45356M, Apr 13 2006, 07:42:19"}.
1962(Contributed by Barry Warsaw.)
1963
Andrew M. Kuchlingc6027232006-05-23 12:44:36 +00001964\item \cfunction{PyErr_NewException(\var{name}, \var{base},
1965\var{dict})} can now accept a tuple of base classes as its \var{base}
1966argument. (Contributed by Georg Brandl.)
1967
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001968\item The CPython interpreter is still written in C, but
1969the code can now be compiled with a {\Cpp} compiler without errors.
1970(Implemented by Anthony Baxter, Martin von~L\"owis, Skip Montanaro.)
1971
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001972\item The \cfunction{PyRange_New()} function was removed. It was
1973never documented, never used in the core code, and had dangerously lax
1974error checking.
Fred Drake2db76802004-12-01 05:05:47 +00001975
1976\end{itemize}
1977
1978
1979%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001980\subsection{Port-Specific Changes\label{ports}}
Fred Drake2db76802004-12-01 05:05:47 +00001981
Andrew M. Kuchling6fc69762006-04-13 12:37:21 +00001982\begin{itemize}
1983
1984\item MacOS X (10.3 and higher): dynamic loading of modules
1985now uses the \cfunction{dlopen()} function instead of MacOS-specific
1986functions.
1987
Andrew M. Kuchlingb37bcb52006-04-29 11:53:15 +00001988\item MacOS X: a \longprogramopt{enable-universalsdk} switch was added
1989to the \program{configure} script that compiles the interpreter as a
1990universal binary able to run on both PowerPC and Intel processors.
1991(Contributed by Ronald Oussoren.)
1992
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001993\item Windows: \file{.dll} is no longer supported as a filename extension for
1994extension modules. \file{.pyd} is now the only filename extension that will
1995be searched for.
1996
Andrew M. Kuchling6fc69762006-04-13 12:37:21 +00001997\end{itemize}
Fred Drake2db76802004-12-01 05:05:47 +00001998
1999
2000%======================================================================
2001\section{Other Changes and Fixes \label{section-other}}
2002
2003As usual, there were a bunch of other improvements and bugfixes
Andrew M. Kuchlingf688cc52006-03-10 18:50:08 +00002004scattered throughout the source tree. A search through the SVN change
Fred Drake2db76802004-12-01 05:05:47 +00002005logs finds there were XXX patches applied and YYY bugs fixed between
Andrew M. Kuchling92e24952004-12-03 13:54:09 +00002006Python 2.4 and 2.5. Both figures are likely to be underestimates.
Fred Drake2db76802004-12-01 05:05:47 +00002007
2008Some of the more notable changes are:
2009
2010\begin{itemize}
2011
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00002012\item Evan Jones's patch to obmalloc, first described in a talk
2013at PyCon DC 2005, was applied. Python 2.4 allocated small objects in
2014256K-sized arenas, but never freed arenas. With this patch, Python
2015will free arenas when they're empty. The net effect is that on some
2016platforms, when you allocate many objects, Python's memory usage may
2017actually drop when you delete them, and the memory may be returned to
2018the operating system. (Implemented by Evan Jones, and reworked by Tim
2019Peters.)
Fred Drake2db76802004-12-01 05:05:47 +00002020
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00002021Note that this change means extension modules need to be more careful
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +00002022with how they allocate memory. Python's API has many different
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00002023functions for allocating memory that are grouped into families. For
2024example, \cfunction{PyMem_Malloc()}, \cfunction{PyMem_Realloc()}, and
2025\cfunction{PyMem_Free()} are one family that allocates raw memory,
2026while \cfunction{PyObject_Malloc()}, \cfunction{PyObject_Realloc()},
2027and \cfunction{PyObject_Free()} are another family that's supposed to
2028be used for creating Python objects.
2029
2030Previously these different families all reduced to the platform's
2031\cfunction{malloc()} and \cfunction{free()} functions. This meant
2032it didn't matter if you got things wrong and allocated memory with the
2033\cfunction{PyMem} function but freed it with the \cfunction{PyObject}
2034function. With the obmalloc change, these families now do different
2035things, and mismatches will probably result in a segfault. You should
2036carefully test your C extension modules with Python 2.5.
2037
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00002038\item Coverity, a company that markets a source code analysis tool
2039 called Prevent, provided the results of their examination of the Python
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +00002040 source code. The analysis found about 60 bugs that
2041 were quickly fixed. Many of the bugs were refcounting problems, often
2042 occurring in error-handling code. See
2043 \url{http://scan.coverity.com} for the statistics.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00002044
Fred Drake2db76802004-12-01 05:05:47 +00002045\end{itemize}
2046
2047
2048%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00002049\section{Porting to Python 2.5\label{porting}}
Fred Drake2db76802004-12-01 05:05:47 +00002050
2051This section lists previously described changes that may require
2052changes to your code:
2053
2054\begin{itemize}
2055
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00002056\item ASCII is now the default encoding for modules. It's now
2057a syntax error if a module contains string literals with 8-bit
2058characters but doesn't have an encoding declaration. In Python 2.4
2059this triggered a warning, not a syntax error.
2060
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +00002061\item Previously, the \member{gi_frame} attribute of a generator
2062was always a frame object. Because of the \pep{342} changes
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +00002063described in section~\ref{pep-342}, it's now possible
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +00002064for \member{gi_frame} to be \code{None}.
2065
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00002066
2067\item Library: The \module{pickle} and \module{cPickle} modules no
2068longer accept a return value of \code{None} from the
2069\method{__reduce__()} method; the method must return a tuple of
2070arguments instead. The modules also no longer accept the deprecated
2071\var{bin} keyword parameter.
2072
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00002073\item C API: Many functions now use \ctype{Py_ssize_t}
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00002074instead of \ctype{int} to allow processing more data on 64-bit
2075machines. Extension code may need to make the same change to avoid
2076warnings and to support 64-bit machines. See the earlier
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +00002077section~\ref{pep-353} for a discussion of this change.
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00002078
2079\item C API:
2080The obmalloc changes mean that
2081you must be careful to not mix usage
2082of the \cfunction{PyMem_*()} and \cfunction{PyObject_*()}
2083families of functions. Memory allocated with
2084one family's \cfunction{*_Malloc()} must be
2085freed with the corresponding family's \cfunction{*_Free()} function.
2086
Fred Drake2db76802004-12-01 05:05:47 +00002087\end{itemize}
2088
2089
2090%======================================================================
2091\section{Acknowledgements \label{acks}}
2092
2093The author would like to thank the following people for offering
2094suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchlinge3c958c2006-05-01 12:45:02 +00002095article: Phillip J. Eby, Kent Johnson, Martin von~L\"owis, Fredrik Lundh,
Andrew M. Kuchling356af462006-05-10 17:19:04 +00002096Gustavo Niemeyer, James Pryor, Mike Rovner, Scott Weikart, Thomas Wouters.
Fred Drake2db76802004-12-01 05:05:47 +00002097
2098\end{document}