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