Bump version number
[pytest.git] / Doc / whatsnew / whatsnew25.tex
blob132f3a242586c5cc7d732d0a6b5b38c756db46f3
1 \documentclass{howto}
2 \usepackage{distutils}
3 % $Id$
5 % Fix XXX comments
6 % Count up the patches and bugs
8 \title{What's New in Python 2.5}
9 \release{0.9}
10 \author{A.M. Kuchling}
11 \authoraddress{\email{amk@amk.ca}}
13 \begin{document}
14 \maketitle
15 \tableofcontents
17 This article explains the new features in Python 2.5. The final
18 release of Python 2.5 is scheduled for August 2006;
19 \pep{356} describes the planned release schedule.
21 The changes in Python 2.5 are an interesting mix of language and
22 library improvements. The library enhancements will be more important
23 to Python's user community, I think, because several widely-useful
24 packages were added. New modules include ElementTree for XML
25 processing (section~\ref{module-etree}), the SQLite database module
26 (section~\ref{module-sqlite}), and the \module{ctypes} module for
27 calling C functions (section~\ref{module-ctypes}).
29 The language changes are of middling significance. Some pleasant new
30 features were added, but most of them aren't features that you'll use
31 every day. Conditional expressions were finally added to the language
32 using a novel syntax; see section~\ref{pep-308}. The new
33 '\keyword{with}' statement will make writing cleanup code easier
34 (section~\ref{pep-343}). Values can now be passed into generators
35 (section~\ref{pep-342}). Imports are now visible as either absolute
36 or relative (section~\ref{pep-328}). Some corner cases of exception
37 handling are handled better (section~\ref{pep-341}). All these
38 improvements are worthwhile, but they're improvements to one specific
39 language feature or another; none of them are broad modifications to
40 Python's semantics.
42 As well as the language and library additions, other improvements and
43 bugfixes were made throughout the source tree. A search through the
44 SVN change logs finds there were 334 patches applied and 443 bugs
45 fixed between Python 2.4 and 2.5. (Both figures are likely to be
46 underestimates.)
48 This article doesn't try to be a complete specification of the new
49 features; instead changes are briefly introduced using helpful
50 examples. For full details, you should always refer to the
51 documentation for Python 2.5.
52 % XXX add hyperlink when the documentation becomes available online.
53 If you want to understand the complete implementation and design
54 rationale, refer to the PEP for a particular new feature.
56 Comments, suggestions, and error reports for this document are
57 welcome; please e-mail them to the author or open a bug in the Python
58 bug tracker.
60 %======================================================================
61 \section{PEP 308: Conditional Expressions\label{pep-308}}
63 For a long time, people have been requesting a way to write
64 conditional expressions, which are expressions that return value A or
65 value B depending on whether a Boolean value is true or false. A
66 conditional expression lets you write a single assignment statement
67 that has the same effect as the following:
69 \begin{verbatim}
70 if condition:
71 x = true_value
72 else:
73 x = false_value
74 \end{verbatim}
76 There have been endless tedious discussions of syntax on both
77 python-dev and comp.lang.python. A vote was even held that found the
78 majority of voters wanted conditional expressions in some form,
79 but there was no syntax that was preferred by a clear majority.
80 Candidates included C's \code{cond ? true_v : false_v},
81 \code{if cond then true_v else false_v}, and 16 other variations.
83 Guido van~Rossum eventually chose a surprising syntax:
85 \begin{verbatim}
86 x = true_value if condition else false_value
87 \end{verbatim}
89 Evaluation is still lazy as in existing Boolean expressions, so the
90 order of evaluation jumps around a bit. The \var{condition}
91 expression in the middle is evaluated first, and the \var{true_value}
92 expression is evaluated only if the condition was true. Similarly,
93 the \var{false_value} expression is only evaluated when the condition
94 is false.
96 This syntax may seem strange and backwards; why does the condition go
97 in the \emph{middle} of the expression, and not in the front as in C's
98 \code{c ? x : y}? The decision was checked by applying the new syntax
99 to the modules in the standard library and seeing how the resulting
100 code read. In many cases where a conditional expression is used, one
101 value seems to be the 'common case' and one value is an 'exceptional
102 case', used only on rarer occasions when the condition isn't met. The
103 conditional syntax makes this pattern a bit more obvious:
105 \begin{verbatim}
106 contents = ((doc + '\n') if doc else '')
107 \end{verbatim}
109 I read the above statement as meaning ``here \var{contents} is
110 usually assigned a value of \code{doc+'\e n'}; sometimes
111 \var{doc} is empty, in which special case an empty string is returned.''
112 I doubt I will use conditional expressions very often where there
113 isn't a clear common and uncommon case.
115 There was some discussion of whether the language should require
116 surrounding conditional expressions with parentheses. The decision
117 was made to \emph{not} require parentheses in the Python language's
118 grammar, but as a matter of style I think you should always use them.
119 Consider these two statements:
121 \begin{verbatim}
122 # First version -- no parens
123 level = 1 if logging else 0
125 # Second version -- with parens
126 level = (1 if logging else 0)
127 \end{verbatim}
129 In the first version, I think a reader's eye might group the statement
130 into 'level = 1', 'if logging', 'else 0', and think that the condition
131 decides whether the assignment to \var{level} is performed. The
132 second version reads better, in my opinion, because it makes it clear
133 that the assignment is always performed and the choice is being made
134 between two values.
136 Another reason for including the brackets: a few odd combinations of
137 list comprehensions and lambdas could look like incorrect conditional
138 expressions. See \pep{308} for some examples. If you put parentheses
139 around your conditional expressions, you won't run into this case.
142 \begin{seealso}
144 \seepep{308}{Conditional Expressions}{PEP written by
145 Guido van~Rossum and Raymond D. Hettinger; implemented by Thomas
146 Wouters.}
148 \end{seealso}
151 %======================================================================
152 \section{PEP 309: Partial Function Application\label{pep-309}}
154 The \module{functools} module is intended to contain tools for
155 functional-style programming.
157 One useful tool in this module is the \function{partial()} function.
158 For programs written in a functional style, you'll sometimes want to
159 construct variants of existing functions that have some of the
160 parameters filled in. Consider a Python function \code{f(a, b, c)};
161 you could create a new function \code{g(b, c)} that was equivalent to
162 \code{f(1, b, c)}. This is called ``partial function application''.
164 \function{partial} takes the arguments
165 \code{(\var{function}, \var{arg1}, \var{arg2}, ...
166 \var{kwarg1}=\var{value1}, \var{kwarg2}=\var{value2})}. The resulting
167 object is callable, so you can just call it to invoke \var{function}
168 with the filled-in arguments.
170 Here's a small but realistic example:
172 \begin{verbatim}
173 import functools
175 def log (message, subsystem):
176 "Write the contents of 'message' to the specified subsystem."
177 print '%s: %s' % (subsystem, message)
180 server_log = functools.partial(log, subsystem='server')
181 server_log('Unable to open socket')
182 \end{verbatim}
184 Here's another example, from a program that uses PyGTK. Here a
185 context-sensitive pop-up menu is being constructed dynamically. The
186 callback provided for the menu option is a partially applied version
187 of the \method{open_item()} method, where the first argument has been
188 provided.
190 \begin{verbatim}
192 class Application:
193 def open_item(self, path):
195 def init (self):
196 open_func = functools.partial(self.open_item, item_path)
197 popup_menu.append( ("Open", open_func, 1) )
198 \end{verbatim}
201 Another function in the \module{functools} module is the
202 \function{update_wrapper(\var{wrapper}, \var{wrapped})} function that
203 helps you write well-behaved decorators. \function{update_wrapper()}
204 copies the name, module, and docstring attribute to a wrapper function
205 so that tracebacks inside the wrapped function are easier to
206 understand. For example, you might write:
208 \begin{verbatim}
209 def my_decorator(f):
210 def wrapper(*args, **kwds):
211 print 'Calling decorated function'
212 return f(*args, **kwds)
213 functools.update_wrapper(wrapper, f)
214 return wrapper
215 \end{verbatim}
217 \function{wraps()} is a decorator that can be used inside your own
218 decorators to copy the wrapped function's information. An alternate
219 version of the previous example would be:
221 \begin{verbatim}
222 def my_decorator(f):
223 @functools.wraps(f)
224 def wrapper(*args, **kwds):
225 print 'Calling decorated function'
226 return f(*args, **kwds)
227 return wrapper
228 \end{verbatim}
230 \begin{seealso}
232 \seepep{309}{Partial Function Application}{PEP proposed and written by
233 Peter Harris; implemented by Hye-Shik Chang and Nick Coghlan, with
234 adaptations by Raymond Hettinger.}
236 \end{seealso}
239 %======================================================================
240 \section{PEP 314: Metadata for Python Software Packages v1.1\label{pep-314}}
242 Some simple dependency support was added to Distutils. The
243 \function{setup()} function now has \code{requires}, \code{provides},
244 and \code{obsoletes} keyword parameters. When you build a source
245 distribution using the \code{sdist} command, the dependency
246 information will be recorded in the \file{PKG-INFO} file.
248 Another new keyword parameter is \code{download_url}, which should be
249 set to a URL for the package's source code. This means it's now
250 possible to look up an entry in the package index, determine the
251 dependencies for a package, and download the required packages.
253 \begin{verbatim}
254 VERSION = '1.0'
255 setup(name='PyPackage',
256 version=VERSION,
257 requires=['numarray', 'zlib (>=1.1.4)'],
258 obsoletes=['OldPackage']
259 download_url=('http://www.example.com/pypackage/dist/pkg-%s.tar.gz'
260 % VERSION),
262 \end{verbatim}
264 Another new enhancement to the Python package index at
265 \url{http://cheeseshop.python.org} is storing source and binary
266 archives for a package. The new \command{upload} Distutils command
267 will upload a package to the repository.
269 Before a package can be uploaded, you must be able to build a
270 distribution using the \command{sdist} Distutils command. Once that
271 works, you can run \code{python setup.py upload} to add your package
272 to the PyPI archive. Optionally you can GPG-sign the package by
273 supplying the \longprogramopt{sign} and
274 \longprogramopt{identity} options.
276 Package uploading was implemented by Martin von~L\"owis and Richard Jones.
278 \begin{seealso}
280 \seepep{314}{Metadata for Python Software Packages v1.1}{PEP proposed
281 and written by A.M. Kuchling, Richard Jones, and Fred Drake;
282 implemented by Richard Jones and Fred Drake.}
284 \end{seealso}
287 %======================================================================
288 \section{PEP 328: Absolute and Relative Imports\label{pep-328}}
290 The simpler part of PEP 328 was implemented in Python 2.4: parentheses
291 could now be used to enclose the names imported from a module using
292 the \code{from ... import ...} statement, making it easier to import
293 many different names.
295 The more complicated part has been implemented in Python 2.5:
296 importing a module can be specified to use absolute or
297 package-relative imports. The plan is to move toward making absolute
298 imports the default in future versions of Python.
300 Let's say you have a package directory like this:
301 \begin{verbatim}
302 pkg/
303 pkg/__init__.py
304 pkg/main.py
305 pkg/string.py
306 \end{verbatim}
308 This defines a package named \module{pkg} containing the
309 \module{pkg.main} and \module{pkg.string} submodules.
311 Consider the code in the \file{main.py} module. What happens if it
312 executes the statement \code{import string}? In Python 2.4 and
313 earlier, it will first look in the package's directory to perform a
314 relative import, finds \file{pkg/string.py}, imports the contents of
315 that file as the \module{pkg.string} module, and that module is bound
316 to the name \samp{string} in the \module{pkg.main} module's namespace.
318 That's fine if \module{pkg.string} was what you wanted. But what if
319 you wanted Python's standard \module{string} module? There's no clean
320 way to ignore \module{pkg.string} and look for the standard module;
321 generally you had to look at the contents of \code{sys.modules}, which
322 is slightly unclean.
323 Holger Krekel's \module{py.std} package provides a tidier way to perform
324 imports from the standard library, \code{import py ; py.std.string.join()},
325 but that package isn't available on all Python installations.
327 Reading code which relies on relative imports is also less clear,
328 because a reader may be confused about which module, \module{string}
329 or \module{pkg.string}, is intended to be used. Python users soon
330 learned not to duplicate the names of standard library modules in the
331 names of their packages' submodules, but you can't protect against
332 having your submodule's name being used for a new module added in a
333 future version of Python.
335 In Python 2.5, you can switch \keyword{import}'s behaviour to
336 absolute imports using a \code{from __future__ import absolute_import}
337 directive. This absolute-import behaviour will become the default in
338 a future version (probably Python 2.7). Once absolute imports
339 are the default, \code{import string} will
340 always find the standard library's version.
341 It's suggested that users should begin using absolute imports as much
342 as possible, so it's preferable to begin writing \code{from pkg import
343 string} in your code.
345 Relative imports are still possible by adding a leading period
346 to the module name when using the \code{from ... import} form:
348 \begin{verbatim}
349 # Import names from pkg.string
350 from .string import name1, name2
351 # Import pkg.string
352 from . import string
353 \end{verbatim}
355 This imports the \module{string} module relative to the current
356 package, so in \module{pkg.main} this will import \var{name1} and
357 \var{name2} from \module{pkg.string}. Additional leading periods
358 perform the relative import starting from the parent of the current
359 package. For example, code in the \module{A.B.C} module can do:
361 \begin{verbatim}
362 from . import D # Imports A.B.D
363 from .. import E # Imports A.E
364 from ..F import G # Imports A.F.G
365 \end{verbatim}
367 Leading periods cannot be used with the \code{import \var{modname}}
368 form of the import statement, only the \code{from ... import} form.
370 \begin{seealso}
372 \seepep{328}{Imports: Multi-Line and Absolute/Relative}
373 {PEP written by Aahz; implemented by Thomas Wouters.}
375 \seeurl{http://codespeak.net/py/current/doc/index.html}
376 {The py library by Holger Krekel, which contains the \module{py.std} package.}
378 \end{seealso}
381 %======================================================================
382 \section{PEP 338: Executing Modules as Scripts\label{pep-338}}
384 The \programopt{-m} switch added in Python 2.4 to execute a module as
385 a script gained a few more abilities. Instead of being implemented in
386 C code inside the Python interpreter, the switch now uses an
387 implementation in a new module, \module{runpy}.
389 The \module{runpy} module implements a more sophisticated import
390 mechanism so that it's now possible to run modules in a package such
391 as \module{pychecker.checker}. The module also supports alternative
392 import mechanisms such as the \module{zipimport} module. This means
393 you can add a .zip archive's path to \code{sys.path} and then use the
394 \programopt{-m} switch to execute code from the archive.
397 \begin{seealso}
399 \seepep{338}{Executing modules as scripts}{PEP written and
400 implemented by Nick Coghlan.}
402 \end{seealso}
405 %======================================================================
406 \section{PEP 341: Unified try/except/finally\label{pep-341}}
408 Until Python 2.5, the \keyword{try} statement came in two
409 flavours. You could use a \keyword{finally} block to ensure that code
410 is always executed, or one or more \keyword{except} blocks to catch
411 specific exceptions. You couldn't combine both \keyword{except} blocks and a
412 \keyword{finally} block, because generating the right bytecode for the
413 combined version was complicated and it wasn't clear what the
414 semantics of the combined should be.
416 Guido van~Rossum spent some time working with Java, which does support the
417 equivalent of combining \keyword{except} blocks and a
418 \keyword{finally} block, and this clarified what the statement should
419 mean. In Python 2.5, you can now write:
421 \begin{verbatim}
422 try:
423 block-1 ...
424 except Exception1:
425 handler-1 ...
426 except Exception2:
427 handler-2 ...
428 else:
429 else-block
430 finally:
431 final-block
432 \end{verbatim}
434 The code in \var{block-1} is executed. If the code raises an
435 exception, the various \keyword{except} blocks are tested: if the
436 exception is of class \class{Exception1}, \var{handler-1} is executed;
437 otherwise if it's of class \class{Exception2}, \var{handler-2} is
438 executed, and so forth. If no exception is raised, the
439 \var{else-block} is executed.
441 No matter what happened previously, the \var{final-block} is executed
442 once the code block is complete and any raised exceptions handled.
443 Even if there's an error in an exception handler or the
444 \var{else-block} and a new exception is raised, the
445 code in the \var{final-block} is still run.
447 \begin{seealso}
449 \seepep{341}{Unifying try-except and try-finally}{PEP written by Georg Brandl;
450 implementation by Thomas Lee.}
452 \end{seealso}
455 %======================================================================
456 \section{PEP 342: New Generator Features\label{pep-342}}
458 Python 2.5 adds a simple way to pass values \emph{into} a generator.
459 As introduced in Python 2.3, generators only produce output; once a
460 generator's code was invoked to create an iterator, there was no way to
461 pass any new information into the function when its execution is
462 resumed. Sometimes the ability to pass in some information would be
463 useful. Hackish solutions to this include making the generator's code
464 look at a global variable and then changing the global variable's
465 value, or passing in some mutable object that callers then modify.
467 To refresh your memory of basic generators, here's a simple example:
469 \begin{verbatim}
470 def counter (maximum):
471 i = 0
472 while i < maximum:
473 yield i
474 i += 1
475 \end{verbatim}
477 When you call \code{counter(10)}, the result is an iterator that
478 returns the values from 0 up to 9. On encountering the
479 \keyword{yield} statement, the iterator returns the provided value and
480 suspends the function's execution, preserving the local variables.
481 Execution resumes on the following call to the iterator's
482 \method{next()} method, picking up after the \keyword{yield} statement.
484 In Python 2.3, \keyword{yield} was a statement; it didn't return any
485 value. In 2.5, \keyword{yield} is now an expression, returning a
486 value that can be assigned to a variable or otherwise operated on:
488 \begin{verbatim}
489 val = (yield i)
490 \end{verbatim}
492 I recommend that you always put parentheses around a \keyword{yield}
493 expression when you're doing something with the returned value, as in
494 the above example. The parentheses aren't always necessary, but it's
495 easier to always add them instead of having to remember when they're
496 needed.
498 (\pep{342} explains the exact rules, which are that a
499 \keyword{yield}-expression must always be parenthesized except when it
500 occurs at the top-level expression on the right-hand side of an
501 assignment. This means you can write \code{val = yield i} but have to
502 use parentheses when there's an operation, as in \code{val = (yield i)
503 + 12}.)
505 Values are sent into a generator by calling its
506 \method{send(\var{value})} method. The generator's code is then
507 resumed and the \keyword{yield} expression returns the specified
508 \var{value}. If the regular \method{next()} method is called, the
509 \keyword{yield} returns \constant{None}.
511 Here's the previous example, modified to allow changing the value of
512 the internal counter.
514 \begin{verbatim}
515 def counter (maximum):
516 i = 0
517 while i < maximum:
518 val = (yield i)
519 # If value provided, change counter
520 if val is not None:
521 i = val
522 else:
523 i += 1
524 \end{verbatim}
526 And here's an example of changing the counter:
528 \begin{verbatim}
529 >>> it = counter(10)
530 >>> print it.next()
532 >>> print it.next()
534 >>> print it.send(8)
536 >>> print it.next()
538 >>> print it.next()
539 Traceback (most recent call last):
540 File ``t.py'', line 15, in ?
541 print it.next()
542 StopIteration
543 \end{verbatim}
545 Because \keyword{yield} will often be returning \constant{None}, you
546 should always check for this case. Don't just use its value in
547 expressions unless you're sure that the \method{send()} method
548 will be the only method used resume your generator function.
550 In addition to \method{send()}, there are two other new methods on
551 generators:
553 \begin{itemize}
555 \item \method{throw(\var{type}, \var{value}=None,
556 \var{traceback}=None)} is used to raise an exception inside the
557 generator; the exception is raised by the \keyword{yield} expression
558 where the generator's execution is paused.
560 \item \method{close()} raises a new \exception{GeneratorExit}
561 exception inside the generator to terminate the iteration.
562 On receiving this
563 exception, the generator's code must either raise
564 \exception{GeneratorExit} or \exception{StopIteration}; catching the
565 exception and doing anything else is illegal and will trigger
566 a \exception{RuntimeError}. \method{close()} will also be called by
567 Python's garbage collector when the generator is garbage-collected.
569 If you need to run cleanup code when a \exception{GeneratorExit} occurs,
570 I suggest using a \code{try: ... finally:} suite instead of
571 catching \exception{GeneratorExit}.
573 \end{itemize}
575 The cumulative effect of these changes is to turn generators from
576 one-way producers of information into both producers and consumers.
578 Generators also become \emph{coroutines}, a more generalized form of
579 subroutines. Subroutines are entered at one point and exited at
580 another point (the top of the function, and a \keyword{return}
581 statement), but coroutines can be entered, exited, and resumed at
582 many different points (the \keyword{yield} statements). We'll have to
583 figure out patterns for using coroutines effectively in Python.
585 The addition of the \method{close()} method has one side effect that
586 isn't obvious. \method{close()} is called when a generator is
587 garbage-collected, so this means the generator's code gets one last
588 chance to run before the generator is destroyed. This last chance
589 means that \code{try...finally} statements in generators can now be
590 guaranteed to work; the \keyword{finally} clause will now always get a
591 chance to run. The syntactic restriction that you couldn't mix
592 \keyword{yield} statements with a \code{try...finally} suite has
593 therefore been removed. This seems like a minor bit of language
594 trivia, but using generators and \code{try...finally} is actually
595 necessary in order to implement the \keyword{with} statement
596 described by PEP 343. I'll look at this new statement in the following
597 section.
599 Another even more esoteric effect of this change: previously, the
600 \member{gi_frame} attribute of a generator was always a frame object.
601 It's now possible for \member{gi_frame} to be \code{None}
602 once the generator has been exhausted.
604 \begin{seealso}
606 \seepep{342}{Coroutines via Enhanced Generators}{PEP written by
607 Guido van~Rossum and Phillip J. Eby;
608 implemented by Phillip J. Eby. Includes examples of
609 some fancier uses of generators as coroutines.
611 Earlier versions of these features were proposed in
612 \pep{288} by Raymond Hettinger and \pep{325} by Samuele Pedroni.
615 \seeurl{http://en.wikipedia.org/wiki/Coroutine}{The Wikipedia entry for
616 coroutines.}
618 \seeurl{http://www.sidhe.org/\~{}dan/blog/archives/000178.html}{An
619 explanation of coroutines from a Perl point of view, written by Dan
620 Sugalski.}
622 \end{seealso}
625 %======================================================================
626 \section{PEP 343: The 'with' statement\label{pep-343}}
628 The '\keyword{with}' statement clarifies code that previously would
629 use \code{try...finally} blocks to ensure that clean-up code is
630 executed. In this section, I'll discuss the statement as it will
631 commonly be used. In the next section, I'll examine the
632 implementation details and show how to write objects for use with this
633 statement.
635 The '\keyword{with}' statement is a new control-flow structure whose
636 basic structure is:
638 \begin{verbatim}
639 with expression [as variable]:
640 with-block
641 \end{verbatim}
643 The expression is evaluated, and it should result in an object that
644 supports the context management protocol. This object may return a
645 value that can optionally be bound to the name \var{variable}. (Note
646 carefully that \var{variable} is \emph{not} assigned the result of
647 \var{expression}.) The object can then run set-up code
648 before \var{with-block} is executed and some clean-up code
649 is executed after the block is done, even if the block raised an exception.
651 To enable the statement in Python 2.5, you need
652 to add the following directive to your module:
654 \begin{verbatim}
655 from __future__ import with_statement
656 \end{verbatim}
658 The statement will always be enabled in Python 2.6.
660 Some standard Python objects now support the context management
661 protocol and can be used with the '\keyword{with}' statement. File
662 objects are one example:
664 \begin{verbatim}
665 with open('/etc/passwd', 'r') as f:
666 for line in f:
667 print line
668 ... more processing code ...
669 \end{verbatim}
671 After this statement has executed, the file object in \var{f} will
672 have been automatically closed, even if the 'for' loop
673 raised an exception part-way through the block.
675 The \module{threading} module's locks and condition variables
676 also support the '\keyword{with}' statement:
678 \begin{verbatim}
679 lock = threading.Lock()
680 with lock:
681 # Critical section of code
683 \end{verbatim}
685 The lock is acquired before the block is executed and always released once
686 the block is complete.
688 The \module{decimal} module's contexts, which encapsulate the desired
689 precision and rounding characteristics for computations, provide a
690 \method{context_manager()} method for getting a context manager:
692 \begin{verbatim}
693 import decimal
695 # Displays with default precision of 28 digits
696 v1 = decimal.Decimal('578')
697 print v1.sqrt()
699 ctx = decimal.Context(prec=16)
700 with ctx.context_manager():
701 # All code in this block uses a precision of 16 digits.
702 # The original context is restored on exiting the block.
703 print v1.sqrt()
704 \end{verbatim}
706 \subsection{Writing Context Managers\label{context-managers}}
708 Under the hood, the '\keyword{with}' statement is fairly complicated.
709 Most people will only use '\keyword{with}' in company with existing
710 objects and don't need to know these details, so you can skip the rest
711 of this section if you like. Authors of new objects will need to
712 understand the details of the underlying implementation and should
713 keep reading.
715 A high-level explanation of the context management protocol is:
717 \begin{itemize}
719 \item The expression is evaluated and should result in an object
720 called a ``context manager''. The context manager must have
721 \method{__enter__()} and \method{__exit__()} methods.
723 \item The context manager's \method{__enter__()} method is called. The value
724 returned is assigned to \var{VAR}. If no \code{'as \var{VAR}'} clause
725 is present, the value is simply discarded.
727 \item The code in \var{BLOCK} is executed.
729 \item If \var{BLOCK} raises an exception, the
730 \method{__exit__(\var{type}, \var{value}, \var{traceback})} is called
731 with the exception details, the same values returned by
732 \function{sys.exc_info()}. The method's return value controls whether
733 the exception is re-raised: any false value re-raises the exception,
734 and \code{True} will result in suppressing it. You'll only rarely
735 want to suppress the exception, because if you do
736 the author of the code containing the
737 '\keyword{with}' statement will never realize anything went wrong.
739 \item If \var{BLOCK} didn't raise an exception,
740 the \method{__exit__()} method is still called,
741 but \var{type}, \var{value}, and \var{traceback} are all \code{None}.
743 \end{itemize}
745 Let's think through an example. I won't present detailed code but
746 will only sketch the methods necessary for a database that supports
747 transactions.
749 (For people unfamiliar with database terminology: a set of changes to
750 the database are grouped into a transaction. Transactions can be
751 either committed, meaning that all the changes are written into the
752 database, or rolled back, meaning that the changes are all discarded
753 and the database is unchanged. See any database textbook for more
754 information.)
755 % XXX find a shorter reference?
757 Let's assume there's an object representing a database connection.
758 Our goal will be to let the user write code like this:
760 \begin{verbatim}
761 db_connection = DatabaseConnection()
762 with db_connection as cursor:
763 cursor.execute('insert into ...')
764 cursor.execute('delete from ...')
765 # ... more operations ...
766 \end{verbatim}
768 The transaction should be committed if the code in the block
769 runs flawlessly or rolled back if there's an exception.
770 Here's the basic interface
771 for \class{DatabaseConnection} that I'll assume:
773 \begin{verbatim}
774 class DatabaseConnection:
775 # Database interface
776 def cursor (self):
777 "Returns a cursor object and starts a new transaction"
778 def commit (self):
779 "Commits current transaction"
780 def rollback (self):
781 "Rolls back current transaction"
782 \end{verbatim}
784 The \method {__enter__()} method is pretty easy, having only to start
785 a new transaction. For this application the resulting cursor object
786 would be a useful result, so the method will return it. The user can
787 then add \code{as cursor} to their '\keyword{with}' statement to bind
788 the cursor to a variable name.
790 \begin{verbatim}
791 class DatabaseConnection:
793 def __enter__ (self):
794 # Code to start a new transaction
795 cursor = self.cursor()
796 return cursor
797 \end{verbatim}
799 The \method{__exit__()} method is the most complicated because it's
800 where most of the work has to be done. The method has to check if an
801 exception occurred. If there was no exception, the transaction is
802 committed. The transaction is rolled back if there was an exception.
804 In the code below, execution will just fall off the end of the
805 function, returning the default value of \code{None}. \code{None} is
806 false, so the exception will be re-raised automatically. If you
807 wished, you could be more explicit and add a \keyword{return}
808 statement at the marked location.
810 \begin{verbatim}
811 class DatabaseConnection:
813 def __exit__ (self, type, value, tb):
814 if tb is None:
815 # No exception, so commit
816 self.commit()
817 else:
818 # Exception occurred, so rollback.
819 self.rollback()
820 # return False
821 \end{verbatim}
824 \subsection{The contextlib module\label{module-contextlib}}
826 The new \module{contextlib} module provides some functions and a
827 decorator that are useful for writing objects for use with the
828 '\keyword{with}' statement.
830 The decorator is called \function{contextmanager}, and lets you write
831 a single generator function instead of defining a new class. The generator
832 should yield exactly one value. The code up to the \keyword{yield}
833 will be executed as the \method{__enter__()} method, and the value
834 yielded will be the method's return value that will get bound to the
835 variable in the '\keyword{with}' statement's \keyword{as} clause, if
836 any. The code after the \keyword{yield} will be executed in the
837 \method{__exit__()} method. Any exception raised in the block will be
838 raised by the \keyword{yield} statement.
840 Our database example from the previous section could be written
841 using this decorator as:
843 \begin{verbatim}
844 from contextlib import contextmanager
846 @contextmanager
847 def db_transaction (connection):
848 cursor = connection.cursor()
849 try:
850 yield cursor
851 except:
852 connection.rollback()
853 raise
854 else:
855 connection.commit()
857 db = DatabaseConnection()
858 with db_transaction(db) as cursor:
860 \end{verbatim}
862 The \module{contextlib} module also has a \function{nested(\var{mgr1},
863 \var{mgr2}, ...)} function that combines a number of context managers so you
864 don't need to write nested '\keyword{with}' statements. In this
865 example, the single '\keyword{with}' statement both starts a database
866 transaction and acquires a thread lock:
868 \begin{verbatim}
869 lock = threading.Lock()
870 with nested (db_transaction(db), lock) as (cursor, locked):
872 \end{verbatim}
874 Finally, the \function{closing(\var{object})} function
875 returns \var{object} so that it can be bound to a variable,
876 and calls \code{\var{object}.close()} at the end of the block.
878 \begin{verbatim}
879 import urllib, sys
880 from contextlib import closing
882 with closing(urllib.urlopen('http://www.yahoo.com')) as f:
883 for line in f:
884 sys.stdout.write(line)
885 \end{verbatim}
887 \begin{seealso}
889 \seepep{343}{The ``with'' statement}{PEP written by Guido van~Rossum
890 and Nick Coghlan; implemented by Mike Bland, Guido van~Rossum, and
891 Neal Norwitz. The PEP shows the code generated for a '\keyword{with}'
892 statement, which can be helpful in learning how the statement works.}
894 \seeurl{../lib/module-contextlib.html}{The documentation
895 for the \module{contextlib} module.}
897 \end{seealso}
900 %======================================================================
901 \section{PEP 352: Exceptions as New-Style Classes\label{pep-352}}
903 Exception classes can now be new-style classes, not just classic
904 classes, and the built-in \exception{Exception} class and all the
905 standard built-in exceptions (\exception{NameError},
906 \exception{ValueError}, etc.) are now new-style classes.
908 The inheritance hierarchy for exceptions has been rearranged a bit.
909 In 2.5, the inheritance relationships are:
911 \begin{verbatim}
912 BaseException # New in Python 2.5
913 |- KeyboardInterrupt
914 |- SystemExit
915 |- Exception
916 |- (all other current built-in exceptions)
917 \end{verbatim}
919 This rearrangement was done because people often want to catch all
920 exceptions that indicate program errors. \exception{KeyboardInterrupt} and
921 \exception{SystemExit} aren't errors, though, and usually represent an explicit
922 action such as the user hitting Control-C or code calling
923 \function{sys.exit()}. A bare \code{except:} will catch all exceptions,
924 so you commonly need to list \exception{KeyboardInterrupt} and
925 \exception{SystemExit} in order to re-raise them. The usual pattern is:
927 \begin{verbatim}
928 try:
930 except (KeyboardInterrupt, SystemExit):
931 raise
932 except:
933 # Log error...
934 # Continue running program...
935 \end{verbatim}
937 In Python 2.5, you can now write \code{except Exception} to achieve
938 the same result, catching all the exceptions that usually indicate errors
939 but leaving \exception{KeyboardInterrupt} and
940 \exception{SystemExit} alone. As in previous versions,
941 a bare \code{except:} still catches all exceptions.
943 The goal for Python 3.0 is to require any class raised as an exception
944 to derive from \exception{BaseException} or some descendant of
945 \exception{BaseException}, and future releases in the
946 Python 2.x series may begin to enforce this constraint. Therefore, I
947 suggest you begin making all your exception classes derive from
948 \exception{Exception} now. It's been suggested that the bare
949 \code{except:} form should be removed in Python 3.0, but Guido van~Rossum
950 hasn't decided whether to do this or not.
952 Raising of strings as exceptions, as in the statement \code{raise
953 "Error occurred"}, is deprecated in Python 2.5 and will trigger a
954 warning. The aim is to be able to remove the string-exception feature
955 in a few releases.
958 \begin{seealso}
960 \seepep{352}{Required Superclass for Exceptions}{PEP written by
961 Brett Cannon and Guido van~Rossum; implemented by Brett Cannon.}
963 \end{seealso}
966 %======================================================================
967 \section{PEP 353: Using ssize_t as the index type\label{pep-353}}
969 A wide-ranging change to Python's C API, using a new
970 \ctype{Py_ssize_t} type definition instead of \ctype{int},
971 will permit the interpreter to handle more data on 64-bit platforms.
972 This change doesn't affect Python's capacity on 32-bit platforms.
974 Various pieces of the Python interpreter used C's \ctype{int} type to
975 store sizes or counts; for example, the number of items in a list or
976 tuple were stored in an \ctype{int}. The C compilers for most 64-bit
977 platforms still define \ctype{int} as a 32-bit type, so that meant
978 that lists could only hold up to \code{2**31 - 1} = 2147483647 items.
979 (There are actually a few different programming models that 64-bit C
980 compilers can use -- see
981 \url{http://www.unix.org/version2/whatsnew/lp64_wp.html} for a
982 discussion -- but the most commonly available model leaves \ctype{int}
983 as 32 bits.)
985 A limit of 2147483647 items doesn't really matter on a 32-bit platform
986 because you'll run out of memory before hitting the length limit.
987 Each list item requires space for a pointer, which is 4 bytes, plus
988 space for a \ctype{PyObject} representing the item. 2147483647*4 is
989 already more bytes than a 32-bit address space can contain.
991 It's possible to address that much memory on a 64-bit platform,
992 however. The pointers for a list that size would only require 16~GiB
993 of space, so it's not unreasonable that Python programmers might
994 construct lists that large. Therefore, the Python interpreter had to
995 be changed to use some type other than \ctype{int}, and this will be a
996 64-bit type on 64-bit platforms. The change will cause
997 incompatibilities on 64-bit machines, so it was deemed worth making
998 the transition now, while the number of 64-bit users is still
999 relatively small. (In 5 or 10 years, we may \emph{all} be on 64-bit
1000 machines, and the transition would be more painful then.)
1002 This change most strongly affects authors of C extension modules.
1003 Python strings and container types such as lists and tuples
1004 now use \ctype{Py_ssize_t} to store their size.
1005 Functions such as \cfunction{PyList_Size()}
1006 now return \ctype{Py_ssize_t}. Code in extension modules
1007 may therefore need to have some variables changed to
1008 \ctype{Py_ssize_t}.
1010 The \cfunction{PyArg_ParseTuple()} and \cfunction{Py_BuildValue()} functions
1011 have a new conversion code, \samp{n}, for \ctype{Py_ssize_t}.
1012 \cfunction{PyArg_ParseTuple()}'s \samp{s\#} and \samp{t\#} still output
1013 \ctype{int} by default, but you can define the macro
1014 \csimplemacro{PY_SSIZE_T_CLEAN} before including \file{Python.h}
1015 to make them return \ctype{Py_ssize_t}.
1017 \pep{353} has a section on conversion guidelines that
1018 extension authors should read to learn about supporting 64-bit
1019 platforms.
1021 \begin{seealso}
1023 \seepep{353}{Using ssize_t as the index type}{PEP written and implemented by Martin von~L\"owis.}
1025 \end{seealso}
1028 %======================================================================
1029 \section{PEP 357: The '__index__' method\label{pep-357}}
1031 The NumPy developers had a problem that could only be solved by adding
1032 a new special method, \method{__index__}. When using slice notation,
1033 as in \code{[\var{start}:\var{stop}:\var{step}]}, the values of the
1034 \var{start}, \var{stop}, and \var{step} indexes must all be either
1035 integers or long integers. NumPy defines a variety of specialized
1036 integer types corresponding to unsigned and signed integers of 8, 16,
1037 32, and 64 bits, but there was no way to signal that these types could
1038 be used as slice indexes.
1040 Slicing can't just use the existing \method{__int__} method because
1041 that method is also used to implement coercion to integers. If
1042 slicing used \method{__int__}, floating-point numbers would also
1043 become legal slice indexes and that's clearly an undesirable
1044 behaviour.
1046 Instead, a new special method called \method{__index__} was added. It
1047 takes no arguments and returns an integer giving the slice index to
1048 use. For example:
1050 \begin{verbatim}
1051 class C:
1052 def __index__ (self):
1053 return self.value
1054 \end{verbatim}
1056 The return value must be either a Python integer or long integer.
1057 The interpreter will check that the type returned is correct, and
1058 raises a \exception{TypeError} if this requirement isn't met.
1060 A corresponding \member{nb_index} slot was added to the C-level
1061 \ctype{PyNumberMethods} structure to let C extensions implement this
1062 protocol. \cfunction{PyNumber_Index(\var{obj})} can be used in
1063 extension code to call the \method{__index__} function and retrieve
1064 its result.
1066 \begin{seealso}
1068 \seepep{357}{Allowing Any Object to be Used for Slicing}{PEP written
1069 and implemented by Travis Oliphant.}
1071 \end{seealso}
1074 %======================================================================
1075 \section{Other Language Changes\label{other-lang}}
1077 Here are all of the changes that Python 2.5 makes to the core Python
1078 language.
1080 \begin{itemize}
1082 \item The \class{dict} type has a new hook for letting subclasses
1083 provide a default value when a key isn't contained in the dictionary.
1084 When a key isn't found, the dictionary's
1085 \method{__missing__(\var{key})}
1086 method will be called. This hook is used to implement
1087 the new \class{defaultdict} class in the \module{collections}
1088 module. The following example defines a dictionary
1089 that returns zero for any missing key:
1091 \begin{verbatim}
1092 class zerodict (dict):
1093 def __missing__ (self, key):
1094 return 0
1096 d = zerodict({1:1, 2:2})
1097 print d[1], d[2] # Prints 1, 2
1098 print d[3], d[4] # Prints 0, 0
1099 \end{verbatim}
1101 \item Both 8-bit and Unicode strings have new \method{partition(sep)}
1102 and \method{rpartition(sep)} methods that simplify a common use case.
1103 The \method{find(S)} method is often used to get an index which is
1104 then used to slice the string and obtain the pieces that are before
1105 and after the separator.
1107 \method{partition(sep)} condenses this
1108 pattern into a single method call that returns a 3-tuple containing
1109 the substring before the separator, the separator itself, and the
1110 substring after the separator. If the separator isn't found, the
1111 first element of the tuple is the entire string and the other two
1112 elements are empty. \method{rpartition(sep)} also returns a 3-tuple
1113 but starts searching from the end of the string; the \samp{r} stands
1114 for 'reverse'.
1116 Some examples:
1118 \begin{verbatim}
1119 >>> ('http://www.python.org').partition('://')
1120 ('http', '://', 'www.python.org')
1121 >>> (u'Subject: a quick question').partition(':')
1122 (u'Subject', u':', u' a quick question')
1123 >>> ('file:/usr/share/doc/index.html').partition('://')
1124 ('file:/usr/share/doc/index.html', '', '')
1125 >>> 'www.python.org'.rpartition('.')
1126 ('www.python', '.', 'org')
1127 \end{verbatim}
1129 (Implemented by Fredrik Lundh following a suggestion by Raymond Hettinger.)
1131 \item The \method{startswith()} and \method{endswith()} methods
1132 of string types now accept tuples of strings to check for.
1134 \begin{verbatim}
1135 def is_image_file (filename):
1136 return filename.endswith(('.gif', '.jpg', '.tiff'))
1137 \end{verbatim}
1139 (Implemented by Georg Brandl following a suggestion by Tom Lynn.)
1140 % RFE #1491485
1142 \item The \function{min()} and \function{max()} built-in functions
1143 gained a \code{key} keyword parameter analogous to the \code{key}
1144 argument for \method{sort()}. This parameter supplies a function that
1145 takes a single argument and is called for every value in the list;
1146 \function{min()}/\function{max()} will return the element with the
1147 smallest/largest return value from this function.
1148 For example, to find the longest string in a list, you can do:
1150 \begin{verbatim}
1151 L = ['medium', 'longest', 'short']
1152 # Prints 'longest'
1153 print max(L, key=len)
1154 # Prints 'short', because lexicographically 'short' has the largest value
1155 print max(L)
1156 \end{verbatim}
1158 (Contributed by Steven Bethard and Raymond Hettinger.)
1160 \item Two new built-in functions, \function{any()} and
1161 \function{all()}, evaluate whether an iterator contains any true or
1162 false values. \function{any()} returns \constant{True} if any value
1163 returned by the iterator is true; otherwise it will return
1164 \constant{False}. \function{all()} returns \constant{True} only if
1165 all of the values returned by the iterator evaluate as true.
1166 (Suggested by Guido van~Rossum, and implemented by Raymond Hettinger.)
1168 \item ASCII is now the default encoding for modules. It's now
1169 a syntax error if a module contains string literals with 8-bit
1170 characters but doesn't have an encoding declaration. In Python 2.4
1171 this triggered a warning, not a syntax error. See \pep{263}
1172 for how to declare a module's encoding; for example, you might add
1173 a line like this near the top of the source file:
1175 \begin{verbatim}
1176 # -*- coding: latin1 -*-
1177 \end{verbatim}
1179 \item One error that Python programmers sometimes make is forgetting
1180 to include an \file{__init__.py} module in a package directory.
1181 Debugging this mistake can be confusing, and usually requires running
1182 Python with the \programopt{-v} switch to log all the paths searched.
1183 In Python 2.5, a new \exception{ImportWarning} warning is triggered when
1184 an import would have picked up a directory as a package but no
1185 \file{__init__.py} was found. This warning is silently ignored by default;
1186 provide the \programopt{-Wd} option when running the Python executable
1187 to display the warning message.
1188 (Implemented by Thomas Wouters.)
1190 \item The list of base classes in a class definition can now be empty.
1191 As an example, this is now legal:
1193 \begin{verbatim}
1194 class C():
1195 pass
1196 \end{verbatim}
1197 (Implemented by Brett Cannon.)
1199 \end{itemize}
1202 %======================================================================
1203 \subsection{Interactive Interpreter Changes\label{interactive}}
1205 In the interactive interpreter, \code{quit} and \code{exit}
1206 have long been strings so that new users get a somewhat helpful message
1207 when they try to quit:
1209 \begin{verbatim}
1210 >>> quit
1211 'Use Ctrl-D (i.e. EOF) to exit.'
1212 \end{verbatim}
1214 In Python 2.5, \code{quit} and \code{exit} are now objects that still
1215 produce string representations of themselves, but are also callable.
1216 Newbies who try \code{quit()} or \code{exit()} will now exit the
1217 interpreter as they expect. (Implemented by Georg Brandl.)
1219 The Python executable now accepts the standard long options
1220 \longprogramopt{help} and \longprogramopt{version}; on Windows,
1221 it also accepts the \programopt{/?} option for displaying a help message.
1222 (Implemented by Georg Brandl.)
1225 %======================================================================
1226 \subsection{Optimizations\label{opts}}
1228 Several of the optimizations were developed at the NeedForSpeed
1229 sprint, an event held in Reykjavik, Iceland, from May 21--28 2006.
1230 The sprint focused on speed enhancements to the CPython implementation
1231 and was funded by EWT LLC with local support from CCP Games. Those
1232 optimizations added at this sprint are specially marked in the
1233 following list.
1235 \begin{itemize}
1237 \item When they were introduced
1238 in Python 2.4, the built-in \class{set} and \class{frozenset} types
1239 were built on top of Python's dictionary type.
1240 In 2.5 the internal data structure has been customized for implementing sets,
1241 and as a result sets will use a third less memory and are somewhat faster.
1242 (Implemented by Raymond Hettinger.)
1244 \item The speed of some Unicode operations, such as finding
1245 substrings, string splitting, and character map encoding and decoding,
1246 has been improved. (Substring search and splitting improvements were
1247 added by Fredrik Lundh and Andrew Dalke at the NeedForSpeed
1248 sprint. Character maps were improved by Walter D\"orwald and
1249 Martin von~L\"owis.)
1250 % Patch 1313939, 1359618
1252 \item The \function{long(\var{str}, \var{base})} function is now
1253 faster on long digit strings because fewer intermediate results are
1254 calculated. The peak is for strings of around 800--1000 digits where
1255 the function is 6 times faster.
1256 (Contributed by Alan McIntyre and committed at the NeedForSpeed sprint.)
1257 % Patch 1442927
1259 \item The \module{struct} module now compiles structure format
1260 strings into an internal representation and caches this
1261 representation, yielding a 20\% speedup. (Contributed by Bob Ippolito
1262 at the NeedForSpeed sprint.)
1264 \item The \module{re} module got a 1 or 2\% speedup by switching to
1265 Python's allocator functions instead of the system's
1266 \cfunction{malloc()} and \cfunction{free()}.
1267 (Contributed by Jack Diederich at the NeedForSpeed sprint.)
1269 \item The code generator's peephole optimizer now performs
1270 simple constant folding in expressions. If you write something like
1271 \code{a = 2+3}, the code generator will do the arithmetic and produce
1272 code corresponding to \code{a = 5}. (Proposed and implemented
1273 by Raymond Hettinger.)
1275 \item Function calls are now faster because code objects now keep
1276 the most recently finished frame (a ``zombie frame'') in an internal
1277 field of the code object, reusing it the next time the code object is
1278 invoked. (Original patch by Michael Hudson, modified by Armin Rigo
1279 and Richard Jones; committed at the NeedForSpeed sprint.)
1280 % Patch 876206
1282 Frame objects are also slightly smaller, which may improve cache locality
1283 and reduce memory usage a bit. (Contributed by Neal Norwitz.)
1284 % Patch 1337051
1286 \item Python's built-in exceptions are now new-style classes, a change
1287 that speeds up instantiation considerably. Exception handling in
1288 Python 2.5 is therefore about 30\% faster than in 2.4.
1289 (Contributed by Richard Jones, Georg Brandl and Sean Reifschneider at
1290 the NeedForSpeed sprint.)
1292 \item Importing now caches the paths tried, recording whether
1293 they exist or not so that the interpreter makes fewer
1294 \cfunction{open()} and \cfunction{stat()} calls on startup.
1295 (Contributed by Martin von~L\"owis and Georg Brandl.)
1296 % Patch 921466
1298 \end{itemize}
1300 The net result of the 2.5 optimizations is that Python 2.5 runs the
1301 pystone benchmark around XXX\% faster than Python 2.4.
1304 %======================================================================
1305 \section{New, Improved, and Removed Modules\label{modules}}
1307 The standard library received many enhancements and bug fixes in
1308 Python 2.5. Here's a partial list of the most notable changes, sorted
1309 alphabetically by module name. Consult the \file{Misc/NEWS} file in
1310 the source tree for a more complete list of changes, or look through
1311 the SVN logs for all the details.
1313 \begin{itemize}
1315 \item The \module{audioop} module now supports the a-LAW encoding,
1316 and the code for u-LAW encoding has been improved. (Contributed by
1317 Lars Immisch.)
1319 \item The \module{codecs} module gained support for incremental
1320 codecs. The \function{codec.lookup()} function now
1321 returns a \class{CodecInfo} instance instead of a tuple.
1322 \class{CodecInfo} instances behave like a 4-tuple to preserve backward
1323 compatibility but also have the attributes \member{encode},
1324 \member{decode}, \member{incrementalencoder}, \member{incrementaldecoder},
1325 \member{streamwriter}, and \member{streamreader}. Incremental codecs
1326 can receive input and produce output in multiple chunks; the output is
1327 the same as if the entire input was fed to the non-incremental codec.
1328 See the \module{codecs} module documentation for details.
1329 (Designed and implemented by Walter D\"orwald.)
1330 % Patch 1436130
1332 \item The \module{collections} module gained a new type,
1333 \class{defaultdict}, that subclasses the standard \class{dict}
1334 type. The new type mostly behaves like a dictionary but constructs a
1335 default value when a key isn't present, automatically adding it to the
1336 dictionary for the requested key value.
1338 The first argument to \class{defaultdict}'s constructor is a factory
1339 function that gets called whenever a key is requested but not found.
1340 This factory function receives no arguments, so you can use built-in
1341 type constructors such as \function{list()} or \function{int()}. For
1342 example,
1343 you can make an index of words based on their initial letter like this:
1345 \begin{verbatim}
1346 words = """Nel mezzo del cammin di nostra vita
1347 mi ritrovai per una selva oscura
1348 che la diritta via era smarrita""".lower().split()
1350 index = defaultdict(list)
1352 for w in words:
1353 init_letter = w[0]
1354 index[init_letter].append(w)
1355 \end{verbatim}
1357 Printing \code{index} results in the following output:
1359 \begin{verbatim}
1360 defaultdict(<type 'list'>, {'c': ['cammin', 'che'], 'e': ['era'],
1361 'd': ['del', 'di', 'diritta'], 'm': ['mezzo', 'mi'],
1362 'l': ['la'], 'o': ['oscura'], 'n': ['nel', 'nostra'],
1363 'p': ['per'], 's': ['selva', 'smarrita'],
1364 'r': ['ritrovai'], 'u': ['una'], 'v': ['vita', 'via']}
1365 \end{verbatim}
1367 (Contributed by Guido van~Rossum.)
1369 \item The \class{deque} double-ended queue type supplied by the
1370 \module{collections} module now has a \method{remove(\var{value})}
1371 method that removes the first occurrence of \var{value} in the queue,
1372 raising \exception{ValueError} if the value isn't found.
1373 (Contributed by Raymond Hettinger.)
1375 \item New module: The \module{contextlib} module contains helper functions for use
1376 with the new '\keyword{with}' statement. See
1377 section~\ref{module-contextlib} for more about this module.
1379 \item New module: The \module{cProfile} module is a C implementation of
1380 the existing \module{profile} module that has much lower overhead.
1381 The module's interface is the same as \module{profile}: you run
1382 \code{cProfile.run('main()')} to profile a function, can save profile
1383 data to a file, etc. It's not yet known if the Hotshot profiler,
1384 which is also written in C but doesn't match the \module{profile}
1385 module's interface, will continue to be maintained in future versions
1386 of Python. (Contributed by Armin Rigo.)
1388 Also, the \module{pstats} module for analyzing the data measured by
1389 the profiler now supports directing the output to any file object
1390 by supplying a \var{stream} argument to the \class{Stats} constructor.
1391 (Contributed by Skip Montanaro.)
1393 \item The \module{csv} module, which parses files in
1394 comma-separated value format, received several enhancements and a
1395 number of bugfixes. You can now set the maximum size in bytes of a
1396 field by calling the \method{csv.field_size_limit(\var{new_limit})}
1397 function; omitting the \var{new_limit} argument will return the
1398 currently-set limit. The \class{reader} class now has a
1399 \member{line_num} attribute that counts the number of physical lines
1400 read from the source; records can span multiple physical lines, so
1401 \member{line_num} is not the same as the number of records read.
1403 The CSV parser is now stricter about multi-line quoted
1404 fields. Previously, if a line ended within a quoted field without a
1405 terminating newline character, a newline would be inserted into the
1406 returned field. This behavior caused problems when reading files that
1407 contained carriage return characters within fields, so the code was
1408 changed to return the field without inserting newlines. As a
1409 consequence, if newlines embedded within fields are important, the
1410 input should be split into lines in a manner that preserves the
1411 newline characters.
1413 (Contributed by Skip Montanaro and Andrew McNamara.)
1415 \item The \class{datetime} class in the \module{datetime}
1416 module now has a \method{strptime(\var{string}, \var{format})}
1417 method for parsing date strings, contributed by Josh Spoerri.
1418 It uses the same format characters as \function{time.strptime()} and
1419 \function{time.strftime()}:
1421 \begin{verbatim}
1422 from datetime import datetime
1424 ts = datetime.strptime('10:13:15 2006-03-07',
1425 '%H:%M:%S %Y-%m-%d')
1426 \end{verbatim}
1428 \item The \method{SequenceMatcher.get_matching_blocks()} method
1429 in the \module{difflib} module now guarantees to return a minimal list
1430 of blocks describing matching subsequences. Previously, the algorithm would
1431 occasionally break a block of matching elements into two list entries.
1432 (Enhancement by Tim Peters.)
1434 \item The \module{doctest} module gained a \code{SKIP} option that
1435 keeps an example from being executed at all. This is intended for
1436 code snippets that are usage examples intended for the reader and
1437 aren't actually test cases.
1439 An \var{encoding} parameter was added to the \function{testfile()}
1440 function and the \class{DocFileSuite} class to specify the file's
1441 encoding. This makes it easier to use non-ASCII characters in
1442 tests contained within a docstring. (Contributed by Bjorn Tillenius.)
1443 % Patch 1080727
1445 \item The \module{email} package has been updated to version 4.0.
1446 % XXX need to provide some more detail here
1447 (Contributed by Barry Warsaw.)
1449 \item The \module{fileinput} module was made more flexible.
1450 Unicode filenames are now supported, and a \var{mode} parameter that
1451 defaults to \code{"r"} was added to the
1452 \function{input()} function to allow opening files in binary or
1453 universal-newline mode. Another new parameter, \var{openhook},
1454 lets you use a function other than \function{open()}
1455 to open the input files. Once you're iterating over
1456 the set of files, the \class{FileInput} object's new
1457 \method{fileno()} returns the file descriptor for the currently opened file.
1458 (Contributed by Georg Brandl.)
1460 \item In the \module{gc} module, the new \function{get_count()} function
1461 returns a 3-tuple containing the current collection counts for the
1462 three GC generations. This is accounting information for the garbage
1463 collector; when these counts reach a specified threshold, a garbage
1464 collection sweep will be made. The existing \function{gc.collect()}
1465 function now takes an optional \var{generation} argument of 0, 1, or 2
1466 to specify which generation to collect.
1467 (Contributed by Barry Warsaw.)
1469 \item The \function{nsmallest()} and
1470 \function{nlargest()} functions in the \module{heapq} module
1471 now support a \code{key} keyword parameter similar to the one
1472 provided by the \function{min()}/\function{max()} functions
1473 and the \method{sort()} methods. For example:
1475 \begin{verbatim}
1476 >>> import heapq
1477 >>> L = ["short", 'medium', 'longest', 'longer still']
1478 >>> heapq.nsmallest(2, L) # Return two lowest elements, lexicographically
1479 ['longer still', 'longest']
1480 >>> heapq.nsmallest(2, L, key=len) # Return two shortest elements
1481 ['short', 'medium']
1482 \end{verbatim}
1484 (Contributed by Raymond Hettinger.)
1486 \item The \function{itertools.islice()} function now accepts
1487 \code{None} for the start and step arguments. This makes it more
1488 compatible with the attributes of slice objects, so that you can now write
1489 the following:
1491 \begin{verbatim}
1492 s = slice(5) # Create slice object
1493 itertools.islice(iterable, s.start, s.stop, s.step)
1494 \end{verbatim}
1496 (Contributed by Raymond Hettinger.)
1498 \item The \module{mailbox} module underwent a massive rewrite to add
1499 the capability to modify mailboxes in addition to reading them. A new
1500 set of classes that include \class{mbox}, \class{MH}, and
1501 \class{Maildir} are used to read mailboxes, and have an
1502 \method{add(\var{message})} method to add messages,
1503 \method{remove(\var{key})} to remove messages, and
1504 \method{lock()}/\method{unlock()} to lock/unlock the mailbox. The
1505 following example converts a maildir-format mailbox into an mbox-format one:
1507 \begin{verbatim}
1508 import mailbox
1510 # 'factory=None' uses email.Message.Message as the class representing
1511 # individual messages.
1512 src = mailbox.Maildir('maildir', factory=None)
1513 dest = mailbox.mbox('/tmp/mbox')
1515 for msg in src:
1516 dest.add(msg)
1517 \end{verbatim}
1519 (Contributed by Gregory K. Johnson. Funding was provided by Google's
1520 2005 Summer of Code.)
1522 \item New module: the \module{msilib} module allows creating
1523 Microsoft Installer \file{.msi} files and CAB files. Some support
1524 for reading the \file{.msi} database is also included.
1525 (Contributed by Martin von~L\"owis.)
1527 \item The \module{nis} module now supports accessing domains other
1528 than the system default domain by supplying a \var{domain} argument to
1529 the \function{nis.match()} and \function{nis.maps()} functions.
1530 (Contributed by Ben Bell.)
1532 \item The \module{operator} module's \function{itemgetter()}
1533 and \function{attrgetter()} functions now support multiple fields.
1534 A call such as \code{operator.attrgetter('a', 'b')}
1535 will return a function
1536 that retrieves the \member{a} and \member{b} attributes. Combining
1537 this new feature with the \method{sort()} method's \code{key} parameter
1538 lets you easily sort lists using multiple fields.
1539 (Contributed by Raymond Hettinger.)
1541 \item The \module{optparse} module was updated to version 1.5.1 of the
1542 Optik library. The \class{OptionParser} class gained an
1543 \member{epilog} attribute, a string that will be printed after the
1544 help message, and a \method{destroy()} method to break reference
1545 cycles created by the object. (Contributed by Greg Ward.)
1547 \item The \module{os} module underwent several changes. The
1548 \member{stat_float_times} variable now defaults to true, meaning that
1549 \function{os.stat()} will now return time values as floats. (This
1550 doesn't necessarily mean that \function{os.stat()} will return times
1551 that are precise to fractions of a second; not all systems support
1552 such precision.)
1554 Constants named \member{os.SEEK_SET}, \member{os.SEEK_CUR}, and
1555 \member{os.SEEK_END} have been added; these are the parameters to the
1556 \function{os.lseek()} function. Two new constants for locking are
1557 \member{os.O_SHLOCK} and \member{os.O_EXLOCK}.
1559 Two new functions, \function{wait3()} and \function{wait4()}, were
1560 added. They're similar the \function{waitpid()} function which waits
1561 for a child process to exit and returns a tuple of the process ID and
1562 its exit status, but \function{wait3()} and \function{wait4()} return
1563 additional information. \function{wait3()} doesn't take a process ID
1564 as input, so it waits for any child process to exit and returns a
1565 3-tuple of \var{process-id}, \var{exit-status}, \var{resource-usage}
1566 as returned from the \function{resource.getrusage()} function.
1567 \function{wait4(\var{pid})} does take a process ID.
1568 (Contributed by Chad J. Schroeder.)
1570 On FreeBSD, the \function{os.stat()} function now returns
1571 times with nanosecond resolution, and the returned object
1572 now has \member{st_gen} and \member{st_birthtime}.
1573 The \member{st_flags} member is also available, if the platform supports it.
1574 (Contributed by Antti Louko and Diego Petten\`o.)
1575 % (Patch 1180695, 1212117)
1577 \item The Python debugger provided by the \module{pdb} module
1578 can now store lists of commands to execute when a breakpoint is
1579 reached and execution stops. Once breakpoint \#1 has been created,
1580 enter \samp{commands 1} and enter a series of commands to be executed,
1581 finishing the list with \samp{end}. The command list can include
1582 commands that resume execution, such as \samp{continue} or
1583 \samp{next}. (Contributed by Gr\'egoire Dooms.)
1584 % Patch 790710
1586 \item The \module{pickle} and \module{cPickle} modules no
1587 longer accept a return value of \code{None} from the
1588 \method{__reduce__()} method; the method must return a tuple of
1589 arguments instead. The ability to return \code{None} was deprecated
1590 in Python 2.4, so this completes the removal of the feature.
1592 \item The \module{pkgutil} module, containing various utility
1593 functions for finding packages, was enhanced to support PEP 302's
1594 import hooks and now also works for packages stored in ZIP-format archives.
1595 (Contributed by Phillip J. Eby.)
1597 \item The pybench benchmark suite by Marc-Andr\'e~Lemburg is now
1598 included in the \file{Tools/pybench} directory. The pybench suite is
1599 an improvement on the commonly used \file{pystone.py} program because
1600 pybench provides a more detailed measurement of the interpreter's
1601 speed. It times particular operations such as function calls,
1602 tuple slicing, method lookups, and numeric operations, instead of
1603 performing many different operations and reducing the result to a
1604 single number as \file{pystone.py} does.
1606 \item The \module{pyexpat} module now uses version 2.0 of the Expat parser.
1607 (Contributed by Trent Mick.)
1609 \item The old \module{regex} and \module{regsub} modules, which have been
1610 deprecated ever since Python 2.0, have finally been deleted.
1611 Other deleted modules: \module{statcache}, \module{tzparse},
1612 \module{whrandom}.
1614 \item Also deleted: the \file{lib-old} directory,
1615 which includes ancient modules such as \module{dircmp} and
1616 \module{ni}, was removed. \file{lib-old} wasn't on the default
1617 \code{sys.path}, so unless your programs explicitly added the directory to
1618 \code{sys.path}, this removal shouldn't affect your code.
1620 \item The \module{rlcompleter} module is no longer
1621 dependent on importing the \module{readline} module and
1622 therefore now works on non-{\UNIX} platforms.
1623 (Patch from Robert Kiendl.)
1624 % Patch #1472854
1626 \item The \module{SimpleXMLRPCServer} and \module{DocXMLRPCServer}
1627 classes now have a \member{rpc_paths} attribute that constrains
1628 XML-RPC operations to a limited set of URL paths; the default is
1629 to allow only \code{'/'} and \code{'/RPC2'}. Setting
1630 \member{rpc_paths} to \code{None} or an empty tuple disables
1631 this path checking.
1632 % Bug #1473048
1634 \item The \module{socket} module now supports \constant{AF_NETLINK}
1635 sockets on Linux, thanks to a patch from Philippe Biondi.
1636 Netlink sockets are a Linux-specific mechanism for communications
1637 between a user-space process and kernel code; an introductory
1638 article about them is at \url{http://www.linuxjournal.com/article/7356}.
1639 In Python code, netlink addresses are represented as a tuple of 2 integers,
1640 \code{(\var{pid}, \var{group_mask})}.
1642 Two new methods on socket objects, \method{recv_buf(\var{buffer})} and
1643 \method{recvfrom_buf(\var{buffer})}, store the received data in an object
1644 that supports the buffer protocol instead of returning the data as a
1645 string. This means you can put the data directly into an array or a
1646 memory-mapped file.
1648 Socket objects also gained \method{getfamily()}, \method{gettype()},
1649 and \method{getproto()} accessor methods to retrieve the family, type,
1650 and protocol values for the socket.
1652 \item New module: the \module{spwd} module provides functions for
1653 accessing the shadow password database on systems that support
1654 shadow passwords.
1656 \item The \module{struct} is now faster because it
1657 compiles format strings into \class{Struct} objects
1658 with \method{pack()} and \method{unpack()} methods. This is similar
1659 to how the \module{re} module lets you create compiled regular
1660 expression objects. You can still use the module-level
1661 \function{pack()} and \function{unpack()} functions; they'll create
1662 \class{Struct} objects and cache them. Or you can use
1663 \class{Struct} instances directly:
1665 \begin{verbatim}
1666 s = struct.Struct('ih3s')
1668 data = s.pack(1972, 187, 'abc')
1669 year, number, name = s.unpack(data)
1670 \end{verbatim}
1672 You can also pack and unpack data to and from buffer objects directly
1673 using the \method{pack_into(\var{buffer}, \var{offset}, \var{v1},
1674 \var{v2}, ...)} and \method{unpack_from(\var{buffer}, \var{offset})}
1675 methods. This lets you store data directly into an array or a
1676 memory-mapped file.
1678 (\class{Struct} objects were implemented by Bob Ippolito at the
1679 NeedForSpeed sprint. Support for buffer objects was added by Martin
1680 Blais, also at the NeedForSpeed sprint.)
1682 \item The Python developers switched from CVS to Subversion during the 2.5
1683 development process. Information about the exact build version is
1684 available as the \code{sys.subversion} variable, a 3-tuple of
1685 \code{(\var{interpreter-name}, \var{branch-name},
1686 \var{revision-range})}. For example, at the time of writing my copy
1687 of 2.5 was reporting \code{('CPython', 'trunk', '45313:45315')}.
1689 This information is also available to C extensions via the
1690 \cfunction{Py_GetBuildInfo()} function that returns a
1691 string of build information like this:
1692 \code{"trunk:45355:45356M, Apr 13 2006, 07:42:19"}.
1693 (Contributed by Barry Warsaw.)
1695 \item Another new function, \function{sys._current_frames()}, returns
1696 the current stack frames for all running threads as a dictionary
1697 mapping thread identifiers to the topmost stack frame currently active
1698 in that thread at the time the function is called. (Contributed by
1699 Tim Peters.)
1701 \item The \class{TarFile} class in the \module{tarfile} module now has
1702 an \method{extractall()} method that extracts all members from the
1703 archive into the current working directory. It's also possible to set
1704 a different directory as the extraction target, and to unpack only a
1705 subset of the archive's members.
1707 The compression used for a tarfile opened in stream mode can now be
1708 autodetected using the mode \code{'r|*'}.
1709 % patch 918101
1710 (Contributed by Lars Gust\"abel.)
1712 \item The \module{threading} module now lets you set the stack size
1713 used when new threads are created. The
1714 \function{stack_size(\optional{\var{size}})} function returns the
1715 currently configured stack size, and supplying the optional \var{size}
1716 parameter sets a new value. Not all platforms support changing the
1717 stack size, but Windows, POSIX threading, and OS/2 all do.
1718 (Contributed by Andrew MacIntyre.)
1719 % Patch 1454481
1721 \item The \module{unicodedata} module has been updated to use version 4.1.0
1722 of the Unicode character database. Version 3.2.0 is required
1723 by some specifications, so it's still available as
1724 \member{unicodedata.ucd_3_2_0}.
1726 \item New module: the \module{uuid} module generates
1727 universally unique identifiers (UUIDs) according to \rfc{4122}. The
1728 RFC defines several different UUID versions that are generated from a
1729 starting string, from system properties, or purely randomly. This
1730 module contains a \class{UUID} class and
1731 functions named \function{uuid1()},
1732 \function{uuid3()}, \function{uuid4()}, and
1733 \function{uuid5()} to generate different versions of UUID. (Version 2 UUIDs
1734 are not specified in \rfc{4122} and are not supported by this module.)
1736 \begin{verbatim}
1737 >>> import uuid
1738 >>> # make a UUID based on the host ID and current time
1739 >>> uuid.uuid1()
1740 UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')
1742 >>> # make a UUID using an MD5 hash of a namespace UUID and a name
1743 >>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
1744 UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')
1746 >>> # make a random UUID
1747 >>> uuid.uuid4()
1748 UUID('16fd2706-8baf-433b-82eb-8c7fada847da')
1750 >>> # make a UUID using a SHA-1 hash of a namespace UUID and a name
1751 >>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
1752 UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')
1753 \end{verbatim}
1755 (Contributed by Ka-Ping Yee.)
1757 \item The \module{weakref} module's \class{WeakKeyDictionary} and
1758 \class{WeakValueDictionary} types gained new methods for iterating
1759 over the weak references contained in the dictionary.
1760 \method{iterkeyrefs()} and \method{keyrefs()} methods were
1761 added to \class{WeakKeyDictionary}, and
1762 \method{itervaluerefs()} and \method{valuerefs()} were added to
1763 \class{WeakValueDictionary}. (Contributed by Fred L.~Drake, Jr.)
1765 \item The \module{webbrowser} module received a number of
1766 enhancements.
1767 It's now usable as a script with \code{python -m webbrowser}, taking a
1768 URL as the argument; there are a number of switches
1769 to control the behaviour (\programopt{-n} for a new browser window,
1770 \programopt{-t} for a new tab). New module-level functions,
1771 \function{open_new()} and \function{open_new_tab()}, were added
1772 to support this. The module's \function{open()} function supports an
1773 additional feature, an \var{autoraise} parameter that signals whether
1774 to raise the open window when possible. A number of additional
1775 browsers were added to the supported list such as Firefox, Opera,
1776 Konqueror, and elinks. (Contributed by Oleg Broytmann and Georg
1777 Brandl.)
1778 % Patch #754022
1780 \item The \module{xmlrpclib} module now supports returning
1781 \class{datetime} objects for the XML-RPC date type. Supply
1782 \code{use_datetime=True} to the \function{loads()} function
1783 or the \class{Unmarshaller} class to enable this feature.
1784 (Contributed by Skip Montanaro.)
1785 % Patch 1120353
1787 \item The \module{zipfile} module now supports the ZIP64 version of the
1788 format, meaning that a .zip archive can now be larger than 4~GiB and
1789 can contain individual files larger than 4~GiB. (Contributed by
1790 Ronald Oussoren.)
1791 % Patch 1446489
1793 \item The \module{zlib} module's \class{Compress} and \class{Decompress}
1794 objects now support a \method{copy()} method that makes a copy of the
1795 object's internal state and returns a new
1796 \class{Compress} or \class{Decompress} object.
1797 (Contributed by Chris AtLee.)
1798 % Patch 1435422
1800 \end{itemize}
1804 %======================================================================
1805 \subsection{The ctypes package\label{module-ctypes}}
1807 The \module{ctypes} package, written by Thomas Heller, has been added
1808 to the standard library. \module{ctypes} lets you call arbitrary functions
1809 in shared libraries or DLLs. Long-time users may remember the \module{dl} module, which
1810 provides functions for loading shared libraries and calling functions in them. The \module{ctypes} package is much fancier.
1812 To load a shared library or DLL, you must create an instance of the
1813 \class{CDLL} class and provide the name or path of the shared library
1814 or DLL. Once that's done, you can call arbitrary functions
1815 by accessing them as attributes of the \class{CDLL} object.
1817 \begin{verbatim}
1818 import ctypes
1820 libc = ctypes.CDLL('libc.so.6')
1821 result = libc.printf("Line of output\n")
1822 \end{verbatim}
1824 Type constructors for the various C types are provided: \function{c_int},
1825 \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
1826 to change the wrapped value. Python integers and strings will be automatically
1827 converted to the corresponding C types, but for other types you
1828 must call the correct type constructor. (And I mean \emph{must};
1829 getting it wrong will often result in the interpreter crashing
1830 with a segmentation fault.)
1832 You 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
1833 supposed to be immutable; breaking this rule will cause puzzling bugs. When you need a modifiable memory area,
1834 use \function{create_string_buffer()}:
1836 \begin{verbatim}
1837 s = "this is a string"
1838 buf = ctypes.create_string_buffer(s)
1839 libc.strfry(buf)
1840 \end{verbatim}
1842 C functions are assumed to return integers, but you can set
1843 the \member{restype} attribute of the function object to
1844 change this:
1846 \begin{verbatim}
1847 >>> libc.atof('2.71828')
1848 -1783957616
1849 >>> libc.atof.restype = ctypes.c_double
1850 >>> libc.atof('2.71828')
1851 2.71828
1852 \end{verbatim}
1854 \module{ctypes} also provides a wrapper for Python's C API
1855 as the \code{ctypes.pythonapi} object. This object does \emph{not}
1856 release the global interpreter lock before calling a function, because the lock must be held when calling into the interpreter's code.
1857 There's a \class{py_object()} type constructor that will create a
1858 \ctype{PyObject *} pointer. A simple usage:
1860 \begin{verbatim}
1861 import ctypes
1863 d = {}
1864 ctypes.pythonapi.PyObject_SetItem(ctypes.py_object(d),
1865 ctypes.py_object("abc"), ctypes.py_object(1))
1866 # d is now {'abc', 1}.
1867 \end{verbatim}
1869 Don't forget to use \class{py_object()}; if it's omitted you end
1870 up with a segmentation fault.
1872 \module{ctypes} has been around for a while, but people still write
1873 and distribution hand-coded extension modules because you can't rely on \module{ctypes} being present.
1874 Perhaps developers will begin to write
1875 Python wrappers atop a library accessed through \module{ctypes} instead
1876 of extension modules, now that \module{ctypes} is included with core Python.
1878 \begin{seealso}
1880 \seeurl{http://starship.python.net/crew/theller/ctypes/}
1881 {The ctypes web page, with a tutorial, reference, and FAQ.}
1883 \seeurl{../lib/module-ctypes.html}{The documentation
1884 for the \module{ctypes} module.}
1886 \end{seealso}
1889 %======================================================================
1890 \subsection{The ElementTree package\label{module-etree}}
1892 A subset of Fredrik Lundh's ElementTree library for processing XML has
1893 been added to the standard library as \module{xml.etree}. The
1894 available modules are
1895 \module{ElementTree}, \module{ElementPath}, and
1896 \module{ElementInclude} from ElementTree 1.2.6.
1897 The \module{cElementTree} accelerator module is also included.
1899 The rest of this section will provide a brief overview of using
1900 ElementTree. Full documentation for ElementTree is available at
1901 \url{http://effbot.org/zone/element-index.htm}.
1903 ElementTree represents an XML document as a tree of element nodes.
1904 The text content of the document is stored as the \member{.text}
1905 and \member{.tail} attributes of
1906 (This is one of the major differences between ElementTree and
1907 the Document Object Model; in the DOM there are many different
1908 types of node, including \class{TextNode}.)
1910 The most commonly used parsing function is \function{parse()}, that
1911 takes either a string (assumed to contain a filename) or a file-like
1912 object and returns an \class{ElementTree} instance:
1914 \begin{verbatim}
1915 from xml.etree import ElementTree as ET
1917 tree = ET.parse('ex-1.xml')
1919 feed = urllib.urlopen(
1920 'http://planet.python.org/rss10.xml')
1921 tree = ET.parse(feed)
1922 \end{verbatim}
1924 Once you have an \class{ElementTree} instance, you
1925 can call its \method{getroot()} method to get the root \class{Element} node.
1927 There's also an \function{XML()} function that takes a string literal
1928 and returns an \class{Element} node (not an \class{ElementTree}).
1929 This function provides a tidy way to incorporate XML fragments,
1930 approaching the convenience of an XML literal:
1932 \begin{verbatim}
1933 svg = ET.XML("""<svg width="10px" version="1.0">
1934 </svg>""")
1935 svg.set('height', '320px')
1936 svg.append(elem1)
1937 \end{verbatim}
1939 Each XML element supports some dictionary-like and some list-like
1940 access methods. Dictionary-like operations are used to access attribute
1941 values, and list-like operations are used to access child nodes.
1943 \begin{tableii}{c|l}{code}{Operation}{Result}
1944 \lineii{elem[n]}{Returns n'th child element.}
1945 \lineii{elem[m:n]}{Returns list of m'th through n'th child elements.}
1946 \lineii{len(elem)}{Returns number of child elements.}
1947 \lineii{list(elem)}{Returns list of child elements.}
1948 \lineii{elem.append(elem2)}{Adds \var{elem2} as a child.}
1949 \lineii{elem.insert(index, elem2)}{Inserts \var{elem2} at the specified location.}
1950 \lineii{del elem[n]}{Deletes n'th child element.}
1951 \lineii{elem.keys()}{Returns list of attribute names.}
1952 \lineii{elem.get(name)}{Returns value of attribute \var{name}.}
1953 \lineii{elem.set(name, value)}{Sets new value for attribute \var{name}.}
1954 \lineii{elem.attrib}{Retrieves the dictionary containing attributes.}
1955 \lineii{del elem.attrib[name]}{Deletes attribute \var{name}.}
1956 \end{tableii}
1958 Comments and processing instructions are also represented as
1959 \class{Element} nodes. To check if a node is a comment or processing
1960 instructions:
1962 \begin{verbatim}
1963 if elem.tag is ET.Comment:
1965 elif elem.tag is ET.ProcessingInstruction:
1967 \end{verbatim}
1969 To generate XML output, you should call the
1970 \method{ElementTree.write()} method. Like \function{parse()},
1971 it can take either a string or a file-like object:
1973 \begin{verbatim}
1974 # Encoding is US-ASCII
1975 tree.write('output.xml')
1977 # Encoding is UTF-8
1978 f = open('output.xml', 'w')
1979 tree.write(f, encoding='utf-8')
1980 \end{verbatim}
1982 (Caution: the default encoding used for output is ASCII. For general
1983 XML work, where an element's name may contain arbitrary Unicode
1984 characters, ASCII isn't a very useful encoding because it will raise
1985 an exception if an element's name contains any characters with values
1986 greater than 127. Therefore, it's best to specify a different
1987 encoding such as UTF-8 that can handle any Unicode character.)
1989 This section is only a partial description of the ElementTree interfaces.
1990 Please read the package's official documentation for more details.
1992 \begin{seealso}
1994 \seeurl{http://effbot.org/zone/element-index.htm}
1995 {Official documentation for ElementTree.}
1997 \end{seealso}
2000 %======================================================================
2001 \subsection{The hashlib package\label{module-hashlib}}
2003 A new \module{hashlib} module, written by Gregory P. Smith,
2004 has been added to replace the
2005 \module{md5} and \module{sha} modules. \module{hashlib} adds support
2006 for additional secure hashes (SHA-224, SHA-256, SHA-384, and SHA-512).
2007 When available, the module uses OpenSSL for fast platform optimized
2008 implementations of algorithms.
2010 The old \module{md5} and \module{sha} modules still exist as wrappers
2011 around hashlib to preserve backwards compatibility. The new module's
2012 interface is very close to that of the old modules, but not identical.
2013 The most significant difference is that the constructor functions
2014 for creating new hashing objects are named differently.
2016 \begin{verbatim}
2017 # Old versions
2018 h = md5.md5()
2019 h = md5.new()
2021 # New version
2022 h = hashlib.md5()
2024 # Old versions
2025 h = sha.sha()
2026 h = sha.new()
2028 # New version
2029 h = hashlib.sha1()
2031 # Hash that weren't previously available
2032 h = hashlib.sha224()
2033 h = hashlib.sha256()
2034 h = hashlib.sha384()
2035 h = hashlib.sha512()
2037 # Alternative form
2038 h = hashlib.new('md5') # Provide algorithm as a string
2039 \end{verbatim}
2041 Once a hash object has been created, its methods are the same as before:
2042 \method{update(\var{string})} hashes the specified string into the
2043 current digest state, \method{digest()} and \method{hexdigest()}
2044 return the digest value as a binary string or a string of hex digits,
2045 and \method{copy()} returns a new hashing object with the same digest state.
2047 \begin{seealso}
2049 \seeurl{../lib/module-hashlib.html}{The documentation
2050 for the \module{hashlib} module.}
2052 \end{seealso}
2055 %======================================================================
2056 \subsection{The sqlite3 package\label{module-sqlite}}
2058 The pysqlite module (\url{http://www.pysqlite.org}), a wrapper for the
2059 SQLite embedded database, has been added to the standard library under
2060 the package name \module{sqlite3}.
2062 SQLite is a C library that provides a SQL-language database that
2063 stores data in disk files without requiring a separate server process.
2064 pysqlite was written by Gerhard H\"aring and provides a SQL interface
2065 compliant with the DB-API 2.0 specification described by
2066 \pep{249}. This means that it should be possible to write the first
2067 version of your applications using SQLite for data storage. If
2068 switching to a larger database such as PostgreSQL or Oracle is
2069 later necessary, the switch should be relatively easy.
2071 If you're compiling the Python source yourself, note that the source
2072 tree doesn't include the SQLite code, only the wrapper module.
2073 You'll need to have the SQLite libraries and headers installed before
2074 compiling Python, and the build process will compile the module when
2075 the necessary headers are available.
2077 To use the module, you must first create a \class{Connection} object
2078 that represents the database. Here the data will be stored in the
2079 \file{/tmp/example} file:
2081 \begin{verbatim}
2082 conn = sqlite3.connect('/tmp/example')
2083 \end{verbatim}
2085 You can also supply the special name \samp{:memory:} to create
2086 a database in RAM.
2088 Once you have a \class{Connection}, you can create a \class{Cursor}
2089 object and call its \method{execute()} method to perform SQL commands:
2091 \begin{verbatim}
2092 c = conn.cursor()
2094 # Create table
2095 c.execute('''create table stocks
2096 (date timestamp, trans varchar, symbol varchar,
2097 qty decimal, price decimal)''')
2099 # Insert a row of data
2100 c.execute("""insert into stocks
2101 values ('2006-01-05','BUY','RHAT',100,35.14)""")
2102 \end{verbatim}
2104 Usually your SQL operations will need to use values from Python
2105 variables. You shouldn't assemble your query using Python's string
2106 operations because doing so is insecure; it makes your program
2107 vulnerable to an SQL injection attack.
2109 Instead, use the DB-API's parameter substitution. Put \samp{?} as a
2110 placeholder wherever you want to use a value, and then provide a tuple
2111 of values as the second argument to the cursor's \method{execute()}
2112 method. (Other database modules may use a different placeholder,
2113 such as \samp{\%s} or \samp{:1}.) For example:
2115 \begin{verbatim}
2116 # Never do this -- insecure!
2117 symbol = 'IBM'
2118 c.execute("... where symbol = '%s'" % symbol)
2120 # Do this instead
2121 t = (symbol,)
2122 c.execute('select * from stocks where symbol=?', t)
2124 # Larger example
2125 for t in (('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
2126 ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
2127 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
2129 c.execute('insert into stocks values (?,?,?,?,?)', t)
2130 \end{verbatim}
2132 To retrieve data after executing a SELECT statement, you can either
2133 treat the cursor as an iterator, call the cursor's \method{fetchone()}
2134 method to retrieve a single matching row,
2135 or call \method{fetchall()} to get a list of the matching rows.
2137 This example uses the iterator form:
2139 \begin{verbatim}
2140 >>> c = conn.cursor()
2141 >>> c.execute('select * from stocks order by price')
2142 >>> for row in c:
2143 ... print row
2145 (u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001)
2146 (u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
2147 (u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
2148 (u'2006-04-05', u'BUY', u'MSOFT', 1000, 72.0)
2150 \end{verbatim}
2152 For more information about the SQL dialect supported by SQLite, see
2153 \url{http://www.sqlite.org}.
2155 \begin{seealso}
2157 \seeurl{http://www.pysqlite.org}
2158 {The pysqlite web page.}
2160 \seeurl{http://www.sqlite.org}
2161 {The SQLite web page; the documentation describes the syntax and the
2162 available data types for the supported SQL dialect.}
2164 \seeurl{../lib/module-sqlite3.html}{The documentation
2165 for the \module{sqlite3} module.}
2167 \seepep{249}{Database API Specification 2.0}{PEP written by
2168 Marc-Andr\'e Lemburg.}
2170 \end{seealso}
2173 %======================================================================
2174 \subsection{The wsgiref package\label{module-wsgiref}}
2176 % XXX should this be in a PEP 333 section instead?
2178 The Web Server Gateway Interface (WSGI) v1.0 defines a standard
2179 interface between web servers and Python web applications and is
2180 described in \pep{333}. The \module{wsgiref} package is a reference
2181 implementation of the WSGI specification.
2183 The package includes a basic HTTP server that will run a WSGI
2184 application; this server is useful for debugging but isn't intended for
2185 production use. Setting up a server takes only a few lines of code:
2187 \begin{verbatim}
2188 from wsgiref import simple_server
2190 wsgi_app = ...
2192 host = ''
2193 port = 8000
2194 httpd = simple_server.make_server(host, port, wsgi_app)
2195 httpd.serve_forever()
2196 \end{verbatim}
2198 % XXX discuss structure of WSGI applications?
2199 % XXX provide an example using Django or some other framework?
2201 \begin{seealso}
2203 \seeurl{http://www.wsgi.org}{A central web site for WSGI-related resources.}
2205 \seepep{333}{Python Web Server Gateway Interface v1.0}{PEP written by
2206 Phillip J. Eby.}
2208 \end{seealso}
2211 % ======================================================================
2212 \section{Build and C API Changes\label{build-api}}
2214 Changes to Python's build process and to the C API include:
2216 \begin{itemize}
2218 \item The Python source tree was converted from CVS to Subversion,
2219 in a complex migration procedure that was supervised and flawlessly
2220 carried out by Martin von~L\"owis. The procedure was developed as
2221 \pep{347}.
2223 \item Coverity, a company that markets a source code analysis tool
2224 called Prevent, provided the results of their examination of the Python
2225 source code. The analysis found about 60 bugs that
2226 were quickly fixed. Many of the bugs were refcounting problems, often
2227 occurring in error-handling code. See
2228 \url{http://scan.coverity.com} for the statistics.
2230 \item The largest change to the C API came from \pep{353},
2231 which modifies the interpreter to use a \ctype{Py_ssize_t} type
2232 definition instead of \ctype{int}. See the earlier
2233 section~\ref{pep-353} for a discussion of this change.
2235 \item The design of the bytecode compiler has changed a great deal,
2236 no longer generating bytecode by traversing the parse tree. Instead
2237 the parse tree is converted to an abstract syntax tree (or AST), and it is
2238 the abstract syntax tree that's traversed to produce the bytecode.
2240 It's possible for Python code to obtain AST objects by using the
2241 \function{compile()} built-in and specifying \code{_ast.PyCF_ONLY_AST}
2242 as the value of the
2243 \var{flags} parameter:
2245 \begin{verbatim}
2246 from _ast import PyCF_ONLY_AST
2247 ast = compile("""a=0
2248 for i in range(10):
2249 a += i
2250 """, "<string>", 'exec', PyCF_ONLY_AST)
2252 assignment = ast.body[0]
2253 for_loop = ast.body[1]
2254 \end{verbatim}
2256 No official documentation has been written for the AST code yet, but
2257 \pep{339} discusses the design. To start learning about the code, read the
2258 definition of the various AST nodes in \file{Parser/Python.asdl}. A
2259 Python script reads this file and generates a set of C structure
2260 definitions in \file{Include/Python-ast.h}. The
2261 \cfunction{PyParser_ASTFromString()} and
2262 \cfunction{PyParser_ASTFromFile()}, defined in
2263 \file{Include/pythonrun.h}, take Python source as input and return the
2264 root of an AST representing the contents. This AST can then be turned
2265 into a code object by \cfunction{PyAST_Compile()}. For more
2266 information, read the source code, and then ask questions on
2267 python-dev.
2269 % List of names taken from Jeremy's python-dev post at
2270 % http://mail.python.org/pipermail/python-dev/2005-October/057500.html
2271 The AST code was developed under Jeremy Hylton's management, and
2272 implemented by (in alphabetical order) Brett Cannon, Nick Coghlan,
2273 Grant Edwards, John Ehresman, Kurt Kaiser, Neal Norwitz, Tim Peters,
2274 Armin Rigo, and Neil Schemenauer, plus the participants in a number of
2275 AST sprints at conferences such as PyCon.
2277 \item Evan Jones's patch to obmalloc, first described in a talk
2278 at PyCon DC 2005, was applied. Python 2.4 allocated small objects in
2279 256K-sized arenas, but never freed arenas. With this patch, Python
2280 will free arenas when they're empty. The net effect is that on some
2281 platforms, when you allocate many objects, Python's memory usage may
2282 actually drop when you delete them and the memory may be returned to
2283 the operating system. (Implemented by Evan Jones, and reworked by Tim
2284 Peters.)
2286 Note that this change means extension modules must be more careful
2287 when allocating memory. Python's API has many different
2288 functions for allocating memory that are grouped into families. For
2289 example, \cfunction{PyMem_Malloc()}, \cfunction{PyMem_Realloc()}, and
2290 \cfunction{PyMem_Free()} are one family that allocates raw memory,
2291 while \cfunction{PyObject_Malloc()}, \cfunction{PyObject_Realloc()},
2292 and \cfunction{PyObject_Free()} are another family that's supposed to
2293 be used for creating Python objects.
2295 Previously these different families all reduced to the platform's
2296 \cfunction{malloc()} and \cfunction{free()} functions. This meant
2297 it didn't matter if you got things wrong and allocated memory with the
2298 \cfunction{PyMem} function but freed it with the \cfunction{PyObject}
2299 function. With 2.5's changes to obmalloc, these families now do different
2300 things and mismatches will probably result in a segfault. You should
2301 carefully test your C extension modules with Python 2.5.
2303 \item The built-in set types now have an official C API. Call
2304 \cfunction{PySet_New()} and \cfunction{PyFrozenSet_New()} to create a
2305 new set, \cfunction{PySet_Add()} and \cfunction{PySet_Discard()} to
2306 add and remove elements, and \cfunction{PySet_Contains} and
2307 \cfunction{PySet_Size} to examine the set's state.
2308 (Contributed by Raymond Hettinger.)
2310 \item C code can now obtain information about the exact revision
2311 of the Python interpreter by calling the
2312 \cfunction{Py_GetBuildInfo()} function that returns a
2313 string of build information like this:
2314 \code{"trunk:45355:45356M, Apr 13 2006, 07:42:19"}.
2315 (Contributed by Barry Warsaw.)
2317 \item Two new macros can be used to indicate C functions that are
2318 local to the current file so that a faster calling convention can be
2319 used. \cfunction{Py_LOCAL(\var{type})} declares the function as
2320 returning a value of the specified \var{type} and uses a fast-calling
2321 qualifier. \cfunction{Py_LOCAL_INLINE(\var{type})} does the same thing
2322 and also requests the function be inlined. If
2323 \cfunction{PY_LOCAL_AGGRESSIVE} is defined before \file{python.h} is
2324 included, a set of more aggressive optimizations are enabled for the
2325 module; you should benchmark the results to find out if these
2326 optimizations actually make the code faster. (Contributed by Fredrik
2327 Lundh at the NeedForSpeed sprint.)
2329 \item \cfunction{PyErr_NewException(\var{name}, \var{base},
2330 \var{dict})} can now accept a tuple of base classes as its \var{base}
2331 argument. (Contributed by Georg Brandl.)
2333 \item The \cfunction{PyErr_Warn()} function for issuing warnings
2334 is now deprecated in favour of \cfunction{PyErr_WarnEx(category,
2335 message, stacklevel)} which lets you specify the number of stack
2336 frames separating this function and the caller. A \var{stacklevel} of
2337 1 is the function calling \cfunction{PyErr_WarnEx()}, 2 is the
2338 function above that, and so forth. (Added by Neal Norwitz.)
2340 \item The CPython interpreter is still written in C, but
2341 the code can now be compiled with a {\Cpp} compiler without errors.
2342 (Implemented by Anthony Baxter, Martin von~L\"owis, Skip Montanaro.)
2344 \item The \cfunction{PyRange_New()} function was removed. It was
2345 never documented, never used in the core code, and had dangerously lax
2346 error checking. In the unlikely case that your extensions were using
2347 it, you can replace it by something like the following:
2348 \begin{verbatim}
2349 range = PyObject_CallFunction((PyObject*) &PyRange_Type, "lll",
2350 start, stop, step);
2351 \end{verbatim}
2353 \end{itemize}
2356 %======================================================================
2357 \subsection{Port-Specific Changes\label{ports}}
2359 \begin{itemize}
2361 \item MacOS X (10.3 and higher): dynamic loading of modules
2362 now uses the \cfunction{dlopen()} function instead of MacOS-specific
2363 functions.
2365 \item MacOS X: a \longprogramopt{enable-universalsdk} switch was added
2366 to the \program{configure} script that compiles the interpreter as a
2367 universal binary able to run on both PowerPC and Intel processors.
2368 (Contributed by Ronald Oussoren.)
2370 \item Windows: \file{.dll} is no longer supported as a filename extension for
2371 extension modules. \file{.pyd} is now the only filename extension that will
2372 be searched for.
2374 \end{itemize}
2377 %======================================================================
2378 \section{Porting to Python 2.5\label{porting}}
2380 This section lists previously described changes that may require
2381 changes to your code:
2383 \begin{itemize}
2385 \item ASCII is now the default encoding for modules. It's now
2386 a syntax error if a module contains string literals with 8-bit
2387 characters but doesn't have an encoding declaration. In Python 2.4
2388 this triggered a warning, not a syntax error.
2390 \item Previously, the \member{gi_frame} attribute of a generator
2391 was always a frame object. Because of the \pep{342} changes
2392 described in section~\ref{pep-342}, it's now possible
2393 for \member{gi_frame} to be \code{None}.
2395 \item Library: the \module{csv} module is now stricter about multi-line quoted
2396 fields. If your files contain newlines embedded within fields, the
2397 input should be split into lines in a manner which preserves the
2398 newline characters.
2400 \item Library: The \module{pickle} and \module{cPickle} modules no
2401 longer accept a return value of \code{None} from the
2402 \method{__reduce__()} method; the method must return a tuple of
2403 arguments instead. The modules also no longer accept the deprecated
2404 \var{bin} keyword parameter.
2406 \item Library: The \module{SimpleXMLRPCServer} and \module{DocXMLRPCServer}
2407 classes now have a \member{rpc_paths} attribute that constrains
2408 XML-RPC operations to a limited set of URL paths; the default is
2409 to allow only \code{'/'} and \code{'/RPC2'}. Setting
2410 \member{rpc_paths} to \code{None} or an empty tuple disables
2411 this path checking.
2413 \item C API: Many functions now use \ctype{Py_ssize_t}
2414 instead of \ctype{int} to allow processing more data on 64-bit
2415 machines. Extension code may need to make the same change to avoid
2416 warnings and to support 64-bit machines. See the earlier
2417 section~\ref{pep-353} for a discussion of this change.
2419 \item C API:
2420 The obmalloc changes mean that
2421 you must be careful to not mix usage
2422 of the \cfunction{PyMem_*()} and \cfunction{PyObject_*()}
2423 families of functions. Memory allocated with
2424 one family's \cfunction{*_Malloc()} must be
2425 freed with the corresponding family's \cfunction{*_Free()} function.
2427 \end{itemize}
2430 %======================================================================
2431 \section{Acknowledgements \label{acks}}
2433 The author would like to thank the following people for offering
2434 suggestions, corrections and assistance with various drafts of this
2435 article: Nick Coghlan, Phillip J. Eby, Lars Gust\"abel, Raymond Hettinger, Ralf
2436 W. Grosse-Kunstleve, Kent Johnson, Martin von~L\"owis, Fredrik Lundh,
2437 Andrew McNamara, Skip Montanaro,
2438 Gustavo Niemeyer, Paul Prescod, James Pryor, Mike Rovner, Scott Weikart, Barry
2439 Warsaw, Thomas Wouters.
2441 \end{document}