blob: 65df70c5fb8f8c53dc2f3fee1a59670b1a8ec202 [file] [log] [blame]
Fred Drake2db76802004-12-01 05:05:47 +00001\documentclass{howto}
2\usepackage{distutils}
3% $Id$
4
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00005% Writing context managers
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00006% The easy_install stuff
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. Kuchling9c67ee02006-04-04 19:07:27 +000024(This is still an early draft, and some sections are still skeletal or
25completely missing. Comments on the present material will still be
26welcomed.)
27
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000028% XXX Compare with previous release in 2 - 3 sentences here.
Fred Drake2db76802004-12-01 05:05:47 +000029
30This article doesn't attempt to provide a complete specification of
31the new features, but instead provides a convenient overview. For
32full details, you should refer to the documentation for Python 2.5.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000033% XXX add hyperlink when the documentation becomes available online.
Fred Drake2db76802004-12-01 05:05:47 +000034If you want to understand the complete implementation and design
35rationale, refer to the PEP for a particular new feature.
36
37
38%======================================================================
Andrew M. Kuchling6a67e4e2006-04-12 13:03:35 +000039\section{PEP 243: Uploading Modules to PyPI}
40
41PEP 243 describes an HTTP-based protocol for submitting software
42packages to a central archive. The Python package index at
43\url{http://cheeseshop.python.org} now supports package uploads, and
44the new \command{upload} Distutils command will upload a package to the
45repository.
46
47Before a package can be uploaded, you must be able to build a
48distribution using the \command{sdist} Distutils command. Once that
49works, you can run \code{python setup.py upload} to add your package
50to the PyPI archive. Optionally you can GPG-sign the package by
51supplying the \programopt{--sign} and
52\programopt{--identity} options.
53
54\begin{seealso}
55
56\seepep{243}{Module Repository Upload Mechanism}{PEP written by
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +000057Sean Reifschneider; implemented by Martin von~L\"owis
Andrew M. Kuchling6a67e4e2006-04-12 13:03:35 +000058and Richard Jones. Note that the PEP doesn't exactly
59describe what's implemented in PyPI.}
60
61\end{seealso}
62
63
64%======================================================================
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000065\section{PEP 308: Conditional Expressions}
66
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000067For a long time, people have been requesting a way to write
68conditional expressions, expressions that return value A or value B
69depending on whether a Boolean value is true or false. A conditional
70expression lets you write a single assignment statement that has the
71same effect as the following:
72
73\begin{verbatim}
74if condition:
75 x = true_value
76else:
77 x = false_value
78\end{verbatim}
79
80There have been endless tedious discussions of syntax on both
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +000081python-dev and comp.lang.python. A vote was even held that found the
82majority of voters wanted conditional expressions in some form,
83but there was no syntax that was preferred by a clear majority.
84Candidates included C's \code{cond ? true_v : false_v},
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000085\code{if cond then true_v else false_v}, and 16 other variations.
86
87GvR eventually chose a surprising syntax:
88
89\begin{verbatim}
90x = true_value if condition else false_value
91\end{verbatim}
92
Andrew M. Kuchling38f85072006-04-02 01:46:32 +000093Evaluation is still lazy as in existing Boolean expressions, so the
94order of evaluation jumps around a bit. The \var{condition}
95expression in the middle is evaluated first, and the \var{true_value}
96expression is evaluated only if the condition was true. Similarly,
97the \var{false_value} expression is only evaluated when the condition
98is false.
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000099
100This syntax may seem strange and backwards; why does the condition go
101in the \emph{middle} of the expression, and not in the front as in C's
102\code{c ? x : y}? The decision was checked by applying the new syntax
103to the modules in the standard library and seeing how the resulting
104code read. In many cases where a conditional expression is used, one
105value seems to be the 'common case' and one value is an 'exceptional
106case', used only on rarer occasions when the condition isn't met. The
107conditional syntax makes this pattern a bit more obvious:
108
109\begin{verbatim}
110contents = ((doc + '\n') if doc else '')
111\end{verbatim}
112
113I read the above statement as meaning ``here \var{contents} is
Andrew M. Kuchlingd0fcc022006-03-09 13:57:28 +0000114usually assigned a value of \code{doc+'\e n'}; sometimes
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +0000115\var{doc} is empty, in which special case an empty string is returned.''
116I doubt I will use conditional expressions very often where there
117isn't a clear common and uncommon case.
118
119There was some discussion of whether the language should require
120surrounding conditional expressions with parentheses. The decision
121was made to \emph{not} require parentheses in the Python language's
122grammar, but as a matter of style I think you should always use them.
123Consider these two statements:
124
125\begin{verbatim}
126# First version -- no parens
127level = 1 if logging else 0
128
129# Second version -- with parens
130level = (1 if logging else 0)
131\end{verbatim}
132
133In the first version, I think a reader's eye might group the statement
134into 'level = 1', 'if logging', 'else 0', and think that the condition
135decides whether the assignment to \var{level} is performed. The
136second version reads better, in my opinion, because it makes it clear
137that the assignment is always performed and the choice is being made
138between two values.
139
140Another reason for including the brackets: a few odd combinations of
141list comprehensions and lambdas could look like incorrect conditional
142expressions. See \pep{308} for some examples. If you put parentheses
143around your conditional expressions, you won't run into this case.
144
145
146\begin{seealso}
147
148\seepep{308}{Conditional Expressions}{PEP written by
149Guido van Rossum and Raymond D. Hettinger; implemented by Thomas
150Wouters.}
151
152\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000153
154
155%======================================================================
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +0000156\section{PEP 309: Partial Function Application}
Fred Drake2db76802004-12-01 05:05:47 +0000157
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000158The \module{functional} module is intended to contain tools for
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000159functional-style programming. Currently it only contains a
160\class{partial()} function, but new functions will probably be added
161in future versions of Python.
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000162
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000163For programs written in a functional style, it can be useful to
164construct variants of existing functions that have some of the
165parameters filled in. Consider a Python function \code{f(a, b, c)};
166you could create a new function \code{g(b, c)} that was equivalent to
167\code{f(1, b, c)}. This is called ``partial function application'',
168and is provided by the \class{partial} class in the new
169\module{functional} module.
170
171The constructor for \class{partial} takes the arguments
172\code{(\var{function}, \var{arg1}, \var{arg2}, ...
173\var{kwarg1}=\var{value1}, \var{kwarg2}=\var{value2})}. The resulting
174object is callable, so you can just call it to invoke \var{function}
175with the filled-in arguments.
176
177Here's a small but realistic example:
178
179\begin{verbatim}
180import functional
181
182def log (message, subsystem):
183 "Write the contents of 'message' to the specified subsystem."
184 print '%s: %s' % (subsystem, message)
185 ...
186
187server_log = functional.partial(log, subsystem='server')
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000188server_log('Unable to open socket')
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000189\end{verbatim}
190
Andrew M. Kuchling6af7fe02005-08-02 17:20:36 +0000191Here's another example, from a program that uses PyGTk. Here a
192context-sensitive pop-up menu is being constructed dynamically. The
193callback provided for the menu option is a partially applied version
194of the \method{open_item()} method, where the first argument has been
195provided.
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000196
Andrew M. Kuchling6af7fe02005-08-02 17:20:36 +0000197\begin{verbatim}
198...
199class Application:
200 def open_item(self, path):
201 ...
202 def init (self):
203 open_func = functional.partial(self.open_item, item_path)
204 popup_menu.append( ("Open", open_func, 1) )
205\end{verbatim}
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000206
207
208\begin{seealso}
209
210\seepep{309}{Partial Function Application}{PEP proposed and written by
211Peter Harris; implemented by Hye-Shik Chang, with adaptations by
212Raymond Hettinger.}
213
214\end{seealso}
Fred Drake2db76802004-12-01 05:05:47 +0000215
216
217%======================================================================
Fred Drakedb7b0022005-03-20 22:19:47 +0000218\section{PEP 314: Metadata for Python Software Packages v1.1}
219
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000220Some simple dependency support was added to Distutils. The
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000221\function{setup()} function now has \code{requires}, \code{provides},
222and \code{obsoletes} keyword parameters. When you build a source
223distribution using the \code{sdist} command, the dependency
224information will be recorded in the \file{PKG-INFO} file.
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000225
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000226Another new keyword parameter is \code{download_url}, which should be
227set to a URL for the package's source code. This means it's now
228possible to look up an entry in the package index, determine the
229dependencies for a package, and download the required packages.
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000230
Andrew M. Kuchling61434b62006-04-13 11:51:07 +0000231\begin{verbatim}
232VERSION = '1.0'
233setup(name='PyPackage',
234 version=VERSION,
235 requires=['numarray', 'zlib (>=1.1.4)'],
236 obsoletes=['OldPackage']
237 download_url=('http://www.example.com/pypackage/dist/pkg-%s.tar.gz'
238 % VERSION),
239 )
240\end{verbatim}
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000241
242\begin{seealso}
243
244\seepep{314}{Metadata for Python Software Packages v1.1}{PEP proposed
245and written by A.M. Kuchling, Richard Jones, and Fred Drake;
246implemented by Richard Jones and Fred Drake.}
247
248\end{seealso}
Fred Drakedb7b0022005-03-20 22:19:47 +0000249
250
251%======================================================================
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000252\section{PEP 328: Absolute and Relative Imports}
253
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000254The simpler part of PEP 328 was implemented in Python 2.4: parentheses
255could now be used to enclose the names imported from a module using
256the \code{from ... import ...} statement, making it easier to import
257many different names.
258
259The more complicated part has been implemented in Python 2.5:
260importing a module can be specified to use absolute or
261package-relative imports. The plan is to move toward making absolute
262imports the default in future versions of Python.
263
264Let's say you have a package directory like this:
265\begin{verbatim}
266pkg/
267pkg/__init__.py
268pkg/main.py
269pkg/string.py
270\end{verbatim}
271
272This defines a package named \module{pkg} containing the
273\module{pkg.main} and \module{pkg.string} submodules.
274
275Consider the code in the \file{main.py} module. What happens if it
276executes the statement \code{import string}? In Python 2.4 and
277earlier, it will first look in the package's directory to perform a
278relative import, finds \file{pkg/string.py}, imports the contents of
279that file as the \module{pkg.string} module, and that module is bound
280to the name \samp{string} in the \module{pkg.main} module's namespace.
281
282That's fine if \module{pkg.string} was what you wanted. But what if
283you wanted Python's standard \module{string} module? There's no clean
284way to ignore \module{pkg.string} and look for the standard module;
285generally you had to look at the contents of \code{sys.modules}, which
286is slightly unclean.
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000287Holger Krekel's \module{py.std} package provides a tidier way to perform
288imports from the standard library, \code{import py ; py.std.string.join()},
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000289but that package isn't available on all Python installations.
290
291Reading code which relies on relative imports is also less clear,
292because a reader may be confused about which module, \module{string}
293or \module{pkg.string}, is intended to be used. Python users soon
294learned not to duplicate the names of standard library modules in the
295names of their packages' submodules, but you can't protect against
296having your submodule's name being used for a new module added in a
297future version of Python.
298
299In Python 2.5, you can switch \keyword{import}'s behaviour to
300absolute imports using a \code{from __future__ import absolute_import}
301directive. This absolute-import behaviour will become the default in
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000302a future version (probably Python 2.7). Once absolute imports
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000303are the default, \code{import string} will
304always find the standard library's version.
305It's suggested that users should begin using absolute imports as much
306as possible, so it's preferable to begin writing \code{from pkg import
307string} in your code.
308
309Relative imports are still possible by adding a leading period
310to the module name when using the \code{from ... import} form:
311
312\begin{verbatim}
313# Import names from pkg.string
314from .string import name1, name2
315# Import pkg.string
316from . import string
317\end{verbatim}
318
319This imports the \module{string} module relative to the current
320package, so in \module{pkg.main} this will import \var{name1} and
321\var{name2} from \module{pkg.string}. Additional leading periods
322perform the relative import starting from the parent of the current
323package. For example, code in the \module{A.B.C} module can do:
324
325\begin{verbatim}
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000326from . import D # Imports A.B.D
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000327from .. import E # Imports A.E
328from ..F import G # Imports A.F.G
329\end{verbatim}
330
331Leading periods cannot be used with the \code{import \var{modname}}
332form of the import statement, only the \code{from ... import} form.
333
334\begin{seealso}
335
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000336\seepep{328}{Imports: Multi-Line and Absolute/Relative}
337{PEP written by Aahz; implemented by Thomas Wouters.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000338
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000339\seeurl{http://codespeak.net/py/current/doc/index.html}
340{The py library by Holger Krekel, which contains the \module{py.std} package.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000341
342\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000343
344
345%======================================================================
Andrew M. Kuchling21d3a7c2006-03-15 11:53:09 +0000346\section{PEP 338: Executing Modules as Scripts}
347
Andrew M. Kuchlingb182db42006-03-17 21:48:46 +0000348The \programopt{-m} switch added in Python 2.4 to execute a module as
349a script gained a few more abilities. Instead of being implemented in
350C code inside the Python interpreter, the switch now uses an
351implementation in a new module, \module{runpy}.
352
353The \module{runpy} module implements a more sophisticated import
354mechanism so that it's now possible to run modules in a package such
355as \module{pychecker.checker}. The module also supports alternative
Andrew M. Kuchling5d4cf5e2006-04-13 13:02:42 +0000356import mechanisms such as the \module{zipimport} module. This means
Andrew M. Kuchlingb182db42006-03-17 21:48:46 +0000357you can add a .zip archive's path to \code{sys.path} and then use the
358\programopt{-m} switch to execute code from the archive.
359
360
361\begin{seealso}
362
363\seepep{338}{Executing modules as scripts}{PEP written and
364implemented by Nick Coghlan.}
365
366\end{seealso}
Andrew M. Kuchling21d3a7c2006-03-15 11:53:09 +0000367
368
369%======================================================================
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000370\section{PEP 341: Unified try/except/finally}
371
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000372Until Python 2.5, the \keyword{try} statement came in two
373flavours. You could use a \keyword{finally} block to ensure that code
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +0000374is always executed, or one or more \keyword{except} blocks to catch
375specific exceptions. You couldn't combine both \keyword{except} blocks and a
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000376\keyword{finally} block, because generating the right bytecode for the
377combined version was complicated and it wasn't clear what the
378semantics of the combined should be.
379
380GvR spent some time working with Java, which does support the
381equivalent of combining \keyword{except} blocks and a
382\keyword{finally} block, and this clarified what the statement should
383mean. In Python 2.5, you can now write:
384
385\begin{verbatim}
386try:
387 block-1 ...
388except Exception1:
389 handler-1 ...
390except Exception2:
391 handler-2 ...
392else:
393 else-block
394finally:
395 final-block
396\end{verbatim}
397
398The code in \var{block-1} is executed. If the code raises an
399exception, the handlers are tried in order: \var{handler-1},
400\var{handler-2}, ... If no exception is raised, the \var{else-block}
401is executed. No matter what happened previously, the
402\var{final-block} is executed once the code block is complete and any
403raised exceptions handled. Even if there's an error in an exception
404handler or the \var{else-block} and a new exception is raised, the
405\var{final-block} is still executed.
406
407\begin{seealso}
408
409\seepep{341}{Unifying try-except and try-finally}{PEP written by Georg Brandl;
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000410implementation by Thomas Lee.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000411
412\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000413
414
415%======================================================================
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +0000416\section{PEP 342: New Generator Features\label{section-generators}}
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000417
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000418Python 2.5 adds a simple way to pass values \emph{into} a generator.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000419As introduced in Python 2.3, generators only produce output; once a
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000420generator's code is invoked to create an iterator, there's no way to
421pass any new information into the function when its execution is
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000422resumed. Sometimes the ability to pass in some information would be
423useful. Hackish solutions to this include making the generator's code
424look at a global variable and then changing the global variable's
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000425value, or passing in some mutable object that callers then modify.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000426
427To refresh your memory of basic generators, here's a simple example:
428
429\begin{verbatim}
430def counter (maximum):
431 i = 0
432 while i < maximum:
433 yield i
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000434 i += 1
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000435\end{verbatim}
436
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000437When you call \code{counter(10)}, the result is an iterator that
438returns the values from 0 up to 9. On encountering the
439\keyword{yield} statement, the iterator returns the provided value and
440suspends the function's execution, preserving the local variables.
441Execution resumes on the following call to the iterator's
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000442\method{next()} method, picking up after the \keyword{yield} statement.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000443
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000444In Python 2.3, \keyword{yield} was a statement; it didn't return any
445value. In 2.5, \keyword{yield} is now an expression, returning a
446value that can be assigned to a variable or otherwise operated on:
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000447
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000448\begin{verbatim}
449val = (yield i)
450\end{verbatim}
451
452I recommend that you always put parentheses around a \keyword{yield}
453expression when you're doing something with the returned value, as in
454the above example. The parentheses aren't always necessary, but it's
455easier to always add them instead of having to remember when they're
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000456needed.\footnote{The exact rules are that a \keyword{yield}-expression must
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000457always be parenthesized except when it occurs at the top-level
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000458expression on the right-hand side of an assignment, meaning you can
459write \code{val = yield i} but have to use parentheses when there's an
460operation, as in \code{val = (yield i) + 12}.}
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000461
462Values are sent into a generator by calling its
463\method{send(\var{value})} method. The generator's code is then
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000464resumed and the \keyword{yield} expression returns the specified
465\var{value}. If the regular \method{next()} method is called, the
466\keyword{yield} returns \constant{None}.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000467
468Here's the previous example, modified to allow changing the value of
469the internal counter.
470
471\begin{verbatim}
472def counter (maximum):
473 i = 0
474 while i < maximum:
475 val = (yield i)
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000476 # If value provided, change counter
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000477 if val is not None:
478 i = val
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000479 else:
480 i += 1
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000481\end{verbatim}
482
483And here's an example of changing the counter:
484
485\begin{verbatim}
486>>> it = counter(10)
487>>> print it.next()
4880
489>>> print it.next()
4901
491>>> print it.send(8)
4928
493>>> print it.next()
4949
495>>> print it.next()
496Traceback (most recent call last):
497 File ``t.py'', line 15, in ?
498 print it.next()
499StopIteration
Andrew M. Kuchlingc2033702005-08-29 13:30:12 +0000500\end{verbatim}
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000501
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000502Because \keyword{yield} will often be returning \constant{None}, you
503should always check for this case. Don't just use its value in
504expressions unless you're sure that the \method{send()} method
505will be the only method used resume your generator function.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000506
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000507In addition to \method{send()}, there are two other new methods on
508generators:
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000509
510\begin{itemize}
511
512 \item \method{throw(\var{type}, \var{value}=None,
513 \var{traceback}=None)} is used to raise an exception inside the
514 generator; the exception is raised by the \keyword{yield} expression
515 where the generator's execution is paused.
516
517 \item \method{close()} raises a new \exception{GeneratorExit}
518 exception inside the generator to terminate the iteration.
519 On receiving this
520 exception, the generator's code must either raise
521 \exception{GeneratorExit} or \exception{StopIteration}; catching the
522 exception and doing anything else is illegal and will trigger
523 a \exception{RuntimeError}. \method{close()} will also be called by
524 Python's garbage collection when the generator is garbage-collected.
525
526 If you need to run cleanup code in case of a \exception{GeneratorExit},
527 I suggest using a \code{try: ... finally:} suite instead of
528 catching \exception{GeneratorExit}.
529
530\end{itemize}
531
532The cumulative effect of these changes is to turn generators from
533one-way producers of information into both producers and consumers.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000534
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000535Generators also become \emph{coroutines}, a more generalized form of
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000536subroutines. Subroutines are entered at one point and exited at
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000537another point (the top of the function, and a \keyword{return
538statement}), but coroutines can be entered, exited, and resumed at
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000539many different points (the \keyword{yield} statements). We'll have to
540figure out patterns for using coroutines effectively in Python.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000541
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000542The addition of the \method{close()} method has one side effect that
543isn't obvious. \method{close()} is called when a generator is
544garbage-collected, so this means the generator's code gets one last
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +0000545chance to run before the generator is destroyed. This last chance
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000546means that \code{try...finally} statements in generators can now be
547guaranteed to work; the \keyword{finally} clause will now always get a
548chance to run. The syntactic restriction that you couldn't mix
549\keyword{yield} statements with a \code{try...finally} suite has
550therefore been removed. This seems like a minor bit of language
551trivia, but using generators and \code{try...finally} is actually
552necessary in order to implement the \keyword{with} statement
553described by PEP 343. We'll look at this new statement in the following
554section.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000555
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +0000556Another even more esoteric effect of this change: previously, the
557\member{gi_frame} attribute of a generator was always a frame object.
558It's now possible for \member{gi_frame} to be \code{None}
559once the generator has been exhausted.
560
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000561\begin{seealso}
562
563\seepep{342}{Coroutines via Enhanced Generators}{PEP written by
564Guido van Rossum and Phillip J. Eby;
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000565implemented by Phillip J. Eby. Includes examples of
566some fancier uses of generators as coroutines.}
567
568\seeurl{http://en.wikipedia.org/wiki/Coroutine}{The Wikipedia entry for
569coroutines.}
570
Neal Norwitz09179882006-03-04 23:31:45 +0000571\seeurl{http://www.sidhe.org/\~{}dan/blog/archives/000178.html}{An
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000572explanation of coroutines from a Perl point of view, written by Dan
573Sugalski.}
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000574
575\end{seealso}
576
577
578%======================================================================
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000579\section{PEP 343: The 'with' statement}
580
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000581The \keyword{with} statement allows a clearer version of code that
582uses \code{try...finally} blocks to ensure that clean-up code is
583executed.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000584
585First, I'll discuss the statement as it will commonly be used, and
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000586then a subsection will examine the implementation details and how to
587write objects (called ``context managers'') that can be used with this
588statement. Most people will only use \keyword{with} in company with
589existing objects that are documented to work as context managers, and
590don't need to know these details, so you can skip the subsection if
591you like. Authors of new context managers will need to understand the
592details of the underlying implementation.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000593
594The \keyword{with} statement is a new control-flow structure whose
595basic structure is:
596
597\begin{verbatim}
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000598with expression [as variable]:
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000599 with-block
600\end{verbatim}
601
602The expression is evaluated, and it should result in a type of object
603that's called a context manager. The context manager can return a
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000604value that can optionally be bound to the name \var{variable}. (Note
605carefully: \var{variable} is \emph{not} assigned the result of
606\var{expression}.) One method of the context manager is run before
607\var{with-block} is executed, and another method is run after the
608block is done, even if the block raised an exception.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000609
610To enable the statement in Python 2.5, you need
611to add the following directive to your module:
612
613\begin{verbatim}
614from __future__ import with_statement
615\end{verbatim}
616
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000617The statement will always be enabled in Python 2.6.
618
619Some standard Python objects can now behave as context managers. File
620objects are one example:
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000621
622\begin{verbatim}
623with open('/etc/passwd', 'r') as f:
624 for line in f:
625 print line
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000626 ... more processing code ...
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000627\end{verbatim}
628
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000629After this statement has executed, the file object in \var{f} will
630have been automatically closed at this point, even if the 'for' loop
631raised an exception part-way through the block.
632
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000633The \module{threading} module's locks and condition variables
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000634also support the \keyword{with} statement:
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000635
636\begin{verbatim}
637lock = threading.Lock()
638with lock:
639 # Critical section of code
640 ...
641\end{verbatim}
642
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000643The lock is acquired before the block is executed, and always released once
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000644the block is complete.
645
646The \module{decimal} module's contexts, which encapsulate the desired
647precision and rounding characteristics for computations, can also be
648used as context managers.
649
650\begin{verbatim}
651import decimal
652
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000653# Displays with default precision of 28 digits
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000654v1 = decimal.Decimal('578')
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000655print v1.sqrt()
656
657with decimal.Context(prec=16):
658 # All code in this block uses a precision of 16 digits.
659 # The original context is restored on exiting the block.
660 print v1.sqrt()
661\end{verbatim}
662
663\subsection{Writing Context Managers}
664
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000665Under the hood, the \keyword{with} statement is fairly complicated.
666The interface demanded of context managers contains several methods.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000667
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000668A high-level explanation of the context management protocol is:
669
670\begin{itemize}
671\item The expression is evaluated and should result in an object
672that's a context manager, meaning that it has a
673\method{__context__()} method.
674
675\item This object's \method{__context__()} method is called, and must
676return a context object.
677
678\item The context's \method{__enter__()} method is called.
679The value returned is assigned to \var{VAR}. If no \code{as \var{VAR}}
680clause is present, the value is simply discarded.
681
682\item The code in \var{BLOCK} is executed.
683
684\item If \var{BLOCK} raises an exception, the context object's
685\method{__exit__(\var{type}, \var{value}, \var{traceback})} is called
686with the exception's information, the same values returned by
687\function{sys.exc_info()}. The method's return value
688controls whether the exception is re-raised: any false value
689re-raises the exception, and \code{True} will result in suppressing it.
690You'll only rarely want to suppress the exception; the
691author of the code containing the \keyword{with} statement will
692never realize anything went wrong.
693
694\item If \var{BLOCK} didn't raise an exception,
695the context object's \method{__exit__()} is still called,
696but \var{type}, \var{value}, and \var{traceback} are all \code{None}.
697
698\end{itemize}
699
700Let's think through an example. I won't present detailed code but
701will only sketch the necessary code. The example will be writing a
702context manager for a database that supports transactions.
703
704(For people unfamiliar with database terminology: a set of changes to
705the database are grouped into a transaction. Transactions can be
706either committed, meaning that all the changes are written into the
707database, or rolled back, meaning that the changes are all discarded
708and the database is unchanged. See any database textbook for more
709information.)
710% XXX find a shorter reference?
711
712Let's assume there's an object representing a database connection.
713Our goal will be to let the user write code like this:
714
715\begin{verbatim}
716db_connection = DatabaseConnection()
717with db_connection as cursor:
718 cursor.execute('insert into ...')
719 cursor.execute('delete from ...')
720 # ... more operations ...
721\end{verbatim}
722
723The transaction should either be committed if the code in the block
724runs flawlessly, or rolled back if there's an exception.
725
726First, the \class{DatabaseConnection} needs a \method{__context__()}
727method. Sometimes an object can be its own context manager and can
728simply return \code{self}; the \module{threading} module's lock objects
729can do this. For our database example, though, we need to
730create a new object; I'll call this class \class{DatabaseContext}.
731Our \method{__context__()} must therefore look like this:
732
733\begin{verbatim}
734class DatabaseConnection:
735 ...
736 def __context__ (self):
737 return DatabaseContext(self)
738
739 # Database interface
740 def cursor (self):
741 "Returns a cursor object and starts a new transaction"
742 def commit (self):
743 "Commits current transaction"
744 def rollback (self):
745 "Rolls back current transaction"
746\end{verbatim}
747
748The context needs the connection object so that the connection
749object's \method{commit()} or \method{rollback()} methods can be
750called:
751
752\begin{verbatim}
753class DatabaseContext:
754 def __init__ (self, connection):
755 self.connection = connection
756\end{verbatim}
757
758The \method {__enter__()} method is pretty easy, having only
759to start a new transaction. In this example,
760the resulting cursor object would be a useful result,
761so the method will return it. The user can
762then add \code{as cursor} to their \keyword{with} statement
763to bind the cursor to a variable name.
764
765\begin{verbatim}
766class DatabaseContext:
767 ...
768 def __enter__ (self):
769 # Code to start a new transaction
770 cursor = self.connection.cursor()
771 return cursor
772\end{verbatim}
773
774The \method{__exit__()} method is the most complicated because it's
775where most of the work has to be done. The method has to check if an
776exception occurred. If there was no exception, the transaction is
777committed. The transaction is rolled back if there was an exception.
778Here the code will just fall off the end of the function, returning
779the default value of \code{None}. \code{None} is false, so the exception
780will be re-raised automatically. If you wished, you could be more explicit
781and add a \keyword{return} at the marked location.
782
783\begin{verbatim}
784class DatabaseContext:
785 ...
786 def __exit__ (self, type, value, tb):
787 if tb is None:
788 # No exception, so commit
789 self.connection.commit()
790 else:
791 # Exception occurred, so rollback.
792 self.connection.rollback()
793 # return False
794\end{verbatim}
795
796\begin{comment}
797% XXX should I give the code, or is the above explanation sufficient?
798\pep{343} shows the code generated for a \keyword{with} statement. A
799statement such as:
800
801\begin{verbatim}
802with EXPR as VAR:
803 BLOCK
804\end{verbatim}
805
806is translated into:
807
808\begin{verbatim}
809ctx = (EXPR).__context__()
810exit = ctx.__exit__ # Not calling it yet
811value = ctx.__enter__()
812exc = True
813try:
814 try:
815 VAR = value # Only if "as VAR" is present
816 BLOCK
817 except:
818 # The exceptional case is handled here
819 exc = False
820 if not exit(*sys.exc_info()):
821 raise
822finally:
823 # The normal and non-local-goto cases are handled here
824 if exc:
825 exit(None, None, None)
826\end{verbatim}
827\end{comment}
828
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000829
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000830The new \module{contextlib} module provides some functions and a
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000831decorator that are useful for writing context managers.
832Future versions will go into more detail.
833
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000834% XXX describe further
835
836\begin{seealso}
837
838\seepep{343}{The ``with'' statement}{PEP written by
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +0000839Guido van Rossum and Nick Coghlan.
840The PEP shows the code generated for a \keyword{with} statement,
841which can be helpful in learning how context managers work.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000842
843\end{seealso}
844
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000845
846%======================================================================
Andrew M. Kuchling8f4d2552006-03-08 01:50:20 +0000847\section{PEP 352: Exceptions as New-Style Classes}
848
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000849Exception classes can now be new-style classes, not just classic
850classes, and the built-in \exception{Exception} class and all the
851standard built-in exceptions (\exception{NameError},
852\exception{ValueError}, etc.) are now new-style classes.
Andrew M. Kuchlingaeadf952006-03-09 19:06:05 +0000853
854The inheritance hierarchy for exceptions has been rearranged a bit.
855In 2.5, the inheritance relationships are:
856
857\begin{verbatim}
858BaseException # New in Python 2.5
859|- KeyboardInterrupt
860|- SystemExit
861|- Exception
862 |- (all other current built-in exceptions)
863\end{verbatim}
864
865This rearrangement was done because people often want to catch all
866exceptions that indicate program errors. \exception{KeyboardInterrupt} and
867\exception{SystemExit} aren't errors, though, and usually represent an explicit
868action such as the user hitting Control-C or code calling
869\function{sys.exit()}. A bare \code{except:} will catch all exceptions,
870so you commonly need to list \exception{KeyboardInterrupt} and
871\exception{SystemExit} in order to re-raise them. The usual pattern is:
872
873\begin{verbatim}
874try:
875 ...
876except (KeyboardInterrupt, SystemExit):
877 raise
878except:
879 # Log error...
880 # Continue running program...
881\end{verbatim}
882
883In Python 2.5, you can now write \code{except Exception} to achieve
884the same result, catching all the exceptions that usually indicate errors
885but leaving \exception{KeyboardInterrupt} and
886\exception{SystemExit} alone. As in previous versions,
887a bare \code{except:} still catches all exceptions.
888
889The goal for Python 3.0 is to require any class raised as an exception
890to derive from \exception{BaseException} or some descendant of
891\exception{BaseException}, and future releases in the
892Python 2.x series may begin to enforce this constraint. Therefore, I
893suggest you begin making all your exception classes derive from
894\exception{Exception} now. It's been suggested that the bare
895\code{except:} form should be removed in Python 3.0, but Guido van~Rossum
896hasn't decided whether to do this or not.
897
898Raising of strings as exceptions, as in the statement \code{raise
899"Error occurred"}, is deprecated in Python 2.5 and will trigger a
900warning. The aim is to be able to remove the string-exception feature
901in a few releases.
902
903
904\begin{seealso}
905
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000906\seepep{352}{Required Superclass for Exceptions}{PEP written by
Andrew M. Kuchlingaeadf952006-03-09 19:06:05 +0000907Brett Cannon and Guido van Rossum; implemented by Brett Cannon.}
908
909\end{seealso}
Andrew M. Kuchling8f4d2552006-03-08 01:50:20 +0000910
911
912%======================================================================
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000913\section{PEP 353: Using ssize_t as the index type\label{section-353}}
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000914
915A wide-ranging change to Python's C API, using a new
916\ctype{Py_ssize_t} type definition instead of \ctype{int},
917will permit the interpreter to handle more data on 64-bit platforms.
918This change doesn't affect Python's capacity on 32-bit platforms.
919
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000920Various pieces of the Python interpreter used C's \ctype{int} type to
921store sizes or counts; for example, the number of items in a list or
922tuple were stored in an \ctype{int}. The C compilers for most 64-bit
923platforms still define \ctype{int} as a 32-bit type, so that meant
924that lists could only hold up to \code{2**31 - 1} = 2147483647 items.
925(There are actually a few different programming models that 64-bit C
926compilers can use -- see
927\url{http://www.unix.org/version2/whatsnew/lp64_wp.html} for a
928discussion -- but the most commonly available model leaves \ctype{int}
929as 32 bits.)
930
931A limit of 2147483647 items doesn't really matter on a 32-bit platform
932because you'll run out of memory before hitting the length limit.
933Each list item requires space for a pointer, which is 4 bytes, plus
934space for a \ctype{PyObject} representing the item. 2147483647*4 is
935already more bytes than a 32-bit address space can contain.
936
937It's possible to address that much memory on a 64-bit platform,
938however. The pointers for a list that size would only require 16GiB
939of space, so it's not unreasonable that Python programmers might
940construct lists that large. Therefore, the Python interpreter had to
941be changed to use some type other than \ctype{int}, and this will be a
94264-bit type on 64-bit platforms. The change will cause
943incompatibilities on 64-bit machines, so it was deemed worth making
944the transition now, while the number of 64-bit users is still
945relatively small. (In 5 or 10 years, we may \emph{all} be on 64-bit
946machines, and the transition would be more painful then.)
947
948This change most strongly affects authors of C extension modules.
949Python strings and container types such as lists and tuples
950now use \ctype{Py_ssize_t} to store their size.
951Functions such as \cfunction{PyList_Size()}
952now return \ctype{Py_ssize_t}. Code in extension modules
953may therefore need to have some variables changed to
954\ctype{Py_ssize_t}.
955
956The \cfunction{PyArg_ParseTuple()} and \cfunction{Py_BuildValue()} functions
957have a new conversion code, \samp{n}, for \ctype{Py_ssize_t}.
Andrew M. Kuchlinga4d651f2006-04-06 13:24:58 +0000958\cfunction{PyArg_ParseTuple()}'s \samp{s\#} and \samp{t\#} still output
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000959\ctype{int} by default, but you can define the macro
960\csimplemacro{PY_SSIZE_T_CLEAN} before including \file{Python.h}
961to make them return \ctype{Py_ssize_t}.
962
963\pep{353} has a section on conversion guidelines that
964extension authors should read to learn about supporting 64-bit
965platforms.
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000966
967\begin{seealso}
968
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +0000969\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 +0000970
971\end{seealso}
972
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000973
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000974%======================================================================
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000975\section{PEP 357: The '__index__' method}
976
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000977The NumPy developers had a problem that could only be solved by adding
978a new special method, \method{__index__}. When using slice notation,
Fred Drake1c0e3282006-04-02 03:30:06 +0000979as in \code{[\var{start}:\var{stop}:\var{step}]}, the values of the
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000980\var{start}, \var{stop}, and \var{step} indexes must all be either
981integers or long integers. NumPy defines a variety of specialized
982integer types corresponding to unsigned and signed integers of 8, 16,
98332, and 64 bits, but there was no way to signal that these types could
984be used as slice indexes.
985
986Slicing can't just use the existing \method{__int__} method because
987that method is also used to implement coercion to integers. If
988slicing used \method{__int__}, floating-point numbers would also
989become legal slice indexes and that's clearly an undesirable
990behaviour.
991
992Instead, a new special method called \method{__index__} was added. It
993takes no arguments and returns an integer giving the slice index to
994use. For example:
995
996\begin{verbatim}
997class C:
998 def __index__ (self):
999 return self.value
1000\end{verbatim}
1001
1002The return value must be either a Python integer or long integer.
1003The interpreter will check that the type returned is correct, and
1004raises a \exception{TypeError} if this requirement isn't met.
1005
1006A corresponding \member{nb_index} slot was added to the C-level
1007\ctype{PyNumberMethods} structure to let C extensions implement this
1008protocol. \cfunction{PyNumber_Index(\var{obj})} can be used in
1009extension code to call the \method{__index__} function and retrieve
1010its result.
1011
1012\begin{seealso}
1013
1014\seepep{357}{Allowing Any Object to be Used for Slicing}{PEP written
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +00001015and implemented by Travis Oliphant.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001016
1017\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +00001018
1019
1020%======================================================================
Fred Drake2db76802004-12-01 05:05:47 +00001021\section{Other Language Changes}
1022
1023Here are all of the changes that Python 2.5 makes to the core Python
1024language.
1025
1026\begin{itemize}
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001027
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001028\item The \class{dict} type has a new hook for letting subclasses
1029provide a default value when a key isn't contained in the dictionary.
1030When a key isn't found, the dictionary's
1031\method{__missing__(\var{key})}
1032method will be called. This hook is used to implement
1033the new \class{defaultdict} class in the \module{collections}
1034module. The following example defines a dictionary
1035that returns zero for any missing key:
1036
1037\begin{verbatim}
1038class zerodict (dict):
1039 def __missing__ (self, key):
1040 return 0
1041
1042d = zerodict({1:1, 2:2})
1043print d[1], d[2] # Prints 1, 2
1044print d[3], d[4] # Prints 0, 0
1045\end{verbatim}
1046
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001047\item The \function{min()} and \function{max()} built-in functions
1048gained a \code{key} keyword argument analogous to the \code{key}
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001049argument for \method{sort()}. This argument supplies a function that
1050takes a single argument and is called for every value in the list;
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001051\function{min()}/\function{max()} will return the element with the
1052smallest/largest return value from this function.
1053For example, to find the longest string in a list, you can do:
1054
1055\begin{verbatim}
1056L = ['medium', 'longest', 'short']
1057# Prints 'longest'
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001058print max(L, key=len)
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +00001059# Prints 'short', because lexicographically 'short' has the largest value
1060print max(L)
1061\end{verbatim}
1062
1063(Contributed by Steven Bethard and Raymond Hettinger.)
Fred Drake2db76802004-12-01 05:05:47 +00001064
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001065\item Two new built-in functions, \function{any()} and
1066\function{all()}, evaluate whether an iterator contains any true or
1067false values. \function{any()} returns \constant{True} if any value
1068returned by the iterator is true; otherwise it will return
1069\constant{False}. \function{all()} returns \constant{True} only if
1070all of the values returned by the iterator evaluate as being true.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001071(Suggested by GvR, and implemented by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001072
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001073\item ASCII is now the default encoding for modules. It's now
1074a syntax error if a module contains string literals with 8-bit
1075characters but doesn't have an encoding declaration. In Python 2.4
1076this triggered a warning, not a syntax error. See \pep{263}
1077for how to declare a module's encoding; for example, you might add
1078a line like this near the top of the source file:
1079
1080\begin{verbatim}
1081# -*- coding: latin1 -*-
1082\end{verbatim}
1083
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001084\item The list of base classes in a class definition can now be empty.
1085As an example, this is now legal:
1086
1087\begin{verbatim}
1088class C():
1089 pass
1090\end{verbatim}
1091(Implemented by Brett Cannon.)
1092
Fred Drake2db76802004-12-01 05:05:47 +00001093\end{itemize}
1094
1095
1096%======================================================================
Andrew M. Kuchlingda376042006-03-17 15:56:41 +00001097\subsection{Interactive Interpreter Changes}
1098
1099In the interactive interpreter, \code{quit} and \code{exit}
1100have long been strings so that new users get a somewhat helpful message
1101when they try to quit:
1102
1103\begin{verbatim}
1104>>> quit
1105'Use Ctrl-D (i.e. EOF) to exit.'
1106\end{verbatim}
1107
1108In Python 2.5, \code{quit} and \code{exit} are now objects that still
1109produce string representations of themselves, but are also callable.
1110Newbies who try \code{quit()} or \code{exit()} will now exit the
1111interpreter as they expect. (Implemented by Georg Brandl.)
1112
1113
1114%======================================================================
Fred Drake2db76802004-12-01 05:05:47 +00001115\subsection{Optimizations}
1116
1117\begin{itemize}
1118
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001119\item When they were introduced
1120in Python 2.4, the built-in \class{set} and \class{frozenset} types
1121were built on top of Python's dictionary type.
1122In 2.5 the internal data structure has been customized for implementing sets,
1123and as a result sets will use a third less memory and are somewhat faster.
1124(Implemented by Raymond Hettinger.)
Fred Drake2db76802004-12-01 05:05:47 +00001125
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001126\item The performance of some Unicode operations has been improved.
1127% XXX provide details?
1128
1129\item The code generator's peephole optimizer now performs
1130simple constant folding in expressions. If you write something like
1131\code{a = 2+3}, the code generator will do the arithmetic and produce
1132code corresponding to \code{a = 5}.
1133
Fred Drake2db76802004-12-01 05:05:47 +00001134\end{itemize}
1135
1136The net result of the 2.5 optimizations is that Python 2.5 runs the
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +00001137pystone benchmark around XXX\% faster than Python 2.4.
Fred Drake2db76802004-12-01 05:05:47 +00001138
1139
1140%======================================================================
1141\section{New, Improved, and Deprecated Modules}
1142
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +00001143As usual, Python's standard library received many enhancements and
Fred Drake2db76802004-12-01 05:05:47 +00001144bug fixes. Here's a partial list of the most notable changes, sorted
1145alphabetically by module name. Consult the
1146\file{Misc/NEWS} file in the source tree for a more
Andrew M. Kuchlingf688cc52006-03-10 18:50:08 +00001147complete list of changes, or look through the SVN logs for all the
Fred Drake2db76802004-12-01 05:05:47 +00001148details.
1149
1150\begin{itemize}
1151
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001152% the cPickle module no longer accepts the deprecated None option in the
1153% args tuple returned by __reduce__().
1154
Andrew M. Kuchling6fc69762006-04-13 12:37:21 +00001155% XXX csv module improvements
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001156
Andrew M. Kuchling6fc69762006-04-13 12:37:21 +00001157% XXX datetime.datetime() now has a strptime class method which can be used to
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001158% create datetime object using a string and format.
1159
Andrew M. Kuchling6fc69762006-04-13 12:37:21 +00001160% XXX fileinput: opening hook used to control how files are opened.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001161% .input() now has a mode parameter
1162% now has a fileno() function
1163% accepts Unicode filenames
1164
Andrew M. Kuchling6fc69762006-04-13 12:37:21 +00001165\item The \module{audioop} module now supports the a-LAW encoding,
1166and the code for u-LAW encoding has been improved. (Contributed by
1167Lars Immisch.)
1168
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001169\item The \module{collections} module gained a new type,
1170\class{defaultdict}, that subclasses the standard \class{dict}
1171type. The new type mostly behaves like a dictionary but constructs a
1172default value when a key isn't present, automatically adding it to the
1173dictionary for the requested key value.
1174
1175The first argument to \class{defaultdict}'s constructor is a factory
1176function that gets called whenever a key is requested but not found.
1177This factory function receives no arguments, so you can use built-in
1178type constructors such as \function{list()} or \function{int()}. For
1179example,
1180you can make an index of words based on their initial letter like this:
1181
1182\begin{verbatim}
1183words = """Nel mezzo del cammin di nostra vita
1184mi ritrovai per una selva oscura
1185che la diritta via era smarrita""".lower().split()
1186
1187index = defaultdict(list)
1188
1189for w in words:
1190 init_letter = w[0]
1191 index[init_letter].append(w)
1192\end{verbatim}
1193
1194Printing \code{index} results in the following output:
1195
1196\begin{verbatim}
1197defaultdict(<type 'list'>, {'c': ['cammin', 'che'], 'e': ['era'],
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001198 'd': ['del', 'di', 'diritta'], 'm': ['mezzo', 'mi'],
1199 'l': ['la'], 'o': ['oscura'], 'n': ['nel', 'nostra'],
1200 'p': ['per'], 's': ['selva', 'smarrita'],
1201 'r': ['ritrovai'], 'u': ['una'], 'v': ['vita', 'via']}
Andrew M. Kuchlingc7095842006-04-14 12:41:19 +00001202\end{verbatim}
1203
1204The \class{deque} double-ended queue type supplied by the
1205\module{collections} module now has a \method{remove(\var{value})}
1206method that removes the first occurrence of \var{value} in the queue,
1207raising \exception{ValueError} if the value isn't found.
1208
1209\item The \module{cProfile} module is a C implementation of
1210the existing \module{profile} module that has much lower overhead.
1211The module's interface is the same as \module{profile}: you run
1212\code{cProfile.run('main()')} to profile a function, can save profile
1213data to a file, etc. It's not yet known if the Hotshot profiler,
1214which is also written in C but doesn't match the \module{profile}
1215module's interface, will continue to be maintained in future versions
1216of Python. (Contributed by Armin Rigo.)
1217
Andrew M. Kuchlingda376042006-03-17 15:56:41 +00001218\item In the \module{gc} module, the new \function{get_count()} function
1219returns a 3-tuple containing the current collection counts for the
1220three GC generations. This is accounting information for the garbage
1221collector; when these counts reach a specified threshold, a garbage
1222collection sweep will be made. The existing \function{gc.collect()}
1223function now takes an optional \var{generation} argument of 0, 1, or 2
1224to specify which generation to collect.
1225
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001226\item The \function{nsmallest()} and
1227\function{nlargest()} functions in the \module{heapq} module
1228now support a \code{key} keyword argument similar to the one
1229provided by the \function{min()}/\function{max()} functions
1230and the \method{sort()} methods. For example:
1231Example:
1232
1233\begin{verbatim}
1234>>> import heapq
1235>>> L = ["short", 'medium', 'longest', 'longer still']
1236>>> heapq.nsmallest(2, L) # Return two lowest elements, lexicographically
1237['longer still', 'longest']
1238>>> heapq.nsmallest(2, L, key=len) # Return two shortest elements
1239['short', 'medium']
1240\end{verbatim}
1241
1242(Contributed by Raymond Hettinger.)
1243
Andrew M. Kuchling511a3a82005-03-20 19:52:18 +00001244\item The \function{itertools.islice()} function now accepts
1245\code{None} for the start and step arguments. This makes it more
1246compatible with the attributes of slice objects, so that you can now write
1247the following:
1248
1249\begin{verbatim}
1250s = slice(5) # Create slice object
1251itertools.islice(iterable, s.start, s.stop, s.step)
1252\end{verbatim}
1253
1254(Contributed by Raymond Hettinger.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001255
Andrew M. Kuchling75ba2442006-04-14 10:29:55 +00001256\item The \module{nis} module now supports accessing domains other
1257than the system default domain by supplying a \var{domain} argument to
1258the \function{nis.match()} and \function{nis.maps()} functions.
1259(Contributed by Ben Bell.)
1260
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001261\item The \module{operator} module's \function{itemgetter()}
1262and \function{attrgetter()} functions now support multiple fields.
1263A call such as \code{operator.attrgetter('a', 'b')}
1264will return a function
1265that retrieves the \member{a} and \member{b} attributes. Combining
1266this new feature with the \method{sort()} method's \code{key} parameter
1267lets you easily sort lists using multiple fields.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001268(Contributed by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001269
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001270
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +00001271\item The \module{os} module underwent several changes. The
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001272\member{stat_float_times} variable now defaults to true, meaning that
1273\function{os.stat()} will now return time values as floats. (This
1274doesn't necessarily mean that \function{os.stat()} will return times
1275that are precise to fractions of a second; not all systems support
1276such precision.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001277
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001278Constants named \member{os.SEEK_SET}, \member{os.SEEK_CUR}, and
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001279\member{os.SEEK_END} have been added; these are the parameters to the
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001280\function{os.lseek()} function. Two new constants for locking are
1281\member{os.O_SHLOCK} and \member{os.O_EXLOCK}.
1282
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001283Two new functions, \function{wait3()} and \function{wait4()}, were
1284added. They're similar the \function{waitpid()} function which waits
1285for a child process to exit and returns a tuple of the process ID and
1286its exit status, but \function{wait3()} and \function{wait4()} return
1287additional information. \function{wait3()} doesn't take a process ID
1288as input, so it waits for any child process to exit and returns a
12893-tuple of \var{process-id}, \var{exit-status}, \var{resource-usage}
1290as returned from the \function{resource.getrusage()} function.
1291\function{wait4(\var{pid})} does take a process ID.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001292(Contributed by Chad J. Schroeder.)
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001293
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001294On FreeBSD, the \function{os.stat()} function now returns
1295times with nanosecond resolution, and the returned object
1296now has \member{st_gen} and \member{st_birthtime}.
1297The \member{st_flags} member is also available, if the platform supports it.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001298(Contributed by Antti Louko and Diego Petten\`o.)
1299% (Patch 1180695, 1212117)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001300
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001301\item The old \module{regex} and \module{regsub} modules, which have been
1302deprecated ever since Python 2.0, have finally been deleted.
Andrew M. Kuchlingf4b06602006-03-17 15:39:52 +00001303Other deleted modules: \module{statcache}, \module{tzparse},
1304\module{whrandom}.
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001305
1306\item The \file{lib-old} directory,
1307which includes ancient modules such as \module{dircmp} and
1308\module{ni}, was also deleted. \file{lib-old} wasn't on the default
1309\code{sys.path}, so unless your programs explicitly added the directory to
1310\code{sys.path}, this removal shouldn't affect your code.
1311
Andrew M. Kuchling4678dc82006-01-15 16:11:28 +00001312\item The \module{socket} module now supports \constant{AF_NETLINK}
1313sockets on Linux, thanks to a patch from Philippe Biondi.
1314Netlink sockets are a Linux-specific mechanism for communications
1315between a user-space process and kernel code; an introductory
1316article about them is at \url{http://www.linuxjournal.com/article/7356}.
1317In Python code, netlink addresses are represented as a tuple of 2 integers,
1318\code{(\var{pid}, \var{group_mask})}.
1319
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001320Socket objects also gained accessor methods \method{getfamily()},
1321\method{gettype()}, and \method{getproto()} methods to retrieve the
1322family, type, and protocol values for the socket.
1323
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001324\item New module: \module{spwd} provides functions for accessing the
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001325shadow password database on systems that support it.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001326% XXX give example
Fred Drake2db76802004-12-01 05:05:47 +00001327
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001328\item The Python developers switched from CVS to Subversion during the 2.5
1329development process. Information about the exact build version is
1330available as the \code{sys.subversion} variable, a 3-tuple
1331of \code{(\var{interpreter-name}, \var{branch-name}, \var{revision-range})}.
1332For example, at the time of writing
1333my copy of 2.5 was reporting \code{('CPython', 'trunk', '45313:45315')}.
1334
1335This information is also available to C extensions via the
1336\cfunction{Py_GetBuildInfo()} function that returns a
1337string of build information like this:
1338\code{"trunk:45355:45356M, Apr 13 2006, 07:42:19"}.
1339(Contributed by Barry Warsaw.)
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001340
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001341\item The \class{TarFile} class in the \module{tarfile} module now has
Georg Brandl08c02db2005-07-22 18:39:19 +00001342an \method{extractall()} method that extracts all members from the
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001343archive into the current working directory. It's also possible to set
1344a different directory as the extraction target, and to unpack only a
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001345subset of the archive's members.
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001346
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001347A tarfile's compression can be autodetected by
1348using the mode \code{'r|*'}.
1349% patch 918101
1350(Contributed by Lars Gust\"abel.)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001351
Andrew M. Kuchlingf688cc52006-03-10 18:50:08 +00001352\item The \module{unicodedata} module has been updated to use version 4.1.0
1353of the Unicode character database. Version 3.2.0 is required
1354by some specifications, so it's still available as
1355\member{unicodedata.db_3_2_0}.
1356
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001357% patch #754022: Greatly enhanced webbrowser.py (by Oleg Broytmann).
1358
Fredrik Lundh7e0aef02005-12-12 18:54:55 +00001359
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001360\item The \module{xmlrpclib} module now supports returning
1361 \class{datetime} objects for the XML-RPC date type. Supply
1362 \code{use_datetime=True} to the \function{loads()} function
1363 or the \class{Unmarshaller} class to enable this feature.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001364 (Contributed by Skip Montanaro.)
1365% Patch 1120353
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001366
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001367
Fred Drake114b8ca2005-03-21 05:47:11 +00001368\end{itemize}
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001369
Fred Drake2db76802004-12-01 05:05:47 +00001370
1371
1372%======================================================================
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001373% whole new modules get described in subsections here
Fred Drake2db76802004-12-01 05:05:47 +00001374
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001375%======================================================================
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001376\subsection{The ctypes package}
1377
1378The \module{ctypes} package, written by Thomas Heller, has been added
1379to the standard library. \module{ctypes} lets you call arbitrary functions
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001380in shared libraries or DLLs. Long-time users may remember the \module{dl} module, which
1381provides 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 +00001382
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001383To load a shared library or DLL, you must create an instance of the
1384\class{CDLL} class and provide the name or path of the shared library
1385or DLL. Once that's done, you can call arbitrary functions
1386by accessing them as attributes of the \class{CDLL} object.
1387
1388\begin{verbatim}
1389import ctypes
1390
1391libc = ctypes.CDLL('libc.so.6')
1392result = libc.printf("Line of output\n")
1393\end{verbatim}
1394
1395Type constructors for the various C types are provided: \function{c_int},
1396\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
1397to change the wrapped value. Python integers and strings will be automatically
1398converted to the corresponding C types, but for other types you
1399must call the correct type constructor. (And I mean \emph{must};
1400getting it wrong will often result in the interpreter crashing
1401with a segmentation fault.)
1402
1403You 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
1404supposed to be immutable; breaking this rule will cause puzzling bugs. When you need a modifiable memory area,
Neal Norwitz5f5a69b2006-04-13 03:41:04 +00001405use \function{create_string_buffer()}:
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001406
1407\begin{verbatim}
1408s = "this is a string"
1409buf = ctypes.create_string_buffer(s)
1410libc.strfry(buf)
1411\end{verbatim}
1412
1413C functions are assumed to return integers, but you can set
1414the \member{restype} attribute of the function object to
1415change this:
1416
1417\begin{verbatim}
1418>>> libc.atof('2.71828')
1419-1783957616
1420>>> libc.atof.restype = ctypes.c_double
1421>>> libc.atof('2.71828')
14222.71828
1423\end{verbatim}
1424
1425\module{ctypes} also provides a wrapper for Python's C API
1426as the \code{ctypes.pythonapi} object. This object does \emph{not}
1427release the global interpreter lock before calling a function, because the lock must be held when calling into the interpreter's code.
1428There's a \class{py_object()} type constructor that will create a
1429\ctype{PyObject *} pointer. A simple usage:
1430
1431\begin{verbatim}
1432import ctypes
1433
1434d = {}
1435ctypes.pythonapi.PyObject_SetItem(ctypes.py_object(d),
1436 ctypes.py_object("abc"), ctypes.py_object(1))
1437# d is now {'abc', 1}.
1438\end{verbatim}
1439
1440Don't forget to use \class{py_object()}; if it's omitted you end
1441up with a segmentation fault.
1442
1443\module{ctypes} has been around for a while, but people still write
1444and distribution hand-coded extension modules because you can't rely on \module{ctypes} being present.
1445Perhaps developers will begin to write
1446Python wrappers atop a library accessed through \module{ctypes} instead
1447of extension modules, now that \module{ctypes} is included with core Python.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001448
Andrew M. Kuchling28c5f1f2006-04-13 02:04:42 +00001449\begin{seealso}
1450
1451\seeurl{http://starship.python.net/crew/theller/ctypes/}
1452{The ctypes web page, with a tutorial, reference, and FAQ.}
1453
1454\end{seealso}
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001455
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001456
1457%======================================================================
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001458\subsection{The ElementTree package}
1459
1460A subset of Fredrik Lundh's ElementTree library for processing XML has
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001461been added to the standard library as \module{xmlcore.etree}. The
Georg Brandlce27a062006-04-11 06:27:12 +00001462available modules are
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001463\module{ElementTree}, \module{ElementPath}, and
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00001464\module{ElementInclude} from ElementTree 1.2.6.
1465The \module{cElementTree} accelerator module is also included.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001466
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001467The rest of this section will provide a brief overview of using
1468ElementTree. Full documentation for ElementTree is available at
1469\url{http://effbot.org/zone/element-index.htm}.
1470
1471ElementTree represents an XML document as a tree of element nodes.
1472The text content of the document is stored as the \member{.text}
1473and \member{.tail} attributes of
1474(This is one of the major differences between ElementTree and
1475the Document Object Model; in the DOM there are many different
1476types of node, including \class{TextNode}.)
1477
1478The most commonly used parsing function is \function{parse()}, that
1479takes either a string (assumed to contain a filename) or a file-like
1480object and returns an \class{ElementTree} instance:
1481
1482\begin{verbatim}
1483from xmlcore.etree import ElementTree as ET
1484
1485tree = ET.parse('ex-1.xml')
1486
1487feed = urllib.urlopen(
1488 'http://planet.python.org/rss10.xml')
1489tree = ET.parse(feed)
1490\end{verbatim}
1491
1492Once you have an \class{ElementTree} instance, you
1493can call its \method{getroot()} method to get the root \class{Element} node.
1494
1495There's also an \function{XML()} function that takes a string literal
1496and returns an \class{Element} node (not an \class{ElementTree}).
1497This function provides a tidy way to incorporate XML fragments,
1498approaching the convenience of an XML literal:
1499
1500\begin{verbatim}
1501svg = et.XML("""<svg width="10px" version="1.0">
1502 </svg>""")
1503svg.set('height', '320px')
1504svg.append(elem1)
1505\end{verbatim}
1506
1507Each XML element supports some dictionary-like and some list-like
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001508access methods. Dictionary-like operations are used to access attribute
1509values, and list-like operations are used to access child nodes.
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001510
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001511\begin{tableii}{c|l}{code}{Operation}{Result}
1512 \lineii{elem[n]}{Returns n'th child element.}
1513 \lineii{elem[m:n]}{Returns list of m'th through n'th child elements.}
1514 \lineii{len(elem)}{Returns number of child elements.}
1515 \lineii{elem.getchildren()}{Returns list of child elements.}
1516 \lineii{elem.append(elem2)}{Adds \var{elem2} as a child.}
1517 \lineii{elem.insert(index, elem2)}{Inserts \var{elem2} at the specified location.}
1518 \lineii{del elem[n]}{Deletes n'th child element.}
1519 \lineii{elem.keys()}{Returns list of attribute names.}
1520 \lineii{elem.get(name)}{Returns value of attribute \var{name}.}
1521 \lineii{elem.set(name, value)}{Sets new value for attribute \var{name}.}
1522 \lineii{elem.attrib}{Retrieves the dictionary containing attributes.}
1523 \lineii{del elem.attrib[name]}{Deletes attribute \var{name}.}
1524\end{tableii}
1525
1526Comments and processing instructions are also represented as
1527\class{Element} nodes. To check if a node is a comment or processing
1528instructions:
1529
1530\begin{verbatim}
1531if elem.tag is ET.Comment:
1532 ...
1533elif elem.tag is ET.ProcessingInstruction:
1534 ...
1535\end{verbatim}
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001536
1537To generate XML output, you should call the
1538\method{ElementTree.write()} method. Like \function{parse()},
1539it can take either a string or a file-like object:
1540
1541\begin{verbatim}
1542# Encoding is US-ASCII
1543tree.write('output.xml')
1544
1545# Encoding is UTF-8
1546f = open('output.xml', 'w')
1547tree.write(f, 'utf-8')
1548\end{verbatim}
1549
1550(Caution: the default encoding used for output is ASCII, which isn't
1551very useful for general XML work, raising an exception if there are
1552any characters with values greater than 127. You should always
1553specify a different encoding such as UTF-8 that can handle any Unicode
1554character.)
1555
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001556This section is only a partial description of the ElementTree interfaces.
1557Please read the package's official documentation for more details.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001558
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001559\begin{seealso}
1560
1561\seeurl{http://effbot.org/zone/element-index.htm}
1562{Official documentation for ElementTree.}
1563
1564
1565\end{seealso}
1566
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001567
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001568%======================================================================
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001569\subsection{The hashlib package}
1570
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001571A new \module{hashlib} module, written by Gregory P. Smith,
1572has been added to replace the
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001573\module{md5} and \module{sha} modules. \module{hashlib} adds support
1574for additional secure hashes (SHA-224, SHA-256, SHA-384, and SHA-512).
1575When available, the module uses OpenSSL for fast platform optimized
1576implementations of algorithms.
1577
1578The old \module{md5} and \module{sha} modules still exist as wrappers
1579around hashlib to preserve backwards compatibility. The new module's
1580interface is very close to that of the old modules, but not identical.
1581The most significant difference is that the constructor functions
1582for creating new hashing objects are named differently.
1583
1584\begin{verbatim}
1585# Old versions
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001586h = md5.md5()
1587h = md5.new()
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001588
1589# New version
1590h = hashlib.md5()
1591
1592# Old versions
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001593h = sha.sha()
1594h = sha.new()
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001595
1596# New version
1597h = hashlib.sha1()
1598
1599# Hash that weren't previously available
1600h = hashlib.sha224()
1601h = hashlib.sha256()
1602h = hashlib.sha384()
1603h = hashlib.sha512()
1604
1605# Alternative form
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001606h = hashlib.new('md5') # Provide algorithm as a string
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001607\end{verbatim}
1608
1609Once a hash object has been created, its methods are the same as before:
1610\method{update(\var{string})} hashes the specified string into the
1611current digest state, \method{digest()} and \method{hexdigest()}
1612return the digest value as a binary string or a string of hex digits,
1613and \method{copy()} returns a new hashing object with the same digest state.
1614
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001615
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001616%======================================================================
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001617\subsection{The sqlite3 package}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001618
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001619The pysqlite module (\url{http://www.pysqlite.org}), a wrapper for the
1620SQLite embedded database, has been added to the standard library under
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001621the package name \module{sqlite3}.
1622
1623SQLite is a C library that provides a SQL-language database that
1624stores data in disk files without requiring a separate server process.
1625pysqlite was written by Gerhard H\"aring and provides a SQL interface
1626compliant with the DB-API 2.0 specification described by
1627\pep{249}. This means that it should be possible to write the first
1628version of your applications using SQLite for data storage. If
1629switching to a larger database such as PostgreSQL or Oracle is
1630later necessary, the switch should be relatively easy.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001631
1632If you're compiling the Python source yourself, note that the source
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001633tree doesn't include the SQLite code, only the wrapper module.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001634You'll need to have the SQLite libraries and headers installed before
1635compiling Python, and the build process will compile the module when
1636the necessary headers are available.
1637
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001638To use the module, you must first create a \class{Connection} object
1639that represents the database. Here the data will be stored in the
1640\file{/tmp/example} file:
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001641
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001642\begin{verbatim}
1643conn = sqlite3.connect('/tmp/example')
1644\end{verbatim}
1645
1646You can also supply the special name \samp{:memory:} to create
1647a database in RAM.
1648
1649Once you have a \class{Connection}, you can create a \class{Cursor}
1650object and call its \method{execute()} method to perform SQL commands:
1651
1652\begin{verbatim}
1653c = conn.cursor()
1654
1655# Create table
1656c.execute('''create table stocks
1657(date timestamp, trans varchar, symbol varchar,
1658 qty decimal, price decimal)''')
1659
1660# Insert a row of data
1661c.execute("""insert into stocks
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001662 values ('2006-01-05','BUY','RHAT',100,35.14)""")
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001663\end{verbatim}
1664
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001665Usually your SQL operations will need to use values from Python
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001666variables. You shouldn't assemble your query using Python's string
1667operations because doing so is insecure; it makes your program
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001668vulnerable to an SQL injection attack.
1669
1670Instead, use SQLite's parameter substitution. Put \samp{?} as a
1671placeholder wherever you want to use a value, and then provide a tuple
1672of values as the second argument to the cursor's \method{execute()}
1673method. For example:
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001674
1675\begin{verbatim}
1676# Never do this -- insecure!
1677symbol = 'IBM'
1678c.execute("... where symbol = '%s'" % symbol)
1679
1680# Do this instead
1681t = (symbol,)
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001682c.execute('select * from stocks where symbol=?', ('IBM',))
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001683
1684# Larger example
1685for t in (('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
Andrew M. Kuchlingd058d002006-04-16 18:20:05 +00001686 ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
1687 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
1688 ):
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001689 c.execute('insert into stocks values (?,?,?,?,?)', t)
1690\end{verbatim}
1691
1692To retrieve data after executing a SELECT statement, you can either
1693treat the cursor as an iterator, call the cursor's \method{fetchone()}
1694method to retrieve a single matching row,
1695or call \method{fetchall()} to get a list of the matching rows.
1696
1697This example uses the iterator form:
1698
1699\begin{verbatim}
1700>>> c = conn.cursor()
1701>>> c.execute('select * from stocks order by price')
1702>>> for row in c:
1703... print row
1704...
1705(u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001)
1706(u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
1707(u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
1708(u'2006-04-05', u'BUY', u'MSOFT', 1000, 72.0)
1709>>>
1710\end{verbatim}
1711
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001712For more information about the SQL dialect supported by SQLite, see
1713\url{http://www.sqlite.org}.
1714
1715\begin{seealso}
1716
1717\seeurl{http://www.pysqlite.org}
1718{The pysqlite web page.}
1719
1720\seeurl{http://www.sqlite.org}
1721{The SQLite web page; the documentation describes the syntax and the
1722available data types for the supported SQL dialect.}
1723
1724\seepep{249}{Database API Specification 2.0}{PEP written by
1725Marc-Andr\'e Lemburg.}
1726
1727\end{seealso}
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001728
Fred Drake2db76802004-12-01 05:05:47 +00001729
1730% ======================================================================
1731\section{Build and C API Changes}
1732
1733Changes to Python's build process and to the C API include:
1734
1735\begin{itemize}
1736
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00001737\item The largest change to the C API came from \pep{353},
1738which modifies the interpreter to use a \ctype{Py_ssize_t} type
1739definition instead of \ctype{int}. See the earlier
1740section~ref{section-353} for a discussion of this change.
1741
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001742\item The design of the bytecode compiler has changed a great deal, to
1743no longer generate bytecode by traversing the parse tree. Instead
Andrew M. Kuchlingdb85ed52005-10-23 21:52:59 +00001744the parse tree is converted to an abstract syntax tree (or AST), and it is
1745the abstract syntax tree that's traversed to produce the bytecode.
1746
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00001747It's possible for Python code to obtain AST objects by using the
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001748\function{compile()} built-in and specifying \code{_ast.PyCF_ONLY_AST}
1749as the value of the
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00001750\var{flags} parameter:
1751
1752\begin{verbatim}
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001753from _ast import PyCF_ONLY_AST
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00001754ast = compile("""a=0
1755for i in range(10):
1756 a += i
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001757""", "<string>", 'exec', PyCF_ONLY_AST)
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00001758
1759assignment = ast.body[0]
1760for_loop = ast.body[1]
1761\end{verbatim}
1762
Andrew M. Kuchlingdb85ed52005-10-23 21:52:59 +00001763No documentation has been written for the AST code yet. To start
1764learning about it, read the definition of the various AST nodes in
1765\file{Parser/Python.asdl}. A Python script reads this file and
1766generates a set of C structure definitions in
1767\file{Include/Python-ast.h}. The \cfunction{PyParser_ASTFromString()}
1768and \cfunction{PyParser_ASTFromFile()}, defined in
1769\file{Include/pythonrun.h}, take Python source as input and return the
1770root of an AST representing the contents. This AST can then be turned
1771into a code object by \cfunction{PyAST_Compile()}. For more
1772information, read the source code, and then ask questions on
1773python-dev.
1774
1775% List of names taken from Jeremy's python-dev post at
1776% http://mail.python.org/pipermail/python-dev/2005-October/057500.html
1777The AST code was developed under Jeremy Hylton's management, and
1778implemented by (in alphabetical order) Brett Cannon, Nick Coghlan,
1779Grant Edwards, John Ehresman, Kurt Kaiser, Neal Norwitz, Tim Peters,
1780Armin Rigo, and Neil Schemenauer, plus the participants in a number of
1781AST sprints at conferences such as PyCon.
1782
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001783\item The built-in set types now have an official C API. Call
1784\cfunction{PySet_New()} and \cfunction{PyFrozenSet_New()} to create a
1785new set, \cfunction{PySet_Add()} and \cfunction{PySet_Discard()} to
1786add and remove elements, and \cfunction{PySet_Contains} and
1787\cfunction{PySet_Size} to examine the set's state.
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001788(Contributed by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001789
Andrew M. Kuchling61434b62006-04-13 11:51:07 +00001790\item C code can now obtain information about the exact revision
1791of the Python interpreter by calling the
1792\cfunction{Py_GetBuildInfo()} function that returns a
1793string of build information like this:
1794\code{"trunk:45355:45356M, Apr 13 2006, 07:42:19"}.
1795(Contributed by Barry Warsaw.)
1796
Andrew M. Kuchling29b3d082006-04-14 20:35:17 +00001797\item The CPython interpreter is still written in C, but
1798the code can now be compiled with a {\Cpp} compiler without errors.
1799(Implemented by Anthony Baxter, Martin von~L\"owis, Skip Montanaro.)
1800
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001801\item The \cfunction{PyRange_New()} function was removed. It was
1802never documented, never used in the core code, and had dangerously lax
1803error checking.
Fred Drake2db76802004-12-01 05:05:47 +00001804
1805\end{itemize}
1806
1807
1808%======================================================================
Andrew M. Kuchling6fc69762006-04-13 12:37:21 +00001809\subsection{Port-Specific Changes}
Fred Drake2db76802004-12-01 05:05:47 +00001810
Andrew M. Kuchling6fc69762006-04-13 12:37:21 +00001811\begin{itemize}
1812
1813\item MacOS X (10.3 and higher): dynamic loading of modules
1814now uses the \cfunction{dlopen()} function instead of MacOS-specific
1815functions.
1816
1817\end{itemize}
Fred Drake2db76802004-12-01 05:05:47 +00001818
1819
1820%======================================================================
1821\section{Other Changes and Fixes \label{section-other}}
1822
1823As usual, there were a bunch of other improvements and bugfixes
Andrew M. Kuchlingf688cc52006-03-10 18:50:08 +00001824scattered throughout the source tree. A search through the SVN change
Fred Drake2db76802004-12-01 05:05:47 +00001825logs finds there were XXX patches applied and YYY bugs fixed between
Andrew M. Kuchling92e24952004-12-03 13:54:09 +00001826Python 2.4 and 2.5. Both figures are likely to be underestimates.
Fred Drake2db76802004-12-01 05:05:47 +00001827
1828Some of the more notable changes are:
1829
1830\begin{itemize}
1831
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001832\item Evan Jones's patch to obmalloc, first described in a talk
1833at PyCon DC 2005, was applied. Python 2.4 allocated small objects in
1834256K-sized arenas, but never freed arenas. With this patch, Python
1835will free arenas when they're empty. The net effect is that on some
1836platforms, when you allocate many objects, Python's memory usage may
1837actually drop when you delete them, and the memory may be returned to
1838the operating system. (Implemented by Evan Jones, and reworked by Tim
1839Peters.)
Fred Drake2db76802004-12-01 05:05:47 +00001840
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00001841Note that this change means extension modules need to be more careful
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +00001842with how they allocate memory. Python's API has many different
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00001843functions for allocating memory that are grouped into families. For
1844example, \cfunction{PyMem_Malloc()}, \cfunction{PyMem_Realloc()}, and
1845\cfunction{PyMem_Free()} are one family that allocates raw memory,
1846while \cfunction{PyObject_Malloc()}, \cfunction{PyObject_Realloc()},
1847and \cfunction{PyObject_Free()} are another family that's supposed to
1848be used for creating Python objects.
1849
1850Previously these different families all reduced to the platform's
1851\cfunction{malloc()} and \cfunction{free()} functions. This meant
1852it didn't matter if you got things wrong and allocated memory with the
1853\cfunction{PyMem} function but freed it with the \cfunction{PyObject}
1854function. With the obmalloc change, these families now do different
1855things, and mismatches will probably result in a segfault. You should
1856carefully test your C extension modules with Python 2.5.
1857
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001858\item Coverity, a company that markets a source code analysis tool
1859 called Prevent, provided the results of their examination of the Python
Andrew M. Kuchling0f1955d2006-04-13 12:09:08 +00001860 source code. The analysis found about 60 bugs that
1861 were quickly fixed. Many of the bugs were refcounting problems, often
1862 occurring in error-handling code. See
1863 \url{http://scan.coverity.com} for the statistics.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001864
Fred Drake2db76802004-12-01 05:05:47 +00001865\end{itemize}
1866
1867
1868%======================================================================
1869\section{Porting to Python 2.5}
1870
1871This section lists previously described changes that may require
1872changes to your code:
1873
1874\begin{itemize}
1875
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001876\item ASCII is now the default encoding for modules. It's now
1877a syntax error if a module contains string literals with 8-bit
1878characters but doesn't have an encoding declaration. In Python 2.4
1879this triggered a warning, not a syntax error.
1880
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +00001881\item The \module{pickle} module no longer uses the deprecated \var{bin} parameter.
Fred Drake2db76802004-12-01 05:05:47 +00001882
Andrew M. Kuchling3b4fb042006-04-13 12:49:39 +00001883\item Previously, the \member{gi_frame} attribute of a generator
1884was always a frame object. Because of the \pep{342} changes
1885described in section~\ref{section-generators}, it's now possible
1886for \member{gi_frame} to be \code{None}.
1887
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00001888\item C API: Many functions now use \ctype{Py_ssize_t}
1889instead of \ctype{int} to allow processing more data
1890on 64-bit machines. Extension code may need to make
1891the same change to avoid warnings and to support 64-bit machines.
1892See the earlier
1893section~ref{section-353} for a discussion of this change.
1894
1895\item C API:
1896The obmalloc changes mean that
1897you must be careful to not mix usage
1898of the \cfunction{PyMem_*()} and \cfunction{PyObject_*()}
1899families of functions. Memory allocated with
1900one family's \cfunction{*_Malloc()} must be
1901freed with the corresponding family's \cfunction{*_Free()} function.
1902
Fred Drake2db76802004-12-01 05:05:47 +00001903\end{itemize}
1904
1905
1906%======================================================================
1907\section{Acknowledgements \label{acks}}
1908
1909The author would like to thank the following people for offering
1910suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001911article: Martin von~L\"owis, Mike Rovner, Thomas Wouters.
Fred Drake2db76802004-12-01 05:05:47 +00001912
1913\end{document}