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