blob: b2f73804e4c413fbc1bf1ebbcd9e9fa082bd6523 [file] [log] [blame]
Fred Drake2db76802004-12-01 05:05:47 +00001\documentclass{howto}
2\usepackage{distutils}
3% $Id$
4
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00005% Fix XXX comments
Fred Drake2db76802004-12-01 05:05:47 +00006
7\title{What's New in Python 2.5}
Thomas Wouters902d6eb2007-01-09 23:18:33 +00008\release{1.01}
Andrew M. Kuchling92e24952004-12-03 13:54:09 +00009\author{A.M. Kuchling}
10\authoraddress{\email{amk@amk.ca}}
Fred Drake2db76802004-12-01 05:05:47 +000011
12\begin{document}
13\maketitle
14\tableofcontents
15
Thomas Wouters0e3f5912006-08-11 14:57:12 +000016This article explains the new features in Python 2.5. The final
17release of Python 2.5 is scheduled for August 2006;
18\pep{356} describes the planned release schedule.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000019
Thomas Wouters0e3f5912006-08-11 14:57:12 +000020The changes in Python 2.5 are an interesting mix of language and
21library improvements. The library enhancements will be more important
22to Python's user community, I think, because several widely-useful
23packages were added. New modules include ElementTree for XML
24processing (section~\ref{module-etree}), the SQLite database module
25(section~\ref{module-sqlite}), and the \module{ctypes} module for
26calling C functions (section~\ref{module-ctypes}).
Fred Drake2db76802004-12-01 05:05:47 +000027
Thomas Wouters0e3f5912006-08-11 14:57:12 +000028The language changes are of middling significance. Some pleasant new
29features were added, but most of them aren't features that you'll use
30every day. Conditional expressions were finally added to the language
31using a novel syntax; see section~\ref{pep-308}. The new
32'\keyword{with}' statement will make writing cleanup code easier
33(section~\ref{pep-343}). Values can now be passed into generators
34(section~\ref{pep-342}). Imports are now visible as either absolute
35or relative (section~\ref{pep-328}). Some corner cases of exception
36handling are handled better (section~\ref{pep-341}). All these
37improvements are worthwhile, but they're improvements to one specific
38language feature or another; none of them are broad modifications to
39Python's semantics.
Fred Drake2db76802004-12-01 05:05:47 +000040
Thomas Wouters0e3f5912006-08-11 14:57:12 +000041As well as the language and library additions, other improvements and
42bugfixes were made throughout the source tree. A search through the
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000043SVN change logs finds there were 353 patches applied and 458 bugs
Thomas Wouters0e3f5912006-08-11 14:57:12 +000044fixed between Python 2.4 and 2.5. (Both figures are likely to be
45underestimates.)
46
47This article doesn't try to be a complete specification of the new
48features; instead changes are briefly introduced using helpful
49examples. For full details, you should always refer to the
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000050documentation for Python 2.5 at \url{http://docs.python.org}.
Fred Drake2db76802004-12-01 05:05:47 +000051If you want to understand the complete implementation and design
52rationale, refer to the PEP for a particular new feature.
53
Thomas Wouters0e3f5912006-08-11 14:57:12 +000054Comments, suggestions, and error reports for this document are
55welcome; please e-mail them to the author or open a bug in the Python
56bug tracker.
Fred Drake2db76802004-12-01 05:05:47 +000057
58%======================================================================
Thomas Woutersd4ec0c32006-04-21 16:44:05 +000059\section{PEP 308: Conditional Expressions\label{pep-308}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000060
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000061For a long time, people have been requesting a way to write
Thomas Wouters0e3f5912006-08-11 14:57:12 +000062conditional expressions, which are expressions that return value A or
63value B depending on whether a Boolean value is true or false. A
64conditional expression lets you write a single assignment statement
65that has the same effect as the following:
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000066
67\begin{verbatim}
68if condition:
69 x = true_value
70else:
71 x = false_value
72\end{verbatim}
73
74There have been endless tedious discussions of syntax on both
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000075python-dev and comp.lang.python. A vote was even held that found the
76majority of voters wanted conditional expressions in some form,
77but there was no syntax that was preferred by a clear majority.
78Candidates included C's \code{cond ? true_v : false_v},
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000079\code{if cond then true_v else false_v}, and 16 other variations.
80
Thomas Wouters0e3f5912006-08-11 14:57:12 +000081Guido van~Rossum eventually chose a surprising syntax:
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000082
83\begin{verbatim}
84x = true_value if condition else false_value
85\end{verbatim}
86
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000087Evaluation is still lazy as in existing Boolean expressions, so the
88order of evaluation jumps around a bit. The \var{condition}
89expression in the middle is evaluated first, and the \var{true_value}
90expression is evaluated only if the condition was true. Similarly,
91the \var{false_value} expression is only evaluated when the condition
92is false.
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000093
94This syntax may seem strange and backwards; why does the condition go
95in the \emph{middle} of the expression, and not in the front as in C's
96\code{c ? x : y}? The decision was checked by applying the new syntax
97to the modules in the standard library and seeing how the resulting
98code read. In many cases where a conditional expression is used, one
99value seems to be the 'common case' and one value is an 'exceptional
100case', used only on rarer occasions when the condition isn't met. The
101conditional syntax makes this pattern a bit more obvious:
102
103\begin{verbatim}
104contents = ((doc + '\n') if doc else '')
105\end{verbatim}
106
107I read the above statement as meaning ``here \var{contents} is
Andrew M. Kuchlingd0fcc022006-03-09 13:57:28 +0000108usually assigned a value of \code{doc+'\e n'}; sometimes
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +0000109\var{doc} is empty, in which special case an empty string is returned.''
110I doubt I will use conditional expressions very often where there
111isn't a clear common and uncommon case.
112
113There was some discussion of whether the language should require
114surrounding conditional expressions with parentheses. The decision
115was made to \emph{not} require parentheses in the Python language's
116grammar, but as a matter of style I think you should always use them.
117Consider these two statements:
118
119\begin{verbatim}
120# First version -- no parens
121level = 1 if logging else 0
122
123# Second version -- with parens
124level = (1 if logging else 0)
125\end{verbatim}
126
127In the first version, I think a reader's eye might group the statement
128into 'level = 1', 'if logging', 'else 0', and think that the condition
129decides whether the assignment to \var{level} is performed. The
130second version reads better, in my opinion, because it makes it clear
131that the assignment is always performed and the choice is being made
132between two values.
133
134Another reason for including the brackets: a few odd combinations of
135list comprehensions and lambdas could look like incorrect conditional
136expressions. See \pep{308} for some examples. If you put parentheses
137around your conditional expressions, you won't run into this case.
138
139
140\begin{seealso}
141
142\seepep{308}{Conditional Expressions}{PEP written by
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000143Guido van~Rossum and Raymond D. Hettinger; implemented by Thomas
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +0000144Wouters.}
145
146\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000147
148
149%======================================================================
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000150\section{PEP 309: Partial Function Application\label{pep-309}}
Fred Drake2db76802004-12-01 05:05:47 +0000151
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000152The \module{functools} module is intended to contain tools for
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000153functional-style programming.
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000154
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000155One useful tool in this module is the \function{partial()} function.
156For programs written in a functional style, you'll sometimes want to
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000157construct variants of existing functions that have some of the
158parameters filled in. Consider a Python function \code{f(a, b, c)};
159you could create a new function \code{g(b, c)} that was equivalent to
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000160\code{f(1, b, c)}. This is called ``partial function application''.
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000161
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000162\function{partial} takes the arguments
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000163\code{(\var{function}, \var{arg1}, \var{arg2}, ...
164\var{kwarg1}=\var{value1}, \var{kwarg2}=\var{value2})}. The resulting
165object is callable, so you can just call it to invoke \var{function}
166with the filled-in arguments.
167
168Here's a small but realistic example:
169
170\begin{verbatim}
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000171import functools
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000172
173def log (message, subsystem):
174 "Write the contents of 'message' to the specified subsystem."
175 print '%s: %s' % (subsystem, message)
176 ...
177
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000178server_log = functools.partial(log, subsystem='server')
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000179server_log('Unable to open socket')
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000180\end{verbatim}
181
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000182Here's another example, from a program that uses PyGTK. Here a
Andrew M. Kuchling6af7fe02005-08-02 17:20:36 +0000183context-sensitive pop-up menu is being constructed dynamically. The
184callback provided for the menu option is a partially applied version
185of the \method{open_item()} method, where the first argument has been
186provided.
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000187
Andrew M. Kuchling6af7fe02005-08-02 17:20:36 +0000188\begin{verbatim}
189...
190class Application:
191 def open_item(self, path):
192 ...
193 def init (self):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000194 open_func = functools.partial(self.open_item, item_path)
Andrew M. Kuchling6af7fe02005-08-02 17:20:36 +0000195 popup_menu.append( ("Open", open_func, 1) )
196\end{verbatim}
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000197
198
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000199Another function in the \module{functools} module is the
200\function{update_wrapper(\var{wrapper}, \var{wrapped})} function that
201helps you write well-behaved decorators. \function{update_wrapper()}
202copies the name, module, and docstring attribute to a wrapper function
203so that tracebacks inside the wrapped function are easier to
204understand. For example, you might write:
205
206\begin{verbatim}
207def my_decorator(f):
208 def wrapper(*args, **kwds):
209 print 'Calling decorated function'
210 return f(*args, **kwds)
211 functools.update_wrapper(wrapper, f)
212 return wrapper
213\end{verbatim}
214
215\function{wraps()} is a decorator that can be used inside your own
216decorators to copy the wrapped function's information. An alternate
217version of the previous example would be:
218
219\begin{verbatim}
220def my_decorator(f):
221 @functools.wraps(f)
222 def wrapper(*args, **kwds):
223 print 'Calling decorated function'
224 return f(*args, **kwds)
225 return wrapper
226\end{verbatim}
227
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000228\begin{seealso}
229
230\seepep{309}{Partial Function Application}{PEP proposed and written by
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000231Peter Harris; implemented by Hye-Shik Chang and Nick Coghlan, with
232adaptations by Raymond Hettinger.}
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000233
234\end{seealso}
Fred Drake2db76802004-12-01 05:05:47 +0000235
236
237%======================================================================
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000238\section{PEP 314: Metadata for Python Software Packages v1.1\label{pep-314}}
Fred Drakedb7b0022005-03-20 22:19:47 +0000239
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000240Some simple dependency support was added to Distutils. The
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000241\function{setup()} function now has \code{requires}, \code{provides},
242and \code{obsoletes} keyword parameters. When you build a source
243distribution using the \code{sdist} command, the dependency
244information will be recorded in the \file{PKG-INFO} file.
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000245
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000246Another new keyword parameter is \code{download_url}, which should be
247set to a URL for the package's source code. This means it's now
248possible to look up an entry in the package index, determine the
249dependencies for a package, and download the required packages.
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000250
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000251\begin{verbatim}
252VERSION = '1.0'
253setup(name='PyPackage',
254 version=VERSION,
255 requires=['numarray', 'zlib (>=1.1.4)'],
256 obsoletes=['OldPackage']
257 download_url=('http://www.example.com/pypackage/dist/pkg-%s.tar.gz'
258 % VERSION),
259 )
260\end{verbatim}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000261
262Another new enhancement to the Python package index at
263\url{http://cheeseshop.python.org} is storing source and binary
264archives for a package. The new \command{upload} Distutils command
265will upload a package to the repository.
266
267Before a package can be uploaded, you must be able to build a
268distribution using the \command{sdist} Distutils command. Once that
269works, you can run \code{python setup.py upload} to add your package
270to the PyPI archive. Optionally you can GPG-sign the package by
271supplying the \longprogramopt{sign} and
272\longprogramopt{identity} options.
273
274Package uploading was implemented by Martin von~L\"owis and Richard Jones.
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000275
276\begin{seealso}
277
278\seepep{314}{Metadata for Python Software Packages v1.1}{PEP proposed
279and written by A.M. Kuchling, Richard Jones, and Fred Drake;
280implemented by Richard Jones and Fred Drake.}
281
282\end{seealso}
Fred Drakedb7b0022005-03-20 22:19:47 +0000283
284
285%======================================================================
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000286\section{PEP 328: Absolute and Relative Imports\label{pep-328}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000287
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000288The simpler part of PEP 328 was implemented in Python 2.4: parentheses
289could now be used to enclose the names imported from a module using
290the \code{from ... import ...} statement, making it easier to import
291many different names.
292
293The more complicated part has been implemented in Python 2.5:
294importing a module can be specified to use absolute or
295package-relative imports. The plan is to move toward making absolute
296imports the default in future versions of Python.
297
298Let's say you have a package directory like this:
299\begin{verbatim}
300pkg/
301pkg/__init__.py
302pkg/main.py
303pkg/string.py
304\end{verbatim}
305
306This defines a package named \module{pkg} containing the
307\module{pkg.main} and \module{pkg.string} submodules.
308
309Consider the code in the \file{main.py} module. What happens if it
310executes the statement \code{import string}? In Python 2.4 and
311earlier, it will first look in the package's directory to perform a
312relative import, finds \file{pkg/string.py}, imports the contents of
313that file as the \module{pkg.string} module, and that module is bound
314to the name \samp{string} in the \module{pkg.main} module's namespace.
315
316That's fine if \module{pkg.string} was what you wanted. But what if
317you wanted Python's standard \module{string} module? There's no clean
318way to ignore \module{pkg.string} and look for the standard module;
319generally you had to look at the contents of \code{sys.modules}, which
320is slightly unclean.
321Holger Krekel's \module{py.std} package provides a tidier way to perform
322imports from the standard library, \code{import py ; py.std.string.join()},
323but that package isn't available on all Python installations.
324
325Reading code which relies on relative imports is also less clear,
326because a reader may be confused about which module, \module{string}
327or \module{pkg.string}, is intended to be used. Python users soon
328learned not to duplicate the names of standard library modules in the
329names of their packages' submodules, but you can't protect against
330having your submodule's name being used for a new module added in a
331future version of Python.
332
333In Python 2.5, you can switch \keyword{import}'s behaviour to
334absolute imports using a \code{from __future__ import absolute_import}
335directive. This absolute-import behaviour will become the default in
336a future version (probably Python 2.7). Once absolute imports
337are the default, \code{import string} will
338always find the standard library's version.
339It's suggested that users should begin using absolute imports as much
340as possible, so it's preferable to begin writing \code{from pkg import
341string} in your code.
342
343Relative imports are still possible by adding a leading period
344to the module name when using the \code{from ... import} form:
345
346\begin{verbatim}
347# Import names from pkg.string
348from .string import name1, name2
349# Import pkg.string
350from . import string
351\end{verbatim}
352
353This imports the \module{string} module relative to the current
354package, so in \module{pkg.main} this will import \var{name1} and
355\var{name2} from \module{pkg.string}. Additional leading periods
356perform the relative import starting from the parent of the current
357package. For example, code in the \module{A.B.C} module can do:
358
359\begin{verbatim}
360from . import D # Imports A.B.D
361from .. import E # Imports A.E
362from ..F import G # Imports A.F.G
363\end{verbatim}
364
365Leading periods cannot be used with the \code{import \var{modname}}
366form of the import statement, only the \code{from ... import} form.
367
368\begin{seealso}
369
370\seepep{328}{Imports: Multi-Line and Absolute/Relative}
371{PEP written by Aahz; implemented by Thomas Wouters.}
372
373\seeurl{http://codespeak.net/py/current/doc/index.html}
374{The py library by Holger Krekel, which contains the \module{py.std} package.}
375
376\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000377
378
379%======================================================================
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000380\section{PEP 338: Executing Modules as Scripts\label{pep-338}}
Thomas Woutersa9773292006-04-21 09:43:23 +0000381
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000382The \programopt{-m} switch added in Python 2.4 to execute a module as
383a script gained a few more abilities. Instead of being implemented in
384C code inside the Python interpreter, the switch now uses an
385implementation in a new module, \module{runpy}.
386
387The \module{runpy} module implements a more sophisticated import
388mechanism so that it's now possible to run modules in a package such
389as \module{pychecker.checker}. The module also supports alternative
390import mechanisms such as the \module{zipimport} module. This means
391you can add a .zip archive's path to \code{sys.path} and then use the
392\programopt{-m} switch to execute code from the archive.
393
394
395\begin{seealso}
396
397\seepep{338}{Executing modules as scripts}{PEP written and
398implemented by Nick Coghlan.}
399
400\end{seealso}
Thomas Woutersa9773292006-04-21 09:43:23 +0000401
402
403%======================================================================
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000404\section{PEP 341: Unified try/except/finally\label{pep-341}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000405
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000406Until Python 2.5, the \keyword{try} statement came in two
407flavours. You could use a \keyword{finally} block to ensure that code
408is always executed, or one or more \keyword{except} blocks to catch
409specific exceptions. You couldn't combine both \keyword{except} blocks and a
410\keyword{finally} block, because generating the right bytecode for the
411combined version was complicated and it wasn't clear what the
Thomas Wouters89f507f2006-12-13 04:49:30 +0000412semantics of the combined statement should be.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000413
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000414Guido van~Rossum spent some time working with Java, which does support the
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000415equivalent of combining \keyword{except} blocks and a
416\keyword{finally} block, and this clarified what the statement should
417mean. In Python 2.5, you can now write:
418
419\begin{verbatim}
420try:
421 block-1 ...
422except Exception1:
423 handler-1 ...
424except Exception2:
425 handler-2 ...
426else:
427 else-block
428finally:
429 final-block
430\end{verbatim}
431
432The code in \var{block-1} is executed. If the code raises an
Thomas Wouters477c8d52006-05-27 19:21:47 +0000433exception, the various \keyword{except} blocks are tested: if the
434exception is of class \class{Exception1}, \var{handler-1} is executed;
435otherwise if it's of class \class{Exception2}, \var{handler-2} is
436executed, and so forth. If no exception is raised, the
437\var{else-block} is executed.
438
439No matter what happened previously, the \var{final-block} is executed
440once the code block is complete and any raised exceptions handled.
441Even if there's an error in an exception handler or the
442\var{else-block} and a new exception is raised, the
443code in the \var{final-block} is still run.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000444
445\begin{seealso}
446
447\seepep{341}{Unifying try-except and try-finally}{PEP written by Georg Brandl;
448implementation by Thomas Lee.}
449
450\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000451
452
453%======================================================================
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000454\section{PEP 342: New Generator Features\label{pep-342}}
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000455
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000456Python 2.5 adds a simple way to pass values \emph{into} a generator.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000457As introduced in Python 2.3, generators only produce output; once a
Thomas Wouters477c8d52006-05-27 19:21:47 +0000458generator's code was invoked to create an iterator, there was no way to
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000459pass any new information into the function when its execution is
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000460resumed. Sometimes the ability to pass in some information would be
461useful. Hackish solutions to this include making the generator's code
462look at a global variable and then changing the global variable's
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000463value, or passing in some mutable object that callers then modify.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000464
465To refresh your memory of basic generators, here's a simple example:
466
467\begin{verbatim}
468def counter (maximum):
469 i = 0
470 while i < maximum:
471 yield i
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000472 i += 1
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000473\end{verbatim}
474
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000475When you call \code{counter(10)}, the result is an iterator that
476returns the values from 0 up to 9. On encountering the
477\keyword{yield} statement, the iterator returns the provided value and
478suspends the function's execution, preserving the local variables.
479Execution resumes on the following call to the iterator's
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000480\method{next()} method, picking up after the \keyword{yield} statement.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000481
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000482In Python 2.3, \keyword{yield} was a statement; it didn't return any
483value. In 2.5, \keyword{yield} is now an expression, returning a
484value that can be assigned to a variable or otherwise operated on:
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000485
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000486\begin{verbatim}
487val = (yield i)
488\end{verbatim}
489
490I recommend that you always put parentheses around a \keyword{yield}
491expression when you're doing something with the returned value, as in
492the above example. The parentheses aren't always necessary, but it's
493easier to always add them instead of having to remember when they're
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000494needed.
495
496(\pep{342} explains the exact rules, which are that a
497\keyword{yield}-expression must always be parenthesized except when it
498occurs at the top-level expression on the right-hand side of an
499assignment. This means you can write \code{val = yield i} but have to
500use parentheses when there's an operation, as in \code{val = (yield i)
501+ 12}.)
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000502
503Values are sent into a generator by calling its
504\method{send(\var{value})} method. The generator's code is then
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000505resumed and the \keyword{yield} expression returns the specified
506\var{value}. If the regular \method{next()} method is called, the
507\keyword{yield} returns \constant{None}.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000508
509Here's the previous example, modified to allow changing the value of
510the internal counter.
511
512\begin{verbatim}
513def counter (maximum):
514 i = 0
515 while i < maximum:
516 val = (yield i)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000517 # If value provided, change counter
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000518 if val is not None:
519 i = val
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000520 else:
521 i += 1
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000522\end{verbatim}
523
524And here's an example of changing the counter:
525
526\begin{verbatim}
527>>> it = counter(10)
528>>> print it.next()
5290
530>>> print it.next()
5311
532>>> print it.send(8)
5338
534>>> print it.next()
5359
536>>> print it.next()
537Traceback (most recent call last):
538 File ``t.py'', line 15, in ?
539 print it.next()
540StopIteration
Andrew M. Kuchlingc2033702005-08-29 13:30:12 +0000541\end{verbatim}
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000542
Thomas Wouters89f507f2006-12-13 04:49:30 +0000543\keyword{yield} will usually return \constant{None}, so you
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000544should always check for this case. Don't just use its value in
545expressions unless you're sure that the \method{send()} method
Thomas Wouters89f507f2006-12-13 04:49:30 +0000546will be the only method used to resume your generator function.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000547
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000548In addition to \method{send()}, there are two other new methods on
549generators:
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000550
551\begin{itemize}
552
553 \item \method{throw(\var{type}, \var{value}=None,
554 \var{traceback}=None)} is used to raise an exception inside the
555 generator; the exception is raised by the \keyword{yield} expression
556 where the generator's execution is paused.
557
558 \item \method{close()} raises a new \exception{GeneratorExit}
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000559 exception inside the generator to terminate the iteration. On
560 receiving this exception, the generator's code must either raise
561 \exception{GeneratorExit} or \exception{StopIteration}. Catching
562 the \exception{GeneratorExit} exception and returning a value is
563 illegal and will trigger a \exception{RuntimeError}; if the function
564 raises some other exception, that exception is propagated to the
565 caller. \method{close()} will also be called by Python's garbage
566 collector when the generator is garbage-collected.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000567
Thomas Wouters477c8d52006-05-27 19:21:47 +0000568 If you need to run cleanup code when a \exception{GeneratorExit} occurs,
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000569 I suggest using a \code{try: ... finally:} suite instead of
570 catching \exception{GeneratorExit}.
571
572\end{itemize}
573
574The cumulative effect of these changes is to turn generators from
575one-way producers of information into both producers and consumers.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000576
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000577Generators also become \emph{coroutines}, a more generalized form of
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000578subroutines. Subroutines are entered at one point and exited at
Thomas Wouters477c8d52006-05-27 19:21:47 +0000579another point (the top of the function, and a \keyword{return}
580statement), but coroutines can be entered, exited, and resumed at
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000581many different points (the \keyword{yield} statements). We'll have to
582figure out patterns for using coroutines effectively in Python.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000583
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000584The addition of the \method{close()} method has one side effect that
585isn't obvious. \method{close()} is called when a generator is
586garbage-collected, so this means the generator's code gets one last
587chance to run before the generator is destroyed. This last chance
588means that \code{try...finally} statements in generators can now be
589guaranteed to work; the \keyword{finally} clause will now always get a
590chance to run. The syntactic restriction that you couldn't mix
591\keyword{yield} statements with a \code{try...finally} suite has
592therefore been removed. This seems like a minor bit of language
593trivia, but using generators and \code{try...finally} is actually
594necessary in order to implement the \keyword{with} statement
595described by PEP 343. I'll look at this new statement in the following
596section.
597
598Another even more esoteric effect of this change: previously, the
599\member{gi_frame} attribute of a generator was always a frame object.
600It's now possible for \member{gi_frame} to be \code{None}
601once the generator has been exhausted.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000602
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000603\begin{seealso}
604
605\seepep{342}{Coroutines via Enhanced Generators}{PEP written by
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000606Guido van~Rossum and Phillip J. Eby;
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000607implemented by Phillip J. Eby. Includes examples of
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000608some fancier uses of generators as coroutines.
609
610Earlier versions of these features were proposed in
611\pep{288} by Raymond Hettinger and \pep{325} by Samuele Pedroni.
612}
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000613
614\seeurl{http://en.wikipedia.org/wiki/Coroutine}{The Wikipedia entry for
615coroutines.}
616
Neal Norwitz09179882006-03-04 23:31:45 +0000617\seeurl{http://www.sidhe.org/\~{}dan/blog/archives/000178.html}{An
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000618explanation of coroutines from a Perl point of view, written by Dan
619Sugalski.}
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000620
621\end{seealso}
622
623
624%======================================================================
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000625\section{PEP 343: The 'with' statement\label{pep-343}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000626
Thomas Wouters477c8d52006-05-27 19:21:47 +0000627The '\keyword{with}' statement clarifies code that previously would
628use \code{try...finally} blocks to ensure that clean-up code is
629executed. In this section, I'll discuss the statement as it will
630commonly be used. In the next section, I'll examine the
631implementation details and show how to write objects for use with this
632statement.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000633
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000634The '\keyword{with}' statement is a new control-flow structure whose
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000635basic structure is:
636
637\begin{verbatim}
638with expression [as variable]:
639 with-block
640\end{verbatim}
641
Thomas Wouters477c8d52006-05-27 19:21:47 +0000642The expression is evaluated, and it should result in an object that
643supports the context management protocol. This object may return a
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000644value that can optionally be bound to the name \var{variable}. (Note
Thomas Wouters477c8d52006-05-27 19:21:47 +0000645carefully that \var{variable} is \emph{not} assigned the result of
646\var{expression}.) The object can then run set-up code
647before \var{with-block} is executed and some clean-up code
648is executed after the block is done, even if the block raised an exception.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000649
650To enable the statement in Python 2.5, you need
651to add the following directive to your module:
652
653\begin{verbatim}
654from __future__ import with_statement
655\end{verbatim}
656
657The statement will always be enabled in Python 2.6.
658
Thomas Wouters477c8d52006-05-27 19:21:47 +0000659Some standard Python objects now support the context management
660protocol and can be used with the '\keyword{with}' statement. File
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000661objects are one example:
662
663\begin{verbatim}
664with open('/etc/passwd', 'r') as f:
665 for line in f:
666 print line
667 ... more processing code ...
668\end{verbatim}
669
670After this statement has executed, the file object in \var{f} will
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000671have been automatically closed, even if the 'for' loop
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000672raised an exception part-way through the block.
673
674The \module{threading} module's locks and condition variables
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000675also support the '\keyword{with}' statement:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000676
677\begin{verbatim}
678lock = threading.Lock()
679with lock:
680 # Critical section of code
681 ...
682\end{verbatim}
683
Thomas Wouters477c8d52006-05-27 19:21:47 +0000684The lock is acquired before the block is executed and always released once
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000685the block is complete.
686
Thomas Wouters89f507f2006-12-13 04:49:30 +0000687The new \function{localcontext()} function in the \module{decimal} module
688makes it easy to save and restore the current decimal context, which
689encapsulates the desired precision and rounding characteristics for
690computations:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000691
692\begin{verbatim}
Thomas Wouters89f507f2006-12-13 04:49:30 +0000693from decimal import Decimal, Context, localcontext
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000694
695# Displays with default precision of 28 digits
Thomas Wouters89f507f2006-12-13 04:49:30 +0000696v = Decimal('578')
697print v.sqrt()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000698
Thomas Wouters89f507f2006-12-13 04:49:30 +0000699with localcontext(Context(prec=16)):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000700 # All code in this block uses a precision of 16 digits.
701 # The original context is restored on exiting the block.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000702 print v.sqrt()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000703\end{verbatim}
704
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000705\subsection{Writing Context Managers\label{context-managers}}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000706
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000707Under the hood, the '\keyword{with}' statement is fairly complicated.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000708Most people will only use '\keyword{with}' in company with existing
709objects and don't need to know these details, so you can skip the rest
710of this section if you like. Authors of new objects will need to
711understand the details of the underlying implementation and should
712keep reading.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000713
714A high-level explanation of the context management protocol is:
715
716\begin{itemize}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000717
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000718\item The expression is evaluated and should result in an object
Thomas Wouters477c8d52006-05-27 19:21:47 +0000719called a ``context manager''. The context manager must have
720\method{__enter__()} and \method{__exit__()} methods.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000721
Thomas Wouters477c8d52006-05-27 19:21:47 +0000722\item The context manager's \method{__enter__()} method is called. The value
723returned is assigned to \var{VAR}. If no \code{'as \var{VAR}'} clause
724is present, the value is simply discarded.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000725
726\item The code in \var{BLOCK} is executed.
727
Thomas Wouters477c8d52006-05-27 19:21:47 +0000728\item If \var{BLOCK} raises an exception, the
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000729\method{__exit__(\var{type}, \var{value}, \var{traceback})} is called
Thomas Wouters477c8d52006-05-27 19:21:47 +0000730with the exception details, the same values returned by
731\function{sys.exc_info()}. The method's return value controls whether
732the exception is re-raised: any false value re-raises the exception,
733and \code{True} will result in suppressing it. You'll only rarely
734want to suppress the exception, because if you do
735the author of the code containing the
736'\keyword{with}' statement will never realize anything went wrong.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000737
738\item If \var{BLOCK} didn't raise an exception,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000739the \method{__exit__()} method is still called,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000740but \var{type}, \var{value}, and \var{traceback} are all \code{None}.
741
742\end{itemize}
743
744Let's think through an example. I won't present detailed code but
Thomas Wouters477c8d52006-05-27 19:21:47 +0000745will only sketch the methods necessary for a database that supports
746transactions.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000747
748(For people unfamiliar with database terminology: a set of changes to
749the database are grouped into a transaction. Transactions can be
750either committed, meaning that all the changes are written into the
751database, or rolled back, meaning that the changes are all discarded
752and the database is unchanged. See any database textbook for more
753information.)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000754
755Let's assume there's an object representing a database connection.
756Our goal will be to let the user write code like this:
757
758\begin{verbatim}
759db_connection = DatabaseConnection()
760with db_connection as cursor:
761 cursor.execute('insert into ...')
762 cursor.execute('delete from ...')
763 # ... more operations ...
764\end{verbatim}
765
Thomas Wouters477c8d52006-05-27 19:21:47 +0000766The transaction should be committed if the code in the block
767runs flawlessly or rolled back if there's an exception.
768Here's the basic interface
769for \class{DatabaseConnection} that I'll assume:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000770
771\begin{verbatim}
772class DatabaseConnection:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000773 # Database interface
774 def cursor (self):
775 "Returns a cursor object and starts a new transaction"
776 def commit (self):
777 "Commits current transaction"
778 def rollback (self):
779 "Rolls back current transaction"
780\end{verbatim}
781
Thomas Wouters477c8d52006-05-27 19:21:47 +0000782The \method {__enter__()} method is pretty easy, having only to start
783a new transaction. For this application the resulting cursor object
784would be a useful result, so the method will return it. The user can
785then add \code{as cursor} to their '\keyword{with}' statement to bind
786the cursor to a variable name.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000787
788\begin{verbatim}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000789class DatabaseConnection:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000790 ...
791 def __enter__ (self):
792 # Code to start a new transaction
Thomas Wouters477c8d52006-05-27 19:21:47 +0000793 cursor = self.cursor()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000794 return cursor
795\end{verbatim}
796
797The \method{__exit__()} method is the most complicated because it's
798where most of the work has to be done. The method has to check if an
799exception occurred. If there was no exception, the transaction is
800committed. The transaction is rolled back if there was an exception.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000801
802In the code below, execution will just fall off the end of the
803function, returning the default value of \code{None}. \code{None} is
804false, so the exception will be re-raised automatically. If you
805wished, you could be more explicit and add a \keyword{return}
806statement at the marked location.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000807
808\begin{verbatim}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000809class DatabaseConnection:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000810 ...
811 def __exit__ (self, type, value, tb):
812 if tb is None:
813 # No exception, so commit
Thomas Wouters477c8d52006-05-27 19:21:47 +0000814 self.commit()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000815 else:
816 # Exception occurred, so rollback.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000817 self.rollback()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000818 # return False
819\end{verbatim}
820
821
822\subsection{The contextlib module\label{module-contextlib}}
823
824The new \module{contextlib} module provides some functions and a
Thomas Wouters477c8d52006-05-27 19:21:47 +0000825decorator that are useful for writing objects for use with the
826'\keyword{with}' statement.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000827
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000828The decorator is called \function{contextmanager}, and lets you write
Thomas Wouters477c8d52006-05-27 19:21:47 +0000829a single generator function instead of defining a new class. The generator
830should yield exactly one value. The code up to the \keyword{yield}
831will be executed as the \method{__enter__()} method, and the value
832yielded will be the method's return value that will get bound to the
833variable in the '\keyword{with}' statement's \keyword{as} clause, if
834any. The code after the \keyword{yield} will be executed in the
835\method{__exit__()} method. Any exception raised in the block will be
836raised by the \keyword{yield} statement.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000837
838Our database example from the previous section could be written
839using this decorator as:
840
841\begin{verbatim}
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000842from contextlib import contextmanager
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000843
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000844@contextmanager
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000845def db_transaction (connection):
846 cursor = connection.cursor()
847 try:
848 yield cursor
849 except:
850 connection.rollback()
851 raise
852 else:
853 connection.commit()
854
855db = DatabaseConnection()
856with db_transaction(db) as cursor:
857 ...
858\end{verbatim}
859
Thomas Wouters477c8d52006-05-27 19:21:47 +0000860The \module{contextlib} module also has a \function{nested(\var{mgr1},
861\var{mgr2}, ...)} function that combines a number of context managers so you
862don't need to write nested '\keyword{with}' statements. In this
863example, the single '\keyword{with}' statement both starts a database
864transaction and acquires a thread lock:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000865
866\begin{verbatim}
867lock = threading.Lock()
868with nested (db_transaction(db), lock) as (cursor, locked):
869 ...
870\end{verbatim}
871
Thomas Wouters477c8d52006-05-27 19:21:47 +0000872Finally, the \function{closing(\var{object})} function
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000873returns \var{object} so that it can be bound to a variable,
874and calls \code{\var{object}.close()} at the end of the block.
875
876\begin{verbatim}
877import urllib, sys
878from contextlib import closing
879
880with closing(urllib.urlopen('http://www.yahoo.com')) as f:
881 for line in f:
882 sys.stdout.write(line)
883\end{verbatim}
884
885\begin{seealso}
886
887\seepep{343}{The ``with'' statement}{PEP written by Guido van~Rossum
888and Nick Coghlan; implemented by Mike Bland, Guido van~Rossum, and
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000889Neal Norwitz. The PEP shows the code generated for a '\keyword{with}'
Thomas Wouters477c8d52006-05-27 19:21:47 +0000890statement, which can be helpful in learning how the statement works.}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000891
892\seeurl{../lib/module-contextlib.html}{The documentation
893for the \module{contextlib} module.}
894
895\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000896
897
898%======================================================================
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000899\section{PEP 352: Exceptions as New-Style Classes\label{pep-352}}
Andrew M. Kuchling8f4d2552006-03-08 01:50:20 +0000900
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000901Exception classes can now be new-style classes, not just classic
902classes, and the built-in \exception{Exception} class and all the
903standard built-in exceptions (\exception{NameError},
904\exception{ValueError}, etc.) are now new-style classes.
Andrew M. Kuchlingaeadf952006-03-09 19:06:05 +0000905
906The inheritance hierarchy for exceptions has been rearranged a bit.
907In 2.5, the inheritance relationships are:
908
909\begin{verbatim}
910BaseException # New in Python 2.5
911|- KeyboardInterrupt
912|- SystemExit
913|- Exception
914 |- (all other current built-in exceptions)
915\end{verbatim}
916
917This rearrangement was done because people often want to catch all
918exceptions that indicate program errors. \exception{KeyboardInterrupt} and
919\exception{SystemExit} aren't errors, though, and usually represent an explicit
920action such as the user hitting Control-C or code calling
921\function{sys.exit()}. A bare \code{except:} will catch all exceptions,
922so you commonly need to list \exception{KeyboardInterrupt} and
923\exception{SystemExit} in order to re-raise them. The usual pattern is:
924
925\begin{verbatim}
926try:
927 ...
928except (KeyboardInterrupt, SystemExit):
929 raise
930except:
931 # Log error...
932 # Continue running program...
933\end{verbatim}
934
935In Python 2.5, you can now write \code{except Exception} to achieve
936the same result, catching all the exceptions that usually indicate errors
937but leaving \exception{KeyboardInterrupt} and
938\exception{SystemExit} alone. As in previous versions,
939a bare \code{except:} still catches all exceptions.
940
941The goal for Python 3.0 is to require any class raised as an exception
942to derive from \exception{BaseException} or some descendant of
943\exception{BaseException}, and future releases in the
944Python 2.x series may begin to enforce this constraint. Therefore, I
945suggest you begin making all your exception classes derive from
946\exception{Exception} now. It's been suggested that the bare
947\code{except:} form should be removed in Python 3.0, but Guido van~Rossum
948hasn't decided whether to do this or not.
949
950Raising of strings as exceptions, as in the statement \code{raise
951"Error occurred"}, is deprecated in Python 2.5 and will trigger a
952warning. The aim is to be able to remove the string-exception feature
953in a few releases.
954
955
956\begin{seealso}
957
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000958\seepep{352}{Required Superclass for Exceptions}{PEP written by
959Brett Cannon and Guido van~Rossum; implemented by Brett Cannon.}
960
961\end{seealso}
962
963
964%======================================================================
Thomas Woutersd4ec0c32006-04-21 16:44:05 +0000965\section{PEP 353: Using ssize_t as the index type\label{pep-353}}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000966
967A wide-ranging change to Python's C API, using a new
968\ctype{Py_ssize_t} type definition instead of \ctype{int},
969will permit the interpreter to handle more data on 64-bit platforms.
970This change doesn't affect Python's capacity on 32-bit platforms.
971
972Various pieces of the Python interpreter used C's \ctype{int} type to
973store sizes or counts; for example, the number of items in a list or
974tuple were stored in an \ctype{int}. The C compilers for most 64-bit
975platforms still define \ctype{int} as a 32-bit type, so that meant
976that lists could only hold up to \code{2**31 - 1} = 2147483647 items.
977(There are actually a few different programming models that 64-bit C
978compilers can use -- see
979\url{http://www.unix.org/version2/whatsnew/lp64_wp.html} for a
980discussion -- but the most commonly available model leaves \ctype{int}
981as 32 bits.)
982
983A limit of 2147483647 items doesn't really matter on a 32-bit platform
984because you'll run out of memory before hitting the length limit.
985Each list item requires space for a pointer, which is 4 bytes, plus
986space for a \ctype{PyObject} representing the item. 2147483647*4 is
987already more bytes than a 32-bit address space can contain.
988
989It's possible to address that much memory on a 64-bit platform,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000990however. The pointers for a list that size would only require 16~GiB
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000991of space, so it's not unreasonable that Python programmers might
992construct lists that large. Therefore, the Python interpreter had to
993be changed to use some type other than \ctype{int}, and this will be a
99464-bit type on 64-bit platforms. The change will cause
995incompatibilities on 64-bit machines, so it was deemed worth making
996the transition now, while the number of 64-bit users is still
997relatively small. (In 5 or 10 years, we may \emph{all} be on 64-bit
998machines, and the transition would be more painful then.)
999
1000This change most strongly affects authors of C extension modules.
1001Python strings and container types such as lists and tuples
1002now use \ctype{Py_ssize_t} to store their size.
1003Functions such as \cfunction{PyList_Size()}
1004now return \ctype{Py_ssize_t}. Code in extension modules
1005may therefore need to have some variables changed to
1006\ctype{Py_ssize_t}.
1007
1008The \cfunction{PyArg_ParseTuple()} and \cfunction{Py_BuildValue()} functions
1009have a new conversion code, \samp{n}, for \ctype{Py_ssize_t}.
1010\cfunction{PyArg_ParseTuple()}'s \samp{s\#} and \samp{t\#} still output
1011\ctype{int} by default, but you can define the macro
1012\csimplemacro{PY_SSIZE_T_CLEAN} before including \file{Python.h}
1013to make them return \ctype{Py_ssize_t}.
1014
1015\pep{353} has a section on conversion guidelines that
1016extension authors should read to learn about supporting 64-bit
1017platforms.
1018
1019\begin{seealso}
1020
1021\seepep{353}{Using ssize_t as the index type}{PEP written and implemented by Martin von~L\"owis.}
Andrew M. Kuchlingaeadf952006-03-09 19:06:05 +00001022
1023\end{seealso}
Andrew M. Kuchling8f4d2552006-03-08 01:50:20 +00001024
1025
1026%======================================================================
Thomas Woutersd4ec0c32006-04-21 16:44:05 +00001027\section{PEP 357: The '__index__' method\label{pep-357}}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +00001028
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001029The NumPy developers had a problem that could only be solved by adding
1030a new special method, \method{__index__}. When using slice notation,
1031as in \code{[\var{start}:\var{stop}:\var{step}]}, the values of the
1032\var{start}, \var{stop}, and \var{step} indexes must all be either
1033integers or long integers. NumPy defines a variety of specialized
1034integer types corresponding to unsigned and signed integers of 8, 16,
103532, and 64 bits, but there was no way to signal that these types could
1036be used as slice indexes.
1037
1038Slicing can't just use the existing \method{__int__} method because
1039that method is also used to implement coercion to integers. If
1040slicing used \method{__int__}, floating-point numbers would also
1041become legal slice indexes and that's clearly an undesirable
1042behaviour.
1043
1044Instead, a new special method called \method{__index__} was added. It
1045takes no arguments and returns an integer giving the slice index to
1046use. For example:
1047
1048\begin{verbatim}
1049class C:
1050 def __index__ (self):
1051 return self.value
1052\end{verbatim}
1053
1054The return value must be either a Python integer or long integer.
1055The interpreter will check that the type returned is correct, and
1056raises a \exception{TypeError} if this requirement isn't met.
1057
1058A corresponding \member{nb_index} slot was added to the C-level
1059\ctype{PyNumberMethods} structure to let C extensions implement this
1060protocol. \cfunction{PyNumber_Index(\var{obj})} can be used in
1061extension code to call the \method{__index__} function and retrieve
1062its result.
1063
1064\begin{seealso}
1065
1066\seepep{357}{Allowing Any Object to be Used for Slicing}{PEP written
1067and implemented by Travis Oliphant.}
1068
1069\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +00001070
1071
1072%======================================================================
Thomas Wouters477c8d52006-05-27 19:21:47 +00001073\section{Other Language Changes\label{other-lang}}
Fred Drake2db76802004-12-01 05:05:47 +00001074
1075Here are all of the changes that Python 2.5 makes to the core Python
1076language.
1077
1078\begin{itemize}
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001079
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001080\item The \class{dict} type has a new hook for letting subclasses
1081provide a default value when a key isn't contained in the dictionary.
1082When a key isn't found, the dictionary's
1083\method{__missing__(\var{key})}
1084method will be called. This hook is used to implement
1085the new \class{defaultdict} class in the \module{collections}
1086module. The following example defines a dictionary
1087that returns zero for any missing key:
1088
1089\begin{verbatim}
1090class zerodict (dict):
1091 def __missing__ (self, key):
1092 return 0
1093
1094d = zerodict({1:1, 2:2})
1095print d[1], d[2] # Prints 1, 2
1096print d[3], d[4] # Prints 0, 0
1097\end{verbatim}
1098
Thomas Wouters477c8d52006-05-27 19:21:47 +00001099\item Both 8-bit and Unicode strings have new \method{partition(sep)}
1100and \method{rpartition(sep)} methods that simplify a common use case.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001101
Thomas Wouters477c8d52006-05-27 19:21:47 +00001102The \method{find(S)} method is often used to get an index which is
1103then used to slice the string and obtain the pieces that are before
1104and after the separator.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001105\method{partition(sep)} condenses this
1106pattern into a single method call that returns a 3-tuple containing
1107the substring before the separator, the separator itself, and the
1108substring after the separator. If the separator isn't found, the
1109first element of the tuple is the entire string and the other two
1110elements are empty. \method{rpartition(sep)} also returns a 3-tuple
1111but starts searching from the end of the string; the \samp{r} stands
1112for 'reverse'.
1113
1114Some examples:
1115
1116\begin{verbatim}
1117>>> ('http://www.python.org').partition('://')
1118('http', '://', 'www.python.org')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001119>>> ('file:/usr/share/doc/index.html').partition('://')
1120('file:/usr/share/doc/index.html', '', '')
Thomas Wouters89f507f2006-12-13 04:49:30 +00001121>>> (u'Subject: a quick question').partition(':')
1122(u'Subject', u':', u' a quick question')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001123>>> 'www.python.org'.rpartition('.')
1124('www.python', '.', 'org')
Thomas Wouters89f507f2006-12-13 04:49:30 +00001125>>> 'www.python.org'.rpartition(':')
1126('', '', 'www.python.org')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001127\end{verbatim}
1128
1129(Implemented by Fredrik Lundh following a suggestion by Raymond Hettinger.)
1130
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001131\item The \method{startswith()} and \method{endswith()} methods
1132of string types now accept tuples of strings to check for.
1133
1134\begin{verbatim}
1135def is_image_file (filename):
1136 return filename.endswith(('.gif', '.jpg', '.tiff'))
1137\end{verbatim}
1138
1139(Implemented by Georg Brandl following a suggestion by Tom Lynn.)
1140% RFE #1491485
1141
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001142\item The \function{min()} and \function{max()} built-in functions
Thomas Woutersd4ec0c32006-04-21 16:44:05 +00001143gained a \code{key} keyword parameter analogous to the \code{key}
1144argument for \method{sort()}. This parameter supplies a function that
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001145takes a single argument and is called for every value in the list;
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001146\function{min()}/\function{max()} will return the element with the
1147smallest/largest return value from this function.
1148For example, to find the longest string in a list, you can do:
1149
1150\begin{verbatim}
1151L = ['medium', 'longest', 'short']
1152# Prints 'longest'
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001153print max(L, key=len)
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001154# Prints 'short', because lexicographically 'short' has the largest value
1155print max(L)
1156\end{verbatim}
1157
1158(Contributed by Steven Bethard and Raymond Hettinger.)
Fred Drake2db76802004-12-01 05:05:47 +00001159
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001160\item Two new built-in functions, \function{any()} and
1161\function{all()}, evaluate whether an iterator contains any true or
1162false values. \function{any()} returns \constant{True} if any value
1163returned by the iterator is true; otherwise it will return
1164\constant{False}. \function{all()} returns \constant{True} only if
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001165all of the values returned by the iterator evaluate as true.
1166(Suggested by Guido van~Rossum, and implemented by Raymond Hettinger.)
1167
1168\item The result of a class's \method{__hash__()} method can now
1169be either a long integer or a regular integer. If a long integer is
1170returned, the hash of that value is taken. In earlier versions the
1171hash value was required to be a regular integer, but in 2.5 the
1172\function{id()} built-in was changed to always return non-negative
1173numbers, and users often seem to use \code{id(self)} in
1174\method{__hash__()} methods (though this is discouraged).
1175% Bug #1536021
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001176
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001177\item ASCII is now the default encoding for modules. It's now
1178a syntax error if a module contains string literals with 8-bit
1179characters but doesn't have an encoding declaration. In Python 2.4
1180this triggered a warning, not a syntax error. See \pep{263}
1181for how to declare a module's encoding; for example, you might add
1182a line like this near the top of the source file:
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001183
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001184\begin{verbatim}
1185# -*- coding: latin1 -*-
1186\end{verbatim}
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001187
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001188\item A new warning, \class{UnicodeWarning}, is triggered when
1189you attempt to compare a Unicode string and an 8-bit string
1190that can't be converted to Unicode using the default ASCII encoding.
1191The result of the comparison is false:
1192
1193\begin{verbatim}
1194>>> chr(128) == unichr(128) # Can't convert chr(128) to Unicode
1195__main__:1: UnicodeWarning: Unicode equal comparison failed
1196 to convert both arguments to Unicode - interpreting them
1197 as being unequal
1198False
1199>>> chr(127) == unichr(127) # chr(127) can be converted
1200True
1201\end{verbatim}
1202
1203Previously this would raise a \class{UnicodeDecodeError} exception,
1204but in 2.5 this could result in puzzling problems when accessing a
1205dictionary. If you looked up \code{unichr(128)} and \code{chr(128)}
1206was being used as a key, you'd get a \class{UnicodeDecodeError}
1207exception. Other changes in 2.5 resulted in this exception being
1208raised instead of suppressed by the code in \file{dictobject.c} that
1209implements dictionaries.
1210
1211Raising an exception for such a comparison is strictly correct, but
1212the change might have broken code, so instead
1213\class{UnicodeWarning} was introduced.
1214
1215(Implemented by Marc-Andr\'e Lemburg.)
1216
Thomas Wouters477c8d52006-05-27 19:21:47 +00001217\item One error that Python programmers sometimes make is forgetting
1218to include an \file{__init__.py} module in a package directory.
1219Debugging this mistake can be confusing, and usually requires running
1220Python with the \programopt{-v} switch to log all the paths searched.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001221In Python 2.5, a new \exception{ImportWarning} warning is triggered when
Thomas Wouters477c8d52006-05-27 19:21:47 +00001222an import would have picked up a directory as a package but no
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001223\file{__init__.py} was found. This warning is silently ignored by default;
1224provide the \programopt{-Wd} option when running the Python executable
1225to display the warning message.
1226(Implemented by Thomas Wouters.)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001227
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001228\item The list of base classes in a class definition can now be empty.
1229As an example, this is now legal:
1230
1231\begin{verbatim}
1232class C():
1233 pass
1234\end{verbatim}
1235(Implemented by Brett Cannon.)
1236
Fred Drake2db76802004-12-01 05:05:47 +00001237\end{itemize}
1238
1239
1240%======================================================================
Thomas Wouters477c8d52006-05-27 19:21:47 +00001241\subsection{Interactive Interpreter Changes\label{interactive}}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001242
1243In the interactive interpreter, \code{quit} and \code{exit}
1244have long been strings so that new users get a somewhat helpful message
1245when they try to quit:
1246
1247\begin{verbatim}
1248>>> quit
1249'Use Ctrl-D (i.e. EOF) to exit.'
1250\end{verbatim}
1251
1252In Python 2.5, \code{quit} and \code{exit} are now objects that still
1253produce string representations of themselves, but are also callable.
1254Newbies who try \code{quit()} or \code{exit()} will now exit the
1255interpreter as they expect. (Implemented by Georg Brandl.)
1256
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001257The Python executable now accepts the standard long options
1258\longprogramopt{help} and \longprogramopt{version}; on Windows,
1259it also accepts the \programopt{/?} option for displaying a help message.
1260(Implemented by Georg Brandl.)
1261
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001262
1263%======================================================================
Thomas Wouters477c8d52006-05-27 19:21:47 +00001264\subsection{Optimizations\label{opts}}
1265
1266Several of the optimizations were developed at the NeedForSpeed
1267sprint, an event held in Reykjavik, Iceland, from May 21--28 2006.
1268The sprint focused on speed enhancements to the CPython implementation
1269and was funded by EWT LLC with local support from CCP Games. Those
1270optimizations added at this sprint are specially marked in the
1271following list.
Fred Drake2db76802004-12-01 05:05:47 +00001272
1273\begin{itemize}
1274
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001275\item When they were introduced
1276in Python 2.4, the built-in \class{set} and \class{frozenset} types
1277were built on top of Python's dictionary type.
1278In 2.5 the internal data structure has been customized for implementing sets,
1279and as a result sets will use a third less memory and are somewhat faster.
1280(Implemented by Raymond Hettinger.)
Fred Drake2db76802004-12-01 05:05:47 +00001281
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001282\item The speed of some Unicode operations, such as finding
1283substrings, string splitting, and character map encoding and decoding,
1284has been improved. (Substring search and splitting improvements were
Thomas Wouters477c8d52006-05-27 19:21:47 +00001285added by Fredrik Lundh and Andrew Dalke at the NeedForSpeed
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001286sprint. Character maps were improved by Walter D\"orwald and
1287Martin von~L\"owis.)
1288% Patch 1313939, 1359618
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001289
Thomas Wouters477c8d52006-05-27 19:21:47 +00001290\item The \function{long(\var{str}, \var{base})} function is now
1291faster on long digit strings because fewer intermediate results are
1292calculated. The peak is for strings of around 800--1000 digits where
1293the function is 6 times faster.
1294(Contributed by Alan McIntyre and committed at the NeedForSpeed sprint.)
1295% Patch 1442927
1296
Guido van Rossumd8faa362007-04-27 19:54:29 +00001297\item It's now illegal to mix iterating over a file
1298with \code{for line in \var{file}} and calling
1299the file object's \method{read()}/\method{readline()}/\method{readlines()}
1300methods. Iteration uses an internal buffer and the
1301\method{read*()} methods don't use that buffer.
1302Instead they would return the data following the buffer, causing the
1303data to appear out of order. Mixing iteration and these methods will
1304now trigger a \exception{ValueError} from the \method{read*()} method.
1305(Implemented by Thomas Wouters.)
1306% Patch 1397960
1307
Thomas Wouters477c8d52006-05-27 19:21:47 +00001308\item The \module{struct} module now compiles structure format
1309strings into an internal representation and caches this
1310representation, yielding a 20\% speedup. (Contributed by Bob Ippolito
1311at the NeedForSpeed sprint.)
1312
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001313\item The \module{re} module got a 1 or 2\% speedup by switching to
1314Python's allocator functions instead of the system's
1315\cfunction{malloc()} and \cfunction{free()}.
1316(Contributed by Jack Diederich at the NeedForSpeed sprint.)
1317
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001318\item The code generator's peephole optimizer now performs
1319simple constant folding in expressions. If you write something like
1320\code{a = 2+3}, the code generator will do the arithmetic and produce
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001321code corresponding to \code{a = 5}. (Proposed and implemented
1322by Raymond Hettinger.)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001323
Thomas Wouters477c8d52006-05-27 19:21:47 +00001324\item Function calls are now faster because code objects now keep
1325the most recently finished frame (a ``zombie frame'') in an internal
1326field of the code object, reusing it the next time the code object is
1327invoked. (Original patch by Michael Hudson, modified by Armin Rigo
1328and Richard Jones; committed at the NeedForSpeed sprint.)
1329% Patch 876206
1330
1331Frame objects are also slightly smaller, which may improve cache locality
1332and reduce memory usage a bit. (Contributed by Neal Norwitz.)
1333% Patch 1337051
1334
1335\item Python's built-in exceptions are now new-style classes, a change
1336that speeds up instantiation considerably. Exception handling in
1337Python 2.5 is therefore about 30\% faster than in 2.4.
1338(Contributed by Richard Jones, Georg Brandl and Sean Reifschneider at
1339the NeedForSpeed sprint.)
1340
1341\item Importing now caches the paths tried, recording whether
1342they exist or not so that the interpreter makes fewer
1343\cfunction{open()} and \cfunction{stat()} calls on startup.
1344(Contributed by Martin von~L\"owis and Georg Brandl.)
1345% Patch 921466
1346
Fred Drake2db76802004-12-01 05:05:47 +00001347\end{itemize}
1348
Fred Drake2db76802004-12-01 05:05:47 +00001349
1350%======================================================================
Thomas Wouters477c8d52006-05-27 19:21:47 +00001351\section{New, Improved, and Removed Modules\label{modules}}
Fred Drake2db76802004-12-01 05:05:47 +00001352
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001353The standard library received many enhancements and bug fixes in
1354Python 2.5. Here's a partial list of the most notable changes, sorted
1355alphabetically by module name. Consult the \file{Misc/NEWS} file in
1356the source tree for a more complete list of changes, or look through
1357the SVN logs for all the details.
Fred Drake2db76802004-12-01 05:05:47 +00001358
1359\begin{itemize}
1360
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001361\item The \module{audioop} module now supports the a-LAW encoding,
1362and the code for u-LAW encoding has been improved. (Contributed by
1363Lars Immisch.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001364
Thomas Woutersd4ec0c32006-04-21 16:44:05 +00001365\item The \module{codecs} module gained support for incremental
1366codecs. The \function{codec.lookup()} function now
1367returns a \class{CodecInfo} instance instead of a tuple.
1368\class{CodecInfo} instances behave like a 4-tuple to preserve backward
1369compatibility but also have the attributes \member{encode},
1370\member{decode}, \member{incrementalencoder}, \member{incrementaldecoder},
1371\member{streamwriter}, and \member{streamreader}. Incremental codecs
1372can receive input and produce output in multiple chunks; the output is
1373the same as if the entire input was fed to the non-incremental codec.
1374See the \module{codecs} module documentation for details.
1375(Designed and implemented by Walter D\"orwald.)
1376% Patch 1436130
1377
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001378\item The \module{collections} module gained a new type,
1379\class{defaultdict}, that subclasses the standard \class{dict}
1380type. The new type mostly behaves like a dictionary but constructs a
1381default value when a key isn't present, automatically adding it to the
1382dictionary for the requested key value.
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001383
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001384The first argument to \class{defaultdict}'s constructor is a factory
1385function that gets called whenever a key is requested but not found.
1386This factory function receives no arguments, so you can use built-in
1387type constructors such as \function{list()} or \function{int()}. For
1388example,
1389you can make an index of words based on their initial letter like this:
1390
1391\begin{verbatim}
1392words = """Nel mezzo del cammin di nostra vita
1393mi ritrovai per una selva oscura
1394che la diritta via era smarrita""".lower().split()
1395
1396index = defaultdict(list)
1397
1398for w in words:
1399 init_letter = w[0]
1400 index[init_letter].append(w)
1401\end{verbatim}
1402
1403Printing \code{index} results in the following output:
1404
1405\begin{verbatim}
1406defaultdict(<type 'list'>, {'c': ['cammin', 'che'], 'e': ['era'],
1407 'd': ['del', 'di', 'diritta'], 'm': ['mezzo', 'mi'],
1408 'l': ['la'], 'o': ['oscura'], 'n': ['nel', 'nostra'],
1409 'p': ['per'], 's': ['selva', 'smarrita'],
1410 'r': ['ritrovai'], 'u': ['una'], 'v': ['vita', 'via']}
1411\end{verbatim}
1412
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001413(Contributed by Guido van~Rossum.)
1414
1415\item The \class{deque} double-ended queue type supplied by the
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001416\module{collections} module now has a \method{remove(\var{value})}
1417method that removes the first occurrence of \var{value} in the queue,
1418raising \exception{ValueError} if the value isn't found.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001419(Contributed by Raymond Hettinger.)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001420
1421\item New module: The \module{contextlib} module contains helper functions for use
Thomas Woutersd4ec0c32006-04-21 16:44:05 +00001422with the new '\keyword{with}' statement. See
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001423section~\ref{module-contextlib} for more about this module.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001424
1425\item New module: The \module{cProfile} module is a C implementation of
1426the existing \module{profile} module that has much lower overhead.
1427The module's interface is the same as \module{profile}: you run
1428\code{cProfile.run('main()')} to profile a function, can save profile
1429data to a file, etc. It's not yet known if the Hotshot profiler,
1430which is also written in C but doesn't match the \module{profile}
1431module's interface, will continue to be maintained in future versions
1432of Python. (Contributed by Armin Rigo.)
1433
Thomas Wouters477c8d52006-05-27 19:21:47 +00001434Also, the \module{pstats} module for analyzing the data measured by
1435the profiler now supports directing the output to any file object
Thomas Woutersd4ec0c32006-04-21 16:44:05 +00001436by supplying a \var{stream} argument to the \class{Stats} constructor.
1437(Contributed by Skip Montanaro.)
1438
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001439\item The \module{csv} module, which parses files in
1440comma-separated value format, received several enhancements and a
1441number of bugfixes. You can now set the maximum size in bytes of a
1442field by calling the \method{csv.field_size_limit(\var{new_limit})}
1443function; omitting the \var{new_limit} argument will return the
1444currently-set limit. The \class{reader} class now has a
1445\member{line_num} attribute that counts the number of physical lines
1446read from the source; records can span multiple physical lines, so
1447\member{line_num} is not the same as the number of records read.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001448
1449The CSV parser is now stricter about multi-line quoted
1450fields. Previously, if a line ended within a quoted field without a
1451terminating newline character, a newline would be inserted into the
1452returned field. This behavior caused problems when reading files that
1453contained carriage return characters within fields, so the code was
1454changed to return the field without inserting newlines. As a
1455consequence, if newlines embedded within fields are important, the
1456input should be split into lines in a manner that preserves the
1457newline characters.
1458
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001459(Contributed by Skip Montanaro and Andrew McNamara.)
1460
1461\item The \class{datetime} class in the \module{datetime}
1462module now has a \method{strptime(\var{string}, \var{format})}
1463method for parsing date strings, contributed by Josh Spoerri.
1464It uses the same format characters as \function{time.strptime()} and
1465\function{time.strftime()}:
1466
1467\begin{verbatim}
1468from datetime import datetime
1469
1470ts = datetime.strptime('10:13:15 2006-03-07',
1471 '%H:%M:%S %Y-%m-%d')
1472\end{verbatim}
1473
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001474\item The \method{SequenceMatcher.get_matching_blocks()} method
1475in the \module{difflib} module now guarantees to return a minimal list
1476of blocks describing matching subsequences. Previously, the algorithm would
1477occasionally break a block of matching elements into two list entries.
1478(Enhancement by Tim Peters.)
1479
Thomas Wouters477c8d52006-05-27 19:21:47 +00001480\item The \module{doctest} module gained a \code{SKIP} option that
1481keeps an example from being executed at all. This is intended for
1482code snippets that are usage examples intended for the reader and
1483aren't actually test cases.
1484
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001485An \var{encoding} parameter was added to the \function{testfile()}
1486function and the \class{DocFileSuite} class to specify the file's
1487encoding. This makes it easier to use non-ASCII characters in
1488tests contained within a docstring. (Contributed by Bjorn Tillenius.)
1489% Patch 1080727
1490
1491\item The \module{email} package has been updated to version 4.0.
1492% XXX need to provide some more detail here
1493(Contributed by Barry Warsaw.)
1494
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001495\item The \module{fileinput} module was made more flexible.
1496Unicode filenames are now supported, and a \var{mode} parameter that
1497defaults to \code{"r"} was added to the
1498\function{input()} function to allow opening files in binary or
1499universal-newline mode. Another new parameter, \var{openhook},
1500lets you use a function other than \function{open()}
1501to open the input files. Once you're iterating over
1502the set of files, the \class{FileInput} object's new
1503\method{fileno()} returns the file descriptor for the currently opened file.
1504(Contributed by Georg Brandl.)
1505
1506\item In the \module{gc} module, the new \function{get_count()} function
1507returns a 3-tuple containing the current collection counts for the
1508three GC generations. This is accounting information for the garbage
1509collector; when these counts reach a specified threshold, a garbage
1510collection sweep will be made. The existing \function{gc.collect()}
1511function now takes an optional \var{generation} argument of 0, 1, or 2
1512to specify which generation to collect.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001513(Contributed by Barry Warsaw.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001514
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001515\item The \function{nsmallest()} and
1516\function{nlargest()} functions in the \module{heapq} module
Thomas Woutersd4ec0c32006-04-21 16:44:05 +00001517now support a \code{key} keyword parameter similar to the one
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001518provided by the \function{min()}/\function{max()} functions
1519and the \method{sort()} methods. For example:
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001520
1521\begin{verbatim}
1522>>> import heapq
1523>>> L = ["short", 'medium', 'longest', 'longer still']
1524>>> heapq.nsmallest(2, L) # Return two lowest elements, lexicographically
1525['longer still', 'longest']
1526>>> heapq.nsmallest(2, L, key=len) # Return two shortest elements
1527['short', 'medium']
1528\end{verbatim}
1529
1530(Contributed by Raymond Hettinger.)
1531
Andrew M. Kuchling511a3a82005-03-20 19:52:18 +00001532\item The \function{itertools.islice()} function now accepts
1533\code{None} for the start and step arguments. This makes it more
1534compatible with the attributes of slice objects, so that you can now write
1535the following:
1536
1537\begin{verbatim}
1538s = slice(5) # Create slice object
1539itertools.islice(iterable, s.start, s.stop, s.step)
1540\end{verbatim}
1541
1542(Contributed by Raymond Hettinger.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001543
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001544\item The \function{format()} function in the \module{locale} module
1545has been modified and two new functions were added,
1546\function{format_string()} and \function{currency()}.
1547
1548The \function{format()} function's \var{val} parameter could
1549previously be a string as long as no more than one \%char specifier
1550appeared; now the parameter must be exactly one \%char specifier with
1551no surrounding text. An optional \var{monetary} parameter was also
1552added which, if \code{True}, will use the locale's rules for
1553formatting currency in placing a separator between groups of three
1554digits.
1555
1556To format strings with multiple \%char specifiers, use the new
1557\function{format_string()} function that works like \function{format()}
1558but also supports mixing \%char specifiers with
1559arbitrary text.
1560
1561A new \function{currency()} function was also added that formats a
1562number according to the current locale's settings.
1563
1564(Contributed by Georg Brandl.)
1565% Patch 1180296
1566
Thomas Wouters477c8d52006-05-27 19:21:47 +00001567\item The \module{mailbox} module underwent a massive rewrite to add
1568the capability to modify mailboxes in addition to reading them. A new
1569set of classes that include \class{mbox}, \class{MH}, and
1570\class{Maildir} are used to read mailboxes, and have an
1571\method{add(\var{message})} method to add messages,
1572\method{remove(\var{key})} to remove messages, and
1573\method{lock()}/\method{unlock()} to lock/unlock the mailbox. The
1574following example converts a maildir-format mailbox into an mbox-format one:
1575
1576\begin{verbatim}
1577import mailbox
1578
1579# 'factory=None' uses email.Message.Message as the class representing
1580# individual messages.
1581src = mailbox.Maildir('maildir', factory=None)
1582dest = mailbox.mbox('/tmp/mbox')
1583
1584for msg in src:
1585 dest.add(msg)
1586\end{verbatim}
1587
1588(Contributed by Gregory K. Johnson. Funding was provided by Google's
15892005 Summer of Code.)
1590
1591\item New module: the \module{msilib} module allows creating
1592Microsoft Installer \file{.msi} files and CAB files. Some support
1593for reading the \file{.msi} database is also included.
1594(Contributed by Martin von~L\"owis.)
1595
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001596\item The \module{nis} module now supports accessing domains other
1597than the system default domain by supplying a \var{domain} argument to
1598the \function{nis.match()} and \function{nis.maps()} functions.
1599(Contributed by Ben Bell.)
1600
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001601\item The \module{operator} module's \function{itemgetter()}
1602and \function{attrgetter()} functions now support multiple fields.
1603A call such as \code{operator.attrgetter('a', 'b')}
1604will return a function
1605that retrieves the \member{a} and \member{b} attributes. Combining
1606this new feature with the \method{sort()} method's \code{key} parameter
1607lets you easily sort lists using multiple fields.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001608(Contributed by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001609
Thomas Wouters477c8d52006-05-27 19:21:47 +00001610\item The \module{optparse} module was updated to version 1.5.1 of the
1611Optik library. The \class{OptionParser} class gained an
1612\member{epilog} attribute, a string that will be printed after the
1613help message, and a \method{destroy()} method to break reference
1614cycles created by the object. (Contributed by Greg Ward.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001615
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001616\item The \module{os} module underwent several changes. The
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001617\member{stat_float_times} variable now defaults to true, meaning that
1618\function{os.stat()} will now return time values as floats. (This
1619doesn't necessarily mean that \function{os.stat()} will return times
1620that are precise to fractions of a second; not all systems support
1621such precision.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001622
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001623Constants named \member{os.SEEK_SET}, \member{os.SEEK_CUR}, and
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001624\member{os.SEEK_END} have been added; these are the parameters to the
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001625\function{os.lseek()} function. Two new constants for locking are
1626\member{os.O_SHLOCK} and \member{os.O_EXLOCK}.
1627
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001628Two new functions, \function{wait3()} and \function{wait4()}, were
1629added. They're similar the \function{waitpid()} function which waits
1630for a child process to exit and returns a tuple of the process ID and
1631its exit status, but \function{wait3()} and \function{wait4()} return
1632additional information. \function{wait3()} doesn't take a process ID
1633as input, so it waits for any child process to exit and returns a
16343-tuple of \var{process-id}, \var{exit-status}, \var{resource-usage}
1635as returned from the \function{resource.getrusage()} function.
1636\function{wait4(\var{pid})} does take a process ID.
1637(Contributed by Chad J. Schroeder.)
1638
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001639On FreeBSD, the \function{os.stat()} function now returns
1640times with nanosecond resolution, and the returned object
1641now has \member{st_gen} and \member{st_birthtime}.
1642The \member{st_flags} member is also available, if the platform supports it.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001643(Contributed by Antti Louko and Diego Petten\`o.)
1644% (Patch 1180695, 1212117)
1645
Thomas Wouters477c8d52006-05-27 19:21:47 +00001646\item The Python debugger provided by the \module{pdb} module
1647can now store lists of commands to execute when a breakpoint is
1648reached and execution stops. Once breakpoint \#1 has been created,
1649enter \samp{commands 1} and enter a series of commands to be executed,
1650finishing the list with \samp{end}. The command list can include
1651commands that resume execution, such as \samp{continue} or
1652\samp{next}. (Contributed by Gr\'egoire Dooms.)
1653% Patch 790710
1654
Thomas Woutersd4ec0c32006-04-21 16:44:05 +00001655\item The \module{pickle} and \module{cPickle} modules no
1656longer accept a return value of \code{None} from the
1657\method{__reduce__()} method; the method must return a tuple of
1658arguments instead. The ability to return \code{None} was deprecated
1659in Python 2.4, so this completes the removal of the feature.
1660
Thomas Wouters477c8d52006-05-27 19:21:47 +00001661\item The \module{pkgutil} module, containing various utility
1662functions for finding packages, was enhanced to support PEP 302's
1663import hooks and now also works for packages stored in ZIP-format archives.
1664(Contributed by Phillip J. Eby.)
1665
1666\item The pybench benchmark suite by Marc-Andr\'e~Lemburg is now
1667included in the \file{Tools/pybench} directory. The pybench suite is
1668an improvement on the commonly used \file{pystone.py} program because
1669pybench provides a more detailed measurement of the interpreter's
1670speed. It times particular operations such as function calls,
1671tuple slicing, method lookups, and numeric operations, instead of
1672performing many different operations and reducing the result to a
1673single number as \file{pystone.py} does.
1674
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001675\item The \module{pyexpat} module now uses version 2.0 of the Expat parser.
1676(Contributed by Trent Mick.)
1677
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001678\item The \class{Queue} class provided by the \module{Queue} module
1679gained two new methods. \method{join()} blocks until all items in
1680the queue have been retrieved and all processing work on the items
1681have been completed. Worker threads call the other new method,
1682\method{task_done()}, to signal that processing for an item has been
1683completed. (Contributed by Raymond Hettinger.)
1684
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001685\item The old \module{regex} and \module{regsub} modules, which have been
1686deprecated ever since Python 2.0, have finally been deleted.
1687Other deleted modules: \module{statcache}, \module{tzparse},
1688\module{whrandom}.
1689
Thomas Woutersd4ec0c32006-04-21 16:44:05 +00001690\item Also deleted: the \file{lib-old} directory,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001691which includes ancient modules such as \module{dircmp} and
Thomas Woutersd4ec0c32006-04-21 16:44:05 +00001692\module{ni}, was removed. \file{lib-old} wasn't on the default
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001693\code{sys.path}, so unless your programs explicitly added the directory to
1694\code{sys.path}, this removal shouldn't affect your code.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001695
Thomas Wouters477c8d52006-05-27 19:21:47 +00001696\item The \module{rlcompleter} module is no longer
1697dependent on importing the \module{readline} module and
1698therefore now works on non-{\UNIX} platforms.
1699(Patch from Robert Kiendl.)
1700% Patch #1472854
1701
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001702\item The \module{SimpleXMLRPCServer} and \module{DocXMLRPCServer}
1703classes now have a \member{rpc_paths} attribute that constrains
1704XML-RPC operations to a limited set of URL paths; the default is
1705to allow only \code{'/'} and \code{'/RPC2'}. Setting
1706\member{rpc_paths} to \code{None} or an empty tuple disables
1707this path checking.
1708% Bug #1473048
1709
Andrew M. Kuchling4678dc82006-01-15 16:11:28 +00001710\item The \module{socket} module now supports \constant{AF_NETLINK}
1711sockets on Linux, thanks to a patch from Philippe Biondi.
1712Netlink sockets are a Linux-specific mechanism for communications
1713between a user-space process and kernel code; an introductory
1714article about them is at \url{http://www.linuxjournal.com/article/7356}.
1715In Python code, netlink addresses are represented as a tuple of 2 integers,
1716\code{(\var{pid}, \var{group_mask})}.
1717
Guido van Rossumd8faa362007-04-27 19:54:29 +00001718Two new methods on socket objects, \method{recv_into(\var{buffer})} and
1719\method{recvfrom_into(\var{buffer})}, store the received data in an object
Thomas Wouters477c8d52006-05-27 19:21:47 +00001720that supports the buffer protocol instead of returning the data as a
1721string. This means you can put the data directly into an array or a
1722memory-mapped file.
1723
1724Socket objects also gained \method{getfamily()}, \method{gettype()},
1725and \method{getproto()} accessor methods to retrieve the family, type,
1726and protocol values for the socket.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001727
1728\item New module: the \module{spwd} module provides functions for
1729accessing the shadow password database on systems that support
1730shadow passwords.
1731
Thomas Wouters477c8d52006-05-27 19:21:47 +00001732\item The \module{struct} is now faster because it
1733compiles format strings into \class{Struct} objects
1734with \method{pack()} and \method{unpack()} methods. This is similar
1735to how the \module{re} module lets you create compiled regular
1736expression objects. You can still use the module-level
1737\function{pack()} and \function{unpack()} functions; they'll create
1738\class{Struct} objects and cache them. Or you can use
1739\class{Struct} instances directly:
1740
1741\begin{verbatim}
1742s = struct.Struct('ih3s')
1743
1744data = s.pack(1972, 187, 'abc')
1745year, number, name = s.unpack(data)
1746\end{verbatim}
1747
1748You can also pack and unpack data to and from buffer objects directly
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001749using the \method{pack_into(\var{buffer}, \var{offset}, \var{v1},
Thomas Wouters477c8d52006-05-27 19:21:47 +00001750\var{v2}, ...)} and \method{unpack_from(\var{buffer}, \var{offset})}
1751methods. This lets you store data directly into an array or a
1752memory-mapped file.
1753
1754(\class{Struct} objects were implemented by Bob Ippolito at the
1755NeedForSpeed sprint. Support for buffer objects was added by Martin
1756Blais, also at the NeedForSpeed sprint.)
1757
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001758\item The Python developers switched from CVS to Subversion during the 2.5
Thomas Wouters477c8d52006-05-27 19:21:47 +00001759development process. Information about the exact build version is
1760available as the \code{sys.subversion} variable, a 3-tuple of
1761\code{(\var{interpreter-name}, \var{branch-name},
1762\var{revision-range})}. For example, at the time of writing my copy
1763of 2.5 was reporting \code{('CPython', 'trunk', '45313:45315')}.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001764
1765This information is also available to C extensions via the
1766\cfunction{Py_GetBuildInfo()} function that returns a
1767string of build information like this:
1768\code{"trunk:45355:45356M, Apr 13 2006, 07:42:19"}.
1769(Contributed by Barry Warsaw.)
Fred Drake2db76802004-12-01 05:05:47 +00001770
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001771\item Another new function, \function{sys._current_frames()}, returns
1772the current stack frames for all running threads as a dictionary
1773mapping thread identifiers to the topmost stack frame currently active
1774in that thread at the time the function is called. (Contributed by
1775Tim Peters.)
1776
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001777\item The \class{TarFile} class in the \module{tarfile} module now has
Georg Brandl08c02db2005-07-22 18:39:19 +00001778an \method{extractall()} method that extracts all members from the
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001779archive into the current working directory. It's also possible to set
1780a different directory as the extraction target, and to unpack only a
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001781subset of the archive's members.
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001782
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001783The compression used for a tarfile opened in stream mode can now be
1784autodetected using the mode \code{'r|*'}.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001785% patch 918101
1786(Contributed by Lars Gust\"abel.)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001787
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001788\item The \module{threading} module now lets you set the stack size
1789used when new threads are created. The
1790\function{stack_size(\optional{\var{size}})} function returns the
1791currently configured stack size, and supplying the optional \var{size}
1792parameter sets a new value. Not all platforms support changing the
1793stack size, but Windows, POSIX threading, and OS/2 all do.
1794(Contributed by Andrew MacIntyre.)
1795% Patch 1454481
1796
Andrew M. Kuchlingf688cc52006-03-10 18:50:08 +00001797\item The \module{unicodedata} module has been updated to use version 4.1.0
1798of the Unicode character database. Version 3.2.0 is required
1799by some specifications, so it's still available as
Thomas Wouters477c8d52006-05-27 19:21:47 +00001800\member{unicodedata.ucd_3_2_0}.
Andrew M. Kuchlingf688cc52006-03-10 18:50:08 +00001801
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001802\item New module: the \module{uuid} module generates
1803universally unique identifiers (UUIDs) according to \rfc{4122}. The
1804RFC defines several different UUID versions that are generated from a
1805starting string, from system properties, or purely randomly. This
1806module contains a \class{UUID} class and
1807functions named \function{uuid1()},
1808\function{uuid3()}, \function{uuid4()}, and
1809\function{uuid5()} to generate different versions of UUID. (Version 2 UUIDs
1810are not specified in \rfc{4122} and are not supported by this module.)
1811
1812\begin{verbatim}
1813>>> import uuid
1814>>> # make a UUID based on the host ID and current time
1815>>> uuid.uuid1()
1816UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')
1817
1818>>> # make a UUID using an MD5 hash of a namespace UUID and a name
1819>>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
1820UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')
1821
1822>>> # make a random UUID
1823>>> uuid.uuid4()
1824UUID('16fd2706-8baf-433b-82eb-8c7fada847da')
1825
1826>>> # make a UUID using a SHA-1 hash of a namespace UUID and a name
1827>>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
1828UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')
1829\end{verbatim}
1830
1831(Contributed by Ka-Ping Yee.)
1832
1833\item The \module{weakref} module's \class{WeakKeyDictionary} and
1834\class{WeakValueDictionary} types gained new methods for iterating
1835over the weak references contained in the dictionary.
1836\method{iterkeyrefs()} and \method{keyrefs()} methods were
1837added to \class{WeakKeyDictionary}, and
1838\method{itervaluerefs()} and \method{valuerefs()} were added to
1839\class{WeakValueDictionary}. (Contributed by Fred L.~Drake, Jr.)
1840
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001841\item The \module{webbrowser} module received a number of
1842enhancements.
1843It's now usable as a script with \code{python -m webbrowser}, taking a
1844URL as the argument; there are a number of switches
1845to control the behaviour (\programopt{-n} for a new browser window,
1846\programopt{-t} for a new tab). New module-level functions,
1847\function{open_new()} and \function{open_new_tab()}, were added
1848to support this. The module's \function{open()} function supports an
1849additional feature, an \var{autoraise} parameter that signals whether
1850to raise the open window when possible. A number of additional
1851browsers were added to the supported list such as Firefox, Opera,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001852Konqueror, and elinks. (Contributed by Oleg Broytmann and Georg
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001853Brandl.)
1854% Patch #754022
1855
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001856\item The \module{xmlrpclib} module now supports returning
1857 \class{datetime} objects for the XML-RPC date type. Supply
1858 \code{use_datetime=True} to the \function{loads()} function
1859 or the \class{Unmarshaller} class to enable this feature.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001860 (Contributed by Skip Montanaro.)
1861% Patch 1120353
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001862
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001863\item The \module{zipfile} module now supports the ZIP64 version of the
1864format, meaning that a .zip archive can now be larger than 4~GiB and
1865can contain individual files larger than 4~GiB. (Contributed by
1866Ronald Oussoren.)
1867% Patch 1446489
1868
Thomas Wouters477c8d52006-05-27 19:21:47 +00001869\item The \module{zlib} module's \class{Compress} and \class{Decompress}
1870objects now support a \method{copy()} method that makes a copy of the
1871object's internal state and returns a new
1872\class{Compress} or \class{Decompress} object.
1873(Contributed by Chris AtLee.)
1874% Patch 1435422
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001875
Fred Drake114b8ca2005-03-21 05:47:11 +00001876\end{itemize}
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001877
Fred Drake2db76802004-12-01 05:05:47 +00001878
1879
1880%======================================================================
Thomas Wouters477c8d52006-05-27 19:21:47 +00001881\subsection{The ctypes package\label{module-ctypes}}
Fred Drake2db76802004-12-01 05:05:47 +00001882
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001883The \module{ctypes} package, written by Thomas Heller, has been added
1884to the standard library. \module{ctypes} lets you call arbitrary functions
1885in shared libraries or DLLs. Long-time users may remember the \module{dl} module, which
1886provides functions for loading shared libraries and calling functions in them. The \module{ctypes} package is much fancier.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001887
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001888To load a shared library or DLL, you must create an instance of the
1889\class{CDLL} class and provide the name or path of the shared library
1890or DLL. Once that's done, you can call arbitrary functions
1891by accessing them as attributes of the \class{CDLL} object.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001892
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001893\begin{verbatim}
1894import ctypes
1895
1896libc = ctypes.CDLL('libc.so.6')
1897result = libc.printf("Line of output\n")
1898\end{verbatim}
1899
1900Type constructors for the various C types are provided: \function{c_int},
1901\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
1902to change the wrapped value. Python integers and strings will be automatically
1903converted to the corresponding C types, but for other types you
1904must call the correct type constructor. (And I mean \emph{must};
1905getting it wrong will often result in the interpreter crashing
1906with a segmentation fault.)
1907
1908You 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
1909supposed to be immutable; breaking this rule will cause puzzling bugs. When you need a modifiable memory area,
1910use \function{create_string_buffer()}:
1911
1912\begin{verbatim}
1913s = "this is a string"
1914buf = ctypes.create_string_buffer(s)
1915libc.strfry(buf)
1916\end{verbatim}
1917
1918C functions are assumed to return integers, but you can set
1919the \member{restype} attribute of the function object to
1920change this:
1921
1922\begin{verbatim}
1923>>> libc.atof('2.71828')
1924-1783957616
1925>>> libc.atof.restype = ctypes.c_double
1926>>> libc.atof('2.71828')
19272.71828
1928\end{verbatim}
1929
1930\module{ctypes} also provides a wrapper for Python's C API
1931as the \code{ctypes.pythonapi} object. This object does \emph{not}
1932release the global interpreter lock before calling a function, because the lock must be held when calling into the interpreter's code.
1933There's a \class{py_object()} type constructor that will create a
1934\ctype{PyObject *} pointer. A simple usage:
1935
1936\begin{verbatim}
1937import ctypes
1938
1939d = {}
1940ctypes.pythonapi.PyObject_SetItem(ctypes.py_object(d),
1941 ctypes.py_object("abc"), ctypes.py_object(1))
1942# d is now {'abc', 1}.
1943\end{verbatim}
1944
1945Don't forget to use \class{py_object()}; if it's omitted you end
1946up with a segmentation fault.
1947
1948\module{ctypes} has been around for a while, but people still write
1949and distribution hand-coded extension modules because you can't rely on \module{ctypes} being present.
1950Perhaps developers will begin to write
1951Python wrappers atop a library accessed through \module{ctypes} instead
1952of extension modules, now that \module{ctypes} is included with core Python.
1953
1954\begin{seealso}
1955
1956\seeurl{http://starship.python.net/crew/theller/ctypes/}
1957{The ctypes web page, with a tutorial, reference, and FAQ.}
1958
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001959\seeurl{../lib/module-ctypes.html}{The documentation
1960for the \module{ctypes} module.}
1961
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001962\end{seealso}
1963
1964
1965%======================================================================
Thomas Wouters477c8d52006-05-27 19:21:47 +00001966\subsection{The ElementTree package\label{module-etree}}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001967
1968A subset of Fredrik Lundh's ElementTree library for processing XML has
Thomas Wouters477c8d52006-05-27 19:21:47 +00001969been added to the standard library as \module{xml.etree}. The
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001970available modules are
1971\module{ElementTree}, \module{ElementPath}, and
1972\module{ElementInclude} from ElementTree 1.2.6.
1973The \module{cElementTree} accelerator module is also included.
1974
1975The rest of this section will provide a brief overview of using
1976ElementTree. Full documentation for ElementTree is available at
1977\url{http://effbot.org/zone/element-index.htm}.
1978
1979ElementTree represents an XML document as a tree of element nodes.
1980The text content of the document is stored as the \member{.text}
1981and \member{.tail} attributes of
1982(This is one of the major differences between ElementTree and
1983the Document Object Model; in the DOM there are many different
1984types of node, including \class{TextNode}.)
1985
1986The most commonly used parsing function is \function{parse()}, that
1987takes either a string (assumed to contain a filename) or a file-like
1988object and returns an \class{ElementTree} instance:
1989
1990\begin{verbatim}
Thomas Wouters477c8d52006-05-27 19:21:47 +00001991from xml.etree import ElementTree as ET
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001992
1993tree = ET.parse('ex-1.xml')
1994
1995feed = urllib.urlopen(
1996 'http://planet.python.org/rss10.xml')
1997tree = ET.parse(feed)
1998\end{verbatim}
1999
2000Once you have an \class{ElementTree} instance, you
2001can call its \method{getroot()} method to get the root \class{Element} node.
2002
2003There's also an \function{XML()} function that takes a string literal
2004and returns an \class{Element} node (not an \class{ElementTree}).
2005This function provides a tidy way to incorporate XML fragments,
2006approaching the convenience of an XML literal:
2007
2008\begin{verbatim}
Thomas Wouters477c8d52006-05-27 19:21:47 +00002009svg = ET.XML("""<svg width="10px" version="1.0">
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002010 </svg>""")
2011svg.set('height', '320px')
2012svg.append(elem1)
2013\end{verbatim}
2014
2015Each XML element supports some dictionary-like and some list-like
2016access methods. Dictionary-like operations are used to access attribute
2017values, and list-like operations are used to access child nodes.
2018
2019\begin{tableii}{c|l}{code}{Operation}{Result}
2020 \lineii{elem[n]}{Returns n'th child element.}
2021 \lineii{elem[m:n]}{Returns list of m'th through n'th child elements.}
2022 \lineii{len(elem)}{Returns number of child elements.}
Thomas Wouters477c8d52006-05-27 19:21:47 +00002023 \lineii{list(elem)}{Returns list of child elements.}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002024 \lineii{elem.append(elem2)}{Adds \var{elem2} as a child.}
2025 \lineii{elem.insert(index, elem2)}{Inserts \var{elem2} at the specified location.}
2026 \lineii{del elem[n]}{Deletes n'th child element.}
2027 \lineii{elem.keys()}{Returns list of attribute names.}
2028 \lineii{elem.get(name)}{Returns value of attribute \var{name}.}
2029 \lineii{elem.set(name, value)}{Sets new value for attribute \var{name}.}
2030 \lineii{elem.attrib}{Retrieves the dictionary containing attributes.}
2031 \lineii{del elem.attrib[name]}{Deletes attribute \var{name}.}
2032\end{tableii}
2033
2034Comments and processing instructions are also represented as
2035\class{Element} nodes. To check if a node is a comment or processing
2036instructions:
2037
2038\begin{verbatim}
2039if elem.tag is ET.Comment:
2040 ...
2041elif elem.tag is ET.ProcessingInstruction:
2042 ...
2043\end{verbatim}
2044
2045To generate XML output, you should call the
2046\method{ElementTree.write()} method. Like \function{parse()},
2047it can take either a string or a file-like object:
2048
2049\begin{verbatim}
2050# Encoding is US-ASCII
2051tree.write('output.xml')
2052
2053# Encoding is UTF-8
2054f = open('output.xml', 'w')
Thomas Wouters477c8d52006-05-27 19:21:47 +00002055tree.write(f, encoding='utf-8')
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002056\end{verbatim}
2057
Thomas Wouters477c8d52006-05-27 19:21:47 +00002058(Caution: the default encoding used for output is ASCII. For general
2059XML work, where an element's name may contain arbitrary Unicode
2060characters, ASCII isn't a very useful encoding because it will raise
2061an exception if an element's name contains any characters with values
2062greater than 127. Therefore, it's best to specify a different
2063encoding such as UTF-8 that can handle any Unicode character.)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002064
2065This section is only a partial description of the ElementTree interfaces.
2066Please read the package's official documentation for more details.
2067
2068\begin{seealso}
2069
2070\seeurl{http://effbot.org/zone/element-index.htm}
2071{Official documentation for ElementTree.}
2072
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002073\end{seealso}
2074
2075
2076%======================================================================
Thomas Wouters477c8d52006-05-27 19:21:47 +00002077\subsection{The hashlib package\label{module-hashlib}}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002078
2079A new \module{hashlib} module, written by Gregory P. Smith,
2080has been added to replace the
2081\module{md5} and \module{sha} modules. \module{hashlib} adds support
2082for additional secure hashes (SHA-224, SHA-256, SHA-384, and SHA-512).
2083When available, the module uses OpenSSL for fast platform optimized
2084implementations of algorithms.
2085
2086The old \module{md5} and \module{sha} modules still exist as wrappers
2087around hashlib to preserve backwards compatibility. The new module's
2088interface is very close to that of the old modules, but not identical.
2089The most significant difference is that the constructor functions
2090for creating new hashing objects are named differently.
2091
2092\begin{verbatim}
2093# Old versions
2094h = md5.md5()
2095h = md5.new()
2096
2097# New version
2098h = hashlib.md5()
2099
2100# Old versions
2101h = sha.sha()
2102h = sha.new()
2103
2104# New version
2105h = hashlib.sha1()
2106
2107# Hash that weren't previously available
2108h = hashlib.sha224()
2109h = hashlib.sha256()
2110h = hashlib.sha384()
2111h = hashlib.sha512()
2112
2113# Alternative form
2114h = hashlib.new('md5') # Provide algorithm as a string
2115\end{verbatim}
2116
2117Once a hash object has been created, its methods are the same as before:
2118\method{update(\var{string})} hashes the specified string into the
2119current digest state, \method{digest()} and \method{hexdigest()}
2120return the digest value as a binary string or a string of hex digits,
2121and \method{copy()} returns a new hashing object with the same digest state.
2122
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002123\begin{seealso}
2124
2125\seeurl{../lib/module-hashlib.html}{The documentation
2126for the \module{hashlib} module.}
2127
2128\end{seealso}
2129
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002130
2131%======================================================================
Thomas Wouters477c8d52006-05-27 19:21:47 +00002132\subsection{The sqlite3 package\label{module-sqlite}}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002133
2134The pysqlite module (\url{http://www.pysqlite.org}), a wrapper for the
2135SQLite embedded database, has been added to the standard library under
2136the package name \module{sqlite3}.
2137
Thomas Wouters89f507f2006-12-13 04:49:30 +00002138SQLite is a C library that provides a lightweight disk-based database
2139that doesn't require a separate server process and allows accessing
2140the database using a nonstandard variant of the SQL query language.
2141Some applications can use SQLite for internal data storage. It's also
2142possible to prototype an application using SQLite and then port the
2143code to a larger database such as PostgreSQL or Oracle.
2144
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002145pysqlite was written by Gerhard H\"aring and provides a SQL interface
2146compliant with the DB-API 2.0 specification described by
Thomas Wouters89f507f2006-12-13 04:49:30 +00002147\pep{249}.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002148
2149If you're compiling the Python source yourself, note that the source
2150tree doesn't include the SQLite code, only the wrapper module.
2151You'll need to have the SQLite libraries and headers installed before
2152compiling Python, and the build process will compile the module when
2153the necessary headers are available.
2154
2155To use the module, you must first create a \class{Connection} object
2156that represents the database. Here the data will be stored in the
2157\file{/tmp/example} file:
2158
2159\begin{verbatim}
2160conn = sqlite3.connect('/tmp/example')
2161\end{verbatim}
2162
2163You can also supply the special name \samp{:memory:} to create
2164a database in RAM.
2165
2166Once you have a \class{Connection}, you can create a \class{Cursor}
2167object and call its \method{execute()} method to perform SQL commands:
2168
2169\begin{verbatim}
2170c = conn.cursor()
2171
2172# Create table
2173c.execute('''create table stocks
Thomas Wouters89f507f2006-12-13 04:49:30 +00002174(date text, trans text, symbol text,
2175 qty real, price real)''')
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002176
2177# Insert a row of data
2178c.execute("""insert into stocks
2179 values ('2006-01-05','BUY','RHAT',100,35.14)""")
2180\end{verbatim}
2181
2182Usually your SQL operations will need to use values from Python
2183variables. You shouldn't assemble your query using Python's string
2184operations because doing so is insecure; it makes your program
2185vulnerable to an SQL injection attack.
2186
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002187Instead, use the DB-API's parameter substitution. Put \samp{?} as a
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002188placeholder wherever you want to use a value, and then provide a tuple
2189of values as the second argument to the cursor's \method{execute()}
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00002190method. (Other database modules may use a different placeholder,
2191such as \samp{\%s} or \samp{:1}.) For example:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002192
2193\begin{verbatim}
2194# Never do this -- insecure!
2195symbol = 'IBM'
2196c.execute("... where symbol = '%s'" % symbol)
2197
2198# Do this instead
2199t = (symbol,)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002200c.execute('select * from stocks where symbol=?', t)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002201
2202# Larger example
2203for t in (('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
2204 ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
2205 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
2206 ):
2207 c.execute('insert into stocks values (?,?,?,?,?)', t)
2208\end{verbatim}
2209
2210To retrieve data after executing a SELECT statement, you can either
2211treat the cursor as an iterator, call the cursor's \method{fetchone()}
2212method to retrieve a single matching row,
2213or call \method{fetchall()} to get a list of the matching rows.
2214
2215This example uses the iterator form:
2216
2217\begin{verbatim}
2218>>> c = conn.cursor()
2219>>> c.execute('select * from stocks order by price')
2220>>> for row in c:
2221... print row
2222...
2223(u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001)
2224(u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
2225(u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
2226(u'2006-04-05', u'BUY', u'MSOFT', 1000, 72.0)
2227>>>
2228\end{verbatim}
2229
2230For more information about the SQL dialect supported by SQLite, see
2231\url{http://www.sqlite.org}.
2232
2233\begin{seealso}
2234
2235\seeurl{http://www.pysqlite.org}
2236{The pysqlite web page.}
2237
2238\seeurl{http://www.sqlite.org}
2239{The SQLite web page; the documentation describes the syntax and the
2240available data types for the supported SQL dialect.}
2241
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002242\seeurl{../lib/module-sqlite3.html}{The documentation
2243for the \module{sqlite3} module.}
2244
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002245\seepep{249}{Database API Specification 2.0}{PEP written by
2246Marc-Andr\'e Lemburg.}
2247
2248\end{seealso}
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00002249
Fred Drake2db76802004-12-01 05:05:47 +00002250
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002251%======================================================================
2252\subsection{The wsgiref package\label{module-wsgiref}}
2253
2254% XXX should this be in a PEP 333 section instead?
2255
2256The Web Server Gateway Interface (WSGI) v1.0 defines a standard
2257interface between web servers and Python web applications and is
2258described in \pep{333}. The \module{wsgiref} package is a reference
2259implementation of the WSGI specification.
2260
2261The package includes a basic HTTP server that will run a WSGI
2262application; this server is useful for debugging but isn't intended for
2263production use. Setting up a server takes only a few lines of code:
2264
2265\begin{verbatim}
2266from wsgiref import simple_server
2267
2268wsgi_app = ...
2269
2270host = ''
2271port = 8000
2272httpd = simple_server.make_server(host, port, wsgi_app)
2273httpd.serve_forever()
2274\end{verbatim}
2275
2276% XXX discuss structure of WSGI applications?
2277% XXX provide an example using Django or some other framework?
2278
2279\begin{seealso}
2280
2281\seeurl{http://www.wsgi.org}{A central web site for WSGI-related resources.}
2282
2283\seepep{333}{Python Web Server Gateway Interface v1.0}{PEP written by
2284Phillip J. Eby.}
2285
2286\end{seealso}
2287
2288
Fred Drake2db76802004-12-01 05:05:47 +00002289% ======================================================================
Thomas Wouters477c8d52006-05-27 19:21:47 +00002290\section{Build and C API Changes\label{build-api}}
Fred Drake2db76802004-12-01 05:05:47 +00002291
2292Changes to Python's build process and to the C API include:
2293
2294\begin{itemize}
2295
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002296\item The Python source tree was converted from CVS to Subversion,
2297in a complex migration procedure that was supervised and flawlessly
2298carried out by Martin von~L\"owis. The procedure was developed as
2299\pep{347}.
2300
2301\item Coverity, a company that markets a source code analysis tool
2302called Prevent, provided the results of their examination of the Python
2303source code. The analysis found about 60 bugs that
2304were quickly fixed. Many of the bugs were refcounting problems, often
2305occurring in error-handling code. See
2306\url{http://scan.coverity.com} for the statistics.
2307
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002308\item The largest change to the C API came from \pep{353},
2309which modifies the interpreter to use a \ctype{Py_ssize_t} type
2310definition instead of \ctype{int}. See the earlier
Thomas Woutersd4ec0c32006-04-21 16:44:05 +00002311section~\ref{pep-353} for a discussion of this change.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002312
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002313\item The design of the bytecode compiler has changed a great deal,
2314no longer generating bytecode by traversing the parse tree. Instead
Andrew M. Kuchlingdb85ed52005-10-23 21:52:59 +00002315the parse tree is converted to an abstract syntax tree (or AST), and it is
2316the abstract syntax tree that's traversed to produce the bytecode.
2317
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002318It's possible for Python code to obtain AST objects by using the
2319\function{compile()} built-in and specifying \code{_ast.PyCF_ONLY_AST}
2320as the value of the
2321\var{flags} parameter:
2322
2323\begin{verbatim}
2324from _ast import PyCF_ONLY_AST
2325ast = compile("""a=0
2326for i in range(10):
2327 a += i
2328""", "<string>", 'exec', PyCF_ONLY_AST)
2329
2330assignment = ast.body[0]
2331for_loop = ast.body[1]
2332\end{verbatim}
2333
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002334No official documentation has been written for the AST code yet, but
2335\pep{339} discusses the design. To start learning about the code, read the
2336definition of the various AST nodes in \file{Parser/Python.asdl}. A
2337Python script reads this file and generates a set of C structure
2338definitions in \file{Include/Python-ast.h}. The
2339\cfunction{PyParser_ASTFromString()} and
2340\cfunction{PyParser_ASTFromFile()}, defined in
Andrew M. Kuchlingdb85ed52005-10-23 21:52:59 +00002341\file{Include/pythonrun.h}, take Python source as input and return the
2342root of an AST representing the contents. This AST can then be turned
2343into a code object by \cfunction{PyAST_Compile()}. For more
2344information, read the source code, and then ask questions on
2345python-dev.
2346
2347% List of names taken from Jeremy's python-dev post at
2348% http://mail.python.org/pipermail/python-dev/2005-October/057500.html
2349The AST code was developed under Jeremy Hylton's management, and
2350implemented by (in alphabetical order) Brett Cannon, Nick Coghlan,
2351Grant Edwards, John Ehresman, Kurt Kaiser, Neal Norwitz, Tim Peters,
2352Armin Rigo, and Neil Schemenauer, plus the participants in a number of
2353AST sprints at conferences such as PyCon.
2354
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002355\item Evan Jones's patch to obmalloc, first described in a talk
2356at PyCon DC 2005, was applied. Python 2.4 allocated small objects in
2357256K-sized arenas, but never freed arenas. With this patch, Python
2358will free arenas when they're empty. The net effect is that on some
2359platforms, when you allocate many objects, Python's memory usage may
2360actually drop when you delete them and the memory may be returned to
2361the operating system. (Implemented by Evan Jones, and reworked by Tim
2362Peters.)
2363
2364Note that this change means extension modules must be more careful
2365when allocating memory. Python's API has many different
2366functions for allocating memory that are grouped into families. For
2367example, \cfunction{PyMem_Malloc()}, \cfunction{PyMem_Realloc()}, and
2368\cfunction{PyMem_Free()} are one family that allocates raw memory,
2369while \cfunction{PyObject_Malloc()}, \cfunction{PyObject_Realloc()},
2370and \cfunction{PyObject_Free()} are another family that's supposed to
2371be used for creating Python objects.
2372
2373Previously these different families all reduced to the platform's
2374\cfunction{malloc()} and \cfunction{free()} functions. This meant
2375it didn't matter if you got things wrong and allocated memory with the
2376\cfunction{PyMem} function but freed it with the \cfunction{PyObject}
2377function. With 2.5's changes to obmalloc, these families now do different
2378things and mismatches will probably result in a segfault. You should
2379carefully test your C extension modules with Python 2.5.
2380
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00002381\item The built-in set types now have an official C API. Call
2382\cfunction{PySet_New()} and \cfunction{PyFrozenSet_New()} to create a
2383new set, \cfunction{PySet_Add()} and \cfunction{PySet_Discard()} to
2384add and remove elements, and \cfunction{PySet_Contains} and
2385\cfunction{PySet_Size} to examine the set's state.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002386(Contributed by Raymond Hettinger.)
2387
2388\item C code can now obtain information about the exact revision
2389of the Python interpreter by calling the
2390\cfunction{Py_GetBuildInfo()} function that returns a
2391string of build information like this:
2392\code{"trunk:45355:45356M, Apr 13 2006, 07:42:19"}.
2393(Contributed by Barry Warsaw.)
2394
Thomas Wouters477c8d52006-05-27 19:21:47 +00002395\item Two new macros can be used to indicate C functions that are
2396local to the current file so that a faster calling convention can be
2397used. \cfunction{Py_LOCAL(\var{type})} declares the function as
2398returning a value of the specified \var{type} and uses a fast-calling
2399qualifier. \cfunction{Py_LOCAL_INLINE(\var{type})} does the same thing
2400and also requests the function be inlined. If
2401\cfunction{PY_LOCAL_AGGRESSIVE} is defined before \file{python.h} is
2402included, a set of more aggressive optimizations are enabled for the
2403module; you should benchmark the results to find out if these
2404optimizations actually make the code faster. (Contributed by Fredrik
2405Lundh at the NeedForSpeed sprint.)
2406
2407\item \cfunction{PyErr_NewException(\var{name}, \var{base},
2408\var{dict})} can now accept a tuple of base classes as its \var{base}
2409argument. (Contributed by Georg Brandl.)
2410
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002411\item The \cfunction{PyErr_Warn()} function for issuing warnings
2412is now deprecated in favour of \cfunction{PyErr_WarnEx(category,
2413message, stacklevel)} which lets you specify the number of stack
2414frames separating this function and the caller. A \var{stacklevel} of
24151 is the function calling \cfunction{PyErr_WarnEx()}, 2 is the
2416function above that, and so forth. (Added by Neal Norwitz.)
2417
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002418\item The CPython interpreter is still written in C, but
2419the code can now be compiled with a {\Cpp} compiler without errors.
2420(Implemented by Anthony Baxter, Martin von~L\"owis, Skip Montanaro.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00002421
2422\item The \cfunction{PyRange_New()} function was removed. It was
2423never documented, never used in the core code, and had dangerously lax
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002424error checking. In the unlikely case that your extensions were using
2425it, you can replace it by something like the following:
2426\begin{verbatim}
2427range = PyObject_CallFunction((PyObject*) &PyRange_Type, "lll",
2428 start, stop, step);
2429\end{verbatim}
Fred Drake2db76802004-12-01 05:05:47 +00002430
2431\end{itemize}
2432
2433
2434%======================================================================
Thomas Wouters477c8d52006-05-27 19:21:47 +00002435\subsection{Port-Specific Changes\label{ports}}
Fred Drake2db76802004-12-01 05:05:47 +00002436
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002437\begin{itemize}
2438
2439\item MacOS X (10.3 and higher): dynamic loading of modules
2440now uses the \cfunction{dlopen()} function instead of MacOS-specific
2441functions.
2442
Thomas Wouters477c8d52006-05-27 19:21:47 +00002443\item MacOS X: a \longprogramopt{enable-universalsdk} switch was added
2444to the \program{configure} script that compiles the interpreter as a
2445universal binary able to run on both PowerPC and Intel processors.
2446(Contributed by Ronald Oussoren.)
2447
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002448\item Windows: \file{.dll} is no longer supported as a filename extension for
2449extension modules. \file{.pyd} is now the only filename extension that will
2450be searched for.
2451
2452\end{itemize}
Fred Drake2db76802004-12-01 05:05:47 +00002453
2454
2455%======================================================================
Thomas Wouters477c8d52006-05-27 19:21:47 +00002456\section{Porting to Python 2.5\label{porting}}
Fred Drake2db76802004-12-01 05:05:47 +00002457
2458This section lists previously described changes that may require
2459changes to your code:
2460
2461\begin{itemize}
2462
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002463\item ASCII is now the default encoding for modules. It's now
2464a syntax error if a module contains string literals with 8-bit
2465characters but doesn't have an encoding declaration. In Python 2.4
2466this triggered a warning, not a syntax error.
Andrew M. Kuchling0c35db92005-03-20 20:06:49 +00002467
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002468\item Previously, the \member{gi_frame} attribute of a generator
2469was always a frame object. Because of the \pep{342} changes
Thomas Woutersd4ec0c32006-04-21 16:44:05 +00002470described in section~\ref{pep-342}, it's now possible
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002471for \member{gi_frame} to be \code{None}.
Andrew M. Kuchling0c35db92005-03-20 20:06:49 +00002472
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002473\item A new warning, \class{UnicodeWarning}, is triggered when
2474you attempt to compare a Unicode string and an 8-bit string that can't
2475be converted to Unicode using the default ASCII encoding. Previously
2476such comparisons would raise a \class{UnicodeDecodeError} exception.
2477
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002478\item Library: the \module{csv} module is now stricter about multi-line quoted
2479fields. If your files contain newlines embedded within fields, the
2480input should be split into lines in a manner which preserves the
2481newline characters.
2482
2483\item Library: the \module{locale} module's
2484\function{format()} function's would previously
2485accept any string as long as no more than one \%char specifier
2486appeared. In Python 2.5, the argument must be exactly one \%char
2487specifier with no surrounding text.
Thomas Woutersd4ec0c32006-04-21 16:44:05 +00002488
2489\item Library: The \module{pickle} and \module{cPickle} modules no
2490longer accept a return value of \code{None} from the
2491\method{__reduce__()} method; the method must return a tuple of
2492arguments instead. The modules also no longer accept the deprecated
2493\var{bin} keyword parameter.
2494
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002495\item Library: The \module{SimpleXMLRPCServer} and \module{DocXMLRPCServer}
2496classes now have a \member{rpc_paths} attribute that constrains
2497XML-RPC operations to a limited set of URL paths; the default is
2498to allow only \code{'/'} and \code{'/RPC2'}. Setting
2499\member{rpc_paths} to \code{None} or an empty tuple disables
2500this path checking.
2501
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002502\item C API: Many functions now use \ctype{Py_ssize_t}
Thomas Woutersd4ec0c32006-04-21 16:44:05 +00002503instead of \ctype{int} to allow processing more data on 64-bit
2504machines. Extension code may need to make the same change to avoid
2505warnings and to support 64-bit machines. See the earlier
2506section~\ref{pep-353} for a discussion of this change.
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00002507
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002508\item C API:
2509The obmalloc changes mean that
2510you must be careful to not mix usage
2511of the \cfunction{PyMem_*()} and \cfunction{PyObject_*()}
2512families of functions. Memory allocated with
2513one family's \cfunction{*_Malloc()} must be
2514freed with the corresponding family's \cfunction{*_Free()} function.
Fred Drake2db76802004-12-01 05:05:47 +00002515
2516\end{itemize}
2517
2518
2519%======================================================================
2520\section{Acknowledgements \label{acks}}
2521
2522The author would like to thank the following people for offering
2523suggestions, corrections and assistance with various drafts of this
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002524article: Georg Brandl, Nick Coghlan, Phillip J. Eby, Lars Gust\"abel,
2525Raymond Hettinger, Ralf W. Grosse-Kunstleve, Kent Johnson, Iain Lowe,
2526Martin von~L\"owis, Fredrik Lundh, Andrew McNamara, Skip Montanaro,
2527Gustavo Niemeyer, Paul Prescod, James Pryor, Mike Rovner, Scott
2528Weikart, Barry Warsaw, Thomas Wouters.
Fred Drake2db76802004-12-01 05:05:47 +00002529
2530\end{document}