blob: fb4e717ba7e99950d73a8a6c7cdfbf10d2a925b5 [file] [log] [blame]
Fred Drake2db76802004-12-01 05:05:47 +00001\documentclass{howto}
2\usepackage{distutils}
3% $Id$
4
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00005% Fix XXX comments
Andrew M. Kuchlinga4d651f2006-04-06 13:24:58 +00006% Distutils upload (PEP 243)
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00007% The easy_install stuff
Fred Drake2db76802004-12-01 05:05:47 +00008
9\title{What's New in Python 2.5}
Andrew M. Kuchling2cdb23e2006-04-05 13:59:01 +000010\release{0.1}
Andrew M. Kuchling92e24952004-12-03 13:54:09 +000011\author{A.M. Kuchling}
12\authoraddress{\email{amk@amk.ca}}
Fred Drake2db76802004-12-01 05:05:47 +000013
14\begin{document}
15\maketitle
16\tableofcontents
17
18This article explains the new features in Python 2.5. No release date
Andrew M. Kuchling5eefdca2006-02-08 11:36:09 +000019for Python 2.5 has been set; it will probably be released in the
Andrew M. Kuchlingd96a6ac2006-04-04 19:17:34 +000020autumn of 2006. \pep{356} describes the planned release schedule.
Fred Drake2db76802004-12-01 05:05:47 +000021
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +000022(This is still an early draft, and some sections are still skeletal or
23completely missing. Comments on the present material will still be
24welcomed.)
25
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000026% XXX Compare with previous release in 2 - 3 sentences here.
Fred Drake2db76802004-12-01 05:05:47 +000027
28This article doesn't attempt to provide a complete specification of
29the new features, but instead provides a convenient overview. For
30full details, you should refer to the documentation for Python 2.5.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000031% XXX add hyperlink when the documentation becomes available online.
Fred Drake2db76802004-12-01 05:05:47 +000032If you want to understand the complete implementation and design
33rationale, refer to the PEP for a particular new feature.
34
35
36%======================================================================
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000037\section{PEP 308: Conditional Expressions}
38
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000039For a long time, people have been requesting a way to write
40conditional expressions, expressions that return value A or value B
41depending on whether a Boolean value is true or false. A conditional
42expression lets you write a single assignment statement that has the
43same effect as the following:
44
45\begin{verbatim}
46if condition:
47 x = true_value
48else:
49 x = false_value
50\end{verbatim}
51
52There have been endless tedious discussions of syntax on both
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +000053python-dev and comp.lang.python. A vote was even held that found the
54majority of voters wanted conditional expressions in some form,
55but there was no syntax that was preferred by a clear majority.
56Candidates included C's \code{cond ? true_v : false_v},
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000057\code{if cond then true_v else false_v}, and 16 other variations.
58
59GvR eventually chose a surprising syntax:
60
61\begin{verbatim}
62x = true_value if condition else false_value
63\end{verbatim}
64
Andrew M. Kuchling38f85072006-04-02 01:46:32 +000065Evaluation is still lazy as in existing Boolean expressions, so the
66order of evaluation jumps around a bit. The \var{condition}
67expression in the middle is evaluated first, and the \var{true_value}
68expression is evaluated only if the condition was true. Similarly,
69the \var{false_value} expression is only evaluated when the condition
70is false.
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000071
72This syntax may seem strange and backwards; why does the condition go
73in the \emph{middle} of the expression, and not in the front as in C's
74\code{c ? x : y}? The decision was checked by applying the new syntax
75to the modules in the standard library and seeing how the resulting
76code read. In many cases where a conditional expression is used, one
77value seems to be the 'common case' and one value is an 'exceptional
78case', used only on rarer occasions when the condition isn't met. The
79conditional syntax makes this pattern a bit more obvious:
80
81\begin{verbatim}
82contents = ((doc + '\n') if doc else '')
83\end{verbatim}
84
85I read the above statement as meaning ``here \var{contents} is
Andrew M. Kuchlingd0fcc022006-03-09 13:57:28 +000086usually assigned a value of \code{doc+'\e n'}; sometimes
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000087\var{doc} is empty, in which special case an empty string is returned.''
88I doubt I will use conditional expressions very often where there
89isn't a clear common and uncommon case.
90
91There was some discussion of whether the language should require
92surrounding conditional expressions with parentheses. The decision
93was made to \emph{not} require parentheses in the Python language's
94grammar, but as a matter of style I think you should always use them.
95Consider these two statements:
96
97\begin{verbatim}
98# First version -- no parens
99level = 1 if logging else 0
100
101# Second version -- with parens
102level = (1 if logging else 0)
103\end{verbatim}
104
105In the first version, I think a reader's eye might group the statement
106into 'level = 1', 'if logging', 'else 0', and think that the condition
107decides whether the assignment to \var{level} is performed. The
108second version reads better, in my opinion, because it makes it clear
109that the assignment is always performed and the choice is being made
110between two values.
111
112Another reason for including the brackets: a few odd combinations of
113list comprehensions and lambdas could look like incorrect conditional
114expressions. See \pep{308} for some examples. If you put parentheses
115around your conditional expressions, you won't run into this case.
116
117
118\begin{seealso}
119
120\seepep{308}{Conditional Expressions}{PEP written by
121Guido van Rossum and Raymond D. Hettinger; implemented by Thomas
122Wouters.}
123
124\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000125
126
127%======================================================================
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +0000128\section{PEP 309: Partial Function Application}
Fred Drake2db76802004-12-01 05:05:47 +0000129
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000130The \module{functional} module is intended to contain tools for
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000131functional-style programming. Currently it only contains a
132\class{partial()} function, but new functions will probably be added
133in future versions of Python.
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000134
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000135For programs written in a functional style, it can be useful to
136construct variants of existing functions that have some of the
137parameters filled in. Consider a Python function \code{f(a, b, c)};
138you could create a new function \code{g(b, c)} that was equivalent to
139\code{f(1, b, c)}. This is called ``partial function application'',
140and is provided by the \class{partial} class in the new
141\module{functional} module.
142
143The constructor for \class{partial} takes the arguments
144\code{(\var{function}, \var{arg1}, \var{arg2}, ...
145\var{kwarg1}=\var{value1}, \var{kwarg2}=\var{value2})}. The resulting
146object is callable, so you can just call it to invoke \var{function}
147with the filled-in arguments.
148
149Here's a small but realistic example:
150
151\begin{verbatim}
152import functional
153
154def log (message, subsystem):
155 "Write the contents of 'message' to the specified subsystem."
156 print '%s: %s' % (subsystem, message)
157 ...
158
159server_log = functional.partial(log, subsystem='server')
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000160server_log('Unable to open socket')
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000161\end{verbatim}
162
Andrew M. Kuchling6af7fe02005-08-02 17:20:36 +0000163Here's another example, from a program that uses PyGTk. Here a
164context-sensitive pop-up menu is being constructed dynamically. The
165callback provided for the menu option is a partially applied version
166of the \method{open_item()} method, where the first argument has been
167provided.
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000168
Andrew M. Kuchling6af7fe02005-08-02 17:20:36 +0000169\begin{verbatim}
170...
171class Application:
172 def open_item(self, path):
173 ...
174 def init (self):
175 open_func = functional.partial(self.open_item, item_path)
176 popup_menu.append( ("Open", open_func, 1) )
177\end{verbatim}
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000178
179
180\begin{seealso}
181
182\seepep{309}{Partial Function Application}{PEP proposed and written by
183Peter Harris; implemented by Hye-Shik Chang, with adaptations by
184Raymond Hettinger.}
185
186\end{seealso}
Fred Drake2db76802004-12-01 05:05:47 +0000187
188
189%======================================================================
Fred Drakedb7b0022005-03-20 22:19:47 +0000190\section{PEP 314: Metadata for Python Software Packages v1.1}
191
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000192Some simple dependency support was added to Distutils. The
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000193\function{setup()} function now has \code{requires}, \code{provides},
194and \code{obsoletes} keyword parameters. When you build a source
195distribution using the \code{sdist} command, the dependency
196information will be recorded in the \file{PKG-INFO} file.
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000197
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000198Another new keyword parameter is \code{download_url}, which should be
199set to a URL for the package's source code. This means it's now
200possible to look up an entry in the package index, determine the
201dependencies for a package, and download the required packages.
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000202
203% XXX put example here
204
205\begin{seealso}
206
207\seepep{314}{Metadata for Python Software Packages v1.1}{PEP proposed
208and written by A.M. Kuchling, Richard Jones, and Fred Drake;
209implemented by Richard Jones and Fred Drake.}
210
211\end{seealso}
Fred Drakedb7b0022005-03-20 22:19:47 +0000212
213
214%======================================================================
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000215\section{PEP 328: Absolute and Relative Imports}
216
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000217The simpler part of PEP 328 was implemented in Python 2.4: parentheses
218could now be used to enclose the names imported from a module using
219the \code{from ... import ...} statement, making it easier to import
220many different names.
221
222The more complicated part has been implemented in Python 2.5:
223importing a module can be specified to use absolute or
224package-relative imports. The plan is to move toward making absolute
225imports the default in future versions of Python.
226
227Let's say you have a package directory like this:
228\begin{verbatim}
229pkg/
230pkg/__init__.py
231pkg/main.py
232pkg/string.py
233\end{verbatim}
234
235This defines a package named \module{pkg} containing the
236\module{pkg.main} and \module{pkg.string} submodules.
237
238Consider the code in the \file{main.py} module. What happens if it
239executes the statement \code{import string}? In Python 2.4 and
240earlier, it will first look in the package's directory to perform a
241relative import, finds \file{pkg/string.py}, imports the contents of
242that file as the \module{pkg.string} module, and that module is bound
243to the name \samp{string} in the \module{pkg.main} module's namespace.
244
245That's fine if \module{pkg.string} was what you wanted. But what if
246you wanted Python's standard \module{string} module? There's no clean
247way to ignore \module{pkg.string} and look for the standard module;
248generally you had to look at the contents of \code{sys.modules}, which
249is slightly unclean.
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000250Holger Krekel's \module{py.std} package provides a tidier way to perform
251imports from the standard library, \code{import py ; py.std.string.join()},
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000252but that package isn't available on all Python installations.
253
254Reading code which relies on relative imports is also less clear,
255because a reader may be confused about which module, \module{string}
256or \module{pkg.string}, is intended to be used. Python users soon
257learned not to duplicate the names of standard library modules in the
258names of their packages' submodules, but you can't protect against
259having your submodule's name being used for a new module added in a
260future version of Python.
261
262In Python 2.5, you can switch \keyword{import}'s behaviour to
263absolute imports using a \code{from __future__ import absolute_import}
264directive. This absolute-import behaviour will become the default in
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000265a future version (probably Python 2.7). Once absolute imports
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000266are the default, \code{import string} will
267always find the standard library's version.
268It's suggested that users should begin using absolute imports as much
269as possible, so it's preferable to begin writing \code{from pkg import
270string} in your code.
271
272Relative imports are still possible by adding a leading period
273to the module name when using the \code{from ... import} form:
274
275\begin{verbatim}
276# Import names from pkg.string
277from .string import name1, name2
278# Import pkg.string
279from . import string
280\end{verbatim}
281
282This imports the \module{string} module relative to the current
283package, so in \module{pkg.main} this will import \var{name1} and
284\var{name2} from \module{pkg.string}. Additional leading periods
285perform the relative import starting from the parent of the current
286package. For example, code in the \module{A.B.C} module can do:
287
288\begin{verbatim}
289from . import D # Imports A.B.D
290from .. import E # Imports A.E
291from ..F import G # Imports A.F.G
292\end{verbatim}
293
294Leading periods cannot be used with the \code{import \var{modname}}
295form of the import statement, only the \code{from ... import} form.
296
297\begin{seealso}
298
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000299\seepep{328}{Imports: Multi-Line and Absolute/Relative}
300{PEP written by Aahz; implemented by Thomas Wouters.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000301
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000302\seeurl{http://codespeak.net/py/current/doc/index.html}
303{The py library by Holger Krekel, which contains the \module{py.std} package.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000304
305\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000306
307
308%======================================================================
Andrew M. Kuchling21d3a7c2006-03-15 11:53:09 +0000309\section{PEP 338: Executing Modules as Scripts}
310
Andrew M. Kuchlingb182db42006-03-17 21:48:46 +0000311The \programopt{-m} switch added in Python 2.4 to execute a module as
312a script gained a few more abilities. Instead of being implemented in
313C code inside the Python interpreter, the switch now uses an
314implementation in a new module, \module{runpy}.
315
316The \module{runpy} module implements a more sophisticated import
317mechanism so that it's now possible to run modules in a package such
318as \module{pychecker.checker}. The module also supports alternative
319import mechanisms such as the \module{zipimport} module. (This means
320you can add a .zip archive's path to \code{sys.path} and then use the
321\programopt{-m} switch to execute code from the archive.
322
323
324\begin{seealso}
325
326\seepep{338}{Executing modules as scripts}{PEP written and
327implemented by Nick Coghlan.}
328
329\end{seealso}
Andrew M. Kuchling21d3a7c2006-03-15 11:53:09 +0000330
331
332%======================================================================
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000333\section{PEP 341: Unified try/except/finally}
334
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000335Until Python 2.5, the \keyword{try} statement came in two
336flavours. You could use a \keyword{finally} block to ensure that code
337is always executed, or a number of \keyword{except} blocks to catch an
338exception. You couldn't combine both \keyword{except} blocks and a
339\keyword{finally} block, because generating the right bytecode for the
340combined version was complicated and it wasn't clear what the
341semantics of the combined should be.
342
343GvR spent some time working with Java, which does support the
344equivalent of combining \keyword{except} blocks and a
345\keyword{finally} block, and this clarified what the statement should
346mean. In Python 2.5, you can now write:
347
348\begin{verbatim}
349try:
350 block-1 ...
351except Exception1:
352 handler-1 ...
353except Exception2:
354 handler-2 ...
355else:
356 else-block
357finally:
358 final-block
359\end{verbatim}
360
361The code in \var{block-1} is executed. If the code raises an
362exception, the handlers are tried in order: \var{handler-1},
363\var{handler-2}, ... If no exception is raised, the \var{else-block}
364is executed. No matter what happened previously, the
365\var{final-block} is executed once the code block is complete and any
366raised exceptions handled. Even if there's an error in an exception
367handler or the \var{else-block} and a new exception is raised, the
368\var{final-block} is still executed.
369
370\begin{seealso}
371
372\seepep{341}{Unifying try-except and try-finally}{PEP written by Georg Brandl;
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000373implementation by Thomas Lee.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000374
375\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000376
377
378%======================================================================
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000379\section{PEP 342: New Generator Features}
380
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000381Python 2.5 adds a simple way to pass values \emph{into} a generator.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000382As introduced in Python 2.3, generators only produce output; once a
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000383generator's code is invoked to create an iterator, there's no way to
384pass any new information into the function when its execution is
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000385resumed. Sometimes the ability to pass in some information would be
386useful. Hackish solutions to this include making the generator's code
387look at a global variable and then changing the global variable's
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000388value, or passing in some mutable object that callers then modify.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000389
390To refresh your memory of basic generators, here's a simple example:
391
392\begin{verbatim}
393def counter (maximum):
394 i = 0
395 while i < maximum:
396 yield i
397 i += 1
398\end{verbatim}
399
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000400When you call \code{counter(10)}, the result is an iterator that
401returns the values from 0 up to 9. On encountering the
402\keyword{yield} statement, the iterator returns the provided value and
403suspends the function's execution, preserving the local variables.
404Execution resumes on the following call to the iterator's
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000405\method{next()} method, picking up after the \keyword{yield} statement.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000406
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000407In Python 2.3, \keyword{yield} was a statement; it didn't return any
408value. In 2.5, \keyword{yield} is now an expression, returning a
409value that can be assigned to a variable or otherwise operated on:
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000410
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000411\begin{verbatim}
412val = (yield i)
413\end{verbatim}
414
415I recommend that you always put parentheses around a \keyword{yield}
416expression when you're doing something with the returned value, as in
417the above example. The parentheses aren't always necessary, but it's
418easier to always add them instead of having to remember when they're
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000419needed.\footnote{The exact rules are that a \keyword{yield}-expression must
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000420always be parenthesized except when it occurs at the top-level
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000421expression on the right-hand side of an assignment, meaning you can
422write \code{val = yield i} but have to use parentheses when there's an
423operation, as in \code{val = (yield i) + 12}.}
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000424
425Values are sent into a generator by calling its
426\method{send(\var{value})} method. The generator's code is then
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000427resumed and the \keyword{yield} expression returns the specified
428\var{value}. If the regular \method{next()} method is called, the
429\keyword{yield} returns \constant{None}.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000430
431Here's the previous example, modified to allow changing the value of
432the internal counter.
433
434\begin{verbatim}
435def counter (maximum):
436 i = 0
437 while i < maximum:
438 val = (yield i)
439 # If value provided, change counter
440 if val is not None:
441 i = val
442 else:
443 i += 1
444\end{verbatim}
445
446And here's an example of changing the counter:
447
448\begin{verbatim}
449>>> it = counter(10)
450>>> print it.next()
4510
452>>> print it.next()
4531
454>>> print it.send(8)
4558
456>>> print it.next()
4579
458>>> print it.next()
459Traceback (most recent call last):
460 File ``t.py'', line 15, in ?
461 print it.next()
462StopIteration
Andrew M. Kuchlingc2033702005-08-29 13:30:12 +0000463\end{verbatim}
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000464
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000465Because \keyword{yield} will often be returning \constant{None}, you
466should always check for this case. Don't just use its value in
467expressions unless you're sure that the \method{send()} method
468will be the only method used resume your generator function.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000469
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000470In addition to \method{send()}, there are two other new methods on
471generators:
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000472
473\begin{itemize}
474
475 \item \method{throw(\var{type}, \var{value}=None,
476 \var{traceback}=None)} is used to raise an exception inside the
477 generator; the exception is raised by the \keyword{yield} expression
478 where the generator's execution is paused.
479
480 \item \method{close()} raises a new \exception{GeneratorExit}
481 exception inside the generator to terminate the iteration.
482 On receiving this
483 exception, the generator's code must either raise
484 \exception{GeneratorExit} or \exception{StopIteration}; catching the
485 exception and doing anything else is illegal and will trigger
486 a \exception{RuntimeError}. \method{close()} will also be called by
487 Python's garbage collection when the generator is garbage-collected.
488
489 If you need to run cleanup code in case of a \exception{GeneratorExit},
490 I suggest using a \code{try: ... finally:} suite instead of
491 catching \exception{GeneratorExit}.
492
493\end{itemize}
494
495The cumulative effect of these changes is to turn generators from
496one-way producers of information into both producers and consumers.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000497
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000498Generators also become \emph{coroutines}, a more generalized form of
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000499subroutines. Subroutines are entered at one point and exited at
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000500another point (the top of the function, and a \keyword{return
501statement}), but coroutines can be entered, exited, and resumed at
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000502many different points (the \keyword{yield} statements). We'll have to
503figure out patterns for using coroutines effectively in Python.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000504
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000505The addition of the \method{close()} method has one side effect that
506isn't obvious. \method{close()} is called when a generator is
507garbage-collected, so this means the generator's code gets one last
508chance to run before the generator is destroyed, and this last chance
509means that \code{try...finally} statements in generators can now be
510guaranteed to work; the \keyword{finally} clause will now always get a
511chance to run. The syntactic restriction that you couldn't mix
512\keyword{yield} statements with a \code{try...finally} suite has
513therefore been removed. This seems like a minor bit of language
514trivia, but using generators and \code{try...finally} is actually
515necessary in order to implement the \keyword{with} statement
516described by PEP 343. We'll look at this new statement in the following
517section.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000518
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000519\begin{seealso}
520
521\seepep{342}{Coroutines via Enhanced Generators}{PEP written by
522Guido van Rossum and Phillip J. Eby;
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000523implemented by Phillip J. Eby. Includes examples of
524some fancier uses of generators as coroutines.}
525
526\seeurl{http://en.wikipedia.org/wiki/Coroutine}{The Wikipedia entry for
527coroutines.}
528
Neal Norwitz09179882006-03-04 23:31:45 +0000529\seeurl{http://www.sidhe.org/\~{}dan/blog/archives/000178.html}{An
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000530explanation of coroutines from a Perl point of view, written by Dan
531Sugalski.}
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000532
533\end{seealso}
534
535
536%======================================================================
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000537\section{PEP 343: The 'with' statement}
538
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000539The \keyword{with} statement allows a clearer
540version of code that uses \code{try...finally} blocks
541
542First, I'll discuss the statement as it will commonly be used, and
543then I'll discuss the detailed implementation and how to write objects
544(called ``context managers'') that can be used with this statement.
545Most people, who will only use \keyword{with} in company with an
Andrew M. Kuchlinga4d651f2006-04-06 13:24:58 +0000546existing object, don't need to know these details and can
547just use objects that are documented to work as context managers.
548Authors of new context managers will need to understand the details of
549the underlying implementation.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000550
551The \keyword{with} statement is a new control-flow structure whose
552basic structure is:
553
554\begin{verbatim}
555with expression as variable:
556 with-block
557\end{verbatim}
558
559The expression is evaluated, and it should result in a type of object
560that's called a context manager. The context manager can return a
561value that will be bound to the name \var{variable}. (Note carefully:
562\var{variable} is \emph{not} assigned the result of \var{expression}.
563One method of the context manager is run before \var{with-block} is
564executed, and another method is run after the block is done, even if
565the block raised an exception.
566
567To enable the statement in Python 2.5, you need
568to add the following directive to your module:
569
570\begin{verbatim}
571from __future__ import with_statement
572\end{verbatim}
573
574Some standard Python objects can now behave as context managers. For
575example, file objects:
576
577\begin{verbatim}
578with open('/etc/passwd', 'r') as f:
579 for line in f:
580 print line
581
582# f has been automatically closed at this point.
583\end{verbatim}
584
585The \module{threading} module's locks and condition variables
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000586also support the \keyword{with} statement:
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000587
588\begin{verbatim}
589lock = threading.Lock()
590with lock:
591 # Critical section of code
592 ...
593\end{verbatim}
594
595The lock is acquired before the block is executed, and released once
596the block is complete.
597
598The \module{decimal} module's contexts, which encapsulate the desired
599precision and rounding characteristics for computations, can also be
600used as context managers.
601
602\begin{verbatim}
603import decimal
604
605v1 = decimal.Decimal('578')
606
607# Displays with default precision of 28 digits
608print v1.sqrt()
609
610with decimal.Context(prec=16):
611 # All code in this block uses a precision of 16 digits.
612 # The original context is restored on exiting the block.
613 print v1.sqrt()
614\end{verbatim}
615
616\subsection{Writing Context Managers}
617
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000618% XXX write this
619
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000620This section still needs to be written.
621
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000622The new \module{contextlib} module provides some functions and a
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000623decorator that are useful for writing context managers.
624Future versions will go into more detail.
625
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000626% XXX describe further
627
628\begin{seealso}
629
630\seepep{343}{The ``with'' statement}{PEP written by
631Guido van Rossum and Nick Coghlan. }
632
633\end{seealso}
634
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000635
636%======================================================================
Andrew M. Kuchling8f4d2552006-03-08 01:50:20 +0000637\section{PEP 352: Exceptions as New-Style Classes}
638
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000639Exception classes can now be new-style classes, not just classic
640classes, and the built-in \exception{Exception} class and all the
641standard built-in exceptions (\exception{NameError},
642\exception{ValueError}, etc.) are now new-style classes.
Andrew M. Kuchlingaeadf952006-03-09 19:06:05 +0000643
644The inheritance hierarchy for exceptions has been rearranged a bit.
645In 2.5, the inheritance relationships are:
646
647\begin{verbatim}
648BaseException # New in Python 2.5
649|- KeyboardInterrupt
650|- SystemExit
651|- Exception
652 |- (all other current built-in exceptions)
653\end{verbatim}
654
655This rearrangement was done because people often want to catch all
656exceptions that indicate program errors. \exception{KeyboardInterrupt} and
657\exception{SystemExit} aren't errors, though, and usually represent an explicit
658action such as the user hitting Control-C or code calling
659\function{sys.exit()}. A bare \code{except:} will catch all exceptions,
660so you commonly need to list \exception{KeyboardInterrupt} and
661\exception{SystemExit} in order to re-raise them. The usual pattern is:
662
663\begin{verbatim}
664try:
665 ...
666except (KeyboardInterrupt, SystemExit):
667 raise
668except:
669 # Log error...
670 # Continue running program...
671\end{verbatim}
672
673In Python 2.5, you can now write \code{except Exception} to achieve
674the same result, catching all the exceptions that usually indicate errors
675but leaving \exception{KeyboardInterrupt} and
676\exception{SystemExit} alone. As in previous versions,
677a bare \code{except:} still catches all exceptions.
678
679The goal for Python 3.0 is to require any class raised as an exception
680to derive from \exception{BaseException} or some descendant of
681\exception{BaseException}, and future releases in the
682Python 2.x series may begin to enforce this constraint. Therefore, I
683suggest you begin making all your exception classes derive from
684\exception{Exception} now. It's been suggested that the bare
685\code{except:} form should be removed in Python 3.0, but Guido van~Rossum
686hasn't decided whether to do this or not.
687
688Raising of strings as exceptions, as in the statement \code{raise
689"Error occurred"}, is deprecated in Python 2.5 and will trigger a
690warning. The aim is to be able to remove the string-exception feature
691in a few releases.
692
693
694\begin{seealso}
695
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000696\seepep{352}{Required Superclass for Exceptions}{PEP written by
Andrew M. Kuchlingaeadf952006-03-09 19:06:05 +0000697Brett Cannon and Guido van Rossum; implemented by Brett Cannon.}
698
699\end{seealso}
Andrew M. Kuchling8f4d2552006-03-08 01:50:20 +0000700
701
702%======================================================================
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000703\section{PEP 353: Using ssize_t as the index type\label{section-353}}
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000704
705A wide-ranging change to Python's C API, using a new
706\ctype{Py_ssize_t} type definition instead of \ctype{int},
707will permit the interpreter to handle more data on 64-bit platforms.
708This change doesn't affect Python's capacity on 32-bit platforms.
709
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000710Various pieces of the Python interpreter used C's \ctype{int} type to
711store sizes or counts; for example, the number of items in a list or
712tuple were stored in an \ctype{int}. The C compilers for most 64-bit
713platforms still define \ctype{int} as a 32-bit type, so that meant
714that lists could only hold up to \code{2**31 - 1} = 2147483647 items.
715(There are actually a few different programming models that 64-bit C
716compilers can use -- see
717\url{http://www.unix.org/version2/whatsnew/lp64_wp.html} for a
718discussion -- but the most commonly available model leaves \ctype{int}
719as 32 bits.)
720
721A limit of 2147483647 items doesn't really matter on a 32-bit platform
722because you'll run out of memory before hitting the length limit.
723Each list item requires space for a pointer, which is 4 bytes, plus
724space for a \ctype{PyObject} representing the item. 2147483647*4 is
725already more bytes than a 32-bit address space can contain.
726
727It's possible to address that much memory on a 64-bit platform,
728however. The pointers for a list that size would only require 16GiB
729of space, so it's not unreasonable that Python programmers might
730construct lists that large. Therefore, the Python interpreter had to
731be changed to use some type other than \ctype{int}, and this will be a
73264-bit type on 64-bit platforms. The change will cause
733incompatibilities on 64-bit machines, so it was deemed worth making
734the transition now, while the number of 64-bit users is still
735relatively small. (In 5 or 10 years, we may \emph{all} be on 64-bit
736machines, and the transition would be more painful then.)
737
738This change most strongly affects authors of C extension modules.
739Python strings and container types such as lists and tuples
740now use \ctype{Py_ssize_t} to store their size.
741Functions such as \cfunction{PyList_Size()}
742now return \ctype{Py_ssize_t}. Code in extension modules
743may therefore need to have some variables changed to
744\ctype{Py_ssize_t}.
745
746The \cfunction{PyArg_ParseTuple()} and \cfunction{Py_BuildValue()} functions
747have a new conversion code, \samp{n}, for \ctype{Py_ssize_t}.
Andrew M. Kuchlinga4d651f2006-04-06 13:24:58 +0000748\cfunction{PyArg_ParseTuple()}'s \samp{s\#} and \samp{t\#} still output
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000749\ctype{int} by default, but you can define the macro
750\csimplemacro{PY_SSIZE_T_CLEAN} before including \file{Python.h}
751to make them return \ctype{Py_ssize_t}.
752
753\pep{353} has a section on conversion guidelines that
754extension authors should read to learn about supporting 64-bit
755platforms.
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000756
757\begin{seealso}
758
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000759\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 +0000760
761\end{seealso}
762
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000763
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000764%======================================================================
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000765\section{PEP 357: The '__index__' method}
766
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000767The NumPy developers had a problem that could only be solved by adding
768a new special method, \method{__index__}. When using slice notation,
Fred Drake1c0e3282006-04-02 03:30:06 +0000769as in \code{[\var{start}:\var{stop}:\var{step}]}, the values of the
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000770\var{start}, \var{stop}, and \var{step} indexes must all be either
771integers or long integers. NumPy defines a variety of specialized
772integer types corresponding to unsigned and signed integers of 8, 16,
77332, and 64 bits, but there was no way to signal that these types could
774be used as slice indexes.
775
776Slicing can't just use the existing \method{__int__} method because
777that method is also used to implement coercion to integers. If
778slicing used \method{__int__}, floating-point numbers would also
779become legal slice indexes and that's clearly an undesirable
780behaviour.
781
782Instead, a new special method called \method{__index__} was added. It
783takes no arguments and returns an integer giving the slice index to
784use. For example:
785
786\begin{verbatim}
787class C:
788 def __index__ (self):
789 return self.value
790\end{verbatim}
791
792The return value must be either a Python integer or long integer.
793The interpreter will check that the type returned is correct, and
794raises a \exception{TypeError} if this requirement isn't met.
795
796A corresponding \member{nb_index} slot was added to the C-level
797\ctype{PyNumberMethods} structure to let C extensions implement this
798protocol. \cfunction{PyNumber_Index(\var{obj})} can be used in
799extension code to call the \method{__index__} function and retrieve
800its result.
801
802\begin{seealso}
803
804\seepep{357}{Allowing Any Object to be Used for Slicing}{PEP written
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000805and implemented by Travis Oliphant.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000806
807\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000808
809
810%======================================================================
Fred Drake2db76802004-12-01 05:05:47 +0000811\section{Other Language Changes}
812
813Here are all of the changes that Python 2.5 makes to the core Python
814language.
815
816\begin{itemize}
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +0000817
818\item The \function{min()} and \function{max()} built-in functions
819gained a \code{key} keyword argument analogous to the \code{key}
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +0000820argument for \method{sort()}. This argument supplies a function
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +0000821that takes a single argument and is called for every value in the list;
822\function{min()}/\function{max()} will return the element with the
823smallest/largest return value from this function.
824For example, to find the longest string in a list, you can do:
825
826\begin{verbatim}
827L = ['medium', 'longest', 'short']
828# Prints 'longest'
829print max(L, key=len)
830# Prints 'short', because lexicographically 'short' has the largest value
831print max(L)
832\end{verbatim}
833
834(Contributed by Steven Bethard and Raymond Hettinger.)
Fred Drake2db76802004-12-01 05:05:47 +0000835
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000836\item Two new built-in functions, \function{any()} and
837\function{all()}, evaluate whether an iterator contains any true or
838false values. \function{any()} returns \constant{True} if any value
839returned by the iterator is true; otherwise it will return
840\constant{False}. \function{all()} returns \constant{True} only if
841all of the values returned by the iterator evaluate as being true.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +0000842(Suggested by GvR, and implemented by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000843
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +0000844\item The list of base classes in a class definition can now be empty.
845As an example, this is now legal:
846
847\begin{verbatim}
848class C():
849 pass
850\end{verbatim}
851(Implemented by Brett Cannon.)
852
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000853% XXX __missing__ hook in dictionaries
854
Fred Drake2db76802004-12-01 05:05:47 +0000855\end{itemize}
856
857
858%======================================================================
Andrew M. Kuchlingda376042006-03-17 15:56:41 +0000859\subsection{Interactive Interpreter Changes}
860
861In the interactive interpreter, \code{quit} and \code{exit}
862have long been strings so that new users get a somewhat helpful message
863when they try to quit:
864
865\begin{verbatim}
866>>> quit
867'Use Ctrl-D (i.e. EOF) to exit.'
868\end{verbatim}
869
870In Python 2.5, \code{quit} and \code{exit} are now objects that still
871produce string representations of themselves, but are also callable.
872Newbies who try \code{quit()} or \code{exit()} will now exit the
873interpreter as they expect. (Implemented by Georg Brandl.)
874
875
876%======================================================================
Fred Drake2db76802004-12-01 05:05:47 +0000877\subsection{Optimizations}
878
879\begin{itemize}
880
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000881\item When they were introduced
882in Python 2.4, the built-in \class{set} and \class{frozenset} types
883were built on top of Python's dictionary type.
884In 2.5 the internal data structure has been customized for implementing sets,
885and as a result sets will use a third less memory and are somewhat faster.
886(Implemented by Raymond Hettinger.)
Fred Drake2db76802004-12-01 05:05:47 +0000887
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000888\item The performance of some Unicode operations has been improved.
889% XXX provide details?
890
891\item The code generator's peephole optimizer now performs
892simple constant folding in expressions. If you write something like
893\code{a = 2+3}, the code generator will do the arithmetic and produce
894code corresponding to \code{a = 5}.
895
Fred Drake2db76802004-12-01 05:05:47 +0000896\end{itemize}
897
898The net result of the 2.5 optimizations is that Python 2.5 runs the
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000899pystone benchmark around XXX\% faster than Python 2.4.
Fred Drake2db76802004-12-01 05:05:47 +0000900
901
902%======================================================================
903\section{New, Improved, and Deprecated Modules}
904
905As usual, Python's standard library received a number of enhancements and
906bug fixes. Here's a partial list of the most notable changes, sorted
907alphabetically by module name. Consult the
908\file{Misc/NEWS} file in the source tree for a more
Andrew M. Kuchlingf688cc52006-03-10 18:50:08 +0000909complete list of changes, or look through the SVN logs for all the
Fred Drake2db76802004-12-01 05:05:47 +0000910details.
911
912\begin{itemize}
913
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000914% collections.deque now has .remove()
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000915% collections.defaultdict
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000916
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +0000917% the cPickle module no longer accepts the deprecated None option in the
918% args tuple returned by __reduce__().
919
920% csv module improvements
921
922% datetime.datetime() now has a strptime class method which can be used to
923% create datetime object using a string and format.
924
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000925% fileinput: opening hook used to control how files are opened.
926% .input() now has a mode parameter
927% now has a fileno() function
928% accepts Unicode filenames
929
Andrew M. Kuchlingda376042006-03-17 15:56:41 +0000930\item In the \module{gc} module, the new \function{get_count()} function
931returns a 3-tuple containing the current collection counts for the
932three GC generations. This is accounting information for the garbage
933collector; when these counts reach a specified threshold, a garbage
934collection sweep will be made. The existing \function{gc.collect()}
935function now takes an optional \var{generation} argument of 0, 1, or 2
936to specify which generation to collect.
937
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +0000938\item The \function{nsmallest()} and
939\function{nlargest()} functions in the \module{heapq} module
940now support a \code{key} keyword argument similar to the one
941provided by the \function{min()}/\function{max()} functions
942and the \method{sort()} methods. For example:
943Example:
944
945\begin{verbatim}
946>>> import heapq
947>>> L = ["short", 'medium', 'longest', 'longer still']
948>>> heapq.nsmallest(2, L) # Return two lowest elements, lexicographically
949['longer still', 'longest']
950>>> heapq.nsmallest(2, L, key=len) # Return two shortest elements
951['short', 'medium']
952\end{verbatim}
953
954(Contributed by Raymond Hettinger.)
955
Andrew M. Kuchling511a3a82005-03-20 19:52:18 +0000956\item The \function{itertools.islice()} function now accepts
957\code{None} for the start and step arguments. This makes it more
958compatible with the attributes of slice objects, so that you can now write
959the following:
960
961\begin{verbatim}
962s = slice(5) # Create slice object
963itertools.islice(iterable, s.start, s.stop, s.step)
964\end{verbatim}
965
966(Contributed by Raymond Hettinger.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +0000967
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000968\item The \module{operator} module's \function{itemgetter()}
969and \function{attrgetter()} functions now support multiple fields.
970A call such as \code{operator.attrgetter('a', 'b')}
971will return a function
972that retrieves the \member{a} and \member{b} attributes. Combining
973this new feature with the \method{sort()} method's \code{key} parameter
974lets you easily sort lists using multiple fields.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +0000975(Contributed by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000976
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +0000977
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +0000978\item The \module{os} module underwent a number of changes. The
979\member{stat_float_times} variable now defaults to true, meaning that
980\function{os.stat()} will now return time values as floats. (This
981doesn't necessarily mean that \function{os.stat()} will return times
982that are precise to fractions of a second; not all systems support
983such precision.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +0000984
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000985Constants named \member{os.SEEK_SET}, \member{os.SEEK_CUR}, and
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +0000986\member{os.SEEK_END} have been added; these are the parameters to the
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000987\function{os.lseek()} function. Two new constants for locking are
988\member{os.O_SHLOCK} and \member{os.O_EXLOCK}.
989
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000990Two new functions, \function{wait3()} and \function{wait4()}, were
991added. They're similar the \function{waitpid()} function which waits
992for a child process to exit and returns a tuple of the process ID and
993its exit status, but \function{wait3()} and \function{wait4()} return
994additional information. \function{wait3()} doesn't take a process ID
995as input, so it waits for any child process to exit and returns a
9963-tuple of \var{process-id}, \var{exit-status}, \var{resource-usage}
997as returned from the \function{resource.getrusage()} function.
998\function{wait4(\var{pid})} does take a process ID.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +0000999(Contributed by Chad J. Schroeder.)
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001000
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001001On FreeBSD, the \function{os.stat()} function now returns
1002times with nanosecond resolution, and the returned object
1003now has \member{st_gen} and \member{st_birthtime}.
1004The \member{st_flags} member is also available, if the platform supports it.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001005(Contributed by Antti Louko and Diego Petten\`o.)
1006% (Patch 1180695, 1212117)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001007
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001008\item The old \module{regex} and \module{regsub} modules, which have been
1009deprecated ever since Python 2.0, have finally been deleted.
Andrew M. Kuchlingf4b06602006-03-17 15:39:52 +00001010Other deleted modules: \module{statcache}, \module{tzparse},
1011\module{whrandom}.
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001012
1013\item The \file{lib-old} directory,
1014which includes ancient modules such as \module{dircmp} and
1015\module{ni}, was also deleted. \file{lib-old} wasn't on the default
1016\code{sys.path}, so unless your programs explicitly added the directory to
1017\code{sys.path}, this removal shouldn't affect your code.
1018
Andrew M. Kuchling4678dc82006-01-15 16:11:28 +00001019\item The \module{socket} module now supports \constant{AF_NETLINK}
1020sockets on Linux, thanks to a patch from Philippe Biondi.
1021Netlink sockets are a Linux-specific mechanism for communications
1022between a user-space process and kernel code; an introductory
1023article about them is at \url{http://www.linuxjournal.com/article/7356}.
1024In Python code, netlink addresses are represented as a tuple of 2 integers,
1025\code{(\var{pid}, \var{group_mask})}.
1026
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001027Socket objects also gained accessor methods \method{getfamily()},
1028\method{gettype()}, and \method{getproto()} methods to retrieve the
1029family, type, and protocol values for the socket.
1030
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001031\item New module: \module{spwd} provides functions for accessing the
1032shadow password database on systems that support it.
1033% XXX give example
Fred Drake2db76802004-12-01 05:05:47 +00001034
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001035% XXX patch #1382163: sys.subversion, Py_GetBuildNumber()
1036
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001037\item The \class{TarFile} class in the \module{tarfile} module now has
Georg Brandl08c02db2005-07-22 18:39:19 +00001038an \method{extractall()} method that extracts all members from the
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001039archive into the current working directory. It's also possible to set
1040a different directory as the extraction target, and to unpack only a
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001041subset of the archive's members.
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001042
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001043A tarfile's compression can be autodetected by
1044using the mode \code{'r|*'}.
1045% patch 918101
1046(Contributed by Lars Gust\"abel.)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001047
Andrew M. Kuchlingf688cc52006-03-10 18:50:08 +00001048\item The \module{unicodedata} module has been updated to use version 4.1.0
1049of the Unicode character database. Version 3.2.0 is required
1050by some specifications, so it's still available as
1051\member{unicodedata.db_3_2_0}.
1052
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001053% patch #754022: Greatly enhanced webbrowser.py (by Oleg Broytmann).
1054
Fredrik Lundh7e0aef02005-12-12 18:54:55 +00001055
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001056\item The \module{xmlrpclib} module now supports returning
1057 \class{datetime} objects for the XML-RPC date type. Supply
1058 \code{use_datetime=True} to the \function{loads()} function
1059 or the \class{Unmarshaller} class to enable this feature.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001060 (Contributed by Skip Montanaro.)
1061% Patch 1120353
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001062
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001063
Fred Drake114b8ca2005-03-21 05:47:11 +00001064\end{itemize}
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001065
Fred Drake2db76802004-12-01 05:05:47 +00001066
1067
1068%======================================================================
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001069% whole new modules get described in subsections here
Fred Drake2db76802004-12-01 05:05:47 +00001070
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001071% XXX new distutils features: upload
1072
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001073\subsection{The ctypes package}
1074
1075The \module{ctypes} package, written by Thomas Heller, has been added
1076to the standard library. \module{ctypes} lets you call arbitrary functions
1077in shared libraries or DLLs.
1078
1079In subsequent alpha releases of Python 2.5, I'll add a brief
1080introduction that shows some basic usage of the module.
1081
1082% XXX write introduction
1083
1084
1085\subsection{The ElementTree package}
1086
1087A subset of Fredrik Lundh's ElementTree library for processing XML has
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001088been added to the standard library as \module{xmlcore.etree}. The
Georg Brandlce27a062006-04-11 06:27:12 +00001089available modules are
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001090\module{ElementTree}, \module{ElementPath}, and
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00001091\module{ElementInclude} from ElementTree 1.2.6.
1092The \module{cElementTree} accelerator module is also included.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001093
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001094The rest of this section will provide a brief overview of using
1095ElementTree. Full documentation for ElementTree is available at
1096\url{http://effbot.org/zone/element-index.htm}.
1097
1098ElementTree represents an XML document as a tree of element nodes.
1099The text content of the document is stored as the \member{.text}
1100and \member{.tail} attributes of
1101(This is one of the major differences between ElementTree and
1102the Document Object Model; in the DOM there are many different
1103types of node, including \class{TextNode}.)
1104
1105The most commonly used parsing function is \function{parse()}, that
1106takes either a string (assumed to contain a filename) or a file-like
1107object and returns an \class{ElementTree} instance:
1108
1109\begin{verbatim}
1110from xmlcore.etree import ElementTree as ET
1111
1112tree = ET.parse('ex-1.xml')
1113
1114feed = urllib.urlopen(
1115 'http://planet.python.org/rss10.xml')
1116tree = ET.parse(feed)
1117\end{verbatim}
1118
1119Once you have an \class{ElementTree} instance, you
1120can call its \method{getroot()} method to get the root \class{Element} node.
1121
1122There's also an \function{XML()} function that takes a string literal
1123and returns an \class{Element} node (not an \class{ElementTree}).
1124This function provides a tidy way to incorporate XML fragments,
1125approaching the convenience of an XML literal:
1126
1127\begin{verbatim}
1128svg = et.XML("""<svg width="10px" version="1.0">
1129 </svg>""")
1130svg.set('height', '320px')
1131svg.append(elem1)
1132\end{verbatim}
1133
1134Each XML element supports some dictionary-like and some list-like
1135access methods. Dictionary-like methods are used to access attribute
1136values, and list-like methods are used to access child nodes.
1137
1138% XXX finish this
1139
1140To generate XML output, you should call the
1141\method{ElementTree.write()} method. Like \function{parse()},
1142it can take either a string or a file-like object:
1143
1144\begin{verbatim}
1145# Encoding is US-ASCII
1146tree.write('output.xml')
1147
1148# Encoding is UTF-8
1149f = open('output.xml', 'w')
1150tree.write(f, 'utf-8')
1151\end{verbatim}
1152
1153(Caution: the default encoding used for output is ASCII, which isn't
1154very useful for general XML work, raising an exception if there are
1155any characters with values greater than 127. You should always
1156specify a different encoding such as UTF-8 that can handle any Unicode
1157character.)
1158
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001159
1160% XXX write introduction
1161
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001162\begin{seealso}
1163
1164\seeurl{http://effbot.org/zone/element-index.htm}
1165{Official documentation for ElementTree.}
1166
1167
1168\end{seealso}
1169
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001170
1171\subsection{The hashlib package}
1172
1173A new \module{hashlib} module has been added to replace the
1174\module{md5} and \module{sha} modules. \module{hashlib} adds support
1175for additional secure hashes (SHA-224, SHA-256, SHA-384, and SHA-512).
1176When available, the module uses OpenSSL for fast platform optimized
1177implementations of algorithms.
1178
1179The old \module{md5} and \module{sha} modules still exist as wrappers
1180around hashlib to preserve backwards compatibility. The new module's
1181interface is very close to that of the old modules, but not identical.
1182The most significant difference is that the constructor functions
1183for creating new hashing objects are named differently.
1184
1185\begin{verbatim}
1186# Old versions
1187h = md5.md5()
1188h = md5.new()
1189
1190# New version
1191h = hashlib.md5()
1192
1193# Old versions
1194h = sha.sha()
1195h = sha.new()
1196
1197# New version
1198h = hashlib.sha1()
1199
1200# Hash that weren't previously available
1201h = hashlib.sha224()
1202h = hashlib.sha256()
1203h = hashlib.sha384()
1204h = hashlib.sha512()
1205
1206# Alternative form
1207h = hashlib.new('md5') # Provide algorithm as a string
1208\end{verbatim}
1209
1210Once a hash object has been created, its methods are the same as before:
1211\method{update(\var{string})} hashes the specified string into the
1212current digest state, \method{digest()} and \method{hexdigest()}
1213return the digest value as a binary string or a string of hex digits,
1214and \method{copy()} returns a new hashing object with the same digest state.
1215
1216This module was contributed by Gregory P. Smith.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001217
1218
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001219\subsection{The sqlite3 package}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001220
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001221The pysqlite module (\url{http://www.pysqlite.org}), a wrapper for the
1222SQLite embedded database, has been added to the standard library under
1223the package name \module{sqlite3}. SQLite is a C library that
1224provides a SQL-language database that stores data in disk files
1225without requiring a separate server process. pysqlite was written by
1226Gerhard H\"aring, and provides a SQL interface that complies with the
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001227DB-API 2.0 specification described by \pep{249}. This means that it
1228should be possible to write the first version of your applications
1229using SQLite for data storage and, if switching to a larger database
1230such as PostgreSQL or Oracle is necessary, the switch should be
1231relatively easy.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001232
1233If you're compiling the Python source yourself, note that the source
1234tree doesn't include the SQLite code itself, only the wrapper module.
1235You'll need to have the SQLite libraries and headers installed before
1236compiling Python, and the build process will compile the module when
1237the necessary headers are available.
1238
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001239To use the module, you must first create a \class{Connection} object
1240that represents the database. Here the data will be stored in the
1241\file{/tmp/example} file:
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001242
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001243\begin{verbatim}
1244conn = sqlite3.connect('/tmp/example')
1245\end{verbatim}
1246
1247You can also supply the special name \samp{:memory:} to create
1248a database in RAM.
1249
1250Once you have a \class{Connection}, you can create a \class{Cursor}
1251object and call its \method{execute()} method to perform SQL commands:
1252
1253\begin{verbatim}
1254c = conn.cursor()
1255
1256# Create table
1257c.execute('''create table stocks
1258(date timestamp, trans varchar, symbol varchar,
1259 qty decimal, price decimal)''')
1260
1261# Insert a row of data
1262c.execute("""insert into stocks
1263 values ('2006-01-05','BUY','RHAT',100, 35.14)""")
1264\end{verbatim}
1265
1266Usually your SQL queries will need to reflect the value of Python
1267variables. You shouldn't assemble your query using Python's string
1268operations because doing so is insecure; it makes your program
1269vulnerable to what's called an SQL injection attack. Instead, use
1270SQLite's parameter substitution, putting \samp{?} as a placeholder
1271wherever you want to use a value, and then provide a tuple of values
1272as the second argument to the cursor's \method{execute()} method. For
1273example:
1274
1275\begin{verbatim}
1276# Never do this -- insecure!
1277symbol = 'IBM'
1278c.execute("... where symbol = '%s'" % symbol)
1279
1280# Do this instead
1281t = (symbol,)
1282c.execute("... where symbol = '?'", t)
1283
1284# Larger example
1285for t in (('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
1286 ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
1287 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
1288 ):
1289 c.execute('insert into stocks values (?,?,?,?,?)', t)
1290\end{verbatim}
1291
1292To retrieve data after executing a SELECT statement, you can either
1293treat the cursor as an iterator, call the cursor's \method{fetchone()}
1294method to retrieve a single matching row,
1295or call \method{fetchall()} to get a list of the matching rows.
1296
1297This example uses the iterator form:
1298
1299\begin{verbatim}
1300>>> c = conn.cursor()
1301>>> c.execute('select * from stocks order by price')
1302>>> for row in c:
1303... print row
1304...
1305(u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001)
1306(u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
1307(u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
1308(u'2006-04-05', u'BUY', u'MSOFT', 1000, 72.0)
1309>>>
1310\end{verbatim}
1311
1312You should also use parameter substitution with SELECT statements:
1313
1314\begin{verbatim}
1315>>> c.execute('select * from stocks where symbol=?', ('IBM',))
1316>>> print c.fetchall()
1317[(u'2006-03-28', u'BUY', u'IBM', 1000, 45.0),
1318 (u'2006-04-06', u'SELL', u'IBM', 500, 53.0)]
1319\end{verbatim}
1320
1321For more information about the SQL dialect supported by SQLite, see
1322\url{http://www.sqlite.org}.
1323
1324\begin{seealso}
1325
1326\seeurl{http://www.pysqlite.org}
1327{The pysqlite web page.}
1328
1329\seeurl{http://www.sqlite.org}
1330{The SQLite web page; the documentation describes the syntax and the
1331available data types for the supported SQL dialect.}
1332
1333\seepep{249}{Database API Specification 2.0}{PEP written by
1334Marc-Andr\'e Lemburg.}
1335
1336\end{seealso}
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001337
Fred Drake2db76802004-12-01 05:05:47 +00001338
1339% ======================================================================
1340\section{Build and C API Changes}
1341
1342Changes to Python's build process and to the C API include:
1343
1344\begin{itemize}
1345
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00001346\item The largest change to the C API came from \pep{353},
1347which modifies the interpreter to use a \ctype{Py_ssize_t} type
1348definition instead of \ctype{int}. See the earlier
1349section~ref{section-353} for a discussion of this change.
1350
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001351\item The design of the bytecode compiler has changed a great deal, to
1352no longer generate bytecode by traversing the parse tree. Instead
Andrew M. Kuchlingdb85ed52005-10-23 21:52:59 +00001353the parse tree is converted to an abstract syntax tree (or AST), and it is
1354the abstract syntax tree that's traversed to produce the bytecode.
1355
1356No documentation has been written for the AST code yet. To start
1357learning about it, read the definition of the various AST nodes in
1358\file{Parser/Python.asdl}. A Python script reads this file and
1359generates a set of C structure definitions in
1360\file{Include/Python-ast.h}. The \cfunction{PyParser_ASTFromString()}
1361and \cfunction{PyParser_ASTFromFile()}, defined in
1362\file{Include/pythonrun.h}, take Python source as input and return the
1363root of an AST representing the contents. This AST can then be turned
1364into a code object by \cfunction{PyAST_Compile()}. For more
1365information, read the source code, and then ask questions on
1366python-dev.
1367
1368% List of names taken from Jeremy's python-dev post at
1369% http://mail.python.org/pipermail/python-dev/2005-October/057500.html
1370The AST code was developed under Jeremy Hylton's management, and
1371implemented by (in alphabetical order) Brett Cannon, Nick Coghlan,
1372Grant Edwards, John Ehresman, Kurt Kaiser, Neal Norwitz, Tim Peters,
1373Armin Rigo, and Neil Schemenauer, plus the participants in a number of
1374AST sprints at conferences such as PyCon.
1375
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001376\item The built-in set types now have an official C API. Call
1377\cfunction{PySet_New()} and \cfunction{PyFrozenSet_New()} to create a
1378new set, \cfunction{PySet_Add()} and \cfunction{PySet_Discard()} to
1379add and remove elements, and \cfunction{PySet_Contains} and
1380\cfunction{PySet_Size} to examine the set's state.
1381
1382\item The \cfunction{PyRange_New()} function was removed. It was
1383never documented, never used in the core code, and had dangerously lax
1384error checking.
Fred Drake2db76802004-12-01 05:05:47 +00001385
1386\end{itemize}
1387
1388
1389%======================================================================
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001390%\subsection{Port-Specific Changes}
Fred Drake2db76802004-12-01 05:05:47 +00001391
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001392%Platform-specific changes go here.
Fred Drake2db76802004-12-01 05:05:47 +00001393
1394
1395%======================================================================
1396\section{Other Changes and Fixes \label{section-other}}
1397
1398As usual, there were a bunch of other improvements and bugfixes
Andrew M. Kuchlingf688cc52006-03-10 18:50:08 +00001399scattered throughout the source tree. A search through the SVN change
Fred Drake2db76802004-12-01 05:05:47 +00001400logs finds there were XXX patches applied and YYY bugs fixed between
Andrew M. Kuchling92e24952004-12-03 13:54:09 +00001401Python 2.4 and 2.5. Both figures are likely to be underestimates.
Fred Drake2db76802004-12-01 05:05:47 +00001402
1403Some of the more notable changes are:
1404
1405\begin{itemize}
1406
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001407\item Evan Jones's patch to obmalloc, first described in a talk
1408at PyCon DC 2005, was applied. Python 2.4 allocated small objects in
1409256K-sized arenas, but never freed arenas. With this patch, Python
1410will free arenas when they're empty. The net effect is that on some
1411platforms, when you allocate many objects, Python's memory usage may
1412actually drop when you delete them, and the memory may be returned to
1413the operating system. (Implemented by Evan Jones, and reworked by Tim
1414Peters.)
Fred Drake2db76802004-12-01 05:05:47 +00001415
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001416\item Coverity, a company that markets a source code analysis tool
1417 called Prevent, provided the results of their examination of the Python
1418 source code. The analysis found a number of refcounting bugs, often
1419 in error-handling code. These bugs have been fixed.
1420 % XXX provide reference?
1421
Fred Drake2db76802004-12-01 05:05:47 +00001422\end{itemize}
1423
1424
1425%======================================================================
1426\section{Porting to Python 2.5}
1427
1428This section lists previously described changes that may require
1429changes to your code:
1430
1431\begin{itemize}
1432
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +00001433\item The \module{pickle} module no longer uses the deprecated \var{bin} parameter.
Fred Drake2db76802004-12-01 05:05:47 +00001434
1435\end{itemize}
1436
1437
1438%======================================================================
1439\section{Acknowledgements \label{acks}}
1440
1441The author would like to thank the following people for offering
1442suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001443article: Mike Rovner, Thomas Wouters.
Fred Drake2db76802004-12-01 05:05:47 +00001444
1445\end{document}