blob: 84bab8f8f8aa35ccce124e7b6da3c8b54fb41284 [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. Kuchling10340602006-06-21 17:17:28 +00009\release{0.3}
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
Andrew M. Kuchlingb1992d02006-06-20 13:05:12 +000017This article explains the new features in Python 2.5. The final
18release of Python 2.5 is scheduled for August 2006;
19\pep{356} describes the planned release schedule.
Fred Drake2db76802004-12-01 05:05:47 +000020
Andrew M. Kuchling7c4e79c2006-06-20 13:11:29 +000021The changes in Python 2.5 are an interesting mix of language and
22library improvements. The library enhancements will be more important
23to Python's user community, I think, because several widely-useful
24packages were added. New modules include ElementTree for XML
25processing (section~\ref{module-etree}), the SQLite database module
26(section~\ref{module-sqlite}), and the \module{ctypes} module for
27calling C functions (section~\ref{module-ctypes}).
Fred Drake2db76802004-12-01 05:05:47 +000028
Andrew M. Kuchlingb1992d02006-06-20 13:05:12 +000029The language changes are of middling significance. Some pleasant new
30features were added, but most of them aren't features that you'll use
31every day. Conditional expressions were finally added to the language
32using a novel syntax; see section~\ref{pep-308}. The new
33'\keyword{with}' statement will make writing cleanup code easier
34(section~\ref{pep-343}). Values can now be passed into generators
35(section~\ref{pep-342}). Imports are now visible as either absolute
36or relative (section~\ref{pep-328}). Some corner cases of exception
37handling are handled better (section~\ref{pep-341}). All these
38improvements are worthwhile, but they're improvements to one specific
39language feature or another; none of them are broad modifications to
40Python's semantics.
41
Andrew M. Kuchling7c4e79c2006-06-20 13:11:29 +000042This article doesn't try to be a complete specification of the new
43features; instead changes are briefly introduced using helpful
44examples. For full details, you should always refer to the
45documentation for Python 2.5.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000046% XXX add hyperlink when the documentation becomes available online.
Fred Drake2db76802004-12-01 05:05:47 +000047If you want to understand the complete implementation and design
48rationale, refer to the PEP for a particular new feature.
49
Andrew M. Kuchling7c4e79c2006-06-20 13:11:29 +000050Comments, suggestions, and error reports for this document are
51welcome; please e-mail them to the author or open a bug in the Python
52bug tracker.
Fred Drake2db76802004-12-01 05:05:47 +000053
54%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +000055\section{PEP 308: Conditional Expressions\label{pep-308}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000056
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000057For a long time, people have been requesting a way to write
Andrew M. Kuchlingb1992d02006-06-20 13:05:12 +000058conditional expressions, which are expressions that return value A or
59value B depending on whether a Boolean value is true or false. A
60conditional expression lets you write a single assignment statement
61that has the same effect as the following:
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000062
63\begin{verbatim}
64if condition:
65 x = true_value
66else:
67 x = false_value
68\end{verbatim}
69
70There have been endless tedious discussions of syntax on both
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +000071python-dev and comp.lang.python. A vote was even held that found the
72majority of voters wanted conditional expressions in some form,
73but there was no syntax that was preferred by a clear majority.
74Candidates included C's \code{cond ? true_v : false_v},
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000075\code{if cond then true_v else false_v}, and 16 other variations.
76
77GvR eventually chose a surprising syntax:
78
79\begin{verbatim}
80x = true_value if condition else false_value
81\end{verbatim}
82
Andrew M. Kuchling38f85072006-04-02 01:46:32 +000083Evaluation is still lazy as in existing Boolean expressions, so the
84order of evaluation jumps around a bit. The \var{condition}
85expression in the middle is evaluated first, and the \var{true_value}
86expression is evaluated only if the condition was true. Similarly,
87the \var{false_value} expression is only evaluated when the condition
88is false.
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000089
90This syntax may seem strange and backwards; why does the condition go
91in the \emph{middle} of the expression, and not in the front as in C's
92\code{c ? x : y}? The decision was checked by applying the new syntax
93to the modules in the standard library and seeing how the resulting
94code read. In many cases where a conditional expression is used, one
95value seems to be the 'common case' and one value is an 'exceptional
96case', used only on rarer occasions when the condition isn't met. The
97conditional syntax makes this pattern a bit more obvious:
98
99\begin{verbatim}
100contents = ((doc + '\n') if doc else '')
101\end{verbatim}
102
103I read the above statement as meaning ``here \var{contents} is
Andrew M. Kuchlingd0fcc022006-03-09 13:57:28 +0000104usually assigned a value of \code{doc+'\e n'}; sometimes
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +0000105\var{doc} is empty, in which special case an empty string is returned.''
106I doubt I will use conditional expressions very often where there
107isn't a clear common and uncommon case.
108
109There was some discussion of whether the language should require
110surrounding conditional expressions with parentheses. The decision
111was made to \emph{not} require parentheses in the Python language's
112grammar, but as a matter of style I think you should always use them.
113Consider these two statements:
114
115\begin{verbatim}
116# First version -- no parens
117level = 1 if logging else 0
118
119# Second version -- with parens
120level = (1 if logging else 0)
121\end{verbatim}
122
123In the first version, I think a reader's eye might group the statement
124into 'level = 1', 'if logging', 'else 0', and think that the condition
125decides whether the assignment to \var{level} is performed. The
126second version reads better, in my opinion, because it makes it clear
127that the assignment is always performed and the choice is being made
128between two values.
129
130Another reason for including the brackets: a few odd combinations of
131list comprehensions and lambdas could look like incorrect conditional
132expressions. See \pep{308} for some examples. If you put parentheses
133around your conditional expressions, you won't run into this case.
134
135
136\begin{seealso}
137
138\seepep{308}{Conditional Expressions}{PEP written by
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000139Guido van~Rossum and Raymond D. Hettinger; implemented by Thomas
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +0000140Wouters.}
141
142\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000143
144
145%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000146\section{PEP 309: Partial Function Application\label{pep-309}}
Fred Drake2db76802004-12-01 05:05:47 +0000147
Andrew M. Kuchling0d272bb2006-05-31 13:18:56 +0000148The \module{functools} module is intended to contain tools for
Andrew M. Kuchlinge878fe62006-06-09 01:10:17 +0000149functional-style programming.
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000150
Andrew M. Kuchlinge878fe62006-06-09 01:10:17 +0000151One useful tool in this module is the \function{partial()} function.
152For programs written in a functional style, you'll sometimes want to
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000153construct variants of existing functions that have some of the
154parameters filled in. Consider a Python function \code{f(a, b, c)};
155you could create a new function \code{g(b, c)} that was equivalent to
Andrew M. Kuchlinge878fe62006-06-09 01:10:17 +0000156\code{f(1, b, c)}. This is called ``partial function application''.
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000157
Andrew M. Kuchlinge878fe62006-06-09 01:10:17 +0000158\function{partial} takes the arguments
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000159\code{(\var{function}, \var{arg1}, \var{arg2}, ...
160\var{kwarg1}=\var{value1}, \var{kwarg2}=\var{value2})}. The resulting
161object is callable, so you can just call it to invoke \var{function}
162with the filled-in arguments.
163
164Here's a small but realistic example:
165
166\begin{verbatim}
Andrew M. Kuchling0d272bb2006-05-31 13:18:56 +0000167import functools
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000168
169def log (message, subsystem):
170 "Write the contents of 'message' to the specified subsystem."
171 print '%s: %s' % (subsystem, message)
172 ...
173
Andrew M. Kuchling0d272bb2006-05-31 13:18:56 +0000174server_log = functools.partial(log, subsystem='server')
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000175server_log('Unable to open socket')
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000176\end{verbatim}
177
Andrew M. Kuchling0d272bb2006-05-31 13:18:56 +0000178Here's another example, from a program that uses PyGTK. Here a
Andrew M. Kuchling6af7fe02005-08-02 17:20:36 +0000179context-sensitive pop-up menu is being constructed dynamically. The
180callback provided for the menu option is a partially applied version
181of the \method{open_item()} method, where the first argument has been
182provided.
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000183
Andrew M. Kuchling6af7fe02005-08-02 17:20:36 +0000184\begin{verbatim}
185...
186class Application:
187 def open_item(self, path):
188 ...
189 def init (self):
Andrew M. Kuchling0d272bb2006-05-31 13:18:56 +0000190 open_func = functools.partial(self.open_item, item_path)
Andrew M. Kuchling6af7fe02005-08-02 17:20:36 +0000191 popup_menu.append( ("Open", open_func, 1) )
192\end{verbatim}
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000193
194
Andrew M. Kuchlinge878fe62006-06-09 01:10:17 +0000195Another function in the \module{functools} module is the
Andrew M. Kuchling7dbb1ff2006-06-09 10:22:35 +0000196\function{update_wrapper(\var{wrapper}, \var{wrapped})} function that
Andrew M. Kuchlinge878fe62006-06-09 01:10:17 +0000197helps you write well-behaved decorators. \function{update_wrapper()}
198copies the name, module, and docstring attribute to a wrapper function
199so that tracebacks inside the wrapped function are easier to
200understand. For example, you might write:
201
202\begin{verbatim}
203def my_decorator(f):
204 def wrapper(*args, **kwds):
205 print 'Calling decorated function'
206 return f(*args, **kwds)
207 functools.update_wrapper(wrapper, f)
208 return wrapper
209\end{verbatim}
210
211\function{wraps()} is a decorator that can be used inside your own
212decorators to copy the wrapped function's information. An alternate
213version of the previous example would be:
214
215\begin{verbatim}
216def my_decorator(f):
217 @functools.wraps(f)
218 def wrapper(*args, **kwds):
219 print 'Calling decorated function'
220 return f(*args, **kwds)
221 return wrapper
222\end{verbatim}
223
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000224\begin{seealso}
225
226\seepep{309}{Partial Function Application}{PEP proposed and written by
Andrew M. Kuchlinge878fe62006-06-09 01:10:17 +0000227Peter Harris; implemented by Hye-Shik Chang and Nick Coghlan, with
228adaptations by Raymond Hettinger.}
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000229
230\end{seealso}
Fred Drake2db76802004-12-01 05:05:47 +0000231
232
233%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000234\section{PEP 314: Metadata for Python Software Packages v1.1\label{pep-314}}
Fred Drakedb7b0022005-03-20 22:19:47 +0000235
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000236Some simple dependency support was added to Distutils. The
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000237\function{setup()} function now has \code{requires}, \code{provides},
238and \code{obsoletes} keyword parameters. When you build a source
239distribution using the \code{sdist} command, the dependency
240information will be recorded in the \file{PKG-INFO} file.
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000241
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000242Another new keyword parameter is \code{download_url}, which should be
243set to a URL for the package's source code. This means it's now
244possible to look up an entry in the package index, determine the
245dependencies for a package, and download the required packages.
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000246
Andrew M. Kuchling61434b62006-04-13 11:51:07 +0000247\begin{verbatim}
248VERSION = '1.0'
249setup(name='PyPackage',
250 version=VERSION,
251 requires=['numarray', 'zlib (>=1.1.4)'],
252 obsoletes=['OldPackage']
253 download_url=('http://www.example.com/pypackage/dist/pkg-%s.tar.gz'
254 % VERSION),
255 )
256\end{verbatim}
Andrew M. Kuchlingc0a0dec2006-05-16 16:27:31 +0000257
258Another new enhancement to the Python package index at
259\url{http://cheeseshop.python.org} is storing source and binary
260archives for a package. The new \command{upload} Distutils command
261will upload a package to the repository.
262
263Before a package can be uploaded, you must be able to build a
264distribution using the \command{sdist} Distutils command. Once that
265works, you can run \code{python setup.py upload} to add your package
266to the PyPI archive. Optionally you can GPG-sign the package by
267supplying the \longprogramopt{sign} and
268\longprogramopt{identity} options.
269
270Package uploading was implemented by Martin von~L\"owis and Richard Jones.
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000271
272\begin{seealso}
273
274\seepep{314}{Metadata for Python Software Packages v1.1}{PEP proposed
275and written by A.M. Kuchling, Richard Jones, and Fred Drake;
276implemented by Richard Jones and Fred Drake.}
277
278\end{seealso}
Fred Drakedb7b0022005-03-20 22:19:47 +0000279
280
281%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000282\section{PEP 328: Absolute and Relative Imports\label{pep-328}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000283
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000284The simpler part of PEP 328 was implemented in Python 2.4: parentheses
285could now be used to enclose the names imported from a module using
286the \code{from ... import ...} statement, making it easier to import
287many different names.
288
289The more complicated part has been implemented in Python 2.5:
290importing a module can be specified to use absolute or
291package-relative imports. The plan is to move toward making absolute
292imports the default in future versions of Python.
293
294Let's say you have a package directory like this:
295\begin{verbatim}
296pkg/
297pkg/__init__.py
298pkg/main.py
299pkg/string.py
300\end{verbatim}
301
302This defines a package named \module{pkg} containing the
303\module{pkg.main} and \module{pkg.string} submodules.
304
305Consider the code in the \file{main.py} module. What happens if it
306executes the statement \code{import string}? In Python 2.4 and
307earlier, it will first look in the package's directory to perform a
308relative import, finds \file{pkg/string.py}, imports the contents of
309that file as the \module{pkg.string} module, and that module is bound
310to the name \samp{string} in the \module{pkg.main} module's namespace.
311
312That's fine if \module{pkg.string} was what you wanted. But what if
313you wanted Python's standard \module{string} module? There's no clean
314way to ignore \module{pkg.string} and look for the standard module;
315generally you had to look at the contents of \code{sys.modules}, which
316is slightly unclean.
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000317Holger Krekel's \module{py.std} package provides a tidier way to perform
318imports from the standard library, \code{import py ; py.std.string.join()},
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000319but that package isn't available on all Python installations.
320
321Reading code which relies on relative imports is also less clear,
322because a reader may be confused about which module, \module{string}
323or \module{pkg.string}, is intended to be used. Python users soon
324learned not to duplicate the names of standard library modules in the
325names of their packages' submodules, but you can't protect against
326having your submodule's name being used for a new module added in a
327future version of Python.
328
329In Python 2.5, you can switch \keyword{import}'s behaviour to
330absolute imports using a \code{from __future__ import absolute_import}
331directive. This absolute-import behaviour will become the default in
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000332a future version (probably Python 2.7). Once absolute imports
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000333are the default, \code{import string} will
334always find the standard library's version.
335It's suggested that users should begin using absolute imports as much
336as possible, so it's preferable to begin writing \code{from pkg import
337string} in your code.
338
339Relative imports are still possible by adding a leading period
340to the module name when using the \code{from ... import} form:
341
342\begin{verbatim}
343# Import names from pkg.string
344from .string import name1, name2
345# Import pkg.string
346from . import string
347\end{verbatim}
348
349This imports the \module{string} module relative to the current
350package, so in \module{pkg.main} this will import \var{name1} and
351\var{name2} from \module{pkg.string}. Additional leading periods
352perform the relative import starting from the parent of the current
353package. For example, code in the \module{A.B.C} module can do:
354
355\begin{verbatim}
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000356from . import D # Imports A.B.D
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000357from .. import E # Imports A.E
358from ..F import G # Imports A.F.G
359\end{verbatim}
360
361Leading periods cannot be used with the \code{import \var{modname}}
362form of the import statement, only the \code{from ... import} form.
363
364\begin{seealso}
365
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000366\seepep{328}{Imports: Multi-Line and Absolute/Relative}
367{PEP written by Aahz; implemented by Thomas Wouters.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000368
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000369\seeurl{http://codespeak.net/py/current/doc/index.html}
370{The py library by Holger Krekel, which contains the \module{py.std} package.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000371
372\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000373
374
375%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000376\section{PEP 338: Executing Modules as Scripts\label{pep-338}}
Andrew M. Kuchling21d3a7c2006-03-15 11:53:09 +0000377
Andrew M. Kuchlingb182db42006-03-17 21:48:46 +0000378The \programopt{-m} switch added in Python 2.4 to execute a module as
379a script gained a few more abilities. Instead of being implemented in
380C code inside the Python interpreter, the switch now uses an
381implementation in a new module, \module{runpy}.
382
383The \module{runpy} module implements a more sophisticated import
384mechanism so that it's now possible to run modules in a package such
385as \module{pychecker.checker}. The module also supports alternative
Andrew M. Kuchling5d4cf5e2006-04-13 13:02:42 +0000386import mechanisms such as the \module{zipimport} module. This means
Andrew M. Kuchlingb182db42006-03-17 21:48:46 +0000387you can add a .zip archive's path to \code{sys.path} and then use the
388\programopt{-m} switch to execute code from the archive.
389
390
391\begin{seealso}
392
393\seepep{338}{Executing modules as scripts}{PEP written and
394implemented by Nick Coghlan.}
395
396\end{seealso}
Andrew M. Kuchling21d3a7c2006-03-15 11:53:09 +0000397
398
399%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000400\section{PEP 341: Unified try/except/finally\label{pep-341}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000401
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000402Until Python 2.5, the \keyword{try} statement came in two
403flavours. You could use a \keyword{finally} block to ensure that code
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +0000404is always executed, or one or more \keyword{except} blocks to catch
405specific exceptions. You couldn't combine both \keyword{except} blocks and a
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000406\keyword{finally} block, because generating the right bytecode for the
407combined version was complicated and it wasn't clear what the
408semantics of the combined should be.
409
410GvR spent some time working with Java, which does support the
411equivalent of combining \keyword{except} blocks and a
412\keyword{finally} block, and this clarified what the statement should
413mean. In Python 2.5, you can now write:
414
415\begin{verbatim}
416try:
417 block-1 ...
418except Exception1:
419 handler-1 ...
420except Exception2:
421 handler-2 ...
422else:
423 else-block
424finally:
425 final-block
426\end{verbatim}
427
428The code in \var{block-1} is executed. If the code raises an
Andrew M. Kuchling356af462006-05-10 17:19:04 +0000429exception, the various \keyword{except} blocks are tested: if the
430exception is of class \class{Exception1}, \var{handler-1} is executed;
431otherwise if it's of class \class{Exception2}, \var{handler-2} is
432executed, and so forth. If no exception is raised, the
433\var{else-block} is executed.
434
435No matter what happened previously, the \var{final-block} is executed
436once the code block is complete and any raised exceptions handled.
437Even if there's an error in an exception handler or the
438\var{else-block} and a new exception is raised, the
439code in the \var{final-block} is still run.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000440
441\begin{seealso}
442
443\seepep{341}{Unifying try-except and try-finally}{PEP written by Georg Brandl;
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000444implementation by Thomas Lee.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000445
446\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000447
448
449%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000450\section{PEP 342: New Generator Features\label{pep-342}}
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000451
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000452Python 2.5 adds a simple way to pass values \emph{into} a generator.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000453As introduced in Python 2.3, generators only produce output; once a
Andrew M. Kuchling1e9f5742006-05-20 19:25:16 +0000454generator's code was invoked to create an iterator, there was no way to
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000455pass any new information into the function when its execution is
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000456resumed. Sometimes the ability to pass in some information would be
457useful. Hackish solutions to this include making the generator's code
458look at a global variable and then changing the global variable's
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000459value, or passing in some mutable object that callers then modify.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000460
461To refresh your memory of basic generators, here's a simple example:
462
463\begin{verbatim}
464def counter (maximum):
465 i = 0
466 while i < maximum:
467 yield i
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000468 i += 1
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000469\end{verbatim}
470
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000471When you call \code{counter(10)}, the result is an iterator that
472returns the values from 0 up to 9. On encountering the
473\keyword{yield} statement, the iterator returns the provided value and
474suspends the function's execution, preserving the local variables.
475Execution resumes on the following call to the iterator's
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000476\method{next()} method, picking up after the \keyword{yield} statement.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000477
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000478In Python 2.3, \keyword{yield} was a statement; it didn't return any
479value. In 2.5, \keyword{yield} is now an expression, returning a
480value that can be assigned to a variable or otherwise operated on:
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000481
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000482\begin{verbatim}
483val = (yield i)
484\end{verbatim}
485
486I recommend that you always put parentheses around a \keyword{yield}
487expression when you're doing something with the returned value, as in
488the above example. The parentheses aren't always necessary, but it's
489easier to always add them instead of having to remember when they're
Andrew M. Kuchling3b675d22006-04-20 13:43:21 +0000490needed.
491
492(\pep{342} explains the exact rules, which are that a
493\keyword{yield}-expression must always be parenthesized except when it
494occurs at the top-level expression on the right-hand side of an
495assignment. This means you can write \code{val = yield i} but have to
496use parentheses when there's an operation, as in \code{val = (yield i)
497+ 12}.)
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000498
499Values are sent into a generator by calling its
500\method{send(\var{value})} method. The generator's code is then
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000501resumed and the \keyword{yield} expression returns the specified
502\var{value}. If the regular \method{next()} method is called, the
503\keyword{yield} returns \constant{None}.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000504
505Here's the previous example, modified to allow changing the value of
506the internal counter.
507
508\begin{verbatim}
509def counter (maximum):
510 i = 0
511 while i < maximum:
512 val = (yield i)
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000513 # If value provided, change counter
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000514 if val is not None:
515 i = val
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000516 else:
517 i += 1
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000518\end{verbatim}
519
520And here's an example of changing the counter:
521
522\begin{verbatim}
523>>> it = counter(10)
524>>> print it.next()
5250
526>>> print it.next()
5271
528>>> print it.send(8)
5298
530>>> print it.next()
5319
532>>> print it.next()
533Traceback (most recent call last):
534 File ``t.py'', line 15, in ?
535 print it.next()
536StopIteration
Andrew M. Kuchlingc2033702005-08-29 13:30:12 +0000537\end{verbatim}
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000538
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000539Because \keyword{yield} will often be returning \constant{None}, you
540should always check for this case. Don't just use its value in
541expressions unless you're sure that the \method{send()} method
542will be the only method used resume your generator function.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000543
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000544In addition to \method{send()}, there are two other new methods on
545generators:
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000546
547\begin{itemize}
548
549 \item \method{throw(\var{type}, \var{value}=None,
550 \var{traceback}=None)} is used to raise an exception inside the
551 generator; the exception is raised by the \keyword{yield} expression
552 where the generator's execution is paused.
553
554 \item \method{close()} raises a new \exception{GeneratorExit}
555 exception inside the generator to terminate the iteration.
556 On receiving this
557 exception, the generator's code must either raise
558 \exception{GeneratorExit} or \exception{StopIteration}; catching the
559 exception and doing anything else is illegal and will trigger
560 a \exception{RuntimeError}. \method{close()} will also be called by
Andrew M. Kuchling3cdf24b2006-05-25 00:23:03 +0000561 Python's garbage collector when the generator is garbage-collected.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000562
Andrew M. Kuchling3cdf24b2006-05-25 00:23:03 +0000563 If you need to run cleanup code when a \exception{GeneratorExit} occurs,
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000564 I suggest using a \code{try: ... finally:} suite instead of
565 catching \exception{GeneratorExit}.
566
567\end{itemize}
568
569The cumulative effect of these changes is to turn generators from
570one-way producers of information into both producers and consumers.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000571
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000572Generators also become \emph{coroutines}, a more generalized form of
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000573subroutines. Subroutines are entered at one point and exited at
Andrew M. Kuchling1e9f5742006-05-20 19:25:16 +0000574another point (the top of the function, and a \keyword{return}
575statement), but coroutines can be entered, exited, and resumed at
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000576many different points (the \keyword{yield} statements). We'll have to
577figure out patterns for using coroutines effectively in Python.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000578
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000579The addition of the \method{close()} method has one side effect that
580isn't obvious. \method{close()} is called when a generator is
581garbage-collected, so this means the generator's code gets one last
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +0000582chance to run before the generator is destroyed. This last chance
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000583means that \code{try...finally} statements in generators can now be
584guaranteed to work; the \keyword{finally} clause will now always get a
585chance to run. The syntactic restriction that you couldn't mix
586\keyword{yield} statements with a \code{try...finally} suite has
587therefore been removed. This seems like a minor bit of language
588trivia, but using generators and \code{try...finally} is actually
589necessary in order to implement the \keyword{with} statement
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000590described by PEP 343. I'll look at this new statement in the following
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000591section.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000592
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +0000593Another even more esoteric effect of this change: previously, the
594\member{gi_frame} attribute of a generator was always a frame object.
595It's now possible for \member{gi_frame} to be \code{None}
596once the generator has been exhausted.
597
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000598\begin{seealso}
599
600\seepep{342}{Coroutines via Enhanced Generators}{PEP written by
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000601Guido van~Rossum and Phillip J. Eby;
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000602implemented by Phillip J. Eby. Includes examples of
603some fancier uses of generators as coroutines.}
604
605\seeurl{http://en.wikipedia.org/wiki/Coroutine}{The Wikipedia entry for
606coroutines.}
607
Neal Norwitz09179882006-03-04 23:31:45 +0000608\seeurl{http://www.sidhe.org/\~{}dan/blog/archives/000178.html}{An
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000609explanation of coroutines from a Perl point of view, written by Dan
610Sugalski.}
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000611
612\end{seealso}
613
614
615%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000616\section{PEP 343: The 'with' statement\label{pep-343}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000617
Andrew M. Kuchling0a7ed8c2006-04-24 14:30:47 +0000618The '\keyword{with}' statement clarifies code that previously would
619use \code{try...finally} blocks to ensure that clean-up code is
620executed. In this section, I'll discuss the statement as it will
621commonly be used. In the next section, I'll examine the
622implementation details and show how to write objects for use with this
623statement.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000624
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +0000625The '\keyword{with}' statement is a new control-flow structure whose
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000626basic structure is:
627
628\begin{verbatim}
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000629with expression [as variable]:
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000630 with-block
631\end{verbatim}
632
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000633The expression is evaluated, and it should result in an object that
634supports the context management protocol. This object may return a
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000635value that can optionally be bound to the name \var{variable}. (Note
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000636carefully that \var{variable} is \emph{not} assigned the result of
637\var{expression}.) The object can then run set-up code
638before \var{with-block} is executed and some clean-up code
639is executed after the block is done, even if the block raised an exception.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000640
641To enable the statement in Python 2.5, you need
642to add the following directive to your module:
643
644\begin{verbatim}
645from __future__ import with_statement
646\end{verbatim}
647
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000648The statement will always be enabled in Python 2.6.
649
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000650Some standard Python objects now support the context management
651protocol and can be used with the '\keyword{with}' statement. File
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000652objects are one example:
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000653
654\begin{verbatim}
655with open('/etc/passwd', 'r') as f:
656 for line in f:
657 print line
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000658 ... more processing code ...
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000659\end{verbatim}
660
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000661After this statement has executed, the file object in \var{f} will
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +0000662have been automatically closed, even if the 'for' loop
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000663raised an exception part-way through the block.
664
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000665The \module{threading} module's locks and condition variables
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +0000666also support the '\keyword{with}' statement:
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000667
668\begin{verbatim}
669lock = threading.Lock()
670with lock:
671 # Critical section of code
672 ...
673\end{verbatim}
674
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000675The lock is acquired before the block is executed and always released once
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000676the block is complete.
677
678The \module{decimal} module's contexts, which encapsulate the desired
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000679precision and rounding characteristics for computations, provide a
680\method{context_manager()} method for getting a context manager:
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000681
682\begin{verbatim}
683import decimal
684
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000685# Displays with default precision of 28 digits
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000686v1 = decimal.Decimal('578')
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000687print v1.sqrt()
688
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000689ctx = decimal.Context(prec=16)
690with ctx.context_manager():
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000691 # All code in this block uses a precision of 16 digits.
692 # The original context is restored on exiting the block.
693 print v1.sqrt()
694\end{verbatim}
695
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000696\subsection{Writing Context Managers\label{context-managers}}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000697
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +0000698Under the hood, the '\keyword{with}' statement is fairly complicated.
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000699Most people will only use '\keyword{with}' in company with existing
Andrew M. Kuchling0a7ed8c2006-04-24 14:30:47 +0000700objects and don't need to know these details, so you can skip the rest
701of this section if you like. Authors of new objects will need to
702understand the details of the underlying implementation and should
703keep reading.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000704
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000705A high-level explanation of the context management protocol is:
706
707\begin{itemize}
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000708
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000709\item The expression is evaluated and should result in an object
710called a ``context manager''. The context manager must have
Andrew M. Kuchling0a7ed8c2006-04-24 14:30:47 +0000711\method{__enter__()} and \method{__exit__()} methods.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000712
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000713\item The context manager's \method{__enter__()} method is called. The value
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000714returned is assigned to \var{VAR}. If no \code{'as \var{VAR}'} clause
715is present, the value is simply discarded.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000716
717\item The code in \var{BLOCK} is executed.
718
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000719\item If \var{BLOCK} raises an exception, the
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000720\method{__exit__(\var{type}, \var{value}, \var{traceback})} is called
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000721with the exception details, the same values returned by
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000722\function{sys.exc_info()}. The method's return value controls whether
723the exception is re-raised: any false value re-raises the exception,
724and \code{True} will result in suppressing it. You'll only rarely
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000725want to suppress the exception, because if you do
726the author of the code containing the
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000727'\keyword{with}' statement will never realize anything went wrong.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000728
729\item If \var{BLOCK} didn't raise an exception,
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000730the \method{__exit__()} method is still called,
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000731but \var{type}, \var{value}, and \var{traceback} are all \code{None}.
732
733\end{itemize}
734
735Let's think through an example. I won't present detailed code but
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000736will only sketch the methods necessary for a database that supports
737transactions.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000738
739(For people unfamiliar with database terminology: a set of changes to
740the database are grouped into a transaction. Transactions can be
741either committed, meaning that all the changes are written into the
742database, or rolled back, meaning that the changes are all discarded
743and the database is unchanged. See any database textbook for more
744information.)
745% XXX find a shorter reference?
746
747Let's assume there's an object representing a database connection.
748Our goal will be to let the user write code like this:
749
750\begin{verbatim}
751db_connection = DatabaseConnection()
752with db_connection as cursor:
753 cursor.execute('insert into ...')
754 cursor.execute('delete from ...')
755 # ... more operations ...
756\end{verbatim}
757
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000758The transaction should be committed if the code in the block
759runs flawlessly or rolled back if there's an exception.
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000760Here's the basic interface
761for \class{DatabaseConnection} that I'll assume:
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000762
763\begin{verbatim}
764class DatabaseConnection:
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000765 # Database interface
766 def cursor (self):
767 "Returns a cursor object and starts a new transaction"
768 def commit (self):
769 "Commits current transaction"
770 def rollback (self):
771 "Rolls back current transaction"
772\end{verbatim}
773
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000774The \method {__enter__()} method is pretty easy, having only to start
775a new transaction. For this application the resulting cursor object
776would be a useful result, so the method will return it. The user can
777then add \code{as cursor} to their '\keyword{with}' statement to bind
778the cursor to a variable name.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000779
780\begin{verbatim}
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000781class DatabaseConnection:
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000782 ...
783 def __enter__ (self):
784 # Code to start a new transaction
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000785 cursor = self.cursor()
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000786 return cursor
787\end{verbatim}
788
789The \method{__exit__()} method is the most complicated because it's
790where most of the work has to be done. The method has to check if an
791exception occurred. If there was no exception, the transaction is
792committed. The transaction is rolled back if there was an exception.
Andrew M. Kuchling0a7ed8c2006-04-24 14:30:47 +0000793
794In the code below, execution will just fall off the end of the
795function, returning the default value of \code{None}. \code{None} is
796false, so the exception will be re-raised automatically. If you
797wished, you could be more explicit and add a \keyword{return}
798statement at the marked location.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000799
800\begin{verbatim}
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000801class DatabaseConnection:
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000802 ...
803 def __exit__ (self, type, value, tb):
804 if tb is None:
805 # No exception, so commit
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000806 self.commit()
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000807 else:
808 # Exception occurred, so rollback.
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000809 self.rollback()
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000810 # return False
811\end{verbatim}
812
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000813
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000814\subsection{The contextlib module\label{module-contextlib}}
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000815
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000816The new \module{contextlib} module provides some functions and a
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000817decorator that are useful for writing objects for use with the
818'\keyword{with}' statement.
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000819
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000820The decorator is called \function{contextfactory}, and lets you write
821a single generator function instead of defining a new class. The generator
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000822should yield exactly one value. The code up to the \keyword{yield}
823will be executed as the \method{__enter__()} method, and the value
824yielded will be the method's return value that will get bound to the
825variable in the '\keyword{with}' statement's \keyword{as} clause, if
826any. The code after the \keyword{yield} will be executed in the
827\method{__exit__()} method. Any exception raised in the block will be
828raised by the \keyword{yield} statement.
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000829
830Our database example from the previous section could be written
831using this decorator as:
832
833\begin{verbatim}
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000834from contextlib import contextfactory
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000835
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000836@contextfactory
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000837def db_transaction (connection):
838 cursor = connection.cursor()
839 try:
840 yield cursor
841 except:
842 connection.rollback()
843 raise
844 else:
845 connection.commit()
846
847db = DatabaseConnection()
848with db_transaction(db) as cursor:
849 ...
850\end{verbatim}
851
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000852The \module{contextlib} module also has a \function{nested(\var{mgr1},
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000853\var{mgr2}, ...)} function that combines a number of context managers so you
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000854don't need to write nested '\keyword{with}' statements. In this
855example, the single '\keyword{with}' statement both starts a database
856transaction and acquires a thread lock:
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000857
858\begin{verbatim}
859lock = threading.Lock()
860with nested (db_transaction(db), lock) as (cursor, locked):
861 ...
862\end{verbatim}
863
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000864Finally, the \function{closing(\var{object})} function
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000865returns \var{object} so that it can be bound to a variable,
866and calls \code{\var{object}.close()} at the end of the block.
867
868\begin{verbatim}
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +0000869import urllib, sys
870from contextlib import closing
871
872with closing(urllib.urlopen('http://www.yahoo.com')) as f:
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000873 for line in f:
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +0000874 sys.stdout.write(line)
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000875\end{verbatim}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000876
877\begin{seealso}
878
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000879\seepep{343}{The ``with'' statement}{PEP written by Guido van~Rossum
880and Nick Coghlan; implemented by Mike Bland, Guido van~Rossum, and
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +0000881Neal Norwitz. The PEP shows the code generated for a '\keyword{with}'
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000882statement, which can be helpful in learning how the statement works.}
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000883
884\seeurl{../lib/module-contextlib.html}{The documentation
885for the \module{contextlib} module.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000886
887\end{seealso}
888
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000889
890%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000891\section{PEP 352: Exceptions as New-Style Classes\label{pep-352}}
Andrew M. Kuchling8f4d2552006-03-08 01:50:20 +0000892
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000893Exception classes can now be new-style classes, not just classic
894classes, and the built-in \exception{Exception} class and all the
895standard built-in exceptions (\exception{NameError},
896\exception{ValueError}, etc.) are now new-style classes.
Andrew M. Kuchlingaeadf952006-03-09 19:06:05 +0000897
898The inheritance hierarchy for exceptions has been rearranged a bit.
899In 2.5, the inheritance relationships are:
900
901\begin{verbatim}
902BaseException # New in Python 2.5
903|- KeyboardInterrupt
904|- SystemExit
905|- Exception
906 |- (all other current built-in exceptions)
907\end{verbatim}
908
909This rearrangement was done because people often want to catch all
910exceptions that indicate program errors. \exception{KeyboardInterrupt} and
911\exception{SystemExit} aren't errors, though, and usually represent an explicit
912action such as the user hitting Control-C or code calling
913\function{sys.exit()}. A bare \code{except:} will catch all exceptions,
914so you commonly need to list \exception{KeyboardInterrupt} and
915\exception{SystemExit} in order to re-raise them. The usual pattern is:
916
917\begin{verbatim}
918try:
919 ...
920except (KeyboardInterrupt, SystemExit):
921 raise
922except:
923 # Log error...
924 # Continue running program...
925\end{verbatim}
926
927In Python 2.5, you can now write \code{except Exception} to achieve
928the same result, catching all the exceptions that usually indicate errors
929but leaving \exception{KeyboardInterrupt} and
930\exception{SystemExit} alone. As in previous versions,
931a bare \code{except:} still catches all exceptions.
932
933The goal for Python 3.0 is to require any class raised as an exception
934to derive from \exception{BaseException} or some descendant of
935\exception{BaseException}, and future releases in the
936Python 2.x series may begin to enforce this constraint. Therefore, I
937suggest you begin making all your exception classes derive from
938\exception{Exception} now. It's been suggested that the bare
939\code{except:} form should be removed in Python 3.0, but Guido van~Rossum
940hasn't decided whether to do this or not.
941
942Raising of strings as exceptions, as in the statement \code{raise
943"Error occurred"}, is deprecated in Python 2.5 and will trigger a
944warning. The aim is to be able to remove the string-exception feature
945in a few releases.
946
947
948\begin{seealso}
949
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000950\seepep{352}{Required Superclass for Exceptions}{PEP written by
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000951Brett Cannon and Guido van~Rossum; implemented by Brett Cannon.}
Andrew M. Kuchlingaeadf952006-03-09 19:06:05 +0000952
953\end{seealso}
Andrew M. Kuchling8f4d2552006-03-08 01:50:20 +0000954
955
956%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000957\section{PEP 353: Using ssize_t as the index type\label{pep-353}}
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000958
959A wide-ranging change to Python's C API, using a new
960\ctype{Py_ssize_t} type definition instead of \ctype{int},
961will permit the interpreter to handle more data on 64-bit platforms.
962This change doesn't affect Python's capacity on 32-bit platforms.
963
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000964Various pieces of the Python interpreter used C's \ctype{int} type to
965store sizes or counts; for example, the number of items in a list or
966tuple were stored in an \ctype{int}. The C compilers for most 64-bit
967platforms still define \ctype{int} as a 32-bit type, so that meant
968that lists could only hold up to \code{2**31 - 1} = 2147483647 items.
969(There are actually a few different programming models that 64-bit C
970compilers can use -- see
971\url{http://www.unix.org/version2/whatsnew/lp64_wp.html} for a
972discussion -- but the most commonly available model leaves \ctype{int}
973as 32 bits.)
974
975A limit of 2147483647 items doesn't really matter on a 32-bit platform
976because you'll run out of memory before hitting the length limit.
977Each list item requires space for a pointer, which is 4 bytes, plus
978space for a \ctype{PyObject} representing the item. 2147483647*4 is
979already more bytes than a 32-bit address space can contain.
980
981It's possible to address that much memory on a 64-bit platform,
Andrew M. Kuchling5ab504e2006-06-20 12:19:54 +0000982however. The pointers for a list that size would only require 16~GiB
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000983of space, so it's not unreasonable that Python programmers might
984construct lists that large. Therefore, the Python interpreter had to
985be changed to use some type other than \ctype{int}, and this will be a
98664-bit type on 64-bit platforms. The change will cause
987incompatibilities on 64-bit machines, so it was deemed worth making
988the transition now, while the number of 64-bit users is still
989relatively small. (In 5 or 10 years, we may \emph{all} be on 64-bit
990machines, and the transition would be more painful then.)
991
992This change most strongly affects authors of C extension modules.
993Python strings and container types such as lists and tuples
994now use \ctype{Py_ssize_t} to store their size.
995Functions such as \cfunction{PyList_Size()}
996now return \ctype{Py_ssize_t}. Code in extension modules
997may therefore need to have some variables changed to
998\ctype{Py_ssize_t}.
999
1000The \cfunction{PyArg_ParseTuple()} and \cfunction{Py_BuildValue()} functions
1001have a new conversion code, \samp{n}, for \ctype{Py_ssize_t}.
Andrew M. Kuchlinga4d651f2006-04-06 13:24:58 +00001002\cfunction{PyArg_ParseTuple()}'s \samp{s\#} and \samp{t\#} still output
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00001003\ctype{int} by default, but you can define the macro
1004\csimplemacro{PY_SSIZE_T_CLEAN} before including \file{Python.h}
1005to make them return \ctype{Py_ssize_t}.
1006
1007\pep{353} has a section on conversion guidelines that
1008extension authors should read to learn about supporting 64-bit
1009platforms.
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +00001010
1011\begin{seealso}
1012
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001013\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 +00001014
1015\end{seealso}
1016
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00001017
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +00001018%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +00001019\section{PEP 357: The '__index__' method\label{pep-357}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +00001020
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001021The NumPy developers had a problem that could only be solved by adding
1022a new special method, \method{__index__}. When using slice notation,
Fred Drake1c0e3282006-04-02 03:30:06 +00001023as in \code{[\var{start}:\var{stop}:\var{step}]}, the values of the
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001024\var{start}, \var{stop}, and \var{step} indexes must all be either
1025integers or long integers. NumPy defines a variety of specialized
1026integer types corresponding to unsigned and signed integers of 8, 16,
102732, and 64 bits, but there was no way to signal that these types could
1028be used as slice indexes.
1029
1030Slicing can't just use the existing \method{__int__} method because
1031that method is also used to implement coercion to integers. If
1032slicing used \method{__int__}, floating-point numbers would also
1033become legal slice indexes and that's clearly an undesirable
1034behaviour.
1035
1036Instead, a new special method called \method{__index__} was added. It
1037takes no arguments and returns an integer giving the slice index to
1038use. For example:
1039
1040\begin{verbatim}
1041class C:
1042 def __index__ (self):
1043 return self.value
1044\end{verbatim}
1045
1046The return value must be either a Python integer or long integer.
1047The interpreter will check that the type returned is correct, and
1048raises a \exception{TypeError} if this requirement isn't met.
1049
1050A corresponding \member{nb_index} slot was added to the C-level
1051\ctype{PyNumberMethods} structure to let C extensions implement this
1052protocol. \cfunction{PyNumber_Index(\var{obj})} can be used in
1053extension code to call the \method{__index__} function and retrieve
1054its result.
1055
1056\begin{seealso}
1057
1058\seepep{357}{Allowing Any Object to be Used for Slicing}{PEP written
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +00001059and implemented by Travis Oliphant.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001060
1061\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +00001062
1063
1064%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001065\section{Other Language Changes\label{other-lang}}
Fred Drake2db76802004-12-01 05:05:47 +00001066
1067Here are all of the changes that Python 2.5 makes to the core Python
1068language.
1069
1070\begin{itemize}
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001071
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001072\item The \class{dict} type has a new hook for letting subclasses
1073provide a default value when a key isn't contained in the dictionary.
1074When a key isn't found, the dictionary's
1075\method{__missing__(\var{key})}
1076method will be called. This hook is used to implement
1077the new \class{defaultdict} class in the \module{collections}
1078module. The following example defines a dictionary
1079that returns zero for any missing key:
1080
1081\begin{verbatim}
1082class zerodict (dict):
1083 def __missing__ (self, key):
1084 return 0
1085
1086d = zerodict({1:1, 2:2})
1087print d[1], d[2] # Prints 1, 2
1088print d[3], d[4] # Prints 0, 0
1089\end{verbatim}
1090
Andrew M. Kuchlingafe65982006-05-26 18:41:18 +00001091\item Both 8-bit and Unicode strings have new \method{partition(sep)}
1092and \method{rpartition(sep)} methods that simplify a common use case.
Andrew M. Kuchlingad0cb652006-05-26 12:39:48 +00001093The \method{find(S)} method is often used to get an index which is
1094then used to slice the string and obtain the pieces that are before
Andrew M. Kuchlingafe65982006-05-26 18:41:18 +00001095and after the separator.
1096
1097\method{partition(sep)} condenses this
Andrew M. Kuchlingad0cb652006-05-26 12:39:48 +00001098pattern into a single method call that returns a 3-tuple containing
1099the substring before the separator, the separator itself, and the
1100substring after the separator. If the separator isn't found, the
1101first element of the tuple is the entire string and the other two
Andrew M. Kuchlingafe65982006-05-26 18:41:18 +00001102elements are empty. \method{rpartition(sep)} also returns a 3-tuple
1103but starts searching from the end of the string; the \samp{r} stands
1104for 'reverse'.
1105
1106Some examples:
Andrew M. Kuchlingad0cb652006-05-26 12:39:48 +00001107
1108\begin{verbatim}
1109>>> ('http://www.python.org').partition('://')
1110('http', '://', 'www.python.org')
1111>>> (u'Subject: a quick question').partition(':')
1112(u'Subject', u':', u' a quick question')
1113>>> ('file:/usr/share/doc/index.html').partition('://')
1114('file:/usr/share/doc/index.html', '', '')
Andrew M. Kuchlingafe65982006-05-26 18:41:18 +00001115>>> 'www.python.org'.rpartition('.')
1116('www.python', '.', 'org')
Andrew M. Kuchlingad0cb652006-05-26 12:39:48 +00001117\end{verbatim}
1118
1119(Implemented by Fredrik Lundh following a suggestion by Raymond Hettinger.)
1120
Andrew M. Kuchlinga04d1182006-06-09 19:03:16 +00001121\item The \method{startswith()} and \method{endswith()} methods
1122of string types now accept tuples of strings to check for.
1123
1124\begin{verbatim}
1125def is_image_file (filename):
1126 return filename.endswith(('.gif', '.jpg', '.tiff'))
1127\end{verbatim}
1128
1129(Implemented by Georg Brandl following a suggestion by Tom Lynn.)
1130% RFE #1491485
1131
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001132\item The \function{min()} and \function{max()} built-in functions
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001133gained a \code{key} keyword parameter analogous to the \code{key}
1134argument for \method{sort()}. This parameter supplies a function that
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001135takes a single argument and is called for every value in the list;
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001136\function{min()}/\function{max()} will return the element with the
1137smallest/largest return value from this function.
1138For example, to find the longest string in a list, you can do:
1139
1140\begin{verbatim}
1141L = ['medium', 'longest', 'short']
1142# Prints 'longest'
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001143print max(L, key=len)
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001144# Prints 'short', because lexicographically 'short' has the largest value
1145print max(L)
1146\end{verbatim}
1147
1148(Contributed by Steven Bethard and Raymond Hettinger.)
Fred Drake2db76802004-12-01 05:05:47 +00001149
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001150\item Two new built-in functions, \function{any()} and
1151\function{all()}, evaluate whether an iterator contains any true or
1152false values. \function{any()} returns \constant{True} if any value
1153returned by the iterator is true; otherwise it will return
1154\constant{False}. \function{all()} returns \constant{True} only if
1155all of the values returned by the iterator evaluate as being true.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001156(Suggested by GvR, and implemented by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001157
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001158\item ASCII is now the default encoding for modules. It's now
1159a syntax error if a module contains string literals with 8-bit
1160characters but doesn't have an encoding declaration. In Python 2.4
1161this triggered a warning, not a syntax error. See \pep{263}
1162for how to declare a module's encoding; for example, you might add
1163a line like this near the top of the source file:
1164
1165\begin{verbatim}
1166# -*- coding: latin1 -*-
1167\end{verbatim}
1168
Andrew M. Kuchlingc9236112006-04-30 01:07:09 +00001169\item One error that Python programmers sometimes make is forgetting
1170to include an \file{__init__.py} module in a package directory.
1171Debugging this mistake can be confusing, and usually requires running
1172Python with the \programopt{-v} switch to log all the paths searched.
1173In Python 2.5, a new \exception{ImportWarning} warning is raised when
1174an import would have picked up a directory as a package but no
1175\file{__init__.py} was found. (Implemented by Thomas Wouters.)
1176
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001177\item The list of base classes in a class definition can now be empty.
1178As an example, this is now legal:
1179
1180\begin{verbatim}
1181class C():
1182 pass
1183\end{verbatim}
1184(Implemented by Brett Cannon.)
1185
Fred Drake2db76802004-12-01 05:05:47 +00001186\end{itemize}
1187
1188
1189%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001190\subsection{Interactive Interpreter Changes\label{interactive}}
Andrew M. Kuchlingda376042006-03-17 15:56:41 +00001191
1192In the interactive interpreter, \code{quit} and \code{exit}
1193have long been strings so that new users get a somewhat helpful message
1194when they try to quit:
1195
1196\begin{verbatim}
1197>>> quit
1198'Use Ctrl-D (i.e. EOF) to exit.'
1199\end{verbatim}
1200
1201In Python 2.5, \code{quit} and \code{exit} are now objects that still
1202produce string representations of themselves, but are also callable.
1203Newbies who try \code{quit()} or \code{exit()} will now exit the
1204interpreter as they expect. (Implemented by Georg Brandl.)
1205
1206
1207%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001208\subsection{Optimizations\label{opts}}
Fred Drake2db76802004-12-01 05:05:47 +00001209
Andrew M. Kuchlingc6027232006-05-23 12:44:36 +00001210Several of the optimizations were developed at the NeedForSpeed
1211sprint, an event held in Reykjavik, Iceland, from May 21--28 2006.
1212The sprint focused on speed enhancements to the CPython implementation
1213and was funded by EWT LLC with local support from CCP Games. Those
1214optimizations added at this sprint are specially marked in the
1215following list.
1216
Fred Drake2db76802004-12-01 05:05:47 +00001217\begin{itemize}
1218
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001219\item When they were introduced
1220in Python 2.4, the built-in \class{set} and \class{frozenset} types
1221were built on top of Python's dictionary type.
1222In 2.5 the internal data structure has been customized for implementing sets,
1223and as a result sets will use a third less memory and are somewhat faster.
1224(Implemented by Raymond Hettinger.)
Fred Drake2db76802004-12-01 05:05:47 +00001225
Andrew M. Kuchling1985ff72006-06-05 00:08:09 +00001226\item The speed of some Unicode operations, such as finding
1227substrings, string splitting, and character map encoding and decoding,
1228has been improved. (Substring search and splitting improvements were
Andrew M. Kuchling150faff2006-05-23 19:29:38 +00001229added by Fredrik Lundh and Andrew Dalke at the NeedForSpeed
Andrew M. Kuchling1985ff72006-06-05 00:08:09 +00001230sprint. Character maps were improved by Walter D\"orwald and
1231Martin von~L\"owis.)
1232% Patch 1313939, 1359618
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001233
Andrew M. Kuchling3cdf24b2006-05-25 00:23:03 +00001234\item The \function{long(\var{str}, \var{base})} function is now
1235faster on long digit strings because fewer intermediate results are
1236calculated. The peak is for strings of around 800--1000 digits where
1237the function is 6 times faster.
1238(Contributed by Alan McIntyre and committed at the NeedForSpeed sprint.)
1239% Patch 1442927
1240
Andrew M. Kuchling70bd1992006-05-23 19:32:35 +00001241\item The \module{struct} module now compiles structure format
1242strings into an internal representation and caches this
1243representation, yielding a 20\% speedup. (Contributed by Bob Ippolito
1244at the NeedForSpeed sprint.)
1245
Andrew M. Kuchling3b336c72006-06-07 17:03:46 +00001246\item The \module{re} module got a 1 or 2\% speedup by switching to
1247Python's allocator functions instead of the system's
1248\cfunction{malloc()} and \cfunction{free()}.
1249(Contributed by Jack Diederich at the NeedForSpeed sprint.)
1250
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001251\item The code generator's peephole optimizer now performs
1252simple constant folding in expressions. If you write something like
1253\code{a = 2+3}, the code generator will do the arithmetic and produce
1254code corresponding to \code{a = 5}.
1255
Andrew M. Kuchlingc6027232006-05-23 12:44:36 +00001256\item Function calls are now faster because code objects now keep
1257the most recently finished frame (a ``zombie frame'') in an internal
1258field of the code object, reusing it the next time the code object is
1259invoked. (Original patch by Michael Hudson, modified by Armin Rigo
1260and Richard Jones; committed at the NeedForSpeed sprint.)
1261% Patch 876206
1262
Andrew M. Kuchling150faff2006-05-23 19:29:38 +00001263Frame objects are also slightly smaller, which may improve cache locality
1264and reduce memory usage a bit. (Contributed by Neal Norwitz.)
1265% Patch 1337051
1266
Andrew M. Kuchlingdae266e2006-05-27 13:44:37 +00001267\item Python's built-in exceptions are now new-style classes, a change
1268that speeds up instantiation considerably. Exception handling in
1269Python 2.5 is therefore about 30\% faster than in 2.4.
Richard Jones87f54712006-05-27 13:50:42 +00001270(Contributed by Richard Jones, Georg Brandl and Sean Reifschneider at
1271the NeedForSpeed sprint.)
Andrew M. Kuchlingdae266e2006-05-27 13:44:37 +00001272
Andrew M. Kuchlingafe65982006-05-26 18:41:18 +00001273\item Importing now caches the paths tried, recording whether
1274they exist or not so that the interpreter makes fewer
1275\cfunction{open()} and \cfunction{stat()} calls on startup.
1276(Contributed by Martin von~L\"owis and Georg Brandl.)
1277% Patch 921466
1278
Fred Drake2db76802004-12-01 05:05:47 +00001279\end{itemize}
1280
1281The net result of the 2.5 optimizations is that Python 2.5 runs the
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +00001282pystone benchmark around XXX\% faster than Python 2.4.
Fred Drake2db76802004-12-01 05:05:47 +00001283
1284
1285%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001286\section{New, Improved, and Removed Modules\label{modules}}
Fred Drake2db76802004-12-01 05:05:47 +00001287
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +00001288The standard library received many enhancements and bug fixes in
1289Python 2.5. Here's a partial list of the most notable changes, sorted
1290alphabetically by module name. Consult the \file{Misc/NEWS} file in
1291the source tree for a more complete list of changes, or look through
1292the SVN logs for all the details.
Fred Drake2db76802004-12-01 05:05:47 +00001293
1294\begin{itemize}
1295
Andrew M. Kuchling6fc69762006-04-13 12:37:21 +00001296\item The \module{audioop} module now supports the a-LAW encoding,
1297and the code for u-LAW encoding has been improved. (Contributed by
1298Lars Immisch.)
1299
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001300\item The \module{codecs} module gained support for incremental
1301codecs. The \function{codec.lookup()} function now
1302returns a \class{CodecInfo} instance instead of a tuple.
1303\class{CodecInfo} instances behave like a 4-tuple to preserve backward
1304compatibility but also have the attributes \member{encode},
1305\member{decode}, \member{incrementalencoder}, \member{incrementaldecoder},
1306\member{streamwriter}, and \member{streamreader}. Incremental codecs
1307can receive input and produce output in multiple chunks; the output is
1308the same as if the entire input was fed to the non-incremental codec.
1309See the \module{codecs} module documentation for details.
1310(Designed and implemented by Walter D\"orwald.)
1311% Patch 1436130
1312
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001313\item The \module{collections} module gained a new type,
1314\class{defaultdict}, that subclasses the standard \class{dict}
1315type. The new type mostly behaves like a dictionary but constructs a
1316default value when a key isn't present, automatically adding it to the
1317dictionary for the requested key value.
1318
1319The first argument to \class{defaultdict}'s constructor is a factory
1320function that gets called whenever a key is requested but not found.
1321This factory function receives no arguments, so you can use built-in
1322type constructors such as \function{list()} or \function{int()}. For
1323example,
1324you can make an index of words based on their initial letter like this:
1325
1326\begin{verbatim}
1327words = """Nel mezzo del cammin di nostra vita
1328mi ritrovai per una selva oscura
1329che la diritta via era smarrita""".lower().split()
1330
1331index = defaultdict(list)
1332
1333for w in words:
1334 init_letter = w[0]
1335 index[init_letter].append(w)
1336\end{verbatim}
1337
1338Printing \code{index} results in the following output:
1339
1340\begin{verbatim}
1341defaultdict(<type 'list'>, {'c': ['cammin', 'che'], 'e': ['era'],
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001342 'd': ['del', 'di', 'diritta'], 'm': ['mezzo', 'mi'],
1343 'l': ['la'], 'o': ['oscura'], 'n': ['nel', 'nostra'],
1344 'p': ['per'], 's': ['selva', 'smarrita'],
1345 'r': ['ritrovai'], 'u': ['una'], 'v': ['vita', 'via']}
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001346\end{verbatim}
1347
1348The \class{deque} double-ended queue type supplied by the
1349\module{collections} module now has a \method{remove(\var{value})}
1350method that removes the first occurrence of \var{value} in the queue,
1351raising \exception{ValueError} if the value isn't found.
1352
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001353\item New module: The \module{contextlib} module contains helper functions for use
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001354with the new '\keyword{with}' statement. See
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001355section~\ref{module-contextlib} for more about this module.
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +00001356
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001357\item New module: The \module{cProfile} module is a C implementation of
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001358the existing \module{profile} module that has much lower overhead.
1359The module's interface is the same as \module{profile}: you run
1360\code{cProfile.run('main()')} to profile a function, can save profile
1361data to a file, etc. It's not yet known if the Hotshot profiler,
1362which is also written in C but doesn't match the \module{profile}
1363module's interface, will continue to be maintained in future versions
1364of Python. (Contributed by Armin Rigo.)
1365
Andrew M. Kuchling0a7ed8c2006-04-24 14:30:47 +00001366Also, the \module{pstats} module for analyzing the data measured by
1367the profiler now supports directing the output to any file object
Andrew M. Kuchlinge78eeb12006-04-21 13:26:42 +00001368by supplying a \var{stream} argument to the \class{Stats} constructor.
1369(Contributed by Skip Montanaro.)
1370
Andrew M. Kuchling952f1962006-04-18 12:38:19 +00001371\item The \module{csv} module, which parses files in
1372comma-separated value format, received several enhancements and a
1373number of bugfixes. You can now set the maximum size in bytes of a
1374field by calling the \method{csv.field_size_limit(\var{new_limit})}
1375function; omitting the \var{new_limit} argument will return the
1376currently-set limit. The \class{reader} class now has a
1377\member{line_num} attribute that counts the number of physical lines
1378read from the source; records can span multiple physical lines, so
1379\member{line_num} is not the same as the number of records read.
1380(Contributed by Skip Montanaro and Andrew McNamara.)
1381
Andrew M. Kuchling67191312006-04-19 12:55:39 +00001382\item The \class{datetime} class in the \module{datetime}
1383module now has a \method{strptime(\var{string}, \var{format})}
1384method for parsing date strings, contributed by Josh Spoerri.
1385It uses the same format characters as \function{time.strptime()} and
1386\function{time.strftime()}:
1387
1388\begin{verbatim}
1389from datetime import datetime
1390
1391ts = datetime.strptime('10:13:15 2006-03-07',
1392 '%H:%M:%S %Y-%m-%d')
1393\end{verbatim}
1394
Andrew M. Kuchling7259d7b2006-06-14 13:59:15 +00001395\item The \method{SequenceMatcher.get_matching_blocks()} method
1396in the \module{difflib} module now guarantees to return a minimal list
1397of blocks describing matching subsequences. Previously, the algorithm would
1398occasionally break a block of matching elements into two list entries.
1399(Enhancement by Tim Peters.)
1400
Andrew M. Kuchlingb33842a2006-04-25 12:31:38 +00001401\item The \module{doctest} module gained a \code{SKIP} option that
1402keeps an example from being executed at all. This is intended for
1403code snippets that are usage examples intended for the reader and
1404aren't actually test cases.
1405
Andrew M. Kuchling2c4e4622006-06-20 12:15:09 +00001406An \var{encoding} parameter was added to the \function{testfile()}
1407function and the \class{DocFileSuite} class to specify the file's
1408encoding. This makes it easier to use non-ASCII characters in
1409tests contained within a docstring. (Contributed by Bjorn Tillenius.)
1410% Patch 1080727
1411
Andrew M. Kuchling643b0412006-06-21 17:17:10 +00001412\item The \module{email} package has been updated to version 4.0.
1413% XXX need to provide some more detail here
1414(Contributed by Barry Warsaw.)
1415
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001416\item The \module{fileinput} module was made more flexible.
1417Unicode filenames are now supported, and a \var{mode} parameter that
1418defaults to \code{"r"} was added to the
1419\function{input()} function to allow opening files in binary or
1420universal-newline mode. Another new parameter, \var{openhook},
1421lets you use a function other than \function{open()}
1422to open the input files. Once you're iterating over
1423the set of files, the \class{FileInput} object's new
1424\method{fileno()} returns the file descriptor for the currently opened file.
1425(Contributed by Georg Brandl.)
1426
Andrew M. Kuchlingda376042006-03-17 15:56:41 +00001427\item In the \module{gc} module, the new \function{get_count()} function
1428returns a 3-tuple containing the current collection counts for the
1429three GC generations. This is accounting information for the garbage
1430collector; when these counts reach a specified threshold, a garbage
1431collection sweep will be made. The existing \function{gc.collect()}
1432function now takes an optional \var{generation} argument of 0, 1, or 2
1433to specify which generation to collect.
Andrew M. Kuchling643b0412006-06-21 17:17:10 +00001434(Contributed by Barry Warsaw.)
Andrew M. Kuchlingda376042006-03-17 15:56:41 +00001435
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001436\item The \function{nsmallest()} and
1437\function{nlargest()} functions in the \module{heapq} module
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001438now support a \code{key} keyword parameter similar to the one
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001439provided by the \function{min()}/\function{max()} functions
1440and the \method{sort()} methods. For example:
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001441
1442\begin{verbatim}
1443>>> import heapq
1444>>> L = ["short", 'medium', 'longest', 'longer still']
1445>>> heapq.nsmallest(2, L) # Return two lowest elements, lexicographically
1446['longer still', 'longest']
1447>>> heapq.nsmallest(2, L, key=len) # Return two shortest elements
1448['short', 'medium']
1449\end{verbatim}
1450
1451(Contributed by Raymond Hettinger.)
1452
Andrew M. Kuchling511a3a82005-03-20 19:52:18 +00001453\item The \function{itertools.islice()} function now accepts
1454\code{None} for the start and step arguments. This makes it more
1455compatible with the attributes of slice objects, so that you can now write
1456the following:
1457
1458\begin{verbatim}
1459s = slice(5) # Create slice object
1460itertools.islice(iterable, s.start, s.stop, s.step)
1461\end{verbatim}
1462
1463(Contributed by Raymond Hettinger.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001464
Andrew M. Kuchlingd4c21772006-04-23 21:51:10 +00001465\item The \module{mailbox} module underwent a massive rewrite to add
1466the capability to modify mailboxes in addition to reading them. A new
1467set of classes that include \class{mbox}, \class{MH}, and
1468\class{Maildir} are used to read mailboxes, and have an
1469\method{add(\var{message})} method to add messages,
1470\method{remove(\var{key})} to remove messages, and
1471\method{lock()}/\method{unlock()} to lock/unlock the mailbox. The
1472following example converts a maildir-format mailbox into an mbox-format one:
1473
1474\begin{verbatim}
1475import mailbox
1476
1477# 'factory=None' uses email.Message.Message as the class representing
1478# individual messages.
1479src = mailbox.Maildir('maildir', factory=None)
1480dest = mailbox.mbox('/tmp/mbox')
1481
1482for msg in src:
1483 dest.add(msg)
1484\end{verbatim}
1485
1486(Contributed by Gregory K. Johnson. Funding was provided by Google's
14872005 Summer of Code.)
1488
Andrew M. Kuchling68494882006-05-01 16:32:49 +00001489\item New module: the \module{msilib} module allows creating
1490Microsoft Installer \file{.msi} files and CAB files. Some support
1491for reading the \file{.msi} database is also included.
1492(Contributed by Martin von~L\"owis.)
1493
Andrew M. Kuchling75ba2442006-04-14 10:29:55 +00001494\item The \module{nis} module now supports accessing domains other
1495than the system default domain by supplying a \var{domain} argument to
1496the \function{nis.match()} and \function{nis.maps()} functions.
1497(Contributed by Ben Bell.)
1498
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001499\item The \module{operator} module's \function{itemgetter()}
1500and \function{attrgetter()} functions now support multiple fields.
1501A call such as \code{operator.attrgetter('a', 'b')}
1502will return a function
1503that retrieves the \member{a} and \member{b} attributes. Combining
1504this new feature with the \method{sort()} method's \code{key} parameter
1505lets you easily sort lists using multiple fields.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001506(Contributed by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001507
Andrew M. Kuchlingd4c21772006-04-23 21:51:10 +00001508\item The \module{optparse} module was updated to version 1.5.1 of the
1509Optik library. The \class{OptionParser} class gained an
1510\member{epilog} attribute, a string that will be printed after the
1511help message, and a \method{destroy()} method to break reference
1512cycles created by the object. (Contributed by Greg Ward.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001513
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +00001514\item The \module{os} module underwent several changes. The
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001515\member{stat_float_times} variable now defaults to true, meaning that
1516\function{os.stat()} will now return time values as floats. (This
1517doesn't necessarily mean that \function{os.stat()} will return times
1518that are precise to fractions of a second; not all systems support
1519such precision.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001520
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001521Constants named \member{os.SEEK_SET}, \member{os.SEEK_CUR}, and
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001522\member{os.SEEK_END} have been added; these are the parameters to the
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001523\function{os.lseek()} function. Two new constants for locking are
1524\member{os.O_SHLOCK} and \member{os.O_EXLOCK}.
1525
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001526Two new functions, \function{wait3()} and \function{wait4()}, were
1527added. They're similar the \function{waitpid()} function which waits
1528for a child process to exit and returns a tuple of the process ID and
1529its exit status, but \function{wait3()} and \function{wait4()} return
1530additional information. \function{wait3()} doesn't take a process ID
1531as input, so it waits for any child process to exit and returns a
15323-tuple of \var{process-id}, \var{exit-status}, \var{resource-usage}
1533as returned from the \function{resource.getrusage()} function.
1534\function{wait4(\var{pid})} does take a process ID.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001535(Contributed by Chad J. Schroeder.)
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001536
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001537On FreeBSD, the \function{os.stat()} function now returns
1538times with nanosecond resolution, and the returned object
1539now has \member{st_gen} and \member{st_birthtime}.
1540The \member{st_flags} member is also available, if the platform supports it.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001541(Contributed by Antti Louko and Diego Petten\`o.)
1542% (Patch 1180695, 1212117)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001543
Andrew M. Kuchlingb33842a2006-04-25 12:31:38 +00001544\item The Python debugger provided by the \module{pdb} module
1545can now store lists of commands to execute when a breakpoint is
George Yoshida3bbbc492006-04-25 14:09:58 +00001546reached and execution stops. Once breakpoint \#1 has been created,
Andrew M. Kuchlingb33842a2006-04-25 12:31:38 +00001547enter \samp{commands 1} and enter a series of commands to be executed,
1548finishing the list with \samp{end}. The command list can include
1549commands that resume execution, such as \samp{continue} or
1550\samp{next}. (Contributed by Gr\'egoire Dooms.)
1551% Patch 790710
1552
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001553\item The \module{pickle} and \module{cPickle} modules no
1554longer accept a return value of \code{None} from the
1555\method{__reduce__()} method; the method must return a tuple of
1556arguments instead. The ability to return \code{None} was deprecated
1557in Python 2.4, so this completes the removal of the feature.
1558
Andrew M. Kuchlingaa013da2006-04-29 12:10:43 +00001559\item The \module{pkgutil} module, containing various utility
1560functions for finding packages, was enhanced to support PEP 302's
1561import hooks and now also works for packages stored in ZIP-format archives.
1562(Contributed by Phillip J. Eby.)
1563
Andrew M. Kuchlingc9236112006-04-30 01:07:09 +00001564\item The pybench benchmark suite by Marc-Andr\'e~Lemburg is now
1565included in the \file{Tools/pybench} directory. The pybench suite is
1566an improvement on the commonly used \file{pystone.py} program because
1567pybench provides a more detailed measurement of the interpreter's
Andrew M. Kuchling3e134a52006-05-23 12:49:35 +00001568speed. It times particular operations such as function calls,
Andrew M. Kuchlingc9236112006-04-30 01:07:09 +00001569tuple slicing, method lookups, and numeric operations, instead of
1570performing many different operations and reducing the result to a
1571single number as \file{pystone.py} does.
1572
Andrew M. Kuchling2c4e4622006-06-20 12:15:09 +00001573\item The \module{pyexpat} module now uses version 2.0 of the Expat parser.
1574(Contributed by Trent Mick.)
1575
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001576\item The old \module{regex} and \module{regsub} modules, which have been
1577deprecated ever since Python 2.0, have finally been deleted.
Andrew M. Kuchlingf4b06602006-03-17 15:39:52 +00001578Other deleted modules: \module{statcache}, \module{tzparse},
1579\module{whrandom}.
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001580
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001581\item Also deleted: the \file{lib-old} directory,
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001582which includes ancient modules such as \module{dircmp} and
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001583\module{ni}, was removed. \file{lib-old} wasn't on the default
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001584\code{sys.path}, so unless your programs explicitly added the directory to
1585\code{sys.path}, this removal shouldn't affect your code.
1586
Andrew M. Kuchling09612282006-04-30 21:19:49 +00001587\item The \module{rlcompleter} module is no longer
1588dependent on importing the \module{readline} module and
1589therefore now works on non-{\UNIX} platforms.
1590(Patch from Robert Kiendl.)
1591% Patch #1472854
1592
Andrew M. Kuchling07cf0722006-05-31 14:12:47 +00001593\item The \module{SimpleXMLRPCServer} and \module{DocXMLRPCServer}
1594classes now have a \member{rpc_paths} attribute that constrains
1595XML-RPC operations to a limited set of URL paths; the default is
1596to allow only \code{'/'} and \code{'/RPC2'}. Setting
1597\member{rpc_paths} to \code{None} or an empty tuple disables
1598this path checking.
1599% Bug #1473048
1600
Andrew M. Kuchling4678dc82006-01-15 16:11:28 +00001601\item The \module{socket} module now supports \constant{AF_NETLINK}
1602sockets on Linux, thanks to a patch from Philippe Biondi.
1603Netlink sockets are a Linux-specific mechanism for communications
1604between a user-space process and kernel code; an introductory
1605article about them is at \url{http://www.linuxjournal.com/article/7356}.
1606In Python code, netlink addresses are represented as a tuple of 2 integers,
1607\code{(\var{pid}, \var{group_mask})}.
1608
Andrew M. Kuchling230c3e12006-05-26 14:03:41 +00001609Two new methods on socket objects, \method{recv_buf(\var{buffer})} and
1610\method{recvfrom_buf(\var{buffer})}, store the received data in an object
1611that supports the buffer protocol instead of returning the data as a
1612string. This means you can put the data directly into an array or a
1613memory-mapped file.
1614
1615Socket objects also gained \method{getfamily()}, \method{gettype()},
1616and \method{getproto()} accessor methods to retrieve the family, type,
1617and protocol values for the socket.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001618
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001619\item New module: the \module{spwd} module provides functions for
1620accessing the shadow password database on systems that support
1621shadow passwords.
Fred Drake2db76802004-12-01 05:05:47 +00001622
Andrew M. Kuchlingc6f5c872006-05-26 14:04:19 +00001623\item The \module{struct} is now faster because it
Andrew M. Kuchling230c3e12006-05-26 14:03:41 +00001624compiles format strings into \class{Struct} objects
1625with \method{pack()} and \method{unpack()} methods. This is similar
1626to how the \module{re} module lets you create compiled regular
1627expression objects. You can still use the module-level
1628\function{pack()} and \function{unpack()} functions; they'll create
1629\class{Struct} objects and cache them. Or you can use
1630\class{Struct} instances directly:
1631
1632\begin{verbatim}
1633s = struct.Struct('ih3s')
1634
1635data = s.pack(1972, 187, 'abc')
1636year, number, name = s.unpack(data)
1637\end{verbatim}
1638
1639You can also pack and unpack data to and from buffer objects directly
1640using the \method{pack_to(\var{buffer}, \var{offset}, \var{v1},
1641\var{v2}, ...)} and \method{unpack_from(\var{buffer}, \var{offset})}
1642methods. This lets you store data directly into an array or a
1643memory-mapped file.
1644
1645(\class{Struct} objects were implemented by Bob Ippolito at the
1646NeedForSpeed sprint. Support for buffer objects was added by Martin
1647Blais, also at the NeedForSpeed sprint.)
1648
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001649\item The Python developers switched from CVS to Subversion during the 2.5
Andrew M. Kuchling230c3e12006-05-26 14:03:41 +00001650development process. Information about the exact build version is
1651available as the \code{sys.subversion} variable, a 3-tuple of
1652\code{(\var{interpreter-name}, \var{branch-name},
1653\var{revision-range})}. For example, at the time of writing my copy
1654of 2.5 was reporting \code{('CPython', 'trunk', '45313:45315')}.
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001655
1656This information is also available to C extensions via the
1657\cfunction{Py_GetBuildInfo()} function that returns a
1658string of build information like this:
1659\code{"trunk:45355:45356M, Apr 13 2006, 07:42:19"}.
1660(Contributed by Barry Warsaw.)
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001661
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001662\item The \class{TarFile} class in the \module{tarfile} module now has
Georg Brandl08c02db2005-07-22 18:39:19 +00001663an \method{extractall()} method that extracts all members from the
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001664archive into the current working directory. It's also possible to set
1665a different directory as the extraction target, and to unpack only a
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001666subset of the archive's members.
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001667
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001668A tarfile's compression can be autodetected by
1669using the mode \code{'r|*'}.
1670% patch 918101
1671(Contributed by Lars Gust\"abel.)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001672
Andrew M. Kuchling317af102006-06-13 16:41:41 +00001673\item The \module{threading} module now lets you set the stack size
1674used when new threads are created. The
1675\function{stack_size(\optional{\var{size}})} function returns the
1676currently configured stack size, and supplying the optional \var{size}
1677parameter sets a new value. Not all platforms support changing the
1678stack size, but Windows, POSIX threading, and OS/2 all do.
1679(Contributed by Andrew MacIntyre.)
1680% Patch 1454481
1681
Andrew M. Kuchlingf688cc52006-03-10 18:50:08 +00001682\item The \module{unicodedata} module has been updated to use version 4.1.0
1683of the Unicode character database. Version 3.2.0 is required
1684by some specifications, so it's still available as
George Yoshidaa2d6c8a2006-05-27 17:09:17 +00001685\member{unicodedata.ucd_3_2_0}.
Andrew M. Kuchlingf688cc52006-03-10 18:50:08 +00001686
Andrew M. Kuchlingaabc5f62006-06-13 11:57:04 +00001687\item New module: the \module{uuid} module generates
1688universally unique identifiers (UUIDs) according to \rfc{4122}. The
1689RFC defines several different UUID versions that are generated from a
1690starting string, from system properties, or purely randomly. This
1691module contains a \class{UUID} class and
1692functions named \function{uuid1()},
1693\function{uuid3()}, \function{uuid4()}, and
1694\function{uuid5()} to generate different versions of UUID. (Version 2 UUIDs
1695are not specified in \rfc{4122} and are not supported by this module.)
1696
1697\begin{verbatim}
1698>>> import uuid
1699>>> # make a UUID based on the host ID and current time
1700>>> uuid.uuid1()
1701UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')
1702
1703>>> # make a UUID using an MD5 hash of a namespace UUID and a name
1704>>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
1705UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')
1706
1707>>> # make a random UUID
1708>>> uuid.uuid4()
1709UUID('16fd2706-8baf-433b-82eb-8c7fada847da')
1710
1711>>> # make a UUID using a SHA-1 hash of a namespace UUID and a name
1712>>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
1713UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')
1714\end{verbatim}
1715
1716(Contributed by Ka-Ping Yee.)
1717
Andrew M. Kuchling2c4e4622006-06-20 12:15:09 +00001718\item The \module{weakref} module's \class{WeakKeyDictionary} and
1719\class{WeakValueDictionary} types gained new methods for iterating
1720over the weak references contained in the dictionary.
1721\method{iterkeyrefs()} and \method{keyrefs()} methods were
1722added to \class{WeakKeyDictionary}, and
1723\method{itervaluerefs()} and \method{valuerefs()} were added to
1724\class{WeakValueDictionary}. (Contributed by Fred L.~Drake, Jr.)
1725
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001726\item The \module{webbrowser} module received a number of
1727enhancements.
1728It's now usable as a script with \code{python -m webbrowser}, taking a
1729URL as the argument; there are a number of switches
1730to control the behaviour (\programopt{-n} for a new browser window,
1731\programopt{-t} for a new tab). New module-level functions,
1732\function{open_new()} and \function{open_new_tab()}, were added
1733to support this. The module's \function{open()} function supports an
1734additional feature, an \var{autoraise} parameter that signals whether
1735to raise the open window when possible. A number of additional
1736browsers were added to the supported list such as Firefox, Opera,
1737Konqueror, and elinks. (Contributed by Oleg Broytmann and George
1738Brandl.)
1739% Patch #754022
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001740
Andrew M. Kuchling1fb8d832006-06-20 13:20:30 +00001741\item Python's standard library no longer includes
1742a package named \module{xml}; the library's XML-related package
1743has been renamed to \module{xmlcore}. This means
1744it will always be possible to import the standard library's
1745XML support whether or not the PyXML package is installed.
Fredrik Lundh7e0aef02005-12-12 18:54:55 +00001746
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001747\item The \module{xmlrpclib} module now supports returning
1748 \class{datetime} objects for the XML-RPC date type. Supply
1749 \code{use_datetime=True} to the \function{loads()} function
1750 or the \class{Unmarshaller} class to enable this feature.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001751 (Contributed by Skip Montanaro.)
1752% Patch 1120353
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001753
Andrew M. Kuchling2c4e4622006-06-20 12:15:09 +00001754\item The \module{zipfile} module now supports the ZIP64 version of the
Andrew M. Kuchling5ab504e2006-06-20 12:19:54 +00001755format, meaning that a .zip archive can now be larger than 4~GiB and
1756can contain individual files larger than 4~GiB. (Contributed by
Andrew M. Kuchling2c4e4622006-06-20 12:15:09 +00001757Ronald Oussoren.)
1758% Patch 1446489
1759
Andrew M. Kuchlingd779b352006-05-16 16:11:54 +00001760\item The \module{zlib} module's \class{Compress} and \class{Decompress}
1761objects now support a \method{copy()} method that makes a copy of the
1762object's internal state and returns a new
1763\class{Compress} or \class{Decompress} object.
1764(Contributed by Chris AtLee.)
1765% Patch 1435422
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001766
Fred Drake114b8ca2005-03-21 05:47:11 +00001767\end{itemize}
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001768
Fred Drake2db76802004-12-01 05:05:47 +00001769
1770
1771%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001772\subsection{The ctypes package\label{module-ctypes}}
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001773
1774The \module{ctypes} package, written by Thomas Heller, has been added
1775to the standard library. \module{ctypes} lets you call arbitrary functions
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001776in shared libraries or DLLs. Long-time users may remember the \module{dl} module, which
1777provides 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 +00001778
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001779To load a shared library or DLL, you must create an instance of the
1780\class{CDLL} class and provide the name or path of the shared library
1781or DLL. Once that's done, you can call arbitrary functions
1782by accessing them as attributes of the \class{CDLL} object.
1783
1784\begin{verbatim}
1785import ctypes
1786
1787libc = ctypes.CDLL('libc.so.6')
1788result = libc.printf("Line of output\n")
1789\end{verbatim}
1790
1791Type constructors for the various C types are provided: \function{c_int},
1792\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
1793to change the wrapped value. Python integers and strings will be automatically
1794converted to the corresponding C types, but for other types you
1795must call the correct type constructor. (And I mean \emph{must};
1796getting it wrong will often result in the interpreter crashing
1797with a segmentation fault.)
1798
1799You 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
1800supposed to be immutable; breaking this rule will cause puzzling bugs. When you need a modifiable memory area,
Neal Norwitz5f5a69b2006-04-13 03:41:04 +00001801use \function{create_string_buffer()}:
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001802
1803\begin{verbatim}
1804s = "this is a string"
1805buf = ctypes.create_string_buffer(s)
1806libc.strfry(buf)
1807\end{verbatim}
1808
1809C functions are assumed to return integers, but you can set
1810the \member{restype} attribute of the function object to
1811change this:
1812
1813\begin{verbatim}
1814>>> libc.atof('2.71828')
1815-1783957616
1816>>> libc.atof.restype = ctypes.c_double
1817>>> libc.atof('2.71828')
18182.71828
1819\end{verbatim}
1820
1821\module{ctypes} also provides a wrapper for Python's C API
1822as the \code{ctypes.pythonapi} object. This object does \emph{not}
1823release the global interpreter lock before calling a function, because the lock must be held when calling into the interpreter's code.
1824There's a \class{py_object()} type constructor that will create a
1825\ctype{PyObject *} pointer. A simple usage:
1826
1827\begin{verbatim}
1828import ctypes
1829
1830d = {}
1831ctypes.pythonapi.PyObject_SetItem(ctypes.py_object(d),
1832 ctypes.py_object("abc"), ctypes.py_object(1))
1833# d is now {'abc', 1}.
1834\end{verbatim}
1835
1836Don't forget to use \class{py_object()}; if it's omitted you end
1837up with a segmentation fault.
1838
1839\module{ctypes} has been around for a while, but people still write
1840and distribution hand-coded extension modules because you can't rely on \module{ctypes} being present.
1841Perhaps developers will begin to write
1842Python wrappers atop a library accessed through \module{ctypes} instead
1843of extension modules, now that \module{ctypes} is included with core Python.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001844
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001845\begin{seealso}
1846
1847\seeurl{http://starship.python.net/crew/theller/ctypes/}
1848{The ctypes web page, with a tutorial, reference, and FAQ.}
1849
Andrew M. Kuchlingb4922442006-06-21 17:10:18 +00001850\seeurl{../lib/module-ctypes.html}{The documentation
1851for the \module{ctypes} module.}
1852
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001853\end{seealso}
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001854
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001855
1856%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001857\subsection{The ElementTree package\label{module-etree}}
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001858
1859A subset of Fredrik Lundh's ElementTree library for processing XML has
Andrew M. Kuchlinge3c958c2006-05-01 12:45:02 +00001860been added to the standard library as \module{xml.etree}. The
Georg Brandlce27a062006-04-11 06:27:12 +00001861available modules are
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001862\module{ElementTree}, \module{ElementPath}, and
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00001863\module{ElementInclude} from ElementTree 1.2.6.
1864The \module{cElementTree} accelerator module is also included.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001865
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001866The rest of this section will provide a brief overview of using
1867ElementTree. Full documentation for ElementTree is available at
1868\url{http://effbot.org/zone/element-index.htm}.
1869
1870ElementTree represents an XML document as a tree of element nodes.
1871The text content of the document is stored as the \member{.text}
1872and \member{.tail} attributes of
1873(This is one of the major differences between ElementTree and
1874the Document Object Model; in the DOM there are many different
1875types of node, including \class{TextNode}.)
1876
1877The most commonly used parsing function is \function{parse()}, that
1878takes either a string (assumed to contain a filename) or a file-like
1879object and returns an \class{ElementTree} instance:
1880
1881\begin{verbatim}
Andrew M. Kuchlinge3c958c2006-05-01 12:45:02 +00001882from xml.etree import ElementTree as ET
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001883
1884tree = ET.parse('ex-1.xml')
1885
1886feed = urllib.urlopen(
1887 'http://planet.python.org/rss10.xml')
1888tree = ET.parse(feed)
1889\end{verbatim}
1890
1891Once you have an \class{ElementTree} instance, you
1892can call its \method{getroot()} method to get the root \class{Element} node.
1893
1894There's also an \function{XML()} function that takes a string literal
1895and returns an \class{Element} node (not an \class{ElementTree}).
1896This function provides a tidy way to incorporate XML fragments,
1897approaching the convenience of an XML literal:
1898
1899\begin{verbatim}
Andrew M. Kuchlinge3c958c2006-05-01 12:45:02 +00001900svg = ET.XML("""<svg width="10px" version="1.0">
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001901 </svg>""")
1902svg.set('height', '320px')
1903svg.append(elem1)
1904\end{verbatim}
1905
1906Each XML element supports some dictionary-like and some list-like
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001907access methods. Dictionary-like operations are used to access attribute
1908values, and list-like operations are used to access child nodes.
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001909
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001910\begin{tableii}{c|l}{code}{Operation}{Result}
1911 \lineii{elem[n]}{Returns n'th child element.}
1912 \lineii{elem[m:n]}{Returns list of m'th through n'th child elements.}
1913 \lineii{len(elem)}{Returns number of child elements.}
Andrew M. Kuchlinge3c958c2006-05-01 12:45:02 +00001914 \lineii{list(elem)}{Returns list of child elements.}
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001915 \lineii{elem.append(elem2)}{Adds \var{elem2} as a child.}
1916 \lineii{elem.insert(index, elem2)}{Inserts \var{elem2} at the specified location.}
1917 \lineii{del elem[n]}{Deletes n'th child element.}
1918 \lineii{elem.keys()}{Returns list of attribute names.}
1919 \lineii{elem.get(name)}{Returns value of attribute \var{name}.}
1920 \lineii{elem.set(name, value)}{Sets new value for attribute \var{name}.}
1921 \lineii{elem.attrib}{Retrieves the dictionary containing attributes.}
1922 \lineii{del elem.attrib[name]}{Deletes attribute \var{name}.}
1923\end{tableii}
1924
1925Comments and processing instructions are also represented as
1926\class{Element} nodes. To check if a node is a comment or processing
1927instructions:
1928
1929\begin{verbatim}
1930if elem.tag is ET.Comment:
1931 ...
1932elif elem.tag is ET.ProcessingInstruction:
1933 ...
1934\end{verbatim}
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001935
1936To generate XML output, you should call the
1937\method{ElementTree.write()} method. Like \function{parse()},
1938it can take either a string or a file-like object:
1939
1940\begin{verbatim}
1941# Encoding is US-ASCII
1942tree.write('output.xml')
1943
1944# Encoding is UTF-8
1945f = open('output.xml', 'w')
Andrew M. Kuchlinga8837012006-05-02 11:30:03 +00001946tree.write(f, encoding='utf-8')
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001947\end{verbatim}
1948
Andrew M. Kuchlinga8837012006-05-02 11:30:03 +00001949(Caution: the default encoding used for output is ASCII. For general
1950XML work, where an element's name may contain arbitrary Unicode
1951characters, ASCII isn't a very useful encoding because it will raise
1952an exception if an element's name contains any characters with values
1953greater than 127. Therefore, it's best to specify a different
1954encoding such as UTF-8 that can handle any Unicode character.)
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001955
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001956This section is only a partial description of the ElementTree interfaces.
1957Please read the package's official documentation for more details.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001958
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001959\begin{seealso}
1960
1961\seeurl{http://effbot.org/zone/element-index.htm}
1962{Official documentation for ElementTree.}
1963
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001964\end{seealso}
1965
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001966
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001967%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001968\subsection{The hashlib package\label{module-hashlib}}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001969
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001970A new \module{hashlib} module, written by Gregory P. Smith,
1971has been added to replace the
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001972\module{md5} and \module{sha} modules. \module{hashlib} adds support
1973for additional secure hashes (SHA-224, SHA-256, SHA-384, and SHA-512).
1974When available, the module uses OpenSSL for fast platform optimized
1975implementations of algorithms.
1976
1977The old \module{md5} and \module{sha} modules still exist as wrappers
1978around hashlib to preserve backwards compatibility. The new module's
1979interface is very close to that of the old modules, but not identical.
1980The most significant difference is that the constructor functions
1981for creating new hashing objects are named differently.
1982
1983\begin{verbatim}
1984# Old versions
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001985h = md5.md5()
1986h = md5.new()
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001987
1988# New version
1989h = hashlib.md5()
1990
1991# Old versions
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001992h = sha.sha()
1993h = sha.new()
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001994
1995# New version
1996h = hashlib.sha1()
1997
1998# Hash that weren't previously available
1999h = hashlib.sha224()
2000h = hashlib.sha256()
2001h = hashlib.sha384()
2002h = hashlib.sha512()
2003
2004# Alternative form
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00002005h = hashlib.new('md5') # Provide algorithm as a string
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00002006\end{verbatim}
2007
2008Once a hash object has been created, its methods are the same as before:
2009\method{update(\var{string})} hashes the specified string into the
2010current digest state, \method{digest()} and \method{hexdigest()}
2011return the digest value as a binary string or a string of hex digits,
2012and \method{copy()} returns a new hashing object with the same digest state.
2013
Andrew M. Kuchlingb4922442006-06-21 17:10:18 +00002014\begin{seealso}
2015
2016\seeurl{../lib/module-hashlib.html}{The documentation
2017for the \module{hashlib} module.}
2018
2019\end{seealso}
2020
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00002021
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00002022%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00002023\subsection{The sqlite3 package\label{module-sqlite}}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00002024
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00002025The pysqlite module (\url{http://www.pysqlite.org}), a wrapper for the
2026SQLite embedded database, has been added to the standard library under
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00002027the package name \module{sqlite3}.
2028
2029SQLite is a C library that provides a SQL-language database that
2030stores data in disk files without requiring a separate server process.
2031pysqlite was written by Gerhard H\"aring and provides a SQL interface
2032compliant with the DB-API 2.0 specification described by
2033\pep{249}. This means that it should be possible to write the first
2034version of your applications using SQLite for data storage. If
2035switching to a larger database such as PostgreSQL or Oracle is
2036later necessary, the switch should be relatively easy.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00002037
2038If you're compiling the Python source yourself, note that the source
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00002039tree doesn't include the SQLite code, only the wrapper module.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00002040You'll need to have the SQLite libraries and headers installed before
2041compiling Python, and the build process will compile the module when
2042the necessary headers are available.
2043
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00002044To use the module, you must first create a \class{Connection} object
2045that represents the database. Here the data will be stored in the
2046\file{/tmp/example} file:
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00002047
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00002048\begin{verbatim}
2049conn = sqlite3.connect('/tmp/example')
2050\end{verbatim}
2051
2052You can also supply the special name \samp{:memory:} to create
2053a database in RAM.
2054
2055Once you have a \class{Connection}, you can create a \class{Cursor}
2056object and call its \method{execute()} method to perform SQL commands:
2057
2058\begin{verbatim}
2059c = conn.cursor()
2060
2061# Create table
2062c.execute('''create table stocks
2063(date timestamp, trans varchar, symbol varchar,
2064 qty decimal, price decimal)''')
2065
2066# Insert a row of data
2067c.execute("""insert into stocks
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00002068 values ('2006-01-05','BUY','RHAT',100,35.14)""")
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00002069\end{verbatim}
2070
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00002071Usually your SQL operations will need to use values from Python
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00002072variables. You shouldn't assemble your query using Python's string
2073operations because doing so is insecure; it makes your program
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00002074vulnerable to an SQL injection attack.
2075
Andrew M. Kuchling1271f002006-06-07 17:02:52 +00002076Instead, use the DB-API's parameter substitution. Put \samp{?} as a
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00002077placeholder wherever you want to use a value, and then provide a tuple
2078of values as the second argument to the cursor's \method{execute()}
Andrew M. Kuchling1271f002006-06-07 17:02:52 +00002079method. (Other database modules may use a different placeholder,
Andrew M. Kuchling3b336c72006-06-07 17:03:46 +00002080such as \samp{\%s} or \samp{:1}.) For example:
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00002081
2082\begin{verbatim}
2083# Never do this -- insecure!
2084symbol = 'IBM'
2085c.execute("... where symbol = '%s'" % symbol)
2086
2087# Do this instead
2088t = (symbol,)
Andrew M. Kuchling7e5abb92006-04-26 12:21:06 +00002089c.execute('select * from stocks where symbol=?', t)
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00002090
2091# Larger example
2092for t in (('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00002093 ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
2094 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
2095 ):
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00002096 c.execute('insert into stocks values (?,?,?,?,?)', t)
2097\end{verbatim}
2098
2099To retrieve data after executing a SELECT statement, you can either
2100treat the cursor as an iterator, call the cursor's \method{fetchone()}
2101method to retrieve a single matching row,
2102or call \method{fetchall()} to get a list of the matching rows.
2103
2104This example uses the iterator form:
2105
2106\begin{verbatim}
2107>>> c = conn.cursor()
2108>>> c.execute('select * from stocks order by price')
2109>>> for row in c:
2110... print row
2111...
2112(u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001)
2113(u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
2114(u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
2115(u'2006-04-05', u'BUY', u'MSOFT', 1000, 72.0)
2116>>>
2117\end{verbatim}
2118
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00002119For more information about the SQL dialect supported by SQLite, see
2120\url{http://www.sqlite.org}.
2121
2122\begin{seealso}
2123
2124\seeurl{http://www.pysqlite.org}
2125{The pysqlite web page.}
2126
2127\seeurl{http://www.sqlite.org}
2128{The SQLite web page; the documentation describes the syntax and the
2129available data types for the supported SQL dialect.}
2130
Andrew M. Kuchlingb4922442006-06-21 17:10:18 +00002131\seeurl{../lib/module-sqlite3.html}{The documentation
2132for the \module{sqlite3} module.}
2133
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00002134\seepep{249}{Database API Specification 2.0}{PEP written by
2135Marc-Andr\'e Lemburg.}
2136
2137\end{seealso}
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00002138
Fred Drake2db76802004-12-01 05:05:47 +00002139
Andrew M. Kuchlinga04d1182006-06-09 19:03:16 +00002140%======================================================================
Andrew M. Kuchlingf6856ce2006-06-20 11:52:16 +00002141\subsection{The wsgiref package\label{module-wsgiref}}
Andrew M. Kuchlinga04d1182006-06-09 19:03:16 +00002142
Andrew M. Kuchlingb3f29852006-06-09 19:56:05 +00002143% XXX should this be in a PEP 333 section instead?
Andrew M. Kuchlingb3f29852006-06-09 19:56:05 +00002144
2145The Web Server Gateway Interface (WSGI) v1.0 defines a standard
2146interface between web servers and Python web applications and is
2147described in \pep{333}. The \module{wsgiref} package is a reference
2148implementation of the WSGI specification.
2149
2150The package includes a basic HTTP server that will run a WSGI
2151application; this server is useful for debugging but isn't intended for
Andrew M. Kuchlingf6856ce2006-06-20 11:52:16 +00002152production use. Setting up a server takes only a few lines of code:
Andrew M. Kuchlingb3f29852006-06-09 19:56:05 +00002153
2154\begin{verbatim}
2155from wsgiref import simple_server
2156
2157wsgi_app = ...
2158
2159host = ''
2160port = 8000
2161httpd = make_server(host, port, wsgi_app)
2162httpd.serve_forever()
2163\end{verbatim}
2164
Andrew M. Kuchlingf6856ce2006-06-20 11:52:16 +00002165% XXX discuss structure of WSGI applications?
2166% XXX provide an example using Django or some other framework?
Andrew M. Kuchlingb3f29852006-06-09 19:56:05 +00002167
2168\begin{seealso}
2169
Andrew M. Kuchlingf6856ce2006-06-20 11:52:16 +00002170\seeurl{http://www.wsgi.org}{A central web site for WSGI-related resources.}
2171
Andrew M. Kuchlingb3f29852006-06-09 19:56:05 +00002172\seepep{333}{Python Web Server Gateway Interface v1.0}{PEP written by
2173Phillip J. Eby.}
2174
2175\end{seealso}
2176
2177
Fred Drake2db76802004-12-01 05:05:47 +00002178% ======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00002179\section{Build and C API Changes\label{build-api}}
Fred Drake2db76802004-12-01 05:05:47 +00002180
2181Changes to Python's build process and to the C API include:
2182
2183\begin{itemize}
2184
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00002185\item The largest change to the C API came from \pep{353},
2186which modifies the interpreter to use a \ctype{Py_ssize_t} type
2187definition instead of \ctype{int}. See the earlier
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +00002188section~\ref{pep-353} for a discussion of this change.
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00002189
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00002190\item The design of the bytecode compiler has changed a great deal, to
2191no longer generate bytecode by traversing the parse tree. Instead
Andrew M. Kuchlingdb85ed52005-10-23 21:52:59 +00002192the parse tree is converted to an abstract syntax tree (or AST), and it is
2193the abstract syntax tree that's traversed to produce the bytecode.
2194
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00002195It's possible for Python code to obtain AST objects by using the
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00002196\function{compile()} built-in and specifying \code{_ast.PyCF_ONLY_AST}
2197as the value of the
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00002198\var{flags} parameter:
2199
2200\begin{verbatim}
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00002201from _ast import PyCF_ONLY_AST
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00002202ast = compile("""a=0
2203for i in range(10):
2204 a += i
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00002205""", "<string>", 'exec', PyCF_ONLY_AST)
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00002206
2207assignment = ast.body[0]
2208for_loop = ast.body[1]
2209\end{verbatim}
2210
Andrew M. Kuchlingdb85ed52005-10-23 21:52:59 +00002211No documentation has been written for the AST code yet. To start
2212learning about it, read the definition of the various AST nodes in
2213\file{Parser/Python.asdl}. A Python script reads this file and
2214generates a set of C structure definitions in
2215\file{Include/Python-ast.h}. The \cfunction{PyParser_ASTFromString()}
2216and \cfunction{PyParser_ASTFromFile()}, defined in
2217\file{Include/pythonrun.h}, take Python source as input and return the
2218root of an AST representing the contents. This AST can then be turned
2219into a code object by \cfunction{PyAST_Compile()}. For more
2220information, read the source code, and then ask questions on
2221python-dev.
2222
2223% List of names taken from Jeremy's python-dev post at
2224% http://mail.python.org/pipermail/python-dev/2005-October/057500.html
2225The AST code was developed under Jeremy Hylton's management, and
2226implemented by (in alphabetical order) Brett Cannon, Nick Coghlan,
2227Grant Edwards, John Ehresman, Kurt Kaiser, Neal Norwitz, Tim Peters,
2228Armin Rigo, and Neil Schemenauer, plus the participants in a number of
2229AST sprints at conferences such as PyCon.
2230
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00002231\item The built-in set types now have an official C API. Call
2232\cfunction{PySet_New()} and \cfunction{PyFrozenSet_New()} to create a
2233new set, \cfunction{PySet_Add()} and \cfunction{PySet_Discard()} to
2234add and remove elements, and \cfunction{PySet_Contains} and
2235\cfunction{PySet_Size} to examine the set's state.
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00002236(Contributed by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00002237
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00002238\item C code can now obtain information about the exact revision
2239of the Python interpreter by calling the
2240\cfunction{Py_GetBuildInfo()} function that returns a
2241string of build information like this:
2242\code{"trunk:45355:45356M, Apr 13 2006, 07:42:19"}.
2243(Contributed by Barry Warsaw.)
2244
Andrew M. Kuchlingb98d65c2006-05-27 11:26:33 +00002245\item Two new macros can be used to indicate C functions that are
2246local to the current file so that a faster calling convention can be
2247used. \cfunction{Py_LOCAL(\var{type})} declares the function as
2248returning a value of the specified \var{type} and uses a fast-calling
2249qualifier. \cfunction{Py_LOCAL_INLINE(\var{type})} does the same thing
2250and also requests the function be inlined. If
2251\cfunction{PY_LOCAL_AGGRESSIVE} is defined before \file{python.h} is
2252included, a set of more aggressive optimizations are enabled for the
2253module; you should benchmark the results to find out if these
2254optimizations actually make the code faster. (Contributed by Fredrik
2255Lundh at the NeedForSpeed sprint.)
2256
Andrew M. Kuchlingc6027232006-05-23 12:44:36 +00002257\item \cfunction{PyErr_NewException(\var{name}, \var{base},
2258\var{dict})} can now accept a tuple of base classes as its \var{base}
2259argument. (Contributed by Georg Brandl.)
2260
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00002261\item The CPython interpreter is still written in C, but
2262the code can now be compiled with a {\Cpp} compiler without errors.
2263(Implemented by Anthony Baxter, Martin von~L\"owis, Skip Montanaro.)
2264
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00002265\item The \cfunction{PyRange_New()} function was removed. It was
2266never documented, never used in the core code, and had dangerously lax
2267error checking.
Fred Drake2db76802004-12-01 05:05:47 +00002268
2269\end{itemize}
2270
2271
2272%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00002273\subsection{Port-Specific Changes\label{ports}}
Fred Drake2db76802004-12-01 05:05:47 +00002274
Andrew M. Kuchling6fc69762006-04-13 12:37:21 +00002275\begin{itemize}
2276
2277\item MacOS X (10.3 and higher): dynamic loading of modules
2278now uses the \cfunction{dlopen()} function instead of MacOS-specific
2279functions.
2280
Andrew M. Kuchlingb37bcb52006-04-29 11:53:15 +00002281\item MacOS X: a \longprogramopt{enable-universalsdk} switch was added
2282to the \program{configure} script that compiles the interpreter as a
2283universal binary able to run on both PowerPC and Intel processors.
2284(Contributed by Ronald Oussoren.)
2285
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00002286\item Windows: \file{.dll} is no longer supported as a filename extension for
2287extension modules. \file{.pyd} is now the only filename extension that will
2288be searched for.
2289
Andrew M. Kuchling6fc69762006-04-13 12:37:21 +00002290\end{itemize}
Fred Drake2db76802004-12-01 05:05:47 +00002291
2292
2293%======================================================================
2294\section{Other Changes and Fixes \label{section-other}}
2295
2296As usual, there were a bunch of other improvements and bugfixes
Andrew M. Kuchlingf688cc52006-03-10 18:50:08 +00002297scattered throughout the source tree. A search through the SVN change
Fred Drake2db76802004-12-01 05:05:47 +00002298logs finds there were XXX patches applied and YYY bugs fixed between
Andrew M. Kuchling92e24952004-12-03 13:54:09 +00002299Python 2.4 and 2.5. Both figures are likely to be underestimates.
Fred Drake2db76802004-12-01 05:05:47 +00002300
2301Some of the more notable changes are:
2302
2303\begin{itemize}
2304
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00002305\item Evan Jones's patch to obmalloc, first described in a talk
2306at PyCon DC 2005, was applied. Python 2.4 allocated small objects in
2307256K-sized arenas, but never freed arenas. With this patch, Python
2308will free arenas when they're empty. The net effect is that on some
2309platforms, when you allocate many objects, Python's memory usage may
2310actually drop when you delete them, and the memory may be returned to
2311the operating system. (Implemented by Evan Jones, and reworked by Tim
2312Peters.)
Fred Drake2db76802004-12-01 05:05:47 +00002313
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00002314Note that this change means extension modules need to be more careful
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +00002315with how they allocate memory. Python's API has many different
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00002316functions for allocating memory that are grouped into families. For
2317example, \cfunction{PyMem_Malloc()}, \cfunction{PyMem_Realloc()}, and
2318\cfunction{PyMem_Free()} are one family that allocates raw memory,
2319while \cfunction{PyObject_Malloc()}, \cfunction{PyObject_Realloc()},
2320and \cfunction{PyObject_Free()} are another family that's supposed to
2321be used for creating Python objects.
2322
2323Previously these different families all reduced to the platform's
2324\cfunction{malloc()} and \cfunction{free()} functions. This meant
2325it didn't matter if you got things wrong and allocated memory with the
2326\cfunction{PyMem} function but freed it with the \cfunction{PyObject}
2327function. With the obmalloc change, these families now do different
2328things, and mismatches will probably result in a segfault. You should
2329carefully test your C extension modules with Python 2.5.
2330
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00002331\item Coverity, a company that markets a source code analysis tool
2332 called Prevent, provided the results of their examination of the Python
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +00002333 source code. The analysis found about 60 bugs that
2334 were quickly fixed. Many of the bugs were refcounting problems, often
2335 occurring in error-handling code. See
2336 \url{http://scan.coverity.com} for the statistics.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00002337
Fred Drake2db76802004-12-01 05:05:47 +00002338\end{itemize}
2339
2340
2341%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00002342\section{Porting to Python 2.5\label{porting}}
Fred Drake2db76802004-12-01 05:05:47 +00002343
2344This section lists previously described changes that may require
2345changes to your code:
2346
2347\begin{itemize}
2348
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00002349\item ASCII is now the default encoding for modules. It's now
2350a syntax error if a module contains string literals with 8-bit
2351characters but doesn't have an encoding declaration. In Python 2.4
2352this triggered a warning, not a syntax error.
2353
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +00002354\item Previously, the \member{gi_frame} attribute of a generator
2355was always a frame object. Because of the \pep{342} changes
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +00002356described in section~\ref{pep-342}, it's now possible
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +00002357for \member{gi_frame} to be \code{None}.
2358
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00002359
2360\item Library: The \module{pickle} and \module{cPickle} modules no
2361longer accept a return value of \code{None} from the
2362\method{__reduce__()} method; the method must return a tuple of
2363arguments instead. The modules also no longer accept the deprecated
2364\var{bin} keyword parameter.
2365
Andrew M. Kuchling07cf0722006-05-31 14:12:47 +00002366\item Library: The \module{SimpleXMLRPCServer} and \module{DocXMLRPCServer}
2367classes now have a \member{rpc_paths} attribute that constrains
2368XML-RPC operations to a limited set of URL paths; the default is
2369to allow only \code{'/'} and \code{'/RPC2'}. Setting
2370\member{rpc_paths} to \code{None} or an empty tuple disables
2371this path checking.
2372
Andrew M. Kuchling1fb8d832006-06-20 13:20:30 +00002373\item Library: the \module{xml} package has been renamed to \module{xmlcore}.
2374The PyXML package will therefore be \module{xml}, and the Python
2375distribution's code will always be accessible as \module{xmlcore}.
2376
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00002377\item C API: Many functions now use \ctype{Py_ssize_t}
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00002378instead of \ctype{int} to allow processing more data on 64-bit
2379machines. Extension code may need to make the same change to avoid
2380warnings and to support 64-bit machines. See the earlier
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +00002381section~\ref{pep-353} for a discussion of this change.
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00002382
2383\item C API:
2384The obmalloc changes mean that
2385you must be careful to not mix usage
2386of the \cfunction{PyMem_*()} and \cfunction{PyObject_*()}
2387families of functions. Memory allocated with
2388one family's \cfunction{*_Malloc()} must be
2389freed with the corresponding family's \cfunction{*_Free()} function.
2390
Fred Drake2db76802004-12-01 05:05:47 +00002391\end{itemize}
2392
2393
2394%======================================================================
2395\section{Acknowledgements \label{acks}}
2396
2397The author would like to thank the following people for offering
2398suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchlinge3c958c2006-05-01 12:45:02 +00002399article: Phillip J. Eby, Kent Johnson, Martin von~L\"owis, Fredrik Lundh,
Andrew M. Kuchling643b0412006-06-21 17:17:10 +00002400Gustavo Niemeyer, James Pryor, Mike Rovner, Scott Weikart, Barry Warsaw,
2401Thomas Wouters.
Fred Drake2db76802004-12-01 05:05:47 +00002402
2403\end{document}