blob: 302d9a5021f566219f8ecc42c221ef4a5a7f15e8 [file] [log] [blame]
Fred Drake2db76802004-12-01 05:05:47 +00001\documentclass{howto}
2\usepackage{distutils}
3% $Id$
4
Andrew M. Kuchlinga04d1182006-06-09 19:03:16 +00005% wsgiref section
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00006% Fix XXX comments
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00007% Count up the patches and bugs
Fred Drake2db76802004-12-01 05:05:47 +00008
9\title{What's New in Python 2.5}
Andrew M. Kuchling99714cf2006-04-27 12:23:07 +000010\release{0.2}
Andrew M. Kuchling92e24952004-12-03 13:54:09 +000011\author{A.M. Kuchling}
12\authoraddress{\email{amk@amk.ca}}
Fred Drake2db76802004-12-01 05:05:47 +000013
14\begin{document}
15\maketitle
16\tableofcontents
17
18This article explains the new features in Python 2.5. No release date
Andrew M. Kuchling5eefdca2006-02-08 11:36:09 +000019for Python 2.5 has been set; it will probably be released in the
Andrew M. Kuchlingd96a6ac2006-04-04 19:17:34 +000020autumn of 2006. \pep{356} describes the planned release schedule.
Fred Drake2db76802004-12-01 05:05:47 +000021
Andrew M. Kuchling0d660c02006-04-17 14:01:36 +000022Comments, suggestions, and error reports are welcome; please e-mail them
23to the author or open a bug in the Python bug tracker.
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +000024
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000025% XXX Compare with previous release in 2 - 3 sentences here.
Fred Drake2db76802004-12-01 05:05:47 +000026
27This article doesn't attempt to provide a complete specification of
28the new features, but instead provides a convenient overview. For
29full details, you should refer to the documentation for Python 2.5.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000030% XXX add hyperlink when the documentation becomes available online.
Fred Drake2db76802004-12-01 05:05:47 +000031If you want to understand the complete implementation and design
32rationale, refer to the PEP for a particular new feature.
33
34
35%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +000036\section{PEP 308: Conditional Expressions\label{pep-308}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000037
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000038For a long time, people have been requesting a way to write
39conditional expressions, expressions that return value A or value B
40depending on whether a Boolean value is true or false. A conditional
41expression lets you write a single assignment statement that has the
42same effect as the following:
43
44\begin{verbatim}
45if condition:
46 x = true_value
47else:
48 x = false_value
49\end{verbatim}
50
51There have been endless tedious discussions of syntax on both
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +000052python-dev and comp.lang.python. A vote was even held that found the
53majority of voters wanted conditional expressions in some form,
54but there was no syntax that was preferred by a clear majority.
55Candidates included C's \code{cond ? true_v : false_v},
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000056\code{if cond then true_v else false_v}, and 16 other variations.
57
58GvR eventually chose a surprising syntax:
59
60\begin{verbatim}
61x = true_value if condition else false_value
62\end{verbatim}
63
Andrew M. Kuchling38f85072006-04-02 01:46:32 +000064Evaluation is still lazy as in existing Boolean expressions, so the
65order of evaluation jumps around a bit. The \var{condition}
66expression in the middle is evaluated first, and the \var{true_value}
67expression is evaluated only if the condition was true. Similarly,
68the \var{false_value} expression is only evaluated when the condition
69is false.
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000070
71This syntax may seem strange and backwards; why does the condition go
72in the \emph{middle} of the expression, and not in the front as in C's
73\code{c ? x : y}? The decision was checked by applying the new syntax
74to the modules in the standard library and seeing how the resulting
75code read. In many cases where a conditional expression is used, one
76value seems to be the 'common case' and one value is an 'exceptional
77case', used only on rarer occasions when the condition isn't met. The
78conditional syntax makes this pattern a bit more obvious:
79
80\begin{verbatim}
81contents = ((doc + '\n') if doc else '')
82\end{verbatim}
83
84I read the above statement as meaning ``here \var{contents} is
Andrew M. Kuchlingd0fcc022006-03-09 13:57:28 +000085usually assigned a value of \code{doc+'\e n'}; sometimes
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000086\var{doc} is empty, in which special case an empty string is returned.''
87I doubt I will use conditional expressions very often where there
88isn't a clear common and uncommon case.
89
90There was some discussion of whether the language should require
91surrounding conditional expressions with parentheses. The decision
92was made to \emph{not} require parentheses in the Python language's
93grammar, but as a matter of style I think you should always use them.
94Consider these two statements:
95
96\begin{verbatim}
97# First version -- no parens
98level = 1 if logging else 0
99
100# Second version -- with parens
101level = (1 if logging else 0)
102\end{verbatim}
103
104In the first version, I think a reader's eye might group the statement
105into 'level = 1', 'if logging', 'else 0', and think that the condition
106decides whether the assignment to \var{level} is performed. The
107second version reads better, in my opinion, because it makes it clear
108that the assignment is always performed and the choice is being made
109between two values.
110
111Another reason for including the brackets: a few odd combinations of
112list comprehensions and lambdas could look like incorrect conditional
113expressions. See \pep{308} for some examples. If you put parentheses
114around your conditional expressions, you won't run into this case.
115
116
117\begin{seealso}
118
119\seepep{308}{Conditional Expressions}{PEP written by
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000120Guido van~Rossum and Raymond D. Hettinger; implemented by Thomas
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +0000121Wouters.}
122
123\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000124
125
126%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000127\section{PEP 309: Partial Function Application\label{pep-309}}
Fred Drake2db76802004-12-01 05:05:47 +0000128
Andrew M. Kuchling0d272bb2006-05-31 13:18:56 +0000129The \module{functools} module is intended to contain tools for
Andrew M. Kuchlinge878fe62006-06-09 01:10:17 +0000130functional-style programming.
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000131
Andrew M. Kuchlinge878fe62006-06-09 01:10:17 +0000132One useful tool in this module is the \function{partial()} function.
133For programs written in a functional style, you'll sometimes want to
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000134construct variants of existing functions that have some of the
135parameters filled in. Consider a Python function \code{f(a, b, c)};
136you could create a new function \code{g(b, c)} that was equivalent to
Andrew M. Kuchlinge878fe62006-06-09 01:10:17 +0000137\code{f(1, b, c)}. This is called ``partial function application''.
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000138
Andrew M. Kuchlinge878fe62006-06-09 01:10:17 +0000139\function{partial} takes the arguments
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000140\code{(\var{function}, \var{arg1}, \var{arg2}, ...
141\var{kwarg1}=\var{value1}, \var{kwarg2}=\var{value2})}. The resulting
142object is callable, so you can just call it to invoke \var{function}
143with the filled-in arguments.
144
145Here's a small but realistic example:
146
147\begin{verbatim}
Andrew M. Kuchling0d272bb2006-05-31 13:18:56 +0000148import functools
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000149
150def log (message, subsystem):
151 "Write the contents of 'message' to the specified subsystem."
152 print '%s: %s' % (subsystem, message)
153 ...
154
Andrew M. Kuchling0d272bb2006-05-31 13:18:56 +0000155server_log = functools.partial(log, subsystem='server')
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000156server_log('Unable to open socket')
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000157\end{verbatim}
158
Andrew M. Kuchling0d272bb2006-05-31 13:18:56 +0000159Here's another example, from a program that uses PyGTK. Here a
Andrew M. Kuchling6af7fe02005-08-02 17:20:36 +0000160context-sensitive pop-up menu is being constructed dynamically. The
161callback provided for the menu option is a partially applied version
162of the \method{open_item()} method, where the first argument has been
163provided.
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000164
Andrew M. Kuchling6af7fe02005-08-02 17:20:36 +0000165\begin{verbatim}
166...
167class Application:
168 def open_item(self, path):
169 ...
170 def init (self):
Andrew M. Kuchling0d272bb2006-05-31 13:18:56 +0000171 open_func = functools.partial(self.open_item, item_path)
Andrew M. Kuchling6af7fe02005-08-02 17:20:36 +0000172 popup_menu.append( ("Open", open_func, 1) )
173\end{verbatim}
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000174
175
Andrew M. Kuchlinge878fe62006-06-09 01:10:17 +0000176Another function in the \module{functools} module is the
Andrew M. Kuchling7dbb1ff2006-06-09 10:22:35 +0000177\function{update_wrapper(\var{wrapper}, \var{wrapped})} function that
Andrew M. Kuchlinge878fe62006-06-09 01:10:17 +0000178helps you write well-behaved decorators. \function{update_wrapper()}
179copies the name, module, and docstring attribute to a wrapper function
180so that tracebacks inside the wrapped function are easier to
181understand. For example, you might write:
182
183\begin{verbatim}
184def my_decorator(f):
185 def wrapper(*args, **kwds):
186 print 'Calling decorated function'
187 return f(*args, **kwds)
188 functools.update_wrapper(wrapper, f)
189 return wrapper
190\end{verbatim}
191
192\function{wraps()} is a decorator that can be used inside your own
193decorators to copy the wrapped function's information. An alternate
194version of the previous example would be:
195
196\begin{verbatim}
197def my_decorator(f):
198 @functools.wraps(f)
199 def wrapper(*args, **kwds):
200 print 'Calling decorated function'
201 return f(*args, **kwds)
202 return wrapper
203\end{verbatim}
204
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000205\begin{seealso}
206
207\seepep{309}{Partial Function Application}{PEP proposed and written by
Andrew M. Kuchlinge878fe62006-06-09 01:10:17 +0000208Peter Harris; implemented by Hye-Shik Chang and Nick Coghlan, with
209adaptations by Raymond Hettinger.}
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000210
211\end{seealso}
Fred Drake2db76802004-12-01 05:05:47 +0000212
213
214%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000215\section{PEP 314: Metadata for Python Software Packages v1.1\label{pep-314}}
Fred Drakedb7b0022005-03-20 22:19:47 +0000216
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000217Some simple dependency support was added to Distutils. The
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000218\function{setup()} function now has \code{requires}, \code{provides},
219and \code{obsoletes} keyword parameters. When you build a source
220distribution using the \code{sdist} command, the dependency
221information will be recorded in the \file{PKG-INFO} file.
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000222
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000223Another new keyword parameter is \code{download_url}, which should be
224set to a URL for the package's source code. This means it's now
225possible to look up an entry in the package index, determine the
226dependencies for a package, and download the required packages.
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000227
Andrew M. Kuchling61434b62006-04-13 11:51:07 +0000228\begin{verbatim}
229VERSION = '1.0'
230setup(name='PyPackage',
231 version=VERSION,
232 requires=['numarray', 'zlib (>=1.1.4)'],
233 obsoletes=['OldPackage']
234 download_url=('http://www.example.com/pypackage/dist/pkg-%s.tar.gz'
235 % VERSION),
236 )
237\end{verbatim}
Andrew M. Kuchlingc0a0dec2006-05-16 16:27:31 +0000238
239Another new enhancement to the Python package index at
240\url{http://cheeseshop.python.org} is storing source and binary
241archives for a package. The new \command{upload} Distutils command
242will upload a package to the repository.
243
244Before a package can be uploaded, you must be able to build a
245distribution using the \command{sdist} Distutils command. Once that
246works, you can run \code{python setup.py upload} to add your package
247to the PyPI archive. Optionally you can GPG-sign the package by
248supplying the \longprogramopt{sign} and
249\longprogramopt{identity} options.
250
251Package uploading was implemented by Martin von~L\"owis and Richard Jones.
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000252
253\begin{seealso}
254
255\seepep{314}{Metadata for Python Software Packages v1.1}{PEP proposed
256and written by A.M. Kuchling, Richard Jones, and Fred Drake;
257implemented by Richard Jones and Fred Drake.}
258
259\end{seealso}
Fred Drakedb7b0022005-03-20 22:19:47 +0000260
261
262%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000263\section{PEP 328: Absolute and Relative Imports\label{pep-328}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000264
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000265The simpler part of PEP 328 was implemented in Python 2.4: parentheses
266could now be used to enclose the names imported from a module using
267the \code{from ... import ...} statement, making it easier to import
268many different names.
269
270The more complicated part has been implemented in Python 2.5:
271importing a module can be specified to use absolute or
272package-relative imports. The plan is to move toward making absolute
273imports the default in future versions of Python.
274
275Let's say you have a package directory like this:
276\begin{verbatim}
277pkg/
278pkg/__init__.py
279pkg/main.py
280pkg/string.py
281\end{verbatim}
282
283This defines a package named \module{pkg} containing the
284\module{pkg.main} and \module{pkg.string} submodules.
285
286Consider the code in the \file{main.py} module. What happens if it
287executes the statement \code{import string}? In Python 2.4 and
288earlier, it will first look in the package's directory to perform a
289relative import, finds \file{pkg/string.py}, imports the contents of
290that file as the \module{pkg.string} module, and that module is bound
291to the name \samp{string} in the \module{pkg.main} module's namespace.
292
293That's fine if \module{pkg.string} was what you wanted. But what if
294you wanted Python's standard \module{string} module? There's no clean
295way to ignore \module{pkg.string} and look for the standard module;
296generally you had to look at the contents of \code{sys.modules}, which
297is slightly unclean.
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000298Holger Krekel's \module{py.std} package provides a tidier way to perform
299imports from the standard library, \code{import py ; py.std.string.join()},
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000300but that package isn't available on all Python installations.
301
302Reading code which relies on relative imports is also less clear,
303because a reader may be confused about which module, \module{string}
304or \module{pkg.string}, is intended to be used. Python users soon
305learned not to duplicate the names of standard library modules in the
306names of their packages' submodules, but you can't protect against
307having your submodule's name being used for a new module added in a
308future version of Python.
309
310In Python 2.5, you can switch \keyword{import}'s behaviour to
311absolute imports using a \code{from __future__ import absolute_import}
312directive. This absolute-import behaviour will become the default in
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000313a future version (probably Python 2.7). Once absolute imports
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000314are the default, \code{import string} will
315always find the standard library's version.
316It's suggested that users should begin using absolute imports as much
317as possible, so it's preferable to begin writing \code{from pkg import
318string} in your code.
319
320Relative imports are still possible by adding a leading period
321to the module name when using the \code{from ... import} form:
322
323\begin{verbatim}
324# Import names from pkg.string
325from .string import name1, name2
326# Import pkg.string
327from . import string
328\end{verbatim}
329
330This imports the \module{string} module relative to the current
331package, so in \module{pkg.main} this will import \var{name1} and
332\var{name2} from \module{pkg.string}. Additional leading periods
333perform the relative import starting from the parent of the current
334package. For example, code in the \module{A.B.C} module can do:
335
336\begin{verbatim}
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000337from . import D # Imports A.B.D
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000338from .. import E # Imports A.E
339from ..F import G # Imports A.F.G
340\end{verbatim}
341
342Leading periods cannot be used with the \code{import \var{modname}}
343form of the import statement, only the \code{from ... import} form.
344
345\begin{seealso}
346
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000347\seepep{328}{Imports: Multi-Line and Absolute/Relative}
348{PEP written by Aahz; implemented by Thomas Wouters.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000349
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000350\seeurl{http://codespeak.net/py/current/doc/index.html}
351{The py library by Holger Krekel, which contains the \module{py.std} package.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000352
353\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000354
355
356%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000357\section{PEP 338: Executing Modules as Scripts\label{pep-338}}
Andrew M. Kuchling21d3a7c2006-03-15 11:53:09 +0000358
Andrew M. Kuchlingb182db42006-03-17 21:48:46 +0000359The \programopt{-m} switch added in Python 2.4 to execute a module as
360a script gained a few more abilities. Instead of being implemented in
361C code inside the Python interpreter, the switch now uses an
362implementation in a new module, \module{runpy}.
363
364The \module{runpy} module implements a more sophisticated import
365mechanism so that it's now possible to run modules in a package such
366as \module{pychecker.checker}. The module also supports alternative
Andrew M. Kuchling5d4cf5e2006-04-13 13:02:42 +0000367import mechanisms such as the \module{zipimport} module. This means
Andrew M. Kuchlingb182db42006-03-17 21:48:46 +0000368you can add a .zip archive's path to \code{sys.path} and then use the
369\programopt{-m} switch to execute code from the archive.
370
371
372\begin{seealso}
373
374\seepep{338}{Executing modules as scripts}{PEP written and
375implemented by Nick Coghlan.}
376
377\end{seealso}
Andrew M. Kuchling21d3a7c2006-03-15 11:53:09 +0000378
379
380%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000381\section{PEP 341: Unified try/except/finally\label{pep-341}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000382
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000383Until Python 2.5, the \keyword{try} statement came in two
384flavours. You could use a \keyword{finally} block to ensure that code
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +0000385is always executed, or one or more \keyword{except} blocks to catch
386specific exceptions. You couldn't combine both \keyword{except} blocks and a
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000387\keyword{finally} block, because generating the right bytecode for the
388combined version was complicated and it wasn't clear what the
389semantics of the combined should be.
390
391GvR spent some time working with Java, which does support the
392equivalent of combining \keyword{except} blocks and a
393\keyword{finally} block, and this clarified what the statement should
394mean. In Python 2.5, you can now write:
395
396\begin{verbatim}
397try:
398 block-1 ...
399except Exception1:
400 handler-1 ...
401except Exception2:
402 handler-2 ...
403else:
404 else-block
405finally:
406 final-block
407\end{verbatim}
408
409The code in \var{block-1} is executed. If the code raises an
Andrew M. Kuchling356af462006-05-10 17:19:04 +0000410exception, the various \keyword{except} blocks are tested: if the
411exception is of class \class{Exception1}, \var{handler-1} is executed;
412otherwise if it's of class \class{Exception2}, \var{handler-2} is
413executed, and so forth. If no exception is raised, the
414\var{else-block} is executed.
415
416No matter what happened previously, the \var{final-block} is executed
417once the code block is complete and any raised exceptions handled.
418Even if there's an error in an exception handler or the
419\var{else-block} and a new exception is raised, the
420code in the \var{final-block} is still run.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000421
422\begin{seealso}
423
424\seepep{341}{Unifying try-except and try-finally}{PEP written by Georg Brandl;
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000425implementation by Thomas Lee.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000426
427\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000428
429
430%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000431\section{PEP 342: New Generator Features\label{pep-342}}
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000432
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000433Python 2.5 adds a simple way to pass values \emph{into} a generator.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000434As introduced in Python 2.3, generators only produce output; once a
Andrew M. Kuchling1e9f5742006-05-20 19:25:16 +0000435generator's code was invoked to create an iterator, there was no way to
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000436pass any new information into the function when its execution is
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000437resumed. Sometimes the ability to pass in some information would be
438useful. Hackish solutions to this include making the generator's code
439look at a global variable and then changing the global variable's
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000440value, or passing in some mutable object that callers then modify.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000441
442To refresh your memory of basic generators, here's a simple example:
443
444\begin{verbatim}
445def counter (maximum):
446 i = 0
447 while i < maximum:
448 yield i
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000449 i += 1
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000450\end{verbatim}
451
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000452When you call \code{counter(10)}, the result is an iterator that
453returns the values from 0 up to 9. On encountering the
454\keyword{yield} statement, the iterator returns the provided value and
455suspends the function's execution, preserving the local variables.
456Execution resumes on the following call to the iterator's
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000457\method{next()} method, picking up after the \keyword{yield} statement.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000458
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000459In Python 2.3, \keyword{yield} was a statement; it didn't return any
460value. In 2.5, \keyword{yield} is now an expression, returning a
461value that can be assigned to a variable or otherwise operated on:
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000462
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000463\begin{verbatim}
464val = (yield i)
465\end{verbatim}
466
467I recommend that you always put parentheses around a \keyword{yield}
468expression when you're doing something with the returned value, as in
469the above example. The parentheses aren't always necessary, but it's
470easier to always add them instead of having to remember when they're
Andrew M. Kuchling3b675d22006-04-20 13:43:21 +0000471needed.
472
473(\pep{342} explains the exact rules, which are that a
474\keyword{yield}-expression must always be parenthesized except when it
475occurs at the top-level expression on the right-hand side of an
476assignment. This means you can write \code{val = yield i} but have to
477use parentheses when there's an operation, as in \code{val = (yield i)
478+ 12}.)
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000479
480Values are sent into a generator by calling its
481\method{send(\var{value})} method. The generator's code is then
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000482resumed and the \keyword{yield} expression returns the specified
483\var{value}. If the regular \method{next()} method is called, the
484\keyword{yield} returns \constant{None}.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000485
486Here's the previous example, modified to allow changing the value of
487the internal counter.
488
489\begin{verbatim}
490def counter (maximum):
491 i = 0
492 while i < maximum:
493 val = (yield i)
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000494 # If value provided, change counter
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000495 if val is not None:
496 i = val
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000497 else:
498 i += 1
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000499\end{verbatim}
500
501And here's an example of changing the counter:
502
503\begin{verbatim}
504>>> it = counter(10)
505>>> print it.next()
5060
507>>> print it.next()
5081
509>>> print it.send(8)
5108
511>>> print it.next()
5129
513>>> print it.next()
514Traceback (most recent call last):
515 File ``t.py'', line 15, in ?
516 print it.next()
517StopIteration
Andrew M. Kuchlingc2033702005-08-29 13:30:12 +0000518\end{verbatim}
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000519
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000520Because \keyword{yield} will often be returning \constant{None}, you
521should always check for this case. Don't just use its value in
522expressions unless you're sure that the \method{send()} method
523will be the only method used resume your generator function.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000524
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000525In addition to \method{send()}, there are two other new methods on
526generators:
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000527
528\begin{itemize}
529
530 \item \method{throw(\var{type}, \var{value}=None,
531 \var{traceback}=None)} is used to raise an exception inside the
532 generator; the exception is raised by the \keyword{yield} expression
533 where the generator's execution is paused.
534
535 \item \method{close()} raises a new \exception{GeneratorExit}
536 exception inside the generator to terminate the iteration.
537 On receiving this
538 exception, the generator's code must either raise
539 \exception{GeneratorExit} or \exception{StopIteration}; catching the
540 exception and doing anything else is illegal and will trigger
541 a \exception{RuntimeError}. \method{close()} will also be called by
Andrew M. Kuchling3cdf24b2006-05-25 00:23:03 +0000542 Python's garbage collector when the generator is garbage-collected.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000543
Andrew M. Kuchling3cdf24b2006-05-25 00:23:03 +0000544 If you need to run cleanup code when a \exception{GeneratorExit} occurs,
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000545 I suggest using a \code{try: ... finally:} suite instead of
546 catching \exception{GeneratorExit}.
547
548\end{itemize}
549
550The cumulative effect of these changes is to turn generators from
551one-way producers of information into both producers and consumers.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000552
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000553Generators also become \emph{coroutines}, a more generalized form of
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000554subroutines. Subroutines are entered at one point and exited at
Andrew M. Kuchling1e9f5742006-05-20 19:25:16 +0000555another point (the top of the function, and a \keyword{return}
556statement), but coroutines can be entered, exited, and resumed at
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000557many different points (the \keyword{yield} statements). We'll have to
558figure out patterns for using coroutines effectively in Python.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000559
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000560The addition of the \method{close()} method has one side effect that
561isn't obvious. \method{close()} is called when a generator is
562garbage-collected, so this means the generator's code gets one last
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +0000563chance to run before the generator is destroyed. This last chance
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000564means that \code{try...finally} statements in generators can now be
565guaranteed to work; the \keyword{finally} clause will now always get a
566chance to run. The syntactic restriction that you couldn't mix
567\keyword{yield} statements with a \code{try...finally} suite has
568therefore been removed. This seems like a minor bit of language
569trivia, but using generators and \code{try...finally} is actually
570necessary in order to implement the \keyword{with} statement
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000571described by PEP 343. I'll look at this new statement in the following
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000572section.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000573
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +0000574Another even more esoteric effect of this change: previously, the
575\member{gi_frame} attribute of a generator was always a frame object.
576It's now possible for \member{gi_frame} to be \code{None}
577once the generator has been exhausted.
578
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000579\begin{seealso}
580
581\seepep{342}{Coroutines via Enhanced Generators}{PEP written by
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000582Guido van~Rossum and Phillip J. Eby;
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000583implemented by Phillip J. Eby. Includes examples of
584some fancier uses of generators as coroutines.}
585
586\seeurl{http://en.wikipedia.org/wiki/Coroutine}{The Wikipedia entry for
587coroutines.}
588
Neal Norwitz09179882006-03-04 23:31:45 +0000589\seeurl{http://www.sidhe.org/\~{}dan/blog/archives/000178.html}{An
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000590explanation of coroutines from a Perl point of view, written by Dan
591Sugalski.}
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000592
593\end{seealso}
594
595
596%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000597\section{PEP 343: The 'with' statement\label{pep-343}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000598
Andrew M. Kuchling0a7ed8c2006-04-24 14:30:47 +0000599The '\keyword{with}' statement clarifies code that previously would
600use \code{try...finally} blocks to ensure that clean-up code is
601executed. In this section, I'll discuss the statement as it will
602commonly be used. In the next section, I'll examine the
603implementation details and show how to write objects for use with this
604statement.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000605
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +0000606The '\keyword{with}' statement is a new control-flow structure whose
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000607basic structure is:
608
609\begin{verbatim}
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000610with expression [as variable]:
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000611 with-block
612\end{verbatim}
613
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000614The expression is evaluated, and it should result in an object that
615supports the context management protocol. This object may return a
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000616value that can optionally be bound to the name \var{variable}. (Note
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000617carefully that \var{variable} is \emph{not} assigned the result of
618\var{expression}.) The object can then run set-up code
619before \var{with-block} is executed and some clean-up code
620is executed after the block is done, even if the block raised an exception.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000621
622To enable the statement in Python 2.5, you need
623to add the following directive to your module:
624
625\begin{verbatim}
626from __future__ import with_statement
627\end{verbatim}
628
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000629The statement will always be enabled in Python 2.6.
630
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000631Some standard Python objects now support the context management
632protocol and can be used with the '\keyword{with}' statement. File
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000633objects are one example:
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000634
635\begin{verbatim}
636with open('/etc/passwd', 'r') as f:
637 for line in f:
638 print line
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000639 ... more processing code ...
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000640\end{verbatim}
641
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000642After this statement has executed, the file object in \var{f} will
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +0000643have been automatically closed, even if the 'for' loop
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000644raised an exception part-way through the block.
645
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000646The \module{threading} module's locks and condition variables
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +0000647also support the '\keyword{with}' statement:
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000648
649\begin{verbatim}
650lock = threading.Lock()
651with lock:
652 # Critical section of code
653 ...
654\end{verbatim}
655
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000656The lock is acquired before the block is executed and always released once
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000657the block is complete.
658
659The \module{decimal} module's contexts, which encapsulate the desired
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000660precision and rounding characteristics for computations, provide a
661\method{context_manager()} method for getting a context manager:
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000662
663\begin{verbatim}
664import decimal
665
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000666# Displays with default precision of 28 digits
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000667v1 = decimal.Decimal('578')
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000668print v1.sqrt()
669
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000670ctx = decimal.Context(prec=16)
671with ctx.context_manager():
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000672 # All code in this block uses a precision of 16 digits.
673 # The original context is restored on exiting the block.
674 print v1.sqrt()
675\end{verbatim}
676
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000677\subsection{Writing Context Managers\label{context-managers}}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000678
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +0000679Under the hood, the '\keyword{with}' statement is fairly complicated.
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000680Most people will only use '\keyword{with}' in company with existing
Andrew M. Kuchling0a7ed8c2006-04-24 14:30:47 +0000681objects and don't need to know these details, so you can skip the rest
682of this section if you like. Authors of new objects will need to
683understand the details of the underlying implementation and should
684keep reading.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000685
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000686A high-level explanation of the context management protocol is:
687
688\begin{itemize}
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000689
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000690\item The expression is evaluated and should result in an object
691called a ``context manager''. The context manager must have
Andrew M. Kuchling0a7ed8c2006-04-24 14:30:47 +0000692\method{__enter__()} and \method{__exit__()} methods.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000693
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000694\item The context manager's \method{__enter__()} method is called. The value
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000695returned is assigned to \var{VAR}. If no \code{'as \var{VAR}'} clause
696is present, the value is simply discarded.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000697
698\item The code in \var{BLOCK} is executed.
699
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000700\item If \var{BLOCK} raises an exception, the
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000701\method{__exit__(\var{type}, \var{value}, \var{traceback})} is called
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000702with the exception details, the same values returned by
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000703\function{sys.exc_info()}. The method's return value controls whether
704the exception is re-raised: any false value re-raises the exception,
705and \code{True} will result in suppressing it. You'll only rarely
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000706want to suppress the exception, because if you do
707the author of the code containing the
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000708'\keyword{with}' statement will never realize anything went wrong.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000709
710\item If \var{BLOCK} didn't raise an exception,
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000711the \method{__exit__()} method is still called,
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000712but \var{type}, \var{value}, and \var{traceback} are all \code{None}.
713
714\end{itemize}
715
716Let's think through an example. I won't present detailed code but
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000717will only sketch the methods necessary for a database that supports
718transactions.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000719
720(For people unfamiliar with database terminology: a set of changes to
721the database are grouped into a transaction. Transactions can be
722either committed, meaning that all the changes are written into the
723database, or rolled back, meaning that the changes are all discarded
724and the database is unchanged. See any database textbook for more
725information.)
726% XXX find a shorter reference?
727
728Let's assume there's an object representing a database connection.
729Our goal will be to let the user write code like this:
730
731\begin{verbatim}
732db_connection = DatabaseConnection()
733with db_connection as cursor:
734 cursor.execute('insert into ...')
735 cursor.execute('delete from ...')
736 # ... more operations ...
737\end{verbatim}
738
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000739The transaction should be committed if the code in the block
740runs flawlessly or rolled back if there's an exception.
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000741Here's the basic interface
742for \class{DatabaseConnection} that I'll assume:
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000743
744\begin{verbatim}
745class DatabaseConnection:
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000746 # Database interface
747 def cursor (self):
748 "Returns a cursor object and starts a new transaction"
749 def commit (self):
750 "Commits current transaction"
751 def rollback (self):
752 "Rolls back current transaction"
753\end{verbatim}
754
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000755The \method {__enter__()} method is pretty easy, having only to start
756a new transaction. For this application the resulting cursor object
757would be a useful result, so the method will return it. The user can
758then add \code{as cursor} to their '\keyword{with}' statement to bind
759the cursor to a variable name.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000760
761\begin{verbatim}
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000762class DatabaseConnection:
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000763 ...
764 def __enter__ (self):
765 # Code to start a new transaction
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000766 cursor = self.cursor()
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000767 return cursor
768\end{verbatim}
769
770The \method{__exit__()} method is the most complicated because it's
771where most of the work has to be done. The method has to check if an
772exception occurred. If there was no exception, the transaction is
773committed. The transaction is rolled back if there was an exception.
Andrew M. Kuchling0a7ed8c2006-04-24 14:30:47 +0000774
775In the code below, execution will just fall off the end of the
776function, returning the default value of \code{None}. \code{None} is
777false, so the exception will be re-raised automatically. If you
778wished, you could be more explicit and add a \keyword{return}
779statement at the marked location.
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000780
781\begin{verbatim}
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000782class DatabaseConnection:
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000783 ...
784 def __exit__ (self, type, value, tb):
785 if tb is None:
786 # No exception, so commit
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000787 self.commit()
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000788 else:
789 # Exception occurred, so rollback.
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000790 self.rollback()
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000791 # return False
792\end{verbatim}
793
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000794
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000795\subsection{The contextlib module\label{module-contextlib}}
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000796
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000797The new \module{contextlib} module provides some functions and a
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000798decorator that are useful for writing objects for use with the
799'\keyword{with}' statement.
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000800
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000801The decorator is called \function{contextfactory}, and lets you write
802a single generator function instead of defining a new class. The generator
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000803should yield exactly one value. The code up to the \keyword{yield}
804will be executed as the \method{__enter__()} method, and the value
805yielded will be the method's return value that will get bound to the
806variable in the '\keyword{with}' statement's \keyword{as} clause, if
807any. The code after the \keyword{yield} will be executed in the
808\method{__exit__()} method. Any exception raised in the block will be
809raised by the \keyword{yield} statement.
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000810
811Our database example from the previous section could be written
812using this decorator as:
813
814\begin{verbatim}
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000815from contextlib import contextfactory
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000816
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000817@contextfactory
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000818def db_transaction (connection):
819 cursor = connection.cursor()
820 try:
821 yield cursor
822 except:
823 connection.rollback()
824 raise
825 else:
826 connection.commit()
827
828db = DatabaseConnection()
829with db_transaction(db) as cursor:
830 ...
831\end{verbatim}
832
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000833The \module{contextlib} module also has a \function{nested(\var{mgr1},
Andrew M. Kuchlingf322d682006-05-02 22:47:49 +0000834\var{mgr2}, ...)} function that combines a number of context managers so you
Andrew M. Kuchlingd798a182006-04-25 12:47:25 +0000835don't need to write nested '\keyword{with}' statements. In this
836example, the single '\keyword{with}' statement both starts a database
837transaction and acquires a thread lock:
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000838
839\begin{verbatim}
840lock = threading.Lock()
841with nested (db_transaction(db), lock) as (cursor, locked):
842 ...
843\end{verbatim}
844
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000845Finally, the \function{closing(\var{object})} function
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000846returns \var{object} so that it can be bound to a variable,
847and calls \code{\var{object}.close()} at the end of the block.
848
849\begin{verbatim}
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +0000850import urllib, sys
851from contextlib import closing
852
853with closing(urllib.urlopen('http://www.yahoo.com')) as f:
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000854 for line in f:
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +0000855 sys.stdout.write(line)
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000856\end{verbatim}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000857
858\begin{seealso}
859
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000860\seepep{343}{The ``with'' statement}{PEP written by Guido van~Rossum
861and Nick Coghlan; implemented by Mike Bland, Guido van~Rossum, and
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +0000862Neal Norwitz. The PEP shows the code generated for a '\keyword{with}'
Andrew M. Kuchlingedb575e2006-04-23 21:01:04 +0000863statement, which can be helpful in learning how the statement works.}
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000864
865\seeurl{../lib/module-contextlib.html}{The documentation
866for the \module{contextlib} module.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000867
868\end{seealso}
869
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000870
871%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000872\section{PEP 352: Exceptions as New-Style Classes\label{pep-352}}
Andrew M. Kuchling8f4d2552006-03-08 01:50:20 +0000873
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000874Exception classes can now be new-style classes, not just classic
875classes, and the built-in \exception{Exception} class and all the
876standard built-in exceptions (\exception{NameError},
877\exception{ValueError}, etc.) are now new-style classes.
Andrew M. Kuchlingaeadf952006-03-09 19:06:05 +0000878
879The inheritance hierarchy for exceptions has been rearranged a bit.
880In 2.5, the inheritance relationships are:
881
882\begin{verbatim}
883BaseException # New in Python 2.5
884|- KeyboardInterrupt
885|- SystemExit
886|- Exception
887 |- (all other current built-in exceptions)
888\end{verbatim}
889
890This rearrangement was done because people often want to catch all
891exceptions that indicate program errors. \exception{KeyboardInterrupt} and
892\exception{SystemExit} aren't errors, though, and usually represent an explicit
893action such as the user hitting Control-C or code calling
894\function{sys.exit()}. A bare \code{except:} will catch all exceptions,
895so you commonly need to list \exception{KeyboardInterrupt} and
896\exception{SystemExit} in order to re-raise them. The usual pattern is:
897
898\begin{verbatim}
899try:
900 ...
901except (KeyboardInterrupt, SystemExit):
902 raise
903except:
904 # Log error...
905 # Continue running program...
906\end{verbatim}
907
908In Python 2.5, you can now write \code{except Exception} to achieve
909the same result, catching all the exceptions that usually indicate errors
910but leaving \exception{KeyboardInterrupt} and
911\exception{SystemExit} alone. As in previous versions,
912a bare \code{except:} still catches all exceptions.
913
914The goal for Python 3.0 is to require any class raised as an exception
915to derive from \exception{BaseException} or some descendant of
916\exception{BaseException}, and future releases in the
917Python 2.x series may begin to enforce this constraint. Therefore, I
918suggest you begin making all your exception classes derive from
919\exception{Exception} now. It's been suggested that the bare
920\code{except:} form should be removed in Python 3.0, but Guido van~Rossum
921hasn't decided whether to do this or not.
922
923Raising of strings as exceptions, as in the statement \code{raise
924"Error occurred"}, is deprecated in Python 2.5 and will trigger a
925warning. The aim is to be able to remove the string-exception feature
926in a few releases.
927
928
929\begin{seealso}
930
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000931\seepep{352}{Required Superclass for Exceptions}{PEP written by
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000932Brett Cannon and Guido van~Rossum; implemented by Brett Cannon.}
Andrew M. Kuchlingaeadf952006-03-09 19:06:05 +0000933
934\end{seealso}
Andrew M. Kuchling8f4d2552006-03-08 01:50:20 +0000935
936
937%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +0000938\section{PEP 353: Using ssize_t as the index type\label{pep-353}}
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000939
940A wide-ranging change to Python's C API, using a new
941\ctype{Py_ssize_t} type definition instead of \ctype{int},
942will permit the interpreter to handle more data on 64-bit platforms.
943This change doesn't affect Python's capacity on 32-bit platforms.
944
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000945Various pieces of the Python interpreter used C's \ctype{int} type to
946store sizes or counts; for example, the number of items in a list or
947tuple were stored in an \ctype{int}. The C compilers for most 64-bit
948platforms still define \ctype{int} as a 32-bit type, so that meant
949that lists could only hold up to \code{2**31 - 1} = 2147483647 items.
950(There are actually a few different programming models that 64-bit C
951compilers can use -- see
952\url{http://www.unix.org/version2/whatsnew/lp64_wp.html} for a
953discussion -- but the most commonly available model leaves \ctype{int}
954as 32 bits.)
955
956A limit of 2147483647 items doesn't really matter on a 32-bit platform
957because you'll run out of memory before hitting the length limit.
958Each list item requires space for a pointer, which is 4 bytes, plus
959space for a \ctype{PyObject} representing the item. 2147483647*4 is
960already more bytes than a 32-bit address space can contain.
961
962It's possible to address that much memory on a 64-bit platform,
963however. The pointers for a list that size would only require 16GiB
964of space, so it's not unreasonable that Python programmers might
965construct lists that large. Therefore, the Python interpreter had to
966be changed to use some type other than \ctype{int}, and this will be a
96764-bit type on 64-bit platforms. The change will cause
968incompatibilities on 64-bit machines, so it was deemed worth making
969the transition now, while the number of 64-bit users is still
970relatively small. (In 5 or 10 years, we may \emph{all} be on 64-bit
971machines, and the transition would be more painful then.)
972
973This change most strongly affects authors of C extension modules.
974Python strings and container types such as lists and tuples
975now use \ctype{Py_ssize_t} to store their size.
976Functions such as \cfunction{PyList_Size()}
977now return \ctype{Py_ssize_t}. Code in extension modules
978may therefore need to have some variables changed to
979\ctype{Py_ssize_t}.
980
981The \cfunction{PyArg_ParseTuple()} and \cfunction{Py_BuildValue()} functions
982have a new conversion code, \samp{n}, for \ctype{Py_ssize_t}.
Andrew M. Kuchlinga4d651f2006-04-06 13:24:58 +0000983\cfunction{PyArg_ParseTuple()}'s \samp{s\#} and \samp{t\#} still output
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000984\ctype{int} by default, but you can define the macro
985\csimplemacro{PY_SSIZE_T_CLEAN} before including \file{Python.h}
986to make them return \ctype{Py_ssize_t}.
987
988\pep{353} has a section on conversion guidelines that
989extension authors should read to learn about supporting 64-bit
990platforms.
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000991
992\begin{seealso}
993
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +0000994\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 +0000995
996\end{seealso}
997
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000998
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000999%======================================================================
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +00001000\section{PEP 357: The '__index__' method\label{pep-357}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +00001001
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001002The NumPy developers had a problem that could only be solved by adding
1003a new special method, \method{__index__}. When using slice notation,
Fred Drake1c0e3282006-04-02 03:30:06 +00001004as in \code{[\var{start}:\var{stop}:\var{step}]}, the values of the
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001005\var{start}, \var{stop}, and \var{step} indexes must all be either
1006integers or long integers. NumPy defines a variety of specialized
1007integer types corresponding to unsigned and signed integers of 8, 16,
100832, and 64 bits, but there was no way to signal that these types could
1009be used as slice indexes.
1010
1011Slicing can't just use the existing \method{__int__} method because
1012that method is also used to implement coercion to integers. If
1013slicing used \method{__int__}, floating-point numbers would also
1014become legal slice indexes and that's clearly an undesirable
1015behaviour.
1016
1017Instead, a new special method called \method{__index__} was added. It
1018takes no arguments and returns an integer giving the slice index to
1019use. For example:
1020
1021\begin{verbatim}
1022class C:
1023 def __index__ (self):
1024 return self.value
1025\end{verbatim}
1026
1027The return value must be either a Python integer or long integer.
1028The interpreter will check that the type returned is correct, and
1029raises a \exception{TypeError} if this requirement isn't met.
1030
1031A corresponding \member{nb_index} slot was added to the C-level
1032\ctype{PyNumberMethods} structure to let C extensions implement this
1033protocol. \cfunction{PyNumber_Index(\var{obj})} can be used in
1034extension code to call the \method{__index__} function and retrieve
1035its result.
1036
1037\begin{seealso}
1038
1039\seepep{357}{Allowing Any Object to be Used for Slicing}{PEP written
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +00001040and implemented by Travis Oliphant.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001041
1042\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +00001043
1044
1045%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001046\section{Other Language Changes\label{other-lang}}
Fred Drake2db76802004-12-01 05:05:47 +00001047
1048Here are all of the changes that Python 2.5 makes to the core Python
1049language.
1050
1051\begin{itemize}
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001052
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001053\item The \class{dict} type has a new hook for letting subclasses
1054provide a default value when a key isn't contained in the dictionary.
1055When a key isn't found, the dictionary's
1056\method{__missing__(\var{key})}
1057method will be called. This hook is used to implement
1058the new \class{defaultdict} class in the \module{collections}
1059module. The following example defines a dictionary
1060that returns zero for any missing key:
1061
1062\begin{verbatim}
1063class zerodict (dict):
1064 def __missing__ (self, key):
1065 return 0
1066
1067d = zerodict({1:1, 2:2})
1068print d[1], d[2] # Prints 1, 2
1069print d[3], d[4] # Prints 0, 0
1070\end{verbatim}
1071
Andrew M. Kuchlingafe65982006-05-26 18:41:18 +00001072\item Both 8-bit and Unicode strings have new \method{partition(sep)}
1073and \method{rpartition(sep)} methods that simplify a common use case.
Andrew M. Kuchlingad0cb652006-05-26 12:39:48 +00001074The \method{find(S)} method is often used to get an index which is
1075then used to slice the string and obtain the pieces that are before
Andrew M. Kuchlingafe65982006-05-26 18:41:18 +00001076and after the separator.
1077
1078\method{partition(sep)} condenses this
Andrew M. Kuchlingad0cb652006-05-26 12:39:48 +00001079pattern into a single method call that returns a 3-tuple containing
1080the substring before the separator, the separator itself, and the
1081substring after the separator. If the separator isn't found, the
1082first element of the tuple is the entire string and the other two
Andrew M. Kuchlingafe65982006-05-26 18:41:18 +00001083elements are empty. \method{rpartition(sep)} also returns a 3-tuple
1084but starts searching from the end of the string; the \samp{r} stands
1085for 'reverse'.
1086
1087Some examples:
Andrew M. Kuchlingad0cb652006-05-26 12:39:48 +00001088
1089\begin{verbatim}
1090>>> ('http://www.python.org').partition('://')
1091('http', '://', 'www.python.org')
1092>>> (u'Subject: a quick question').partition(':')
1093(u'Subject', u':', u' a quick question')
1094>>> ('file:/usr/share/doc/index.html').partition('://')
1095('file:/usr/share/doc/index.html', '', '')
Andrew M. Kuchlingafe65982006-05-26 18:41:18 +00001096>>> 'www.python.org'.rpartition('.')
1097('www.python', '.', 'org')
Andrew M. Kuchlingad0cb652006-05-26 12:39:48 +00001098\end{verbatim}
1099
1100(Implemented by Fredrik Lundh following a suggestion by Raymond Hettinger.)
1101
Andrew M. Kuchlinga04d1182006-06-09 19:03:16 +00001102\item The \method{startswith()} and \method{endswith()} methods
1103of string types now accept tuples of strings to check for.
1104
1105\begin{verbatim}
1106def is_image_file (filename):
1107 return filename.endswith(('.gif', '.jpg', '.tiff'))
1108\end{verbatim}
1109
1110(Implemented by Georg Brandl following a suggestion by Tom Lynn.)
1111% RFE #1491485
1112
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001113\item The \function{min()} and \function{max()} built-in functions
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001114gained a \code{key} keyword parameter analogous to the \code{key}
1115argument for \method{sort()}. This parameter supplies a function that
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001116takes a single argument and is called for every value in the list;
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001117\function{min()}/\function{max()} will return the element with the
1118smallest/largest return value from this function.
1119For example, to find the longest string in a list, you can do:
1120
1121\begin{verbatim}
1122L = ['medium', 'longest', 'short']
1123# Prints 'longest'
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001124print max(L, key=len)
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001125# Prints 'short', because lexicographically 'short' has the largest value
1126print max(L)
1127\end{verbatim}
1128
1129(Contributed by Steven Bethard and Raymond Hettinger.)
Fred Drake2db76802004-12-01 05:05:47 +00001130
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001131\item Two new built-in functions, \function{any()} and
1132\function{all()}, evaluate whether an iterator contains any true or
1133false values. \function{any()} returns \constant{True} if any value
1134returned by the iterator is true; otherwise it will return
1135\constant{False}. \function{all()} returns \constant{True} only if
1136all of the values returned by the iterator evaluate as being true.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001137(Suggested by GvR, and implemented by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001138
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001139\item ASCII is now the default encoding for modules. It's now
1140a syntax error if a module contains string literals with 8-bit
1141characters but doesn't have an encoding declaration. In Python 2.4
1142this triggered a warning, not a syntax error. See \pep{263}
1143for how to declare a module's encoding; for example, you might add
1144a line like this near the top of the source file:
1145
1146\begin{verbatim}
1147# -*- coding: latin1 -*-
1148\end{verbatim}
1149
Andrew M. Kuchlingc9236112006-04-30 01:07:09 +00001150\item One error that Python programmers sometimes make is forgetting
1151to include an \file{__init__.py} module in a package directory.
1152Debugging this mistake can be confusing, and usually requires running
1153Python with the \programopt{-v} switch to log all the paths searched.
1154In Python 2.5, a new \exception{ImportWarning} warning is raised when
1155an import would have picked up a directory as a package but no
1156\file{__init__.py} was found. (Implemented by Thomas Wouters.)
1157
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001158\item The list of base classes in a class definition can now be empty.
1159As an example, this is now legal:
1160
1161\begin{verbatim}
1162class C():
1163 pass
1164\end{verbatim}
1165(Implemented by Brett Cannon.)
1166
Fred Drake2db76802004-12-01 05:05:47 +00001167\end{itemize}
1168
1169
1170%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001171\subsection{Interactive Interpreter Changes\label{interactive}}
Andrew M. Kuchlingda376042006-03-17 15:56:41 +00001172
1173In the interactive interpreter, \code{quit} and \code{exit}
1174have long been strings so that new users get a somewhat helpful message
1175when they try to quit:
1176
1177\begin{verbatim}
1178>>> quit
1179'Use Ctrl-D (i.e. EOF) to exit.'
1180\end{verbatim}
1181
1182In Python 2.5, \code{quit} and \code{exit} are now objects that still
1183produce string representations of themselves, but are also callable.
1184Newbies who try \code{quit()} or \code{exit()} will now exit the
1185interpreter as they expect. (Implemented by Georg Brandl.)
1186
1187
1188%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001189\subsection{Optimizations\label{opts}}
Fred Drake2db76802004-12-01 05:05:47 +00001190
Andrew M. Kuchlingc6027232006-05-23 12:44:36 +00001191Several of the optimizations were developed at the NeedForSpeed
1192sprint, an event held in Reykjavik, Iceland, from May 21--28 2006.
1193The sprint focused on speed enhancements to the CPython implementation
1194and was funded by EWT LLC with local support from CCP Games. Those
1195optimizations added at this sprint are specially marked in the
1196following list.
1197
Fred Drake2db76802004-12-01 05:05:47 +00001198\begin{itemize}
1199
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001200\item When they were introduced
1201in Python 2.4, the built-in \class{set} and \class{frozenset} types
1202were built on top of Python's dictionary type.
1203In 2.5 the internal data structure has been customized for implementing sets,
1204and as a result sets will use a third less memory and are somewhat faster.
1205(Implemented by Raymond Hettinger.)
Fred Drake2db76802004-12-01 05:05:47 +00001206
Andrew M. Kuchling1985ff72006-06-05 00:08:09 +00001207\item The speed of some Unicode operations, such as finding
1208substrings, string splitting, and character map encoding and decoding,
1209has been improved. (Substring search and splitting improvements were
Andrew M. Kuchling150faff2006-05-23 19:29:38 +00001210added by Fredrik Lundh and Andrew Dalke at the NeedForSpeed
Andrew M. Kuchling1985ff72006-06-05 00:08:09 +00001211sprint. Character maps were improved by Walter D\"orwald and
1212Martin von~L\"owis.)
1213% Patch 1313939, 1359618
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001214
Andrew M. Kuchling3cdf24b2006-05-25 00:23:03 +00001215\item The \function{long(\var{str}, \var{base})} function is now
1216faster on long digit strings because fewer intermediate results are
1217calculated. The peak is for strings of around 800--1000 digits where
1218the function is 6 times faster.
1219(Contributed by Alan McIntyre and committed at the NeedForSpeed sprint.)
1220% Patch 1442927
1221
Andrew M. Kuchling70bd1992006-05-23 19:32:35 +00001222\item The \module{struct} module now compiles structure format
1223strings into an internal representation and caches this
1224representation, yielding a 20\% speedup. (Contributed by Bob Ippolito
1225at the NeedForSpeed sprint.)
1226
Andrew M. Kuchling3b336c72006-06-07 17:03:46 +00001227\item The \module{re} module got a 1 or 2\% speedup by switching to
1228Python's allocator functions instead of the system's
1229\cfunction{malloc()} and \cfunction{free()}.
1230(Contributed by Jack Diederich at the NeedForSpeed sprint.)
1231
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001232\item The code generator's peephole optimizer now performs
1233simple constant folding in expressions. If you write something like
1234\code{a = 2+3}, the code generator will do the arithmetic and produce
1235code corresponding to \code{a = 5}.
1236
Andrew M. Kuchlingc6027232006-05-23 12:44:36 +00001237\item Function calls are now faster because code objects now keep
1238the most recently finished frame (a ``zombie frame'') in an internal
1239field of the code object, reusing it the next time the code object is
1240invoked. (Original patch by Michael Hudson, modified by Armin Rigo
1241and Richard Jones; committed at the NeedForSpeed sprint.)
1242% Patch 876206
1243
Andrew M. Kuchling150faff2006-05-23 19:29:38 +00001244Frame objects are also slightly smaller, which may improve cache locality
1245and reduce memory usage a bit. (Contributed by Neal Norwitz.)
1246% Patch 1337051
1247
Andrew M. Kuchlingdae266e2006-05-27 13:44:37 +00001248\item Python's built-in exceptions are now new-style classes, a change
1249that speeds up instantiation considerably. Exception handling in
1250Python 2.5 is therefore about 30\% faster than in 2.4.
Richard Jones87f54712006-05-27 13:50:42 +00001251(Contributed by Richard Jones, Georg Brandl and Sean Reifschneider at
1252the NeedForSpeed sprint.)
Andrew M. Kuchlingdae266e2006-05-27 13:44:37 +00001253
Andrew M. Kuchlingafe65982006-05-26 18:41:18 +00001254\item Importing now caches the paths tried, recording whether
1255they exist or not so that the interpreter makes fewer
1256\cfunction{open()} and \cfunction{stat()} calls on startup.
1257(Contributed by Martin von~L\"owis and Georg Brandl.)
1258% Patch 921466
1259
Fred Drake2db76802004-12-01 05:05:47 +00001260\end{itemize}
1261
1262The net result of the 2.5 optimizations is that Python 2.5 runs the
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +00001263pystone benchmark around XXX\% faster than Python 2.4.
Fred Drake2db76802004-12-01 05:05:47 +00001264
1265
1266%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001267\section{New, Improved, and Removed Modules\label{modules}}
Fred Drake2db76802004-12-01 05:05:47 +00001268
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +00001269The standard library received many enhancements and bug fixes in
1270Python 2.5. Here's a partial list of the most notable changes, sorted
1271alphabetically by module name. Consult the \file{Misc/NEWS} file in
1272the source tree for a more complete list of changes, or look through
1273the SVN logs for all the details.
Fred Drake2db76802004-12-01 05:05:47 +00001274
1275\begin{itemize}
1276
Andrew M. Kuchling6fc69762006-04-13 12:37:21 +00001277\item The \module{audioop} module now supports the a-LAW encoding,
1278and the code for u-LAW encoding has been improved. (Contributed by
1279Lars Immisch.)
1280
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001281\item The \module{codecs} module gained support for incremental
1282codecs. The \function{codec.lookup()} function now
1283returns a \class{CodecInfo} instance instead of a tuple.
1284\class{CodecInfo} instances behave like a 4-tuple to preserve backward
1285compatibility but also have the attributes \member{encode},
1286\member{decode}, \member{incrementalencoder}, \member{incrementaldecoder},
1287\member{streamwriter}, and \member{streamreader}. Incremental codecs
1288can receive input and produce output in multiple chunks; the output is
1289the same as if the entire input was fed to the non-incremental codec.
1290See the \module{codecs} module documentation for details.
1291(Designed and implemented by Walter D\"orwald.)
1292% Patch 1436130
1293
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001294\item The \module{collections} module gained a new type,
1295\class{defaultdict}, that subclasses the standard \class{dict}
1296type. The new type mostly behaves like a dictionary but constructs a
1297default value when a key isn't present, automatically adding it to the
1298dictionary for the requested key value.
1299
1300The first argument to \class{defaultdict}'s constructor is a factory
1301function that gets called whenever a key is requested but not found.
1302This factory function receives no arguments, so you can use built-in
1303type constructors such as \function{list()} or \function{int()}. For
1304example,
1305you can make an index of words based on their initial letter like this:
1306
1307\begin{verbatim}
1308words = """Nel mezzo del cammin di nostra vita
1309mi ritrovai per una selva oscura
1310che la diritta via era smarrita""".lower().split()
1311
1312index = defaultdict(list)
1313
1314for w in words:
1315 init_letter = w[0]
1316 index[init_letter].append(w)
1317\end{verbatim}
1318
1319Printing \code{index} results in the following output:
1320
1321\begin{verbatim}
1322defaultdict(<type 'list'>, {'c': ['cammin', 'che'], 'e': ['era'],
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001323 'd': ['del', 'di', 'diritta'], 'm': ['mezzo', 'mi'],
1324 'l': ['la'], 'o': ['oscura'], 'n': ['nel', 'nostra'],
1325 'p': ['per'], 's': ['selva', 'smarrita'],
1326 'r': ['ritrovai'], 'u': ['una'], 'v': ['vita', 'via']}
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001327\end{verbatim}
1328
1329The \class{deque} double-ended queue type supplied by the
1330\module{collections} module now has a \method{remove(\var{value})}
1331method that removes the first occurrence of \var{value} in the queue,
1332raising \exception{ValueError} if the value isn't found.
1333
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001334\item New module: The \module{contextlib} module contains helper functions for use
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001335with the new '\keyword{with}' statement. See
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001336section~\ref{module-contextlib} for more about this module.
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +00001337
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001338\item New module: The \module{cProfile} module is a C implementation of
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001339the existing \module{profile} module that has much lower overhead.
1340The module's interface is the same as \module{profile}: you run
1341\code{cProfile.run('main()')} to profile a function, can save profile
1342data to a file, etc. It's not yet known if the Hotshot profiler,
1343which is also written in C but doesn't match the \module{profile}
1344module's interface, will continue to be maintained in future versions
1345of Python. (Contributed by Armin Rigo.)
1346
Andrew M. Kuchling0a7ed8c2006-04-24 14:30:47 +00001347Also, the \module{pstats} module for analyzing the data measured by
1348the profiler now supports directing the output to any file object
Andrew M. Kuchlinge78eeb12006-04-21 13:26:42 +00001349by supplying a \var{stream} argument to the \class{Stats} constructor.
1350(Contributed by Skip Montanaro.)
1351
Andrew M. Kuchling952f1962006-04-18 12:38:19 +00001352\item The \module{csv} module, which parses files in
1353comma-separated value format, received several enhancements and a
1354number of bugfixes. You can now set the maximum size in bytes of a
1355field by calling the \method{csv.field_size_limit(\var{new_limit})}
1356function; omitting the \var{new_limit} argument will return the
1357currently-set limit. The \class{reader} class now has a
1358\member{line_num} attribute that counts the number of physical lines
1359read from the source; records can span multiple physical lines, so
1360\member{line_num} is not the same as the number of records read.
1361(Contributed by Skip Montanaro and Andrew McNamara.)
1362
Andrew M. Kuchling67191312006-04-19 12:55:39 +00001363\item The \class{datetime} class in the \module{datetime}
1364module now has a \method{strptime(\var{string}, \var{format})}
1365method for parsing date strings, contributed by Josh Spoerri.
1366It uses the same format characters as \function{time.strptime()} and
1367\function{time.strftime()}:
1368
1369\begin{verbatim}
1370from datetime import datetime
1371
1372ts = datetime.strptime('10:13:15 2006-03-07',
1373 '%H:%M:%S %Y-%m-%d')
1374\end{verbatim}
1375
Andrew M. Kuchling7259d7b2006-06-14 13:59:15 +00001376\item The \method{SequenceMatcher.get_matching_blocks()} method
1377in the \module{difflib} module now guarantees to return a minimal list
1378of blocks describing matching subsequences. Previously, the algorithm would
1379occasionally break a block of matching elements into two list entries.
1380(Enhancement by Tim Peters.)
1381
Andrew M. Kuchlingb33842a2006-04-25 12:31:38 +00001382\item The \module{doctest} module gained a \code{SKIP} option that
1383keeps an example from being executed at all. This is intended for
1384code snippets that are usage examples intended for the reader and
1385aren't actually test cases.
1386
Andrew M. Kuchling2c4e4622006-06-20 12:15:09 +00001387An \var{encoding} parameter was added to the \function{testfile()}
1388function and the \class{DocFileSuite} class to specify the file's
1389encoding. This makes it easier to use non-ASCII characters in
1390tests contained within a docstring. (Contributed by Bjorn Tillenius.)
1391% Patch 1080727
1392
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001393\item The \module{fileinput} module was made more flexible.
1394Unicode filenames are now supported, and a \var{mode} parameter that
1395defaults to \code{"r"} was added to the
1396\function{input()} function to allow opening files in binary or
1397universal-newline mode. Another new parameter, \var{openhook},
1398lets you use a function other than \function{open()}
1399to open the input files. Once you're iterating over
1400the set of files, the \class{FileInput} object's new
1401\method{fileno()} returns the file descriptor for the currently opened file.
1402(Contributed by Georg Brandl.)
1403
Andrew M. Kuchlingda376042006-03-17 15:56:41 +00001404\item In the \module{gc} module, the new \function{get_count()} function
1405returns a 3-tuple containing the current collection counts for the
1406three GC generations. This is accounting information for the garbage
1407collector; when these counts reach a specified threshold, a garbage
1408collection sweep will be made. The existing \function{gc.collect()}
1409function now takes an optional \var{generation} argument of 0, 1, or 2
1410to specify which generation to collect.
1411
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001412\item The \function{nsmallest()} and
1413\function{nlargest()} functions in the \module{heapq} module
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001414now support a \code{key} keyword parameter similar to the one
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001415provided by the \function{min()}/\function{max()} functions
1416and the \method{sort()} methods. For example:
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001417
1418\begin{verbatim}
1419>>> import heapq
1420>>> L = ["short", 'medium', 'longest', 'longer still']
1421>>> heapq.nsmallest(2, L) # Return two lowest elements, lexicographically
1422['longer still', 'longest']
1423>>> heapq.nsmallest(2, L, key=len) # Return two shortest elements
1424['short', 'medium']
1425\end{verbatim}
1426
1427(Contributed by Raymond Hettinger.)
1428
Andrew M. Kuchling511a3a82005-03-20 19:52:18 +00001429\item The \function{itertools.islice()} function now accepts
1430\code{None} for the start and step arguments. This makes it more
1431compatible with the attributes of slice objects, so that you can now write
1432the following:
1433
1434\begin{verbatim}
1435s = slice(5) # Create slice object
1436itertools.islice(iterable, s.start, s.stop, s.step)
1437\end{verbatim}
1438
1439(Contributed by Raymond Hettinger.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001440
Andrew M. Kuchlingd4c21772006-04-23 21:51:10 +00001441\item The \module{mailbox} module underwent a massive rewrite to add
1442the capability to modify mailboxes in addition to reading them. A new
1443set of classes that include \class{mbox}, \class{MH}, and
1444\class{Maildir} are used to read mailboxes, and have an
1445\method{add(\var{message})} method to add messages,
1446\method{remove(\var{key})} to remove messages, and
1447\method{lock()}/\method{unlock()} to lock/unlock the mailbox. The
1448following example converts a maildir-format mailbox into an mbox-format one:
1449
1450\begin{verbatim}
1451import mailbox
1452
1453# 'factory=None' uses email.Message.Message as the class representing
1454# individual messages.
1455src = mailbox.Maildir('maildir', factory=None)
1456dest = mailbox.mbox('/tmp/mbox')
1457
1458for msg in src:
1459 dest.add(msg)
1460\end{verbatim}
1461
1462(Contributed by Gregory K. Johnson. Funding was provided by Google's
14632005 Summer of Code.)
1464
Andrew M. Kuchling68494882006-05-01 16:32:49 +00001465\item New module: the \module{msilib} module allows creating
1466Microsoft Installer \file{.msi} files and CAB files. Some support
1467for reading the \file{.msi} database is also included.
1468(Contributed by Martin von~L\"owis.)
1469
Andrew M. Kuchling75ba2442006-04-14 10:29:55 +00001470\item The \module{nis} module now supports accessing domains other
1471than the system default domain by supplying a \var{domain} argument to
1472the \function{nis.match()} and \function{nis.maps()} functions.
1473(Contributed by Ben Bell.)
1474
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001475\item The \module{operator} module's \function{itemgetter()}
1476and \function{attrgetter()} functions now support multiple fields.
1477A call such as \code{operator.attrgetter('a', 'b')}
1478will return a function
1479that retrieves the \member{a} and \member{b} attributes. Combining
1480this new feature with the \method{sort()} method's \code{key} parameter
1481lets you easily sort lists using multiple fields.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001482(Contributed by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001483
Andrew M. Kuchlingd4c21772006-04-23 21:51:10 +00001484\item The \module{optparse} module was updated to version 1.5.1 of the
1485Optik library. The \class{OptionParser} class gained an
1486\member{epilog} attribute, a string that will be printed after the
1487help message, and a \method{destroy()} method to break reference
1488cycles created by the object. (Contributed by Greg Ward.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001489
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +00001490\item The \module{os} module underwent several changes. The
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001491\member{stat_float_times} variable now defaults to true, meaning that
1492\function{os.stat()} will now return time values as floats. (This
1493doesn't necessarily mean that \function{os.stat()} will return times
1494that are precise to fractions of a second; not all systems support
1495such precision.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001496
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001497Constants named \member{os.SEEK_SET}, \member{os.SEEK_CUR}, and
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001498\member{os.SEEK_END} have been added; these are the parameters to the
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001499\function{os.lseek()} function. Two new constants for locking are
1500\member{os.O_SHLOCK} and \member{os.O_EXLOCK}.
1501
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001502Two new functions, \function{wait3()} and \function{wait4()}, were
1503added. They're similar the \function{waitpid()} function which waits
1504for a child process to exit and returns a tuple of the process ID and
1505its exit status, but \function{wait3()} and \function{wait4()} return
1506additional information. \function{wait3()} doesn't take a process ID
1507as input, so it waits for any child process to exit and returns a
15083-tuple of \var{process-id}, \var{exit-status}, \var{resource-usage}
1509as returned from the \function{resource.getrusage()} function.
1510\function{wait4(\var{pid})} does take a process ID.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001511(Contributed by Chad J. Schroeder.)
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001512
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001513On FreeBSD, the \function{os.stat()} function now returns
1514times with nanosecond resolution, and the returned object
1515now has \member{st_gen} and \member{st_birthtime}.
1516The \member{st_flags} member is also available, if the platform supports it.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001517(Contributed by Antti Louko and Diego Petten\`o.)
1518% (Patch 1180695, 1212117)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001519
Andrew M. Kuchlingb33842a2006-04-25 12:31:38 +00001520\item The Python debugger provided by the \module{pdb} module
1521can now store lists of commands to execute when a breakpoint is
George Yoshida3bbbc492006-04-25 14:09:58 +00001522reached and execution stops. Once breakpoint \#1 has been created,
Andrew M. Kuchlingb33842a2006-04-25 12:31:38 +00001523enter \samp{commands 1} and enter a series of commands to be executed,
1524finishing the list with \samp{end}. The command list can include
1525commands that resume execution, such as \samp{continue} or
1526\samp{next}. (Contributed by Gr\'egoire Dooms.)
1527% Patch 790710
1528
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001529\item The \module{pickle} and \module{cPickle} modules no
1530longer accept a return value of \code{None} from the
1531\method{__reduce__()} method; the method must return a tuple of
1532arguments instead. The ability to return \code{None} was deprecated
1533in Python 2.4, so this completes the removal of the feature.
1534
Andrew M. Kuchlingaa013da2006-04-29 12:10:43 +00001535\item The \module{pkgutil} module, containing various utility
1536functions for finding packages, was enhanced to support PEP 302's
1537import hooks and now also works for packages stored in ZIP-format archives.
1538(Contributed by Phillip J. Eby.)
1539
Andrew M. Kuchlingc9236112006-04-30 01:07:09 +00001540\item The pybench benchmark suite by Marc-Andr\'e~Lemburg is now
1541included in the \file{Tools/pybench} directory. The pybench suite is
1542an improvement on the commonly used \file{pystone.py} program because
1543pybench provides a more detailed measurement of the interpreter's
Andrew M. Kuchling3e134a52006-05-23 12:49:35 +00001544speed. It times particular operations such as function calls,
Andrew M. Kuchlingc9236112006-04-30 01:07:09 +00001545tuple slicing, method lookups, and numeric operations, instead of
1546performing many different operations and reducing the result to a
1547single number as \file{pystone.py} does.
1548
Andrew M. Kuchling2c4e4622006-06-20 12:15:09 +00001549\item The \module{pyexpat} module now uses version 2.0 of the Expat parser.
1550(Contributed by Trent Mick.)
1551
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001552\item The old \module{regex} and \module{regsub} modules, which have been
1553deprecated ever since Python 2.0, have finally been deleted.
Andrew M. Kuchlingf4b06602006-03-17 15:39:52 +00001554Other deleted modules: \module{statcache}, \module{tzparse},
1555\module{whrandom}.
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001556
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001557\item Also deleted: the \file{lib-old} directory,
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001558which includes ancient modules such as \module{dircmp} and
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00001559\module{ni}, was removed. \file{lib-old} wasn't on the default
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001560\code{sys.path}, so unless your programs explicitly added the directory to
1561\code{sys.path}, this removal shouldn't affect your code.
1562
Andrew M. Kuchling09612282006-04-30 21:19:49 +00001563\item The \module{rlcompleter} module is no longer
1564dependent on importing the \module{readline} module and
1565therefore now works on non-{\UNIX} platforms.
1566(Patch from Robert Kiendl.)
1567% Patch #1472854
1568
Andrew M. Kuchling07cf0722006-05-31 14:12:47 +00001569\item The \module{SimpleXMLRPCServer} and \module{DocXMLRPCServer}
1570classes now have a \member{rpc_paths} attribute that constrains
1571XML-RPC operations to a limited set of URL paths; the default is
1572to allow only \code{'/'} and \code{'/RPC2'}. Setting
1573\member{rpc_paths} to \code{None} or an empty tuple disables
1574this path checking.
1575% Bug #1473048
1576
Andrew M. Kuchling4678dc82006-01-15 16:11:28 +00001577\item The \module{socket} module now supports \constant{AF_NETLINK}
1578sockets on Linux, thanks to a patch from Philippe Biondi.
1579Netlink sockets are a Linux-specific mechanism for communications
1580between a user-space process and kernel code; an introductory
1581article about them is at \url{http://www.linuxjournal.com/article/7356}.
1582In Python code, netlink addresses are represented as a tuple of 2 integers,
1583\code{(\var{pid}, \var{group_mask})}.
1584
Andrew M. Kuchling230c3e12006-05-26 14:03:41 +00001585Two new methods on socket objects, \method{recv_buf(\var{buffer})} and
1586\method{recvfrom_buf(\var{buffer})}, store the received data in an object
1587that supports the buffer protocol instead of returning the data as a
1588string. This means you can put the data directly into an array or a
1589memory-mapped file.
1590
1591Socket objects also gained \method{getfamily()}, \method{gettype()},
1592and \method{getproto()} accessor methods to retrieve the family, type,
1593and protocol values for the socket.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001594
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001595\item New module: the \module{spwd} module provides functions for
1596accessing the shadow password database on systems that support
1597shadow passwords.
Fred Drake2db76802004-12-01 05:05:47 +00001598
Andrew M. Kuchlingc6f5c872006-05-26 14:04:19 +00001599\item The \module{struct} is now faster because it
Andrew M. Kuchling230c3e12006-05-26 14:03:41 +00001600compiles format strings into \class{Struct} objects
1601with \method{pack()} and \method{unpack()} methods. This is similar
1602to how the \module{re} module lets you create compiled regular
1603expression objects. You can still use the module-level
1604\function{pack()} and \function{unpack()} functions; they'll create
1605\class{Struct} objects and cache them. Or you can use
1606\class{Struct} instances directly:
1607
1608\begin{verbatim}
1609s = struct.Struct('ih3s')
1610
1611data = s.pack(1972, 187, 'abc')
1612year, number, name = s.unpack(data)
1613\end{verbatim}
1614
1615You can also pack and unpack data to and from buffer objects directly
1616using the \method{pack_to(\var{buffer}, \var{offset}, \var{v1},
1617\var{v2}, ...)} and \method{unpack_from(\var{buffer}, \var{offset})}
1618methods. This lets you store data directly into an array or a
1619memory-mapped file.
1620
1621(\class{Struct} objects were implemented by Bob Ippolito at the
1622NeedForSpeed sprint. Support for buffer objects was added by Martin
1623Blais, also at the NeedForSpeed sprint.)
1624
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001625\item The Python developers switched from CVS to Subversion during the 2.5
Andrew M. Kuchling230c3e12006-05-26 14:03:41 +00001626development process. Information about the exact build version is
1627available as the \code{sys.subversion} variable, a 3-tuple of
1628\code{(\var{interpreter-name}, \var{branch-name},
1629\var{revision-range})}. For example, at the time of writing my copy
1630of 2.5 was reporting \code{('CPython', 'trunk', '45313:45315')}.
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001631
1632This information is also available to C extensions via the
1633\cfunction{Py_GetBuildInfo()} function that returns a
1634string of build information like this:
1635\code{"trunk:45355:45356M, Apr 13 2006, 07:42:19"}.
1636(Contributed by Barry Warsaw.)
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001637
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001638\item The \class{TarFile} class in the \module{tarfile} module now has
Georg Brandl08c02db2005-07-22 18:39:19 +00001639an \method{extractall()} method that extracts all members from the
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001640archive into the current working directory. It's also possible to set
1641a different directory as the extraction target, and to unpack only a
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001642subset of the archive's members.
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001643
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001644A tarfile's compression can be autodetected by
1645using the mode \code{'r|*'}.
1646% patch 918101
1647(Contributed by Lars Gust\"abel.)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001648
Andrew M. Kuchling317af102006-06-13 16:41:41 +00001649\item The \module{threading} module now lets you set the stack size
1650used when new threads are created. The
1651\function{stack_size(\optional{\var{size}})} function returns the
1652currently configured stack size, and supplying the optional \var{size}
1653parameter sets a new value. Not all platforms support changing the
1654stack size, but Windows, POSIX threading, and OS/2 all do.
1655(Contributed by Andrew MacIntyre.)
1656% Patch 1454481
1657
Andrew M. Kuchlingf688cc52006-03-10 18:50:08 +00001658\item The \module{unicodedata} module has been updated to use version 4.1.0
1659of the Unicode character database. Version 3.2.0 is required
1660by some specifications, so it's still available as
George Yoshidaa2d6c8a2006-05-27 17:09:17 +00001661\member{unicodedata.ucd_3_2_0}.
Andrew M. Kuchlingf688cc52006-03-10 18:50:08 +00001662
Andrew M. Kuchlingaabc5f62006-06-13 11:57:04 +00001663\item New module: the \module{uuid} module generates
1664universally unique identifiers (UUIDs) according to \rfc{4122}. The
1665RFC defines several different UUID versions that are generated from a
1666starting string, from system properties, or purely randomly. This
1667module contains a \class{UUID} class and
1668functions named \function{uuid1()},
1669\function{uuid3()}, \function{uuid4()}, and
1670\function{uuid5()} to generate different versions of UUID. (Version 2 UUIDs
1671are not specified in \rfc{4122} and are not supported by this module.)
1672
1673\begin{verbatim}
1674>>> import uuid
1675>>> # make a UUID based on the host ID and current time
1676>>> uuid.uuid1()
1677UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')
1678
1679>>> # make a UUID using an MD5 hash of a namespace UUID and a name
1680>>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
1681UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')
1682
1683>>> # make a random UUID
1684>>> uuid.uuid4()
1685UUID('16fd2706-8baf-433b-82eb-8c7fada847da')
1686
1687>>> # make a UUID using a SHA-1 hash of a namespace UUID and a name
1688>>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
1689UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')
1690\end{verbatim}
1691
1692(Contributed by Ka-Ping Yee.)
1693
Andrew M. Kuchling2c4e4622006-06-20 12:15:09 +00001694\item The \module{weakref} module's \class{WeakKeyDictionary} and
1695\class{WeakValueDictionary} types gained new methods for iterating
1696over the weak references contained in the dictionary.
1697\method{iterkeyrefs()} and \method{keyrefs()} methods were
1698added to \class{WeakKeyDictionary}, and
1699\method{itervaluerefs()} and \method{valuerefs()} were added to
1700\class{WeakValueDictionary}. (Contributed by Fred L.~Drake, Jr.)
1701
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001702\item The \module{webbrowser} module received a number of
1703enhancements.
1704It's now usable as a script with \code{python -m webbrowser}, taking a
1705URL as the argument; there are a number of switches
1706to control the behaviour (\programopt{-n} for a new browser window,
1707\programopt{-t} for a new tab). New module-level functions,
1708\function{open_new()} and \function{open_new_tab()}, were added
1709to support this. The module's \function{open()} function supports an
1710additional feature, an \var{autoraise} parameter that signals whether
1711to raise the open window when possible. A number of additional
1712browsers were added to the supported list such as Firefox, Opera,
1713Konqueror, and elinks. (Contributed by Oleg Broytmann and George
1714Brandl.)
1715% Patch #754022
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001716
Fredrik Lundh7e0aef02005-12-12 18:54:55 +00001717
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001718\item The \module{xmlrpclib} module now supports returning
1719 \class{datetime} objects for the XML-RPC date type. Supply
1720 \code{use_datetime=True} to the \function{loads()} function
1721 or the \class{Unmarshaller} class to enable this feature.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001722 (Contributed by Skip Montanaro.)
1723% Patch 1120353
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001724
Andrew M. Kuchling2c4e4622006-06-20 12:15:09 +00001725\item The \module{zipfile} module now supports the ZIP64 version of the
1726format, meaning that a .zip archive can now be larger than 4 GiB and
1727can contain individual files larger than 4 GiB. (Contributed by
1728Ronald Oussoren.)
1729% Patch 1446489
1730
Andrew M. Kuchlingd779b352006-05-16 16:11:54 +00001731\item The \module{zlib} module's \class{Compress} and \class{Decompress}
1732objects now support a \method{copy()} method that makes a copy of the
1733object's internal state and returns a new
1734\class{Compress} or \class{Decompress} object.
1735(Contributed by Chris AtLee.)
1736% Patch 1435422
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001737
Fred Drake114b8ca2005-03-21 05:47:11 +00001738\end{itemize}
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001739
Fred Drake2db76802004-12-01 05:05:47 +00001740
1741
1742%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001743\subsection{The ctypes package\label{module-ctypes}}
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001744
1745The \module{ctypes} package, written by Thomas Heller, has been added
1746to the standard library. \module{ctypes} lets you call arbitrary functions
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001747in shared libraries or DLLs. Long-time users may remember the \module{dl} module, which
1748provides 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 +00001749
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001750To load a shared library or DLL, you must create an instance of the
1751\class{CDLL} class and provide the name or path of the shared library
1752or DLL. Once that's done, you can call arbitrary functions
1753by accessing them as attributes of the \class{CDLL} object.
1754
1755\begin{verbatim}
1756import ctypes
1757
1758libc = ctypes.CDLL('libc.so.6')
1759result = libc.printf("Line of output\n")
1760\end{verbatim}
1761
1762Type constructors for the various C types are provided: \function{c_int},
1763\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
1764to change the wrapped value. Python integers and strings will be automatically
1765converted to the corresponding C types, but for other types you
1766must call the correct type constructor. (And I mean \emph{must};
1767getting it wrong will often result in the interpreter crashing
1768with a segmentation fault.)
1769
1770You 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
1771supposed to be immutable; breaking this rule will cause puzzling bugs. When you need a modifiable memory area,
Neal Norwitz5f5a69b2006-04-13 03:41:04 +00001772use \function{create_string_buffer()}:
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001773
1774\begin{verbatim}
1775s = "this is a string"
1776buf = ctypes.create_string_buffer(s)
1777libc.strfry(buf)
1778\end{verbatim}
1779
1780C functions are assumed to return integers, but you can set
1781the \member{restype} attribute of the function object to
1782change this:
1783
1784\begin{verbatim}
1785>>> libc.atof('2.71828')
1786-1783957616
1787>>> libc.atof.restype = ctypes.c_double
1788>>> libc.atof('2.71828')
17892.71828
1790\end{verbatim}
1791
1792\module{ctypes} also provides a wrapper for Python's C API
1793as the \code{ctypes.pythonapi} object. This object does \emph{not}
1794release the global interpreter lock before calling a function, because the lock must be held when calling into the interpreter's code.
1795There's a \class{py_object()} type constructor that will create a
1796\ctype{PyObject *} pointer. A simple usage:
1797
1798\begin{verbatim}
1799import ctypes
1800
1801d = {}
1802ctypes.pythonapi.PyObject_SetItem(ctypes.py_object(d),
1803 ctypes.py_object("abc"), ctypes.py_object(1))
1804# d is now {'abc', 1}.
1805\end{verbatim}
1806
1807Don't forget to use \class{py_object()}; if it's omitted you end
1808up with a segmentation fault.
1809
1810\module{ctypes} has been around for a while, but people still write
1811and distribution hand-coded extension modules because you can't rely on \module{ctypes} being present.
1812Perhaps developers will begin to write
1813Python wrappers atop a library accessed through \module{ctypes} instead
1814of extension modules, now that \module{ctypes} is included with core Python.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001815
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001816\begin{seealso}
1817
1818\seeurl{http://starship.python.net/crew/theller/ctypes/}
1819{The ctypes web page, with a tutorial, reference, and FAQ.}
1820
1821\end{seealso}
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001822
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001823
1824%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001825\subsection{The ElementTree package\label{module-etree}}
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001826
1827A subset of Fredrik Lundh's ElementTree library for processing XML has
Andrew M. Kuchlinge3c958c2006-05-01 12:45:02 +00001828been added to the standard library as \module{xml.etree}. The
Georg Brandlce27a062006-04-11 06:27:12 +00001829available modules are
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001830\module{ElementTree}, \module{ElementPath}, and
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00001831\module{ElementInclude} from ElementTree 1.2.6.
1832The \module{cElementTree} accelerator module is also included.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001833
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001834The rest of this section will provide a brief overview of using
1835ElementTree. Full documentation for ElementTree is available at
1836\url{http://effbot.org/zone/element-index.htm}.
1837
1838ElementTree represents an XML document as a tree of element nodes.
1839The text content of the document is stored as the \member{.text}
1840and \member{.tail} attributes of
1841(This is one of the major differences between ElementTree and
1842the Document Object Model; in the DOM there are many different
1843types of node, including \class{TextNode}.)
1844
1845The most commonly used parsing function is \function{parse()}, that
1846takes either a string (assumed to contain a filename) or a file-like
1847object and returns an \class{ElementTree} instance:
1848
1849\begin{verbatim}
Andrew M. Kuchlinge3c958c2006-05-01 12:45:02 +00001850from xml.etree import ElementTree as ET
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001851
1852tree = ET.parse('ex-1.xml')
1853
1854feed = urllib.urlopen(
1855 'http://planet.python.org/rss10.xml')
1856tree = ET.parse(feed)
1857\end{verbatim}
1858
1859Once you have an \class{ElementTree} instance, you
1860can call its \method{getroot()} method to get the root \class{Element} node.
1861
1862There's also an \function{XML()} function that takes a string literal
1863and returns an \class{Element} node (not an \class{ElementTree}).
1864This function provides a tidy way to incorporate XML fragments,
1865approaching the convenience of an XML literal:
1866
1867\begin{verbatim}
Andrew M. Kuchlinge3c958c2006-05-01 12:45:02 +00001868svg = ET.XML("""<svg width="10px" version="1.0">
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001869 </svg>""")
1870svg.set('height', '320px')
1871svg.append(elem1)
1872\end{verbatim}
1873
1874Each XML element supports some dictionary-like and some list-like
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001875access methods. Dictionary-like operations are used to access attribute
1876values, and list-like operations are used to access child nodes.
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001877
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001878\begin{tableii}{c|l}{code}{Operation}{Result}
1879 \lineii{elem[n]}{Returns n'th child element.}
1880 \lineii{elem[m:n]}{Returns list of m'th through n'th child elements.}
1881 \lineii{len(elem)}{Returns number of child elements.}
Andrew M. Kuchlinge3c958c2006-05-01 12:45:02 +00001882 \lineii{list(elem)}{Returns list of child elements.}
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001883 \lineii{elem.append(elem2)}{Adds \var{elem2} as a child.}
1884 \lineii{elem.insert(index, elem2)}{Inserts \var{elem2} at the specified location.}
1885 \lineii{del elem[n]}{Deletes n'th child element.}
1886 \lineii{elem.keys()}{Returns list of attribute names.}
1887 \lineii{elem.get(name)}{Returns value of attribute \var{name}.}
1888 \lineii{elem.set(name, value)}{Sets new value for attribute \var{name}.}
1889 \lineii{elem.attrib}{Retrieves the dictionary containing attributes.}
1890 \lineii{del elem.attrib[name]}{Deletes attribute \var{name}.}
1891\end{tableii}
1892
1893Comments and processing instructions are also represented as
1894\class{Element} nodes. To check if a node is a comment or processing
1895instructions:
1896
1897\begin{verbatim}
1898if elem.tag is ET.Comment:
1899 ...
1900elif elem.tag is ET.ProcessingInstruction:
1901 ...
1902\end{verbatim}
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001903
1904To generate XML output, you should call the
1905\method{ElementTree.write()} method. Like \function{parse()},
1906it can take either a string or a file-like object:
1907
1908\begin{verbatim}
1909# Encoding is US-ASCII
1910tree.write('output.xml')
1911
1912# Encoding is UTF-8
1913f = open('output.xml', 'w')
Andrew M. Kuchlinga8837012006-05-02 11:30:03 +00001914tree.write(f, encoding='utf-8')
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001915\end{verbatim}
1916
Andrew M. Kuchlinga8837012006-05-02 11:30:03 +00001917(Caution: the default encoding used for output is ASCII. For general
1918XML work, where an element's name may contain arbitrary Unicode
1919characters, ASCII isn't a very useful encoding because it will raise
1920an exception if an element's name contains any characters with values
1921greater than 127. Therefore, it's best to specify a different
1922encoding such as UTF-8 that can handle any Unicode character.)
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001923
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001924This section is only a partial description of the ElementTree interfaces.
1925Please read the package's official documentation for more details.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001926
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001927\begin{seealso}
1928
1929\seeurl{http://effbot.org/zone/element-index.htm}
1930{Official documentation for ElementTree.}
1931
1932
1933\end{seealso}
1934
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001935
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001936%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001937\subsection{The hashlib package\label{module-hashlib}}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001938
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001939A new \module{hashlib} module, written by Gregory P. Smith,
1940has been added to replace the
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001941\module{md5} and \module{sha} modules. \module{hashlib} adds support
1942for additional secure hashes (SHA-224, SHA-256, SHA-384, and SHA-512).
1943When available, the module uses OpenSSL for fast platform optimized
1944implementations of algorithms.
1945
1946The old \module{md5} and \module{sha} modules still exist as wrappers
1947around hashlib to preserve backwards compatibility. The new module's
1948interface is very close to that of the old modules, but not identical.
1949The most significant difference is that the constructor functions
1950for creating new hashing objects are named differently.
1951
1952\begin{verbatim}
1953# Old versions
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001954h = md5.md5()
1955h = md5.new()
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001956
1957# New version
1958h = hashlib.md5()
1959
1960# Old versions
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001961h = sha.sha()
1962h = sha.new()
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001963
1964# New version
1965h = hashlib.sha1()
1966
1967# Hash that weren't previously available
1968h = hashlib.sha224()
1969h = hashlib.sha256()
1970h = hashlib.sha384()
1971h = hashlib.sha512()
1972
1973# Alternative form
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001974h = hashlib.new('md5') # Provide algorithm as a string
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001975\end{verbatim}
1976
1977Once a hash object has been created, its methods are the same as before:
1978\method{update(\var{string})} hashes the specified string into the
1979current digest state, \method{digest()} and \method{hexdigest()}
1980return the digest value as a binary string or a string of hex digits,
1981and \method{copy()} returns a new hashing object with the same digest state.
1982
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001983
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001984%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00001985\subsection{The sqlite3 package\label{module-sqlite}}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001986
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001987The pysqlite module (\url{http://www.pysqlite.org}), a wrapper for the
1988SQLite embedded database, has been added to the standard library under
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001989the package name \module{sqlite3}.
1990
1991SQLite is a C library that provides a SQL-language database that
1992stores data in disk files without requiring a separate server process.
1993pysqlite was written by Gerhard H\"aring and provides a SQL interface
1994compliant with the DB-API 2.0 specification described by
1995\pep{249}. This means that it should be possible to write the first
1996version of your applications using SQLite for data storage. If
1997switching to a larger database such as PostgreSQL or Oracle is
1998later necessary, the switch should be relatively easy.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001999
2000If you're compiling the Python source yourself, note that the source
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00002001tree doesn't include the SQLite code, only the wrapper module.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00002002You'll need to have the SQLite libraries and headers installed before
2003compiling Python, and the build process will compile the module when
2004the necessary headers are available.
2005
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00002006To use the module, you must first create a \class{Connection} object
2007that represents the database. Here the data will be stored in the
2008\file{/tmp/example} file:
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00002009
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00002010\begin{verbatim}
2011conn = sqlite3.connect('/tmp/example')
2012\end{verbatim}
2013
2014You can also supply the special name \samp{:memory:} to create
2015a database in RAM.
2016
2017Once you have a \class{Connection}, you can create a \class{Cursor}
2018object and call its \method{execute()} method to perform SQL commands:
2019
2020\begin{verbatim}
2021c = conn.cursor()
2022
2023# Create table
2024c.execute('''create table stocks
2025(date timestamp, trans varchar, symbol varchar,
2026 qty decimal, price decimal)''')
2027
2028# Insert a row of data
2029c.execute("""insert into stocks
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00002030 values ('2006-01-05','BUY','RHAT',100,35.14)""")
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00002031\end{verbatim}
2032
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00002033Usually your SQL operations will need to use values from Python
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00002034variables. You shouldn't assemble your query using Python's string
2035operations because doing so is insecure; it makes your program
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00002036vulnerable to an SQL injection attack.
2037
Andrew M. Kuchling1271f002006-06-07 17:02:52 +00002038Instead, use the DB-API's parameter substitution. Put \samp{?} as a
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00002039placeholder wherever you want to use a value, and then provide a tuple
2040of values as the second argument to the cursor's \method{execute()}
Andrew M. Kuchling1271f002006-06-07 17:02:52 +00002041method. (Other database modules may use a different placeholder,
Andrew M. Kuchling3b336c72006-06-07 17:03:46 +00002042such as \samp{\%s} or \samp{:1}.) For example:
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00002043
2044\begin{verbatim}
2045# Never do this -- insecure!
2046symbol = 'IBM'
2047c.execute("... where symbol = '%s'" % symbol)
2048
2049# Do this instead
2050t = (symbol,)
Andrew M. Kuchling7e5abb92006-04-26 12:21:06 +00002051c.execute('select * from stocks where symbol=?', t)
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00002052
2053# Larger example
2054for t in (('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00002055 ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
2056 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
2057 ):
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00002058 c.execute('insert into stocks values (?,?,?,?,?)', t)
2059\end{verbatim}
2060
2061To retrieve data after executing a SELECT statement, you can either
2062treat the cursor as an iterator, call the cursor's \method{fetchone()}
2063method to retrieve a single matching row,
2064or call \method{fetchall()} to get a list of the matching rows.
2065
2066This example uses the iterator form:
2067
2068\begin{verbatim}
2069>>> c = conn.cursor()
2070>>> c.execute('select * from stocks order by price')
2071>>> for row in c:
2072... print row
2073...
2074(u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001)
2075(u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
2076(u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
2077(u'2006-04-05', u'BUY', u'MSOFT', 1000, 72.0)
2078>>>
2079\end{verbatim}
2080
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00002081For more information about the SQL dialect supported by SQLite, see
2082\url{http://www.sqlite.org}.
2083
2084\begin{seealso}
2085
2086\seeurl{http://www.pysqlite.org}
2087{The pysqlite web page.}
2088
2089\seeurl{http://www.sqlite.org}
2090{The SQLite web page; the documentation describes the syntax and the
2091available data types for the supported SQL dialect.}
2092
2093\seepep{249}{Database API Specification 2.0}{PEP written by
2094Marc-Andr\'e Lemburg.}
2095
2096\end{seealso}
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00002097
Fred Drake2db76802004-12-01 05:05:47 +00002098
Andrew M. Kuchlinga04d1182006-06-09 19:03:16 +00002099%======================================================================
Andrew M. Kuchlingf6856ce2006-06-20 11:52:16 +00002100\subsection{The wsgiref package\label{module-wsgiref}}
Andrew M. Kuchlinga04d1182006-06-09 19:03:16 +00002101
Andrew M. Kuchlingb3f29852006-06-09 19:56:05 +00002102% XXX should this be in a PEP 333 section instead?
Andrew M. Kuchlingb3f29852006-06-09 19:56:05 +00002103
2104The Web Server Gateway Interface (WSGI) v1.0 defines a standard
2105interface between web servers and Python web applications and is
2106described in \pep{333}. The \module{wsgiref} package is a reference
2107implementation of the WSGI specification.
2108
2109The package includes a basic HTTP server that will run a WSGI
2110application; this server is useful for debugging but isn't intended for
Andrew M. Kuchlingf6856ce2006-06-20 11:52:16 +00002111production use. Setting up a server takes only a few lines of code:
Andrew M. Kuchlingb3f29852006-06-09 19:56:05 +00002112
2113\begin{verbatim}
2114from wsgiref import simple_server
2115
2116wsgi_app = ...
2117
2118host = ''
2119port = 8000
2120httpd = make_server(host, port, wsgi_app)
2121httpd.serve_forever()
2122\end{verbatim}
2123
Andrew M. Kuchlingf6856ce2006-06-20 11:52:16 +00002124% XXX discuss structure of WSGI applications?
2125% XXX provide an example using Django or some other framework?
Andrew M. Kuchlingb3f29852006-06-09 19:56:05 +00002126
2127\begin{seealso}
2128
Andrew M. Kuchlingf6856ce2006-06-20 11:52:16 +00002129\seeurl{http://www.wsgi.org}{A central web site for WSGI-related resources.}
2130
Andrew M. Kuchlingb3f29852006-06-09 19:56:05 +00002131\seepep{333}{Python Web Server Gateway Interface v1.0}{PEP written by
2132Phillip J. Eby.}
2133
2134\end{seealso}
2135
2136
Fred Drake2db76802004-12-01 05:05:47 +00002137% ======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00002138\section{Build and C API Changes\label{build-api}}
Fred Drake2db76802004-12-01 05:05:47 +00002139
2140Changes to Python's build process and to the C API include:
2141
2142\begin{itemize}
2143
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00002144\item The largest change to the C API came from \pep{353},
2145which modifies the interpreter to use a \ctype{Py_ssize_t} type
2146definition instead of \ctype{int}. See the earlier
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +00002147section~\ref{pep-353} for a discussion of this change.
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00002148
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00002149\item The design of the bytecode compiler has changed a great deal, to
2150no longer generate bytecode by traversing the parse tree. Instead
Andrew M. Kuchlingdb85ed52005-10-23 21:52:59 +00002151the parse tree is converted to an abstract syntax tree (or AST), and it is
2152the abstract syntax tree that's traversed to produce the bytecode.
2153
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00002154It's possible for Python code to obtain AST objects by using the
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00002155\function{compile()} built-in and specifying \code{_ast.PyCF_ONLY_AST}
2156as the value of the
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00002157\var{flags} parameter:
2158
2159\begin{verbatim}
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00002160from _ast import PyCF_ONLY_AST
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00002161ast = compile("""a=0
2162for i in range(10):
2163 a += i
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00002164""", "<string>", 'exec', PyCF_ONLY_AST)
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00002165
2166assignment = ast.body[0]
2167for_loop = ast.body[1]
2168\end{verbatim}
2169
Andrew M. Kuchlingdb85ed52005-10-23 21:52:59 +00002170No documentation has been written for the AST code yet. To start
2171learning about it, read the definition of the various AST nodes in
2172\file{Parser/Python.asdl}. A Python script reads this file and
2173generates a set of C structure definitions in
2174\file{Include/Python-ast.h}. The \cfunction{PyParser_ASTFromString()}
2175and \cfunction{PyParser_ASTFromFile()}, defined in
2176\file{Include/pythonrun.h}, take Python source as input and return the
2177root of an AST representing the contents. This AST can then be turned
2178into a code object by \cfunction{PyAST_Compile()}. For more
2179information, read the source code, and then ask questions on
2180python-dev.
2181
2182% List of names taken from Jeremy's python-dev post at
2183% http://mail.python.org/pipermail/python-dev/2005-October/057500.html
2184The AST code was developed under Jeremy Hylton's management, and
2185implemented by (in alphabetical order) Brett Cannon, Nick Coghlan,
2186Grant Edwards, John Ehresman, Kurt Kaiser, Neal Norwitz, Tim Peters,
2187Armin Rigo, and Neil Schemenauer, plus the participants in a number of
2188AST sprints at conferences such as PyCon.
2189
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00002190\item The built-in set types now have an official C API. Call
2191\cfunction{PySet_New()} and \cfunction{PyFrozenSet_New()} to create a
2192new set, \cfunction{PySet_Add()} and \cfunction{PySet_Discard()} to
2193add and remove elements, and \cfunction{PySet_Contains} and
2194\cfunction{PySet_Size} to examine the set's state.
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00002195(Contributed by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00002196
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00002197\item C code can now obtain information about the exact revision
2198of the Python interpreter by calling the
2199\cfunction{Py_GetBuildInfo()} function that returns a
2200string of build information like this:
2201\code{"trunk:45355:45356M, Apr 13 2006, 07:42:19"}.
2202(Contributed by Barry Warsaw.)
2203
Andrew M. Kuchlingb98d65c2006-05-27 11:26:33 +00002204\item Two new macros can be used to indicate C functions that are
2205local to the current file so that a faster calling convention can be
2206used. \cfunction{Py_LOCAL(\var{type})} declares the function as
2207returning a value of the specified \var{type} and uses a fast-calling
2208qualifier. \cfunction{Py_LOCAL_INLINE(\var{type})} does the same thing
2209and also requests the function be inlined. If
2210\cfunction{PY_LOCAL_AGGRESSIVE} is defined before \file{python.h} is
2211included, a set of more aggressive optimizations are enabled for the
2212module; you should benchmark the results to find out if these
2213optimizations actually make the code faster. (Contributed by Fredrik
2214Lundh at the NeedForSpeed sprint.)
2215
Andrew M. Kuchlingc6027232006-05-23 12:44:36 +00002216\item \cfunction{PyErr_NewException(\var{name}, \var{base},
2217\var{dict})} can now accept a tuple of base classes as its \var{base}
2218argument. (Contributed by Georg Brandl.)
2219
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00002220\item The CPython interpreter is still written in C, but
2221the code can now be compiled with a {\Cpp} compiler without errors.
2222(Implemented by Anthony Baxter, Martin von~L\"owis, Skip Montanaro.)
2223
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00002224\item The \cfunction{PyRange_New()} function was removed. It was
2225never documented, never used in the core code, and had dangerously lax
2226error checking.
Fred Drake2db76802004-12-01 05:05:47 +00002227
2228\end{itemize}
2229
2230
2231%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00002232\subsection{Port-Specific Changes\label{ports}}
Fred Drake2db76802004-12-01 05:05:47 +00002233
Andrew M. Kuchling6fc69762006-04-13 12:37:21 +00002234\begin{itemize}
2235
2236\item MacOS X (10.3 and higher): dynamic loading of modules
2237now uses the \cfunction{dlopen()} function instead of MacOS-specific
2238functions.
2239
Andrew M. Kuchlingb37bcb52006-04-29 11:53:15 +00002240\item MacOS X: a \longprogramopt{enable-universalsdk} switch was added
2241to the \program{configure} script that compiles the interpreter as a
2242universal binary able to run on both PowerPC and Intel processors.
2243(Contributed by Ronald Oussoren.)
2244
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00002245\item Windows: \file{.dll} is no longer supported as a filename extension for
2246extension modules. \file{.pyd} is now the only filename extension that will
2247be searched for.
2248
Andrew M. Kuchling6fc69762006-04-13 12:37:21 +00002249\end{itemize}
Fred Drake2db76802004-12-01 05:05:47 +00002250
2251
2252%======================================================================
2253\section{Other Changes and Fixes \label{section-other}}
2254
2255As usual, there were a bunch of other improvements and bugfixes
Andrew M. Kuchlingf688cc52006-03-10 18:50:08 +00002256scattered throughout the source tree. A search through the SVN change
Fred Drake2db76802004-12-01 05:05:47 +00002257logs finds there were XXX patches applied and YYY bugs fixed between
Andrew M. Kuchling92e24952004-12-03 13:54:09 +00002258Python 2.4 and 2.5. Both figures are likely to be underestimates.
Fred Drake2db76802004-12-01 05:05:47 +00002259
2260Some of the more notable changes are:
2261
2262\begin{itemize}
2263
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00002264\item Evan Jones's patch to obmalloc, first described in a talk
2265at PyCon DC 2005, was applied. Python 2.4 allocated small objects in
2266256K-sized arenas, but never freed arenas. With this patch, Python
2267will free arenas when they're empty. The net effect is that on some
2268platforms, when you allocate many objects, Python's memory usage may
2269actually drop when you delete them, and the memory may be returned to
2270the operating system. (Implemented by Evan Jones, and reworked by Tim
2271Peters.)
Fred Drake2db76802004-12-01 05:05:47 +00002272
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00002273Note that this change means extension modules need to be more careful
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +00002274with how they allocate memory. Python's API has many different
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00002275functions for allocating memory that are grouped into families. For
2276example, \cfunction{PyMem_Malloc()}, \cfunction{PyMem_Realloc()}, and
2277\cfunction{PyMem_Free()} are one family that allocates raw memory,
2278while \cfunction{PyObject_Malloc()}, \cfunction{PyObject_Realloc()},
2279and \cfunction{PyObject_Free()} are another family that's supposed to
2280be used for creating Python objects.
2281
2282Previously these different families all reduced to the platform's
2283\cfunction{malloc()} and \cfunction{free()} functions. This meant
2284it didn't matter if you got things wrong and allocated memory with the
2285\cfunction{PyMem} function but freed it with the \cfunction{PyObject}
2286function. With the obmalloc change, these families now do different
2287things, and mismatches will probably result in a segfault. You should
2288carefully test your C extension modules with Python 2.5.
2289
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00002290\item Coverity, a company that markets a source code analysis tool
2291 called Prevent, provided the results of their examination of the Python
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +00002292 source code. The analysis found about 60 bugs that
2293 were quickly fixed. Many of the bugs were refcounting problems, often
2294 occurring in error-handling code. See
2295 \url{http://scan.coverity.com} for the statistics.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00002296
Fred Drake2db76802004-12-01 05:05:47 +00002297\end{itemize}
2298
2299
2300%======================================================================
Andrew M. Kuchling98189242006-04-26 12:23:39 +00002301\section{Porting to Python 2.5\label{porting}}
Fred Drake2db76802004-12-01 05:05:47 +00002302
2303This section lists previously described changes that may require
2304changes to your code:
2305
2306\begin{itemize}
2307
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00002308\item ASCII is now the default encoding for modules. It's now
2309a syntax error if a module contains string literals with 8-bit
2310characters but doesn't have an encoding declaration. In Python 2.4
2311this triggered a warning, not a syntax error.
2312
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +00002313\item Previously, the \member{gi_frame} attribute of a generator
2314was always a frame object. Because of the \pep{342} changes
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +00002315described in section~\ref{pep-342}, it's now possible
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +00002316for \member{gi_frame} to be \code{None}.
2317
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00002318
2319\item Library: The \module{pickle} and \module{cPickle} modules no
2320longer accept a return value of \code{None} from the
2321\method{__reduce__()} method; the method must return a tuple of
2322arguments instead. The modules also no longer accept the deprecated
2323\var{bin} keyword parameter.
2324
Andrew M. Kuchling07cf0722006-05-31 14:12:47 +00002325\item Library: The \module{SimpleXMLRPCServer} and \module{DocXMLRPCServer}
2326classes now have a \member{rpc_paths} attribute that constrains
2327XML-RPC operations to a limited set of URL paths; the default is
2328to allow only \code{'/'} and \code{'/RPC2'}. Setting
2329\member{rpc_paths} to \code{None} or an empty tuple disables
2330this path checking.
2331
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00002332\item C API: Many functions now use \ctype{Py_ssize_t}
Andrew M. Kuchling42c6e2f2006-04-21 13:01:45 +00002333instead of \ctype{int} to allow processing more data on 64-bit
2334machines. Extension code may need to make the same change to avoid
2335warnings and to support 64-bit machines. See the earlier
Andrew M. Kuchlingfb08e732006-04-21 13:08:02 +00002336section~\ref{pep-353} for a discussion of this change.
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00002337
2338\item C API:
2339The obmalloc changes mean that
2340you must be careful to not mix usage
2341of the \cfunction{PyMem_*()} and \cfunction{PyObject_*()}
2342families of functions. Memory allocated with
2343one family's \cfunction{*_Malloc()} must be
2344freed with the corresponding family's \cfunction{*_Free()} function.
2345
Fred Drake2db76802004-12-01 05:05:47 +00002346\end{itemize}
2347
2348
2349%======================================================================
2350\section{Acknowledgements \label{acks}}
2351
2352The author would like to thank the following people for offering
2353suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchlinge3c958c2006-05-01 12:45:02 +00002354article: Phillip J. Eby, Kent Johnson, Martin von~L\"owis, Fredrik Lundh,
Andrew M. Kuchling356af462006-05-10 17:19:04 +00002355Gustavo Niemeyer, James Pryor, Mike Rovner, Scott Weikart, Thomas Wouters.
Fred Drake2db76802004-12-01 05:05:47 +00002356
2357\end{document}