blob: db6c25a508b0c819a6776409885af46cb259ea77 [file] [log] [blame]
Fred Drake2db76802004-12-01 05:05:47 +00001\documentclass{howto}
2\usepackage{distutils}
3% $Id$
4
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00005% The easy_install stuff
Andrew M. Kuchling952f1962006-04-18 12:38:19 +00006% Describe the pkgutil module
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00007% Stateful codec changes
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00008% Fix XXX comments
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00009% Count up the patches and bugs
Fred Drake2db76802004-12-01 05:05:47 +000010
11\title{What's New in Python 2.5}
Andrew M. Kuchling2cdb23e2006-04-05 13:59:01 +000012\release{0.1}
Andrew M. Kuchling92e24952004-12-03 13:54:09 +000013\author{A.M. Kuchling}
14\authoraddress{\email{amk@amk.ca}}
Fred Drake2db76802004-12-01 05:05:47 +000015
16\begin{document}
17\maketitle
18\tableofcontents
19
20This article explains the new features in Python 2.5. No release date
Andrew M. Kuchling5eefdca2006-02-08 11:36:09 +000021for Python 2.5 has been set; it will probably be released in the
Andrew M. Kuchlingd96a6ac2006-04-04 19:17:34 +000022autumn of 2006. \pep{356} describes the planned release schedule.
Fred Drake2db76802004-12-01 05:05:47 +000023
Andrew M. Kuchling0d660c02006-04-17 14:01:36 +000024Comments, suggestions, and error reports are welcome; please e-mail them
25to the author or open a bug in the Python bug tracker.
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +000026
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000027% XXX Compare with previous release in 2 - 3 sentences here.
Fred Drake2db76802004-12-01 05:05:47 +000028
29This article doesn't attempt to provide a complete specification of
30the new features, but instead provides a convenient overview. For
31full details, you should refer to the documentation for Python 2.5.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000032% XXX add hyperlink when the documentation becomes available online.
Fred Drake2db76802004-12-01 05:05:47 +000033If you want to understand the complete implementation and design
34rationale, refer to the PEP for a particular new feature.
35
36
37%======================================================================
Andrew M. Kuchling6a67e4e2006-04-12 13:03:35 +000038\section{PEP 243: Uploading Modules to PyPI}
39
40PEP 243 describes an HTTP-based protocol for submitting software
41packages to a central archive. The Python package index at
42\url{http://cheeseshop.python.org} now supports package uploads, and
43the new \command{upload} Distutils command will upload a package to the
44repository.
45
46Before a package can be uploaded, you must be able to build a
47distribution using the \command{sdist} Distutils command. Once that
48works, you can run \code{python setup.py upload} to add your package
49to the PyPI archive. Optionally you can GPG-sign the package by
George Yoshida297bf822006-04-17 15:44:59 +000050supplying the \longprogramopt{sign} and
51\longprogramopt{identity} options.
Andrew M. Kuchling6a67e4e2006-04-12 13:03:35 +000052
53\begin{seealso}
54
55\seepep{243}{Module Repository Upload Mechanism}{PEP written by
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +000056Sean Reifschneider; implemented by Martin von~L\"owis
Andrew M. Kuchling6a67e4e2006-04-12 13:03:35 +000057and Richard Jones. Note that the PEP doesn't exactly
58describe what's implemented in PyPI.}
59
60\end{seealso}
61
62
63%======================================================================
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000064\section{PEP 308: Conditional Expressions}
65
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000066For a long time, people have been requesting a way to write
67conditional expressions, expressions that return value A or value B
68depending on whether a Boolean value is true or false. A conditional
69expression lets you write a single assignment statement that has the
70same effect as the following:
71
72\begin{verbatim}
73if condition:
74 x = true_value
75else:
76 x = false_value
77\end{verbatim}
78
79There have been endless tedious discussions of syntax on both
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +000080python-dev and comp.lang.python. A vote was even held that found the
81majority of voters wanted conditional expressions in some form,
82but there was no syntax that was preferred by a clear majority.
83Candidates included C's \code{cond ? true_v : false_v},
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000084\code{if cond then true_v else false_v}, and 16 other variations.
85
86GvR eventually chose a surprising syntax:
87
88\begin{verbatim}
89x = true_value if condition else false_value
90\end{verbatim}
91
Andrew M. Kuchling38f85072006-04-02 01:46:32 +000092Evaluation is still lazy as in existing Boolean expressions, so the
93order of evaluation jumps around a bit. The \var{condition}
94expression in the middle is evaluated first, and the \var{true_value}
95expression is evaluated only if the condition was true. Similarly,
96the \var{false_value} expression is only evaluated when the condition
97is false.
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000098
99This syntax may seem strange and backwards; why does the condition go
100in the \emph{middle} of the expression, and not in the front as in C's
101\code{c ? x : y}? The decision was checked by applying the new syntax
102to the modules in the standard library and seeing how the resulting
103code read. In many cases where a conditional expression is used, one
104value seems to be the 'common case' and one value is an 'exceptional
105case', used only on rarer occasions when the condition isn't met. The
106conditional syntax makes this pattern a bit more obvious:
107
108\begin{verbatim}
109contents = ((doc + '\n') if doc else '')
110\end{verbatim}
111
112I read the above statement as meaning ``here \var{contents} is
Andrew M. Kuchlingd0fcc022006-03-09 13:57:28 +0000113usually assigned a value of \code{doc+'\e n'}; sometimes
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +0000114\var{doc} is empty, in which special case an empty string is returned.''
115I doubt I will use conditional expressions very often where there
116isn't a clear common and uncommon case.
117
118There was some discussion of whether the language should require
119surrounding conditional expressions with parentheses. The decision
120was made to \emph{not} require parentheses in the Python language's
121grammar, but as a matter of style I think you should always use them.
122Consider these two statements:
123
124\begin{verbatim}
125# First version -- no parens
126level = 1 if logging else 0
127
128# Second version -- with parens
129level = (1 if logging else 0)
130\end{verbatim}
131
132In the first version, I think a reader's eye might group the statement
133into 'level = 1', 'if logging', 'else 0', and think that the condition
134decides whether the assignment to \var{level} is performed. The
135second version reads better, in my opinion, because it makes it clear
136that the assignment is always performed and the choice is being made
137between two values.
138
139Another reason for including the brackets: a few odd combinations of
140list comprehensions and lambdas could look like incorrect conditional
141expressions. See \pep{308} for some examples. If you put parentheses
142around your conditional expressions, you won't run into this case.
143
144
145\begin{seealso}
146
147\seepep{308}{Conditional Expressions}{PEP written by
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000148Guido van~Rossum and Raymond D. Hettinger; implemented by Thomas
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +0000149Wouters.}
150
151\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000152
153
154%======================================================================
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +0000155\section{PEP 309: Partial Function Application}
Fred Drake2db76802004-12-01 05:05:47 +0000156
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000157The \module{functional} module is intended to contain tools for
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000158functional-style programming. Currently it only contains a
159\class{partial()} function, but new functions will probably be added
160in future versions of Python.
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000161
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000162For programs written in a functional style, it can be useful to
163construct variants of existing functions that have some of the
164parameters filled in. Consider a Python function \code{f(a, b, c)};
165you could create a new function \code{g(b, c)} that was equivalent to
166\code{f(1, b, c)}. This is called ``partial function application'',
167and is provided by the \class{partial} class in the new
168\module{functional} module.
169
170The constructor for \class{partial} takes the arguments
171\code{(\var{function}, \var{arg1}, \var{arg2}, ...
172\var{kwarg1}=\var{value1}, \var{kwarg2}=\var{value2})}. The resulting
173object is callable, so you can just call it to invoke \var{function}
174with the filled-in arguments.
175
176Here's a small but realistic example:
177
178\begin{verbatim}
179import functional
180
181def log (message, subsystem):
182 "Write the contents of 'message' to the specified subsystem."
183 print '%s: %s' % (subsystem, message)
184 ...
185
186server_log = functional.partial(log, subsystem='server')
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000187server_log('Unable to open socket')
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000188\end{verbatim}
189
Andrew M. Kuchling6af7fe02005-08-02 17:20:36 +0000190Here's another example, from a program that uses PyGTk. Here a
191context-sensitive pop-up menu is being constructed dynamically. The
192callback provided for the menu option is a partially applied version
193of the \method{open_item()} method, where the first argument has been
194provided.
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000195
Andrew M. Kuchling6af7fe02005-08-02 17:20:36 +0000196\begin{verbatim}
197...
198class Application:
199 def open_item(self, path):
200 ...
201 def init (self):
202 open_func = functional.partial(self.open_item, item_path)
203 popup_menu.append( ("Open", open_func, 1) )
204\end{verbatim}
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000205
206
207\begin{seealso}
208
209\seepep{309}{Partial Function Application}{PEP proposed and written by
210Peter Harris; implemented by Hye-Shik Chang, with adaptations by
211Raymond Hettinger.}
212
213\end{seealso}
Fred Drake2db76802004-12-01 05:05:47 +0000214
215
216%======================================================================
Fred Drakedb7b0022005-03-20 22:19:47 +0000217\section{PEP 314: Metadata for Python Software Packages v1.1}
218
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000219Some simple dependency support was added to Distutils. The
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000220\function{setup()} function now has \code{requires}, \code{provides},
221and \code{obsoletes} keyword parameters. When you build a source
222distribution using the \code{sdist} command, the dependency
223information will be recorded in the \file{PKG-INFO} file.
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000224
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000225Another new keyword parameter is \code{download_url}, which should be
226set to a URL for the package's source code. This means it's now
227possible to look up an entry in the package index, determine the
228dependencies for a package, and download the required packages.
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000229
Andrew M. Kuchling61434b62006-04-13 11:51:07 +0000230\begin{verbatim}
231VERSION = '1.0'
232setup(name='PyPackage',
233 version=VERSION,
234 requires=['numarray', 'zlib (>=1.1.4)'],
235 obsoletes=['OldPackage']
236 download_url=('http://www.example.com/pypackage/dist/pkg-%s.tar.gz'
237 % VERSION),
238 )
239\end{verbatim}
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000240
241\begin{seealso}
242
243\seepep{314}{Metadata for Python Software Packages v1.1}{PEP proposed
244and written by A.M. Kuchling, Richard Jones, and Fred Drake;
245implemented by Richard Jones and Fred Drake.}
246
247\end{seealso}
Fred Drakedb7b0022005-03-20 22:19:47 +0000248
249
250%======================================================================
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000251\section{PEP 328: Absolute and Relative Imports}
252
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000253The simpler part of PEP 328 was implemented in Python 2.4: parentheses
254could now be used to enclose the names imported from a module using
255the \code{from ... import ...} statement, making it easier to import
256many different names.
257
258The more complicated part has been implemented in Python 2.5:
259importing a module can be specified to use absolute or
260package-relative imports. The plan is to move toward making absolute
261imports the default in future versions of Python.
262
263Let's say you have a package directory like this:
264\begin{verbatim}
265pkg/
266pkg/__init__.py
267pkg/main.py
268pkg/string.py
269\end{verbatim}
270
271This defines a package named \module{pkg} containing the
272\module{pkg.main} and \module{pkg.string} submodules.
273
274Consider the code in the \file{main.py} module. What happens if it
275executes the statement \code{import string}? In Python 2.4 and
276earlier, it will first look in the package's directory to perform a
277relative import, finds \file{pkg/string.py}, imports the contents of
278that file as the \module{pkg.string} module, and that module is bound
279to the name \samp{string} in the \module{pkg.main} module's namespace.
280
281That's fine if \module{pkg.string} was what you wanted. But what if
282you wanted Python's standard \module{string} module? There's no clean
283way to ignore \module{pkg.string} and look for the standard module;
284generally you had to look at the contents of \code{sys.modules}, which
285is slightly unclean.
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000286Holger Krekel's \module{py.std} package provides a tidier way to perform
287imports from the standard library, \code{import py ; py.std.string.join()},
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000288but that package isn't available on all Python installations.
289
290Reading code which relies on relative imports is also less clear,
291because a reader may be confused about which module, \module{string}
292or \module{pkg.string}, is intended to be used. Python users soon
293learned not to duplicate the names of standard library modules in the
294names of their packages' submodules, but you can't protect against
295having your submodule's name being used for a new module added in a
296future version of Python.
297
298In Python 2.5, you can switch \keyword{import}'s behaviour to
299absolute imports using a \code{from __future__ import absolute_import}
300directive. This absolute-import behaviour will become the default in
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000301a future version (probably Python 2.7). Once absolute imports
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000302are the default, \code{import string} will
303always find the standard library's version.
304It's suggested that users should begin using absolute imports as much
305as possible, so it's preferable to begin writing \code{from pkg import
306string} in your code.
307
308Relative imports are still possible by adding a leading period
309to the module name when using the \code{from ... import} form:
310
311\begin{verbatim}
312# Import names from pkg.string
313from .string import name1, name2
314# Import pkg.string
315from . import string
316\end{verbatim}
317
318This imports the \module{string} module relative to the current
319package, so in \module{pkg.main} this will import \var{name1} and
320\var{name2} from \module{pkg.string}. Additional leading periods
321perform the relative import starting from the parent of the current
322package. For example, code in the \module{A.B.C} module can do:
323
324\begin{verbatim}
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000325from . import D # Imports A.B.D
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000326from .. import E # Imports A.E
327from ..F import G # Imports A.F.G
328\end{verbatim}
329
330Leading periods cannot be used with the \code{import \var{modname}}
331form of the import statement, only the \code{from ... import} form.
332
333\begin{seealso}
334
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000335\seepep{328}{Imports: Multi-Line and Absolute/Relative}
336{PEP written by Aahz; implemented by Thomas Wouters.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000337
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000338\seeurl{http://codespeak.net/py/current/doc/index.html}
339{The py library by Holger Krekel, which contains the \module{py.std} package.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000340
341\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000342
343
344%======================================================================
Andrew M. Kuchling21d3a7c2006-03-15 11:53:09 +0000345\section{PEP 338: Executing Modules as Scripts}
346
Andrew M. Kuchlingb182db42006-03-17 21:48:46 +0000347The \programopt{-m} switch added in Python 2.4 to execute a module as
348a script gained a few more abilities. Instead of being implemented in
349C code inside the Python interpreter, the switch now uses an
350implementation in a new module, \module{runpy}.
351
352The \module{runpy} module implements a more sophisticated import
353mechanism so that it's now possible to run modules in a package such
354as \module{pychecker.checker}. The module also supports alternative
Andrew M. Kuchling5d4cf5e2006-04-13 13:02:42 +0000355import mechanisms such as the \module{zipimport} module. This means
Andrew M. Kuchlingb182db42006-03-17 21:48:46 +0000356you can add a .zip archive's path to \code{sys.path} and then use the
357\programopt{-m} switch to execute code from the archive.
358
359
360\begin{seealso}
361
362\seepep{338}{Executing modules as scripts}{PEP written and
363implemented by Nick Coghlan.}
364
365\end{seealso}
Andrew M. Kuchling21d3a7c2006-03-15 11:53:09 +0000366
367
368%======================================================================
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000369\section{PEP 341: Unified try/except/finally}
370
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000371Until Python 2.5, the \keyword{try} statement came in two
372flavours. You could use a \keyword{finally} block to ensure that code
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +0000373is always executed, or one or more \keyword{except} blocks to catch
374specific exceptions. You couldn't combine both \keyword{except} blocks and a
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000375\keyword{finally} block, because generating the right bytecode for the
376combined version was complicated and it wasn't clear what the
377semantics of the combined should be.
378
379GvR spent some time working with Java, which does support the
380equivalent of combining \keyword{except} blocks and a
381\keyword{finally} block, and this clarified what the statement should
382mean. In Python 2.5, you can now write:
383
384\begin{verbatim}
385try:
386 block-1 ...
387except Exception1:
388 handler-1 ...
389except Exception2:
390 handler-2 ...
391else:
392 else-block
393finally:
394 final-block
395\end{verbatim}
396
397The code in \var{block-1} is executed. If the code raises an
398exception, the handlers are tried in order: \var{handler-1},
399\var{handler-2}, ... If no exception is raised, the \var{else-block}
400is executed. No matter what happened previously, the
401\var{final-block} is executed once the code block is complete and any
402raised exceptions handled. Even if there's an error in an exception
403handler or the \var{else-block} and a new exception is raised, the
404\var{final-block} is still executed.
405
406\begin{seealso}
407
408\seepep{341}{Unifying try-except and try-finally}{PEP written by Georg Brandl;
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000409implementation by Thomas Lee.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000410
411\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000412
413
414%======================================================================
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +0000415\section{PEP 342: New Generator Features\label{section-generators}}
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000416
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000417Python 2.5 adds a simple way to pass values \emph{into} a generator.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000418As introduced in Python 2.3, generators only produce output; once a
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000419generator's code is invoked to create an iterator, there's no way to
420pass any new information into the function when its execution is
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000421resumed. Sometimes the ability to pass in some information would be
422useful. Hackish solutions to this include making the generator's code
423look at a global variable and then changing the global variable's
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000424value, or passing in some mutable object that callers then modify.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000425
426To refresh your memory of basic generators, here's a simple example:
427
428\begin{verbatim}
429def counter (maximum):
430 i = 0
431 while i < maximum:
432 yield i
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000433 i += 1
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000434\end{verbatim}
435
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000436When you call \code{counter(10)}, the result is an iterator that
437returns the values from 0 up to 9. On encountering the
438\keyword{yield} statement, the iterator returns the provided value and
439suspends the function's execution, preserving the local variables.
440Execution resumes on the following call to the iterator's
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000441\method{next()} method, picking up after the \keyword{yield} statement.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000442
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000443In Python 2.3, \keyword{yield} was a statement; it didn't return any
444value. In 2.5, \keyword{yield} is now an expression, returning a
445value that can be assigned to a variable or otherwise operated on:
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000446
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000447\begin{verbatim}
448val = (yield i)
449\end{verbatim}
450
451I recommend that you always put parentheses around a \keyword{yield}
452expression when you're doing something with the returned value, as in
453the above example. The parentheses aren't always necessary, but it's
454easier to always add them instead of having to remember when they're
Andrew M. Kuchling3b675d22006-04-20 13:43:21 +0000455needed.
456
457(\pep{342} explains the exact rules, which are that a
458\keyword{yield}-expression must always be parenthesized except when it
459occurs at the top-level expression on the right-hand side of an
460assignment. This means you can write \code{val = yield i} but have to
461use parentheses when there's an operation, as in \code{val = (yield i)
462+ 12}.)
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000463
464Values are sent into a generator by calling its
465\method{send(\var{value})} method. The generator's code is then
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000466resumed and the \keyword{yield} expression returns the specified
467\var{value}. If the regular \method{next()} method is called, the
468\keyword{yield} returns \constant{None}.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000469
470Here's the previous example, modified to allow changing the value of
471the internal counter.
472
473\begin{verbatim}
474def counter (maximum):
475 i = 0
476 while i < maximum:
477 val = (yield i)
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000478 # If value provided, change counter
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000479 if val is not None:
480 i = val
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000481 else:
482 i += 1
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000483\end{verbatim}
484
485And here's an example of changing the counter:
486
487\begin{verbatim}
488>>> it = counter(10)
489>>> print it.next()
4900
491>>> print it.next()
4921
493>>> print it.send(8)
4948
495>>> print it.next()
4969
497>>> print it.next()
498Traceback (most recent call last):
499 File ``t.py'', line 15, in ?
500 print it.next()
501StopIteration
Andrew M. Kuchlingc2033702005-08-29 13:30:12 +0000502\end{verbatim}
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000503
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000504Because \keyword{yield} will often be returning \constant{None}, you
505should always check for this case. Don't just use its value in
506expressions unless you're sure that the \method{send()} method
507will be the only method used resume your generator function.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000508
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000509In addition to \method{send()}, there are two other new methods on
510generators:
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000511
512\begin{itemize}
513
514 \item \method{throw(\var{type}, \var{value}=None,
515 \var{traceback}=None)} is used to raise an exception inside the
516 generator; the exception is raised by the \keyword{yield} expression
517 where the generator's execution is paused.
518
519 \item \method{close()} raises a new \exception{GeneratorExit}
520 exception inside the generator to terminate the iteration.
521 On receiving this
522 exception, the generator's code must either raise
523 \exception{GeneratorExit} or \exception{StopIteration}; catching the
524 exception and doing anything else is illegal and will trigger
525 a \exception{RuntimeError}. \method{close()} will also be called by
526 Python's garbage collection when the generator is garbage-collected.
527
528 If you need to run cleanup code in case of a \exception{GeneratorExit},
529 I suggest using a \code{try: ... finally:} suite instead of
530 catching \exception{GeneratorExit}.
531
532\end{itemize}
533
534The cumulative effect of these changes is to turn generators from
535one-way producers of information into both producers and consumers.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000536
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000537Generators also become \emph{coroutines}, a more generalized form of
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000538subroutines. Subroutines are entered at one point and exited at
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000539another point (the top of the function, and a \keyword{return
540statement}), but coroutines can be entered, exited, and resumed at
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000541many different points (the \keyword{yield} statements). We'll have to
542figure out patterns for using coroutines effectively in Python.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000543
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000544The addition of the \method{close()} method has one side effect that
545isn't obvious. \method{close()} is called when a generator is
546garbage-collected, so this means the generator's code gets one last
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +0000547chance to run before the generator is destroyed. This last chance
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000548means that \code{try...finally} statements in generators can now be
549guaranteed to work; the \keyword{finally} clause will now always get a
550chance to run. The syntactic restriction that you couldn't mix
551\keyword{yield} statements with a \code{try...finally} suite has
552therefore been removed. This seems like a minor bit of language
553trivia, but using generators and \code{try...finally} is actually
554necessary in order to implement the \keyword{with} statement
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000555described by PEP 343. I'll look at this new statement in the following
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000556section.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000557
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +0000558Another even more esoteric effect of this change: previously, the
559\member{gi_frame} attribute of a generator was always a frame object.
560It's now possible for \member{gi_frame} to be \code{None}
561once the generator has been exhausted.
562
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000563\begin{seealso}
564
565\seepep{342}{Coroutines via Enhanced Generators}{PEP written by
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000566Guido van~Rossum and Phillip J. Eby;
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000567implemented by Phillip J. Eby. Includes examples of
568some fancier uses of generators as coroutines.}
569
570\seeurl{http://en.wikipedia.org/wiki/Coroutine}{The Wikipedia entry for
571coroutines.}
572
Neal Norwitz09179882006-03-04 23:31:45 +0000573\seeurl{http://www.sidhe.org/\~{}dan/blog/archives/000178.html}{An
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000574explanation of coroutines from a Perl point of view, written by Dan
575Sugalski.}
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000576
577\end{seealso}
578
579
580%======================================================================
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000581\section{PEP 343: The 'with' statement}
582
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000583The \keyword{with} statement allows a clearer version of code that
584uses \code{try...finally} blocks to ensure that clean-up code is
585executed.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000586
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000587In this section, I'll discuss the statement as it will commonly be
588used. In the next section, I'll examine the implementation details
589and show how to write objects called ``context managers'' and
590``contexts'' for use with this statement.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000591
592The \keyword{with} statement is a new control-flow structure whose
593basic structure is:
594
595\begin{verbatim}
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000596with expression [as variable]:
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000597 with-block
598\end{verbatim}
599
600The expression is evaluated, and it should result in a type of object
601that's called a context manager. The context manager can return a
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000602value that can optionally be bound to the name \var{variable}. (Note
603carefully: \var{variable} is \emph{not} assigned the result of
604\var{expression}.) One method of the context manager is run before
605\var{with-block} is executed, and another method is run after the
606block is done, even if the block raised an exception.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000607
608To enable the statement in Python 2.5, you need
609to add the following directive to your module:
610
611\begin{verbatim}
612from __future__ import with_statement
613\end{verbatim}
614
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000615The statement will always be enabled in Python 2.6.
616
617Some standard Python objects can now behave as context managers. File
618objects are one example:
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000619
620\begin{verbatim}
621with open('/etc/passwd', 'r') as f:
622 for line in f:
623 print line
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000624 ... more processing code ...
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000625\end{verbatim}
626
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000627After this statement has executed, the file object in \var{f} will
628have been automatically closed at this point, even if the 'for' loop
629raised an exception part-way through the block.
630
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000631The \module{threading} module's locks and condition variables
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000632also support the \keyword{with} statement:
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000633
634\begin{verbatim}
635lock = threading.Lock()
636with lock:
637 # Critical section of code
638 ...
639\end{verbatim}
640
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000641The lock is acquired before the block is executed, and always released once
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000642the block is complete.
643
644The \module{decimal} module's contexts, which encapsulate the desired
645precision and rounding characteristics for computations, can also be
646used as context managers.
647
648\begin{verbatim}
649import decimal
650
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000651# Displays with default precision of 28 digits
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000652v1 = decimal.Decimal('578')
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000653print v1.sqrt()
654
655with decimal.Context(prec=16):
656 # All code in this block uses a precision of 16 digits.
657 # The original context is restored on exiting the block.
658 print v1.sqrt()
659\end{verbatim}
660
661\subsection{Writing Context Managers}
662
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000663Under the hood, the \keyword{with} statement is fairly complicated.
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000664Most people will only use \keyword{with} in company with
665existing objects that are documented to work as context managers, and
666don't need to know these details, so you can skip the following section if
667you like. Authors of new context managers will need to understand the
668details of the underlying implementation.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000669
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000670A high-level explanation of the context management protocol is:
671
672\begin{itemize}
673\item The expression is evaluated and should result in an object
674that's a context manager, meaning that it has a
675\method{__context__()} method.
676
677\item This object's \method{__context__()} method is called, and must
678return a context object.
679
680\item The context's \method{__enter__()} method is called.
681The value returned is assigned to \var{VAR}. If no \code{as \var{VAR}}
682clause is present, the value is simply discarded.
683
684\item The code in \var{BLOCK} is executed.
685
686\item If \var{BLOCK} raises an exception, the context object's
687\method{__exit__(\var{type}, \var{value}, \var{traceback})} is called
688with the exception's information, the same values returned by
689\function{sys.exc_info()}. The method's return value
690controls whether the exception is re-raised: any false value
691re-raises the exception, and \code{True} will result in suppressing it.
692You'll only rarely want to suppress the exception; the
693author of the code containing the \keyword{with} statement will
694never realize anything went wrong.
695
696\item If \var{BLOCK} didn't raise an exception,
697the context object's \method{__exit__()} is still called,
698but \var{type}, \var{value}, and \var{traceback} are all \code{None}.
699
700\end{itemize}
701
702Let's think through an example. I won't present detailed code but
703will only sketch the necessary code. The example will be writing a
704context manager for a database that supports transactions.
705
706(For people unfamiliar with database terminology: a set of changes to
707the database are grouped into a transaction. Transactions can be
708either committed, meaning that all the changes are written into the
709database, or rolled back, meaning that the changes are all discarded
710and the database is unchanged. See any database textbook for more
711information.)
712% XXX find a shorter reference?
713
714Let's assume there's an object representing a database connection.
715Our goal will be to let the user write code like this:
716
717\begin{verbatim}
718db_connection = DatabaseConnection()
719with db_connection as cursor:
720 cursor.execute('insert into ...')
721 cursor.execute('delete from ...')
722 # ... more operations ...
723\end{verbatim}
724
725The transaction should either be committed if the code in the block
726runs flawlessly, or rolled back if there's an exception.
727
728First, the \class{DatabaseConnection} needs a \method{__context__()}
729method. Sometimes an object can be its own context manager and can
730simply return \code{self}; the \module{threading} module's lock objects
731can do this. For our database example, though, we need to
732create a new object; I'll call this class \class{DatabaseContext}.
733Our \method{__context__()} must therefore look like this:
734
735\begin{verbatim}
736class DatabaseConnection:
737 ...
738 def __context__ (self):
739 return DatabaseContext(self)
740
741 # Database interface
742 def cursor (self):
743 "Returns a cursor object and starts a new transaction"
744 def commit (self):
745 "Commits current transaction"
746 def rollback (self):
747 "Rolls back current transaction"
748\end{verbatim}
749
750The context needs the connection object so that the connection
751object's \method{commit()} or \method{rollback()} methods can be
752called:
753
754\begin{verbatim}
755class DatabaseContext:
756 def __init__ (self, connection):
757 self.connection = connection
758\end{verbatim}
759
760The \method {__enter__()} method is pretty easy, having only
761to start a new transaction. In this example,
762the resulting cursor object would be a useful result,
763so the method will return it. The user can
764then add \code{as cursor} to their \keyword{with} statement
765to bind the cursor to a variable name.
766
767\begin{verbatim}
768class DatabaseContext:
769 ...
770 def __enter__ (self):
771 # Code to start a new transaction
772 cursor = self.connection.cursor()
773 return cursor
774\end{verbatim}
775
776The \method{__exit__()} method is the most complicated because it's
777where most of the work has to be done. The method has to check if an
778exception occurred. If there was no exception, the transaction is
779committed. The transaction is rolled back if there was an exception.
780Here the code will just fall off the end of the function, returning
781the default value of \code{None}. \code{None} is false, so the exception
782will be re-raised automatically. If you wished, you could be more explicit
783and add a \keyword{return} at the marked location.
784
785\begin{verbatim}
786class DatabaseContext:
787 ...
788 def __exit__ (self, type, value, tb):
789 if tb is None:
790 # No exception, so commit
791 self.connection.commit()
792 else:
793 # Exception occurred, so rollback.
794 self.connection.rollback()
795 # return False
796\end{verbatim}
797
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000798
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000799\subsection{The contextlib module\label{module-contextlib}}
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000800
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000801The new \module{contextlib} module provides some functions and a
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000802decorator that are useful for writing context managers.
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000803
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000804The decorator is called \function{contextmanager}, and lets you write
805a simple context manager as a generator. The generator should yield
806exactly one value. The code up to the \keyword{yield} will be
807executed as the \method{__enter__()} method, and the value yielded
808will be the method's return value that will get bound to the variable
809in the \keyword{with} statement's \keyword{as} clause, if any. The
810code after the \keyword{yield} will be executed in the
811\method{__exit__()} method. Any exception raised in the block
812will be raised by the \keyword{yield} statement.
813
814Our database example from the previous section could be written
815using this decorator as:
816
817\begin{verbatim}
818from contextlib import contextmanager
819
820@contextmanager
821def db_transaction (connection):
822 cursor = connection.cursor()
823 try:
824 yield cursor
825 except:
826 connection.rollback()
827 raise
828 else:
829 connection.commit()
830
831db = DatabaseConnection()
832with db_transaction(db) as cursor:
833 ...
834\end{verbatim}
835
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000836You can also use this decorator to write the \method{__context__()} method
837for a class without creating a new class for the context:
838
839\begin{verbatim}
840class DatabaseConnection:
841
842 @contextmanager
843 def __context__ (self):
844 cursor = self.cursor()
845 try:
846 yield cursor
847 except:
848 self.rollback()
849 raise
850 else:
851 self.commit()
852\end{verbatim}
853
854
855There's a \function{nested(\var{mgr1}, \var{mgr2}, ...)} manager that
856combines a number of context managers so you don't need to write
857nested \keyword{with} statements. This example statement does two
858things, starting a database transaction and acquiring a thread lock:
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000859
860\begin{verbatim}
861lock = threading.Lock()
862with nested (db_transaction(db), lock) as (cursor, locked):
863 ...
864\end{verbatim}
865
866Finally, the \function{closing(\var{object})} context manager
867returns \var{object} so that it can be bound to a variable,
868and calls \code{\var{object}.close()} at the end of the block.
869
870\begin{verbatim}
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +0000871import urllib, sys
872from contextlib import closing
873
874with closing(urllib.urlopen('http://www.yahoo.com')) as f:
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000875 for line in f:
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +0000876 sys.stdout.write(line)
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000877\end{verbatim}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000878
879\begin{seealso}
880
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000881\seepep{343}{The ``with'' statement}{PEP written by Guido van~Rossum
882and Nick Coghlan; implemented by Mike Bland, Guido van~Rossum, and
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +0000883Neal Norwitz. The PEP shows the code generated for a \keyword{with}
884statement, which can be helpful in learning how context managers
885work.}
886
887\seeurl{../lib/module-contextlib.html}{The documentation
888for the \module{contextlib} module.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000889
890\end{seealso}
891
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000892
893%======================================================================
Andrew M. Kuchling8f4d2552006-03-08 01:50:20 +0000894\section{PEP 352: Exceptions as New-Style Classes}
895
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000896Exception classes can now be new-style classes, not just classic
897classes, and the built-in \exception{Exception} class and all the
898standard built-in exceptions (\exception{NameError},
899\exception{ValueError}, etc.) are now new-style classes.
Andrew M. Kuchlingaeadf952006-03-09 19:06:05 +0000900
901The inheritance hierarchy for exceptions has been rearranged a bit.
902In 2.5, the inheritance relationships are:
903
904\begin{verbatim}
905BaseException # New in Python 2.5
906|- KeyboardInterrupt
907|- SystemExit
908|- Exception
909 |- (all other current built-in exceptions)
910\end{verbatim}
911
912This rearrangement was done because people often want to catch all
913exceptions that indicate program errors. \exception{KeyboardInterrupt} and
914\exception{SystemExit} aren't errors, though, and usually represent an explicit
915action such as the user hitting Control-C or code calling
916\function{sys.exit()}. A bare \code{except:} will catch all exceptions,
917so you commonly need to list \exception{KeyboardInterrupt} and
918\exception{SystemExit} in order to re-raise them. The usual pattern is:
919
920\begin{verbatim}
921try:
922 ...
923except (KeyboardInterrupt, SystemExit):
924 raise
925except:
926 # Log error...
927 # Continue running program...
928\end{verbatim}
929
930In Python 2.5, you can now write \code{except Exception} to achieve
931the same result, catching all the exceptions that usually indicate errors
932but leaving \exception{KeyboardInterrupt} and
933\exception{SystemExit} alone. As in previous versions,
934a bare \code{except:} still catches all exceptions.
935
936The goal for Python 3.0 is to require any class raised as an exception
937to derive from \exception{BaseException} or some descendant of
938\exception{BaseException}, and future releases in the
939Python 2.x series may begin to enforce this constraint. Therefore, I
940suggest you begin making all your exception classes derive from
941\exception{Exception} now. It's been suggested that the bare
942\code{except:} form should be removed in Python 3.0, but Guido van~Rossum
943hasn't decided whether to do this or not.
944
945Raising of strings as exceptions, as in the statement \code{raise
946"Error occurred"}, is deprecated in Python 2.5 and will trigger a
947warning. The aim is to be able to remove the string-exception feature
948in a few releases.
949
950
951\begin{seealso}
952
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000953\seepep{352}{Required Superclass for Exceptions}{PEP written by
Andrew M. Kuchling67191312006-04-19 12:55:39 +0000954Brett Cannon and Guido van~Rossum; implemented by Brett Cannon.}
Andrew M. Kuchlingaeadf952006-03-09 19:06:05 +0000955
956\end{seealso}
Andrew M. Kuchling8f4d2552006-03-08 01:50:20 +0000957
958
959%======================================================================
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000960\section{PEP 353: Using ssize_t as the index type\label{section-353}}
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000961
962A wide-ranging change to Python's C API, using a new
963\ctype{Py_ssize_t} type definition instead of \ctype{int},
964will permit the interpreter to handle more data on 64-bit platforms.
965This change doesn't affect Python's capacity on 32-bit platforms.
966
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000967Various pieces of the Python interpreter used C's \ctype{int} type to
968store sizes or counts; for example, the number of items in a list or
969tuple were stored in an \ctype{int}. The C compilers for most 64-bit
970platforms still define \ctype{int} as a 32-bit type, so that meant
971that lists could only hold up to \code{2**31 - 1} = 2147483647 items.
972(There are actually a few different programming models that 64-bit C
973compilers can use -- see
974\url{http://www.unix.org/version2/whatsnew/lp64_wp.html} for a
975discussion -- but the most commonly available model leaves \ctype{int}
976as 32 bits.)
977
978A limit of 2147483647 items doesn't really matter on a 32-bit platform
979because you'll run out of memory before hitting the length limit.
980Each list item requires space for a pointer, which is 4 bytes, plus
981space for a \ctype{PyObject} representing the item. 2147483647*4 is
982already more bytes than a 32-bit address space can contain.
983
984It's possible to address that much memory on a 64-bit platform,
985however. The pointers for a list that size would only require 16GiB
986of space, so it's not unreasonable that Python programmers might
987construct lists that large. Therefore, the Python interpreter had to
988be changed to use some type other than \ctype{int}, and this will be a
98964-bit type on 64-bit platforms. The change will cause
990incompatibilities on 64-bit machines, so it was deemed worth making
991the transition now, while the number of 64-bit users is still
992relatively small. (In 5 or 10 years, we may \emph{all} be on 64-bit
993machines, and the transition would be more painful then.)
994
995This change most strongly affects authors of C extension modules.
996Python strings and container types such as lists and tuples
997now use \ctype{Py_ssize_t} to store their size.
998Functions such as \cfunction{PyList_Size()}
999now return \ctype{Py_ssize_t}. Code in extension modules
1000may therefore need to have some variables changed to
1001\ctype{Py_ssize_t}.
1002
1003The \cfunction{PyArg_ParseTuple()} and \cfunction{Py_BuildValue()} functions
1004have a new conversion code, \samp{n}, for \ctype{Py_ssize_t}.
Andrew M. Kuchlinga4d651f2006-04-06 13:24:58 +00001005\cfunction{PyArg_ParseTuple()}'s \samp{s\#} and \samp{t\#} still output
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00001006\ctype{int} by default, but you can define the macro
1007\csimplemacro{PY_SSIZE_T_CLEAN} before including \file{Python.h}
1008to make them return \ctype{Py_ssize_t}.
1009
1010\pep{353} has a section on conversion guidelines that
1011extension authors should read to learn about supporting 64-bit
1012platforms.
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +00001013
1014\begin{seealso}
1015
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001016\seepep{353}{Using ssize_t as the index type}{PEP written and implemented by Martin von~L\"owis.}
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +00001017
1018\end{seealso}
1019
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00001020
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +00001021%======================================================================
Andrew M. Kuchling437567c2006-03-07 20:48:55 +00001022\section{PEP 357: The '__index__' method}
1023
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001024The NumPy developers had a problem that could only be solved by adding
1025a new special method, \method{__index__}. When using slice notation,
Fred Drake1c0e3282006-04-02 03:30:06 +00001026as in \code{[\var{start}:\var{stop}:\var{step}]}, the values of the
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001027\var{start}, \var{stop}, and \var{step} indexes must all be either
1028integers or long integers. NumPy defines a variety of specialized
1029integer types corresponding to unsigned and signed integers of 8, 16,
103032, and 64 bits, but there was no way to signal that these types could
1031be used as slice indexes.
1032
1033Slicing can't just use the existing \method{__int__} method because
1034that method is also used to implement coercion to integers. If
1035slicing used \method{__int__}, floating-point numbers would also
1036become legal slice indexes and that's clearly an undesirable
1037behaviour.
1038
1039Instead, a new special method called \method{__index__} was added. It
1040takes no arguments and returns an integer giving the slice index to
1041use. For example:
1042
1043\begin{verbatim}
1044class C:
1045 def __index__ (self):
1046 return self.value
1047\end{verbatim}
1048
1049The return value must be either a Python integer or long integer.
1050The interpreter will check that the type returned is correct, and
1051raises a \exception{TypeError} if this requirement isn't met.
1052
1053A corresponding \member{nb_index} slot was added to the C-level
1054\ctype{PyNumberMethods} structure to let C extensions implement this
1055protocol. \cfunction{PyNumber_Index(\var{obj})} can be used in
1056extension code to call the \method{__index__} function and retrieve
1057its result.
1058
1059\begin{seealso}
1060
1061\seepep{357}{Allowing Any Object to be Used for Slicing}{PEP written
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +00001062and implemented by Travis Oliphant.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001063
1064\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +00001065
1066
1067%======================================================================
Fred Drake2db76802004-12-01 05:05:47 +00001068\section{Other Language Changes}
1069
1070Here are all of the changes that Python 2.5 makes to the core Python
1071language.
1072
1073\begin{itemize}
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001074
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001075\item The \class{dict} type has a new hook for letting subclasses
1076provide a default value when a key isn't contained in the dictionary.
1077When a key isn't found, the dictionary's
1078\method{__missing__(\var{key})}
1079method will be called. This hook is used to implement
1080the new \class{defaultdict} class in the \module{collections}
1081module. The following example defines a dictionary
1082that returns zero for any missing key:
1083
1084\begin{verbatim}
1085class zerodict (dict):
1086 def __missing__ (self, key):
1087 return 0
1088
1089d = zerodict({1:1, 2:2})
1090print d[1], d[2] # Prints 1, 2
1091print d[3], d[4] # Prints 0, 0
1092\end{verbatim}
1093
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001094\item The \function{min()} and \function{max()} built-in functions
1095gained a \code{key} keyword argument analogous to the \code{key}
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001096argument for \method{sort()}. This argument supplies a function that
1097takes a single argument and is called for every value in the list;
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001098\function{min()}/\function{max()} will return the element with the
1099smallest/largest return value from this function.
1100For example, to find the longest string in a list, you can do:
1101
1102\begin{verbatim}
1103L = ['medium', 'longest', 'short']
1104# Prints 'longest'
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001105print max(L, key=len)
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001106# Prints 'short', because lexicographically 'short' has the largest value
1107print max(L)
1108\end{verbatim}
1109
1110(Contributed by Steven Bethard and Raymond Hettinger.)
Fred Drake2db76802004-12-01 05:05:47 +00001111
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001112\item Two new built-in functions, \function{any()} and
1113\function{all()}, evaluate whether an iterator contains any true or
1114false values. \function{any()} returns \constant{True} if any value
1115returned by the iterator is true; otherwise it will return
1116\constant{False}. \function{all()} returns \constant{True} only if
1117all of the values returned by the iterator evaluate as being true.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001118(Suggested by GvR, and implemented by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001119
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001120\item ASCII is now the default encoding for modules. It's now
1121a syntax error if a module contains string literals with 8-bit
1122characters but doesn't have an encoding declaration. In Python 2.4
1123this triggered a warning, not a syntax error. See \pep{263}
1124for how to declare a module's encoding; for example, you might add
1125a line like this near the top of the source file:
1126
1127\begin{verbatim}
1128# -*- coding: latin1 -*-
1129\end{verbatim}
1130
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001131\item The list of base classes in a class definition can now be empty.
1132As an example, this is now legal:
1133
1134\begin{verbatim}
1135class C():
1136 pass
1137\end{verbatim}
1138(Implemented by Brett Cannon.)
1139
Fred Drake2db76802004-12-01 05:05:47 +00001140\end{itemize}
1141
1142
1143%======================================================================
Andrew M. Kuchlingda376042006-03-17 15:56:41 +00001144\subsection{Interactive Interpreter Changes}
1145
1146In the interactive interpreter, \code{quit} and \code{exit}
1147have long been strings so that new users get a somewhat helpful message
1148when they try to quit:
1149
1150\begin{verbatim}
1151>>> quit
1152'Use Ctrl-D (i.e. EOF) to exit.'
1153\end{verbatim}
1154
1155In Python 2.5, \code{quit} and \code{exit} are now objects that still
1156produce string representations of themselves, but are also callable.
1157Newbies who try \code{quit()} or \code{exit()} will now exit the
1158interpreter as they expect. (Implemented by Georg Brandl.)
1159
1160
1161%======================================================================
Fred Drake2db76802004-12-01 05:05:47 +00001162\subsection{Optimizations}
1163
1164\begin{itemize}
1165
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001166\item When they were introduced
1167in Python 2.4, the built-in \class{set} and \class{frozenset} types
1168were built on top of Python's dictionary type.
1169In 2.5 the internal data structure has been customized for implementing sets,
1170and as a result sets will use a third less memory and are somewhat faster.
1171(Implemented by Raymond Hettinger.)
Fred Drake2db76802004-12-01 05:05:47 +00001172
Andrew M. Kuchling45bb98e2006-04-16 19:53:27 +00001173\item The performance of some Unicode operations, such as
1174character map decoding, has been improved.
1175% Patch 1313939
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001176
1177\item The code generator's peephole optimizer now performs
1178simple constant folding in expressions. If you write something like
1179\code{a = 2+3}, the code generator will do the arithmetic and produce
1180code corresponding to \code{a = 5}.
1181
Fred Drake2db76802004-12-01 05:05:47 +00001182\end{itemize}
1183
1184The net result of the 2.5 optimizations is that Python 2.5 runs the
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +00001185pystone benchmark around XXX\% faster than Python 2.4.
Fred Drake2db76802004-12-01 05:05:47 +00001186
1187
1188%======================================================================
1189\section{New, Improved, and Deprecated Modules}
1190
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +00001191The standard library received many enhancements and bug fixes in
1192Python 2.5. Here's a partial list of the most notable changes, sorted
1193alphabetically by module name. Consult the \file{Misc/NEWS} file in
1194the source tree for a more complete list of changes, or look through
1195the SVN logs for all the details.
Fred Drake2db76802004-12-01 05:05:47 +00001196
1197\begin{itemize}
1198
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001199% the cPickle module no longer accepts the deprecated None option in the
1200% args tuple returned by __reduce__().
1201
Andrew M. Kuchling6fc69762006-04-13 12:37:21 +00001202\item The \module{audioop} module now supports the a-LAW encoding,
1203and the code for u-LAW encoding has been improved. (Contributed by
1204Lars Immisch.)
1205
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001206\item The \module{collections} module gained a new type,
1207\class{defaultdict}, that subclasses the standard \class{dict}
1208type. The new type mostly behaves like a dictionary but constructs a
1209default value when a key isn't present, automatically adding it to the
1210dictionary for the requested key value.
1211
1212The first argument to \class{defaultdict}'s constructor is a factory
1213function that gets called whenever a key is requested but not found.
1214This factory function receives no arguments, so you can use built-in
1215type constructors such as \function{list()} or \function{int()}. For
1216example,
1217you can make an index of words based on their initial letter like this:
1218
1219\begin{verbatim}
1220words = """Nel mezzo del cammin di nostra vita
1221mi ritrovai per una selva oscura
1222che la diritta via era smarrita""".lower().split()
1223
1224index = defaultdict(list)
1225
1226for w in words:
1227 init_letter = w[0]
1228 index[init_letter].append(w)
1229\end{verbatim}
1230
1231Printing \code{index} results in the following output:
1232
1233\begin{verbatim}
1234defaultdict(<type 'list'>, {'c': ['cammin', 'che'], 'e': ['era'],
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001235 'd': ['del', 'di', 'diritta'], 'm': ['mezzo', 'mi'],
1236 'l': ['la'], 'o': ['oscura'], 'n': ['nel', 'nostra'],
1237 'p': ['per'], 's': ['selva', 'smarrita'],
1238 'r': ['ritrovai'], 'u': ['una'], 'v': ['vita', 'via']}
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001239\end{verbatim}
1240
1241The \class{deque} double-ended queue type supplied by the
1242\module{collections} module now has a \method{remove(\var{value})}
1243method that removes the first occurrence of \var{value} in the queue,
1244raising \exception{ValueError} if the value isn't found.
1245
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001246\item New module: The \module{contextlib} module contains helper functions for use
1247with the new \keyword{with} statement. See
1248section~\ref{module-contextlib} for more about this module.
1249(Contributed by Phillip J. Eby.)
Andrew M. Kuchlingde0a23f2006-04-16 18:45:11 +00001250
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001251\item New module: The \module{cProfile} module is a C implementation of
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001252the existing \module{profile} module that has much lower overhead.
1253The module's interface is the same as \module{profile}: you run
1254\code{cProfile.run('main()')} to profile a function, can save profile
1255data to a file, etc. It's not yet known if the Hotshot profiler,
1256which is also written in C but doesn't match the \module{profile}
1257module's interface, will continue to be maintained in future versions
1258of Python. (Contributed by Armin Rigo.)
1259
Andrew M. Kuchling952f1962006-04-18 12:38:19 +00001260\item The \module{csv} module, which parses files in
1261comma-separated value format, received several enhancements and a
1262number of bugfixes. You can now set the maximum size in bytes of a
1263field by calling the \method{csv.field_size_limit(\var{new_limit})}
1264function; omitting the \var{new_limit} argument will return the
1265currently-set limit. The \class{reader} class now has a
1266\member{line_num} attribute that counts the number of physical lines
1267read from the source; records can span multiple physical lines, so
1268\member{line_num} is not the same as the number of records read.
1269(Contributed by Skip Montanaro and Andrew McNamara.)
1270
Andrew M. Kuchling67191312006-04-19 12:55:39 +00001271\item The \class{datetime} class in the \module{datetime}
1272module now has a \method{strptime(\var{string}, \var{format})}
1273method for parsing date strings, contributed by Josh Spoerri.
1274It uses the same format characters as \function{time.strptime()} and
1275\function{time.strftime()}:
1276
1277\begin{verbatim}
1278from datetime import datetime
1279
1280ts = datetime.strptime('10:13:15 2006-03-07',
1281 '%H:%M:%S %Y-%m-%d')
1282\end{verbatim}
1283
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001284\item The \module{fileinput} module was made more flexible.
1285Unicode filenames are now supported, and a \var{mode} parameter that
1286defaults to \code{"r"} was added to the
1287\function{input()} function to allow opening files in binary or
1288universal-newline mode. Another new parameter, \var{openhook},
1289lets you use a function other than \function{open()}
1290to open the input files. Once you're iterating over
1291the set of files, the \class{FileInput} object's new
1292\method{fileno()} returns the file descriptor for the currently opened file.
1293(Contributed by Georg Brandl.)
1294
Andrew M. Kuchlingda376042006-03-17 15:56:41 +00001295\item In the \module{gc} module, the new \function{get_count()} function
1296returns a 3-tuple containing the current collection counts for the
1297three GC generations. This is accounting information for the garbage
1298collector; when these counts reach a specified threshold, a garbage
1299collection sweep will be made. The existing \function{gc.collect()}
1300function now takes an optional \var{generation} argument of 0, 1, or 2
1301to specify which generation to collect.
1302
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001303\item The \function{nsmallest()} and
1304\function{nlargest()} functions in the \module{heapq} module
1305now support a \code{key} keyword argument similar to the one
1306provided by the \function{min()}/\function{max()} functions
1307and the \method{sort()} methods. For example:
1308Example:
1309
1310\begin{verbatim}
1311>>> import heapq
1312>>> L = ["short", 'medium', 'longest', 'longer still']
1313>>> heapq.nsmallest(2, L) # Return two lowest elements, lexicographically
1314['longer still', 'longest']
1315>>> heapq.nsmallest(2, L, key=len) # Return two shortest elements
1316['short', 'medium']
1317\end{verbatim}
1318
1319(Contributed by Raymond Hettinger.)
1320
Andrew M. Kuchling511a3a82005-03-20 19:52:18 +00001321\item The \function{itertools.islice()} function now accepts
1322\code{None} for the start and step arguments. This makes it more
1323compatible with the attributes of slice objects, so that you can now write
1324the following:
1325
1326\begin{verbatim}
1327s = slice(5) # Create slice object
1328itertools.islice(iterable, s.start, s.stop, s.step)
1329\end{verbatim}
1330
1331(Contributed by Raymond Hettinger.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001332
Andrew M. Kuchling75ba2442006-04-14 10:29:55 +00001333\item The \module{nis} module now supports accessing domains other
1334than the system default domain by supplying a \var{domain} argument to
1335the \function{nis.match()} and \function{nis.maps()} functions.
1336(Contributed by Ben Bell.)
1337
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001338\item The \module{operator} module's \function{itemgetter()}
1339and \function{attrgetter()} functions now support multiple fields.
1340A call such as \code{operator.attrgetter('a', 'b')}
1341will return a function
1342that retrieves the \member{a} and \member{b} attributes. Combining
1343this new feature with the \method{sort()} method's \code{key} parameter
1344lets you easily sort lists using multiple fields.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001345(Contributed by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001346
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001347
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +00001348\item The \module{os} module underwent several changes. The
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001349\member{stat_float_times} variable now defaults to true, meaning that
1350\function{os.stat()} will now return time values as floats. (This
1351doesn't necessarily mean that \function{os.stat()} will return times
1352that are precise to fractions of a second; not all systems support
1353such precision.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001354
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001355Constants named \member{os.SEEK_SET}, \member{os.SEEK_CUR}, and
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001356\member{os.SEEK_END} have been added; these are the parameters to the
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001357\function{os.lseek()} function. Two new constants for locking are
1358\member{os.O_SHLOCK} and \member{os.O_EXLOCK}.
1359
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001360Two new functions, \function{wait3()} and \function{wait4()}, were
1361added. They're similar the \function{waitpid()} function which waits
1362for a child process to exit and returns a tuple of the process ID and
1363its exit status, but \function{wait3()} and \function{wait4()} return
1364additional information. \function{wait3()} doesn't take a process ID
1365as input, so it waits for any child process to exit and returns a
13663-tuple of \var{process-id}, \var{exit-status}, \var{resource-usage}
1367as returned from the \function{resource.getrusage()} function.
1368\function{wait4(\var{pid})} does take a process ID.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001369(Contributed by Chad J. Schroeder.)
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001370
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001371On FreeBSD, the \function{os.stat()} function now returns
1372times with nanosecond resolution, and the returned object
1373now has \member{st_gen} and \member{st_birthtime}.
1374The \member{st_flags} member is also available, if the platform supports it.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001375(Contributed by Antti Louko and Diego Petten\`o.)
1376% (Patch 1180695, 1212117)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001377
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001378\item The old \module{regex} and \module{regsub} modules, which have been
1379deprecated ever since Python 2.0, have finally been deleted.
Andrew M. Kuchlingf4b06602006-03-17 15:39:52 +00001380Other deleted modules: \module{statcache}, \module{tzparse},
1381\module{whrandom}.
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001382
1383\item The \file{lib-old} directory,
1384which includes ancient modules such as \module{dircmp} and
1385\module{ni}, was also deleted. \file{lib-old} wasn't on the default
1386\code{sys.path}, so unless your programs explicitly added the directory to
1387\code{sys.path}, this removal shouldn't affect your code.
1388
Andrew M. Kuchling4678dc82006-01-15 16:11:28 +00001389\item The \module{socket} module now supports \constant{AF_NETLINK}
1390sockets on Linux, thanks to a patch from Philippe Biondi.
1391Netlink sockets are a Linux-specific mechanism for communications
1392between a user-space process and kernel code; an introductory
1393article about them is at \url{http://www.linuxjournal.com/article/7356}.
1394In Python code, netlink addresses are represented as a tuple of 2 integers,
1395\code{(\var{pid}, \var{group_mask})}.
1396
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001397Socket objects also gained accessor methods \method{getfamily()},
1398\method{gettype()}, and \method{getproto()} methods to retrieve the
1399family, type, and protocol values for the socket.
1400
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001401\item New module: the \module{spwd} module provides functions for
1402accessing the shadow password database on systems that support
1403shadow passwords.
Fred Drake2db76802004-12-01 05:05:47 +00001404
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001405\item The Python developers switched from CVS to Subversion during the 2.5
1406development process. Information about the exact build version is
1407available as the \code{sys.subversion} variable, a 3-tuple
1408of \code{(\var{interpreter-name}, \var{branch-name}, \var{revision-range})}.
1409For example, at the time of writing
1410my copy of 2.5 was reporting \code{('CPython', 'trunk', '45313:45315')}.
1411
1412This information is also available to C extensions via the
1413\cfunction{Py_GetBuildInfo()} function that returns a
1414string of build information like this:
1415\code{"trunk:45355:45356M, Apr 13 2006, 07:42:19"}.
1416(Contributed by Barry Warsaw.)
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001417
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001418\item The \class{TarFile} class in the \module{tarfile} module now has
Georg Brandl08c02db2005-07-22 18:39:19 +00001419an \method{extractall()} method that extracts all members from the
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001420archive into the current working directory. It's also possible to set
1421a different directory as the extraction target, and to unpack only a
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001422subset of the archive's members.
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001423
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001424A tarfile's compression can be autodetected by
1425using the mode \code{'r|*'}.
1426% patch 918101
1427(Contributed by Lars Gust\"abel.)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001428
Andrew M. Kuchlingf688cc52006-03-10 18:50:08 +00001429\item The \module{unicodedata} module has been updated to use version 4.1.0
1430of the Unicode character database. Version 3.2.0 is required
1431by some specifications, so it's still available as
1432\member{unicodedata.db_3_2_0}.
1433
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001434\item The \module{webbrowser} module received a number of
1435enhancements.
1436It's now usable as a script with \code{python -m webbrowser}, taking a
1437URL as the argument; there are a number of switches
1438to control the behaviour (\programopt{-n} for a new browser window,
1439\programopt{-t} for a new tab). New module-level functions,
1440\function{open_new()} and \function{open_new_tab()}, were added
1441to support this. The module's \function{open()} function supports an
1442additional feature, an \var{autoraise} parameter that signals whether
1443to raise the open window when possible. A number of additional
1444browsers were added to the supported list such as Firefox, Opera,
1445Konqueror, and elinks. (Contributed by Oleg Broytmann and George
1446Brandl.)
1447% Patch #754022
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001448
Fredrik Lundh7e0aef02005-12-12 18:54:55 +00001449
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001450\item The \module{xmlrpclib} module now supports returning
1451 \class{datetime} objects for the XML-RPC date type. Supply
1452 \code{use_datetime=True} to the \function{loads()} function
1453 or the \class{Unmarshaller} class to enable this feature.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001454 (Contributed by Skip Montanaro.)
1455% Patch 1120353
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001456
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001457
Fred Drake114b8ca2005-03-21 05:47:11 +00001458\end{itemize}
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001459
Fred Drake2db76802004-12-01 05:05:47 +00001460
1461
1462%======================================================================
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001463\subsection{The ctypes package}
1464
1465The \module{ctypes} package, written by Thomas Heller, has been added
1466to the standard library. \module{ctypes} lets you call arbitrary functions
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001467in shared libraries or DLLs. Long-time users may remember the \module{dl} module, which
1468provides functions for loading shared libraries and calling functions in them. The \module{ctypes} package is much fancier.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001469
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001470To load a shared library or DLL, you must create an instance of the
1471\class{CDLL} class and provide the name or path of the shared library
1472or DLL. Once that's done, you can call arbitrary functions
1473by accessing them as attributes of the \class{CDLL} object.
1474
1475\begin{verbatim}
1476import ctypes
1477
1478libc = ctypes.CDLL('libc.so.6')
1479result = libc.printf("Line of output\n")
1480\end{verbatim}
1481
1482Type constructors for the various C types are provided: \function{c_int},
1483\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
1484to change the wrapped value. Python integers and strings will be automatically
1485converted to the corresponding C types, but for other types you
1486must call the correct type constructor. (And I mean \emph{must};
1487getting it wrong will often result in the interpreter crashing
1488with a segmentation fault.)
1489
1490You 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
1491supposed to be immutable; breaking this rule will cause puzzling bugs. When you need a modifiable memory area,
Neal Norwitz5f5a69b2006-04-13 03:41:04 +00001492use \function{create_string_buffer()}:
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001493
1494\begin{verbatim}
1495s = "this is a string"
1496buf = ctypes.create_string_buffer(s)
1497libc.strfry(buf)
1498\end{verbatim}
1499
1500C functions are assumed to return integers, but you can set
1501the \member{restype} attribute of the function object to
1502change this:
1503
1504\begin{verbatim}
1505>>> libc.atof('2.71828')
1506-1783957616
1507>>> libc.atof.restype = ctypes.c_double
1508>>> libc.atof('2.71828')
15092.71828
1510\end{verbatim}
1511
1512\module{ctypes} also provides a wrapper for Python's C API
1513as the \code{ctypes.pythonapi} object. This object does \emph{not}
1514release the global interpreter lock before calling a function, because the lock must be held when calling into the interpreter's code.
1515There's a \class{py_object()} type constructor that will create a
1516\ctype{PyObject *} pointer. A simple usage:
1517
1518\begin{verbatim}
1519import ctypes
1520
1521d = {}
1522ctypes.pythonapi.PyObject_SetItem(ctypes.py_object(d),
1523 ctypes.py_object("abc"), ctypes.py_object(1))
1524# d is now {'abc', 1}.
1525\end{verbatim}
1526
1527Don't forget to use \class{py_object()}; if it's omitted you end
1528up with a segmentation fault.
1529
1530\module{ctypes} has been around for a while, but people still write
1531and distribution hand-coded extension modules because you can't rely on \module{ctypes} being present.
1532Perhaps developers will begin to write
1533Python wrappers atop a library accessed through \module{ctypes} instead
1534of extension modules, now that \module{ctypes} is included with core Python.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001535
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001536\begin{seealso}
1537
1538\seeurl{http://starship.python.net/crew/theller/ctypes/}
1539{The ctypes web page, with a tutorial, reference, and FAQ.}
1540
1541\end{seealso}
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001542
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001543
1544%======================================================================
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001545\subsection{The ElementTree package}
1546
1547A subset of Fredrik Lundh's ElementTree library for processing XML has
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001548been added to the standard library as \module{xmlcore.etree}. The
Georg Brandlce27a062006-04-11 06:27:12 +00001549available modules are
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001550\module{ElementTree}, \module{ElementPath}, and
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00001551\module{ElementInclude} from ElementTree 1.2.6.
1552The \module{cElementTree} accelerator module is also included.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001553
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001554The rest of this section will provide a brief overview of using
1555ElementTree. Full documentation for ElementTree is available at
1556\url{http://effbot.org/zone/element-index.htm}.
1557
1558ElementTree represents an XML document as a tree of element nodes.
1559The text content of the document is stored as the \member{.text}
1560and \member{.tail} attributes of
1561(This is one of the major differences between ElementTree and
1562the Document Object Model; in the DOM there are many different
1563types of node, including \class{TextNode}.)
1564
1565The most commonly used parsing function is \function{parse()}, that
1566takes either a string (assumed to contain a filename) or a file-like
1567object and returns an \class{ElementTree} instance:
1568
1569\begin{verbatim}
1570from xmlcore.etree import ElementTree as ET
1571
1572tree = ET.parse('ex-1.xml')
1573
1574feed = urllib.urlopen(
1575 'http://planet.python.org/rss10.xml')
1576tree = ET.parse(feed)
1577\end{verbatim}
1578
1579Once you have an \class{ElementTree} instance, you
1580can call its \method{getroot()} method to get the root \class{Element} node.
1581
1582There's also an \function{XML()} function that takes a string literal
1583and returns an \class{Element} node (not an \class{ElementTree}).
1584This function provides a tidy way to incorporate XML fragments,
1585approaching the convenience of an XML literal:
1586
1587\begin{verbatim}
1588svg = et.XML("""<svg width="10px" version="1.0">
1589 </svg>""")
1590svg.set('height', '320px')
1591svg.append(elem1)
1592\end{verbatim}
1593
1594Each XML element supports some dictionary-like and some list-like
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001595access methods. Dictionary-like operations are used to access attribute
1596values, and list-like operations are used to access child nodes.
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001597
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001598\begin{tableii}{c|l}{code}{Operation}{Result}
1599 \lineii{elem[n]}{Returns n'th child element.}
1600 \lineii{elem[m:n]}{Returns list of m'th through n'th child elements.}
1601 \lineii{len(elem)}{Returns number of child elements.}
1602 \lineii{elem.getchildren()}{Returns list of child elements.}
1603 \lineii{elem.append(elem2)}{Adds \var{elem2} as a child.}
1604 \lineii{elem.insert(index, elem2)}{Inserts \var{elem2} at the specified location.}
1605 \lineii{del elem[n]}{Deletes n'th child element.}
1606 \lineii{elem.keys()}{Returns list of attribute names.}
1607 \lineii{elem.get(name)}{Returns value of attribute \var{name}.}
1608 \lineii{elem.set(name, value)}{Sets new value for attribute \var{name}.}
1609 \lineii{elem.attrib}{Retrieves the dictionary containing attributes.}
1610 \lineii{del elem.attrib[name]}{Deletes attribute \var{name}.}
1611\end{tableii}
1612
1613Comments and processing instructions are also represented as
1614\class{Element} nodes. To check if a node is a comment or processing
1615instructions:
1616
1617\begin{verbatim}
1618if elem.tag is ET.Comment:
1619 ...
1620elif elem.tag is ET.ProcessingInstruction:
1621 ...
1622\end{verbatim}
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001623
1624To generate XML output, you should call the
1625\method{ElementTree.write()} method. Like \function{parse()},
1626it can take either a string or a file-like object:
1627
1628\begin{verbatim}
1629# Encoding is US-ASCII
1630tree.write('output.xml')
1631
1632# Encoding is UTF-8
1633f = open('output.xml', 'w')
1634tree.write(f, 'utf-8')
1635\end{verbatim}
1636
1637(Caution: the default encoding used for output is ASCII, which isn't
1638very useful for general XML work, raising an exception if there are
1639any characters with values greater than 127. You should always
1640specify a different encoding such as UTF-8 that can handle any Unicode
1641character.)
1642
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001643This section is only a partial description of the ElementTree interfaces.
1644Please read the package's official documentation for more details.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001645
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001646\begin{seealso}
1647
1648\seeurl{http://effbot.org/zone/element-index.htm}
1649{Official documentation for ElementTree.}
1650
1651
1652\end{seealso}
1653
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001654
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001655%======================================================================
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001656\subsection{The hashlib package}
1657
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001658A new \module{hashlib} module, written by Gregory P. Smith,
1659has been added to replace the
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001660\module{md5} and \module{sha} modules. \module{hashlib} adds support
1661for additional secure hashes (SHA-224, SHA-256, SHA-384, and SHA-512).
1662When available, the module uses OpenSSL for fast platform optimized
1663implementations of algorithms.
1664
1665The old \module{md5} and \module{sha} modules still exist as wrappers
1666around hashlib to preserve backwards compatibility. The new module's
1667interface is very close to that of the old modules, but not identical.
1668The most significant difference is that the constructor functions
1669for creating new hashing objects are named differently.
1670
1671\begin{verbatim}
1672# Old versions
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001673h = md5.md5()
1674h = md5.new()
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001675
1676# New version
1677h = hashlib.md5()
1678
1679# Old versions
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001680h = sha.sha()
1681h = sha.new()
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001682
1683# New version
1684h = hashlib.sha1()
1685
1686# Hash that weren't previously available
1687h = hashlib.sha224()
1688h = hashlib.sha256()
1689h = hashlib.sha384()
1690h = hashlib.sha512()
1691
1692# Alternative form
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001693h = hashlib.new('md5') # Provide algorithm as a string
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001694\end{verbatim}
1695
1696Once a hash object has been created, its methods are the same as before:
1697\method{update(\var{string})} hashes the specified string into the
1698current digest state, \method{digest()} and \method{hexdigest()}
1699return the digest value as a binary string or a string of hex digits,
1700and \method{copy()} returns a new hashing object with the same digest state.
1701
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001702
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001703%======================================================================
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001704\subsection{The sqlite3 package}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001705
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001706The pysqlite module (\url{http://www.pysqlite.org}), a wrapper for the
1707SQLite embedded database, has been added to the standard library under
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001708the package name \module{sqlite3}.
1709
1710SQLite is a C library that provides a SQL-language database that
1711stores data in disk files without requiring a separate server process.
1712pysqlite was written by Gerhard H\"aring and provides a SQL interface
1713compliant with the DB-API 2.0 specification described by
1714\pep{249}. This means that it should be possible to write the first
1715version of your applications using SQLite for data storage. If
1716switching to a larger database such as PostgreSQL or Oracle is
1717later necessary, the switch should be relatively easy.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001718
1719If you're compiling the Python source yourself, note that the source
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001720tree doesn't include the SQLite code, only the wrapper module.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001721You'll need to have the SQLite libraries and headers installed before
1722compiling Python, and the build process will compile the module when
1723the necessary headers are available.
1724
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001725To use the module, you must first create a \class{Connection} object
1726that represents the database. Here the data will be stored in the
1727\file{/tmp/example} file:
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001728
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001729\begin{verbatim}
1730conn = sqlite3.connect('/tmp/example')
1731\end{verbatim}
1732
1733You can also supply the special name \samp{:memory:} to create
1734a database in RAM.
1735
1736Once you have a \class{Connection}, you can create a \class{Cursor}
1737object and call its \method{execute()} method to perform SQL commands:
1738
1739\begin{verbatim}
1740c = conn.cursor()
1741
1742# Create table
1743c.execute('''create table stocks
1744(date timestamp, trans varchar, symbol varchar,
1745 qty decimal, price decimal)''')
1746
1747# Insert a row of data
1748c.execute("""insert into stocks
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001749 values ('2006-01-05','BUY','RHAT',100,35.14)""")
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001750\end{verbatim}
1751
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001752Usually your SQL operations will need to use values from Python
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001753variables. You shouldn't assemble your query using Python's string
1754operations because doing so is insecure; it makes your program
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001755vulnerable to an SQL injection attack.
1756
1757Instead, use SQLite's parameter substitution. Put \samp{?} as a
1758placeholder wherever you want to use a value, and then provide a tuple
1759of values as the second argument to the cursor's \method{execute()}
1760method. For example:
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001761
1762\begin{verbatim}
1763# Never do this -- insecure!
1764symbol = 'IBM'
1765c.execute("... where symbol = '%s'" % symbol)
1766
1767# Do this instead
1768t = (symbol,)
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001769c.execute('select * from stocks where symbol=?', ('IBM',))
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001770
1771# Larger example
1772for t in (('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001773 ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
1774 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
1775 ):
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001776 c.execute('insert into stocks values (?,?,?,?,?)', t)
1777\end{verbatim}
1778
1779To retrieve data after executing a SELECT statement, you can either
1780treat the cursor as an iterator, call the cursor's \method{fetchone()}
1781method to retrieve a single matching row,
1782or call \method{fetchall()} to get a list of the matching rows.
1783
1784This example uses the iterator form:
1785
1786\begin{verbatim}
1787>>> c = conn.cursor()
1788>>> c.execute('select * from stocks order by price')
1789>>> for row in c:
1790... print row
1791...
1792(u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001)
1793(u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
1794(u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
1795(u'2006-04-05', u'BUY', u'MSOFT', 1000, 72.0)
1796>>>
1797\end{verbatim}
1798
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001799For more information about the SQL dialect supported by SQLite, see
1800\url{http://www.sqlite.org}.
1801
1802\begin{seealso}
1803
1804\seeurl{http://www.pysqlite.org}
1805{The pysqlite web page.}
1806
1807\seeurl{http://www.sqlite.org}
1808{The SQLite web page; the documentation describes the syntax and the
1809available data types for the supported SQL dialect.}
1810
1811\seepep{249}{Database API Specification 2.0}{PEP written by
1812Marc-Andr\'e Lemburg.}
1813
1814\end{seealso}
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001815
Fred Drake2db76802004-12-01 05:05:47 +00001816
1817% ======================================================================
1818\section{Build and C API Changes}
1819
1820Changes to Python's build process and to the C API include:
1821
1822\begin{itemize}
1823
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00001824\item The largest change to the C API came from \pep{353},
1825which modifies the interpreter to use a \ctype{Py_ssize_t} type
1826definition instead of \ctype{int}. See the earlier
Andrew M. Kuchlingaf015cf2006-04-20 13:39:40 +00001827section~\ref{section-353} for a discussion of this change.
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00001828
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001829\item The design of the bytecode compiler has changed a great deal, to
1830no longer generate bytecode by traversing the parse tree. Instead
Andrew M. Kuchlingdb85ed52005-10-23 21:52:59 +00001831the parse tree is converted to an abstract syntax tree (or AST), and it is
1832the abstract syntax tree that's traversed to produce the bytecode.
1833
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00001834It's possible for Python code to obtain AST objects by using the
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001835\function{compile()} built-in and specifying \code{_ast.PyCF_ONLY_AST}
1836as the value of the
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00001837\var{flags} parameter:
1838
1839\begin{verbatim}
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001840from _ast import PyCF_ONLY_AST
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00001841ast = compile("""a=0
1842for i in range(10):
1843 a += i
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001844""", "<string>", 'exec', PyCF_ONLY_AST)
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00001845
1846assignment = ast.body[0]
1847for_loop = ast.body[1]
1848\end{verbatim}
1849
Andrew M. Kuchlingdb85ed52005-10-23 21:52:59 +00001850No documentation has been written for the AST code yet. To start
1851learning about it, read the definition of the various AST nodes in
1852\file{Parser/Python.asdl}. A Python script reads this file and
1853generates a set of C structure definitions in
1854\file{Include/Python-ast.h}. The \cfunction{PyParser_ASTFromString()}
1855and \cfunction{PyParser_ASTFromFile()}, defined in
1856\file{Include/pythonrun.h}, take Python source as input and return the
1857root of an AST representing the contents. This AST can then be turned
1858into a code object by \cfunction{PyAST_Compile()}. For more
1859information, read the source code, and then ask questions on
1860python-dev.
1861
1862% List of names taken from Jeremy's python-dev post at
1863% http://mail.python.org/pipermail/python-dev/2005-October/057500.html
1864The AST code was developed under Jeremy Hylton's management, and
1865implemented by (in alphabetical order) Brett Cannon, Nick Coghlan,
1866Grant Edwards, John Ehresman, Kurt Kaiser, Neal Norwitz, Tim Peters,
1867Armin Rigo, and Neil Schemenauer, plus the participants in a number of
1868AST sprints at conferences such as PyCon.
1869
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001870\item The built-in set types now have an official C API. Call
1871\cfunction{PySet_New()} and \cfunction{PyFrozenSet_New()} to create a
1872new set, \cfunction{PySet_Add()} and \cfunction{PySet_Discard()} to
1873add and remove elements, and \cfunction{PySet_Contains} and
1874\cfunction{PySet_Size} to examine the set's state.
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001875(Contributed by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001876
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001877\item C code can now obtain information about the exact revision
1878of the Python interpreter by calling the
1879\cfunction{Py_GetBuildInfo()} function that returns a
1880string of build information like this:
1881\code{"trunk:45355:45356M, Apr 13 2006, 07:42:19"}.
1882(Contributed by Barry Warsaw.)
1883
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001884\item The CPython interpreter is still written in C, but
1885the code can now be compiled with a {\Cpp} compiler without errors.
1886(Implemented by Anthony Baxter, Martin von~L\"owis, Skip Montanaro.)
1887
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001888\item The \cfunction{PyRange_New()} function was removed. It was
1889never documented, never used in the core code, and had dangerously lax
1890error checking.
Fred Drake2db76802004-12-01 05:05:47 +00001891
1892\end{itemize}
1893
1894
1895%======================================================================
Andrew M. Kuchling6fc69762006-04-13 12:37:21 +00001896\subsection{Port-Specific Changes}
Fred Drake2db76802004-12-01 05:05:47 +00001897
Andrew M. Kuchling6fc69762006-04-13 12:37:21 +00001898\begin{itemize}
1899
1900\item MacOS X (10.3 and higher): dynamic loading of modules
1901now uses the \cfunction{dlopen()} function instead of MacOS-specific
1902functions.
1903
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00001904\item Windows: \file{.dll} is no longer supported as a filename extension for
1905extension modules. \file{.pyd} is now the only filename extension that will
1906be searched for.
1907
Andrew M. Kuchling6fc69762006-04-13 12:37:21 +00001908\end{itemize}
Fred Drake2db76802004-12-01 05:05:47 +00001909
1910
1911%======================================================================
1912\section{Other Changes and Fixes \label{section-other}}
1913
1914As usual, there were a bunch of other improvements and bugfixes
Andrew M. Kuchlingf688cc52006-03-10 18:50:08 +00001915scattered throughout the source tree. A search through the SVN change
Fred Drake2db76802004-12-01 05:05:47 +00001916logs finds there were XXX patches applied and YYY bugs fixed between
Andrew M. Kuchling92e24952004-12-03 13:54:09 +00001917Python 2.4 and 2.5. Both figures are likely to be underestimates.
Fred Drake2db76802004-12-01 05:05:47 +00001918
1919Some of the more notable changes are:
1920
1921\begin{itemize}
1922
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001923\item Evan Jones's patch to obmalloc, first described in a talk
1924at PyCon DC 2005, was applied. Python 2.4 allocated small objects in
1925256K-sized arenas, but never freed arenas. With this patch, Python
1926will free arenas when they're empty. The net effect is that on some
1927platforms, when you allocate many objects, Python's memory usage may
1928actually drop when you delete them, and the memory may be returned to
1929the operating system. (Implemented by Evan Jones, and reworked by Tim
1930Peters.)
Fred Drake2db76802004-12-01 05:05:47 +00001931
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00001932Note that this change means extension modules need to be more careful
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +00001933with how they allocate memory. Python's API has many different
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00001934functions for allocating memory that are grouped into families. For
1935example, \cfunction{PyMem_Malloc()}, \cfunction{PyMem_Realloc()}, and
1936\cfunction{PyMem_Free()} are one family that allocates raw memory,
1937while \cfunction{PyObject_Malloc()}, \cfunction{PyObject_Realloc()},
1938and \cfunction{PyObject_Free()} are another family that's supposed to
1939be used for creating Python objects.
1940
1941Previously these different families all reduced to the platform's
1942\cfunction{malloc()} and \cfunction{free()} functions. This meant
1943it didn't matter if you got things wrong and allocated memory with the
1944\cfunction{PyMem} function but freed it with the \cfunction{PyObject}
1945function. With the obmalloc change, these families now do different
1946things, and mismatches will probably result in a segfault. You should
1947carefully test your C extension modules with Python 2.5.
1948
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001949\item Coverity, a company that markets a source code analysis tool
1950 called Prevent, provided the results of their examination of the Python
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +00001951 source code. The analysis found about 60 bugs that
1952 were quickly fixed. Many of the bugs were refcounting problems, often
1953 occurring in error-handling code. See
1954 \url{http://scan.coverity.com} for the statistics.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001955
Fred Drake2db76802004-12-01 05:05:47 +00001956\end{itemize}
1957
1958
1959%======================================================================
1960\section{Porting to Python 2.5}
1961
1962This section lists previously described changes that may require
1963changes to your code:
1964
1965\begin{itemize}
1966
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001967\item ASCII is now the default encoding for modules. It's now
1968a syntax error if a module contains string literals with 8-bit
1969characters but doesn't have an encoding declaration. In Python 2.4
1970this triggered a warning, not a syntax error.
1971
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +00001972\item The \module{pickle} module no longer uses the deprecated \var{bin} parameter.
Fred Drake2db76802004-12-01 05:05:47 +00001973
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +00001974\item Previously, the \member{gi_frame} attribute of a generator
1975was always a frame object. Because of the \pep{342} changes
1976described in section~\ref{section-generators}, it's now possible
1977for \member{gi_frame} to be \code{None}.
1978
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00001979\item C API: Many functions now use \ctype{Py_ssize_t}
1980instead of \ctype{int} to allow processing more data
1981on 64-bit machines. Extension code may need to make
1982the same change to avoid warnings and to support 64-bit machines.
1983See the earlier
Andrew M. Kuchling33432182006-04-20 13:38:36 +00001984section~\ref{section-353} for a discussion of this change.
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00001985
1986\item C API:
1987The obmalloc changes mean that
1988you must be careful to not mix usage
1989of the \cfunction{PyMem_*()} and \cfunction{PyObject_*()}
1990families of functions. Memory allocated with
1991one family's \cfunction{*_Malloc()} must be
1992freed with the corresponding family's \cfunction{*_Free()} function.
1993
Fred Drake2db76802004-12-01 05:05:47 +00001994\end{itemize}
1995
1996
1997%======================================================================
1998\section{Acknowledgements \label{acks}}
1999
2000The author would like to thank the following people for offering
2001suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchling63fe9b52006-04-20 13:36:06 +00002002article: Phillip J. Eby, Kent Johnson, Martin von~L\"owis, Gustavo
2003Niemeyer, Mike Rovner, Thomas Wouters.
Fred Drake2db76802004-12-01 05:05:47 +00002004
2005\end{document}