Mention string improvements
[python.git] / Doc / whatsnew / whatsnew25.tex
blobacb5bdb2396fd306a7fc466e790049707d89ccf1
1 \documentclass{howto}
2 \usepackage{distutils}
3 % $Id$
5 % Fix XXX comments
6 % Count up the patches and bugs
8 \title{What's New in Python 2.5}
9 \release{0.2}
10 \author{A.M. Kuchling}
11 \authoraddress{\email{amk@amk.ca}}
13 \begin{document}
14 \maketitle
15 \tableofcontents
17 This article explains the new features in Python 2.5. No release date
18 for Python 2.5 has been set; it will probably be released in the
19 autumn of 2006. \pep{356} describes the planned release schedule.
21 Comments, suggestions, and error reports are welcome; please e-mail them
22 to the author or open a bug in the Python bug tracker.
24 % XXX Compare with previous release in 2 - 3 sentences here.
26 This article doesn't attempt to provide a complete specification of
27 the new features, but instead provides a convenient overview. For
28 full details, you should refer to the documentation for Python 2.5.
29 % XXX add hyperlink when the documentation becomes available online.
30 If you want to understand the complete implementation and design
31 rationale, refer to the PEP for a particular new feature.
34 %======================================================================
35 \section{PEP 308: Conditional Expressions\label{pep-308}}
37 For a long time, people have been requesting a way to write
38 conditional expressions, expressions that return value A or value B
39 depending on whether a Boolean value is true or false. A conditional
40 expression lets you write a single assignment statement that has the
41 same effect as the following:
43 \begin{verbatim}
44 if condition:
45 x = true_value
46 else:
47 x = false_value
48 \end{verbatim}
50 There have been endless tedious discussions of syntax on both
51 python-dev and comp.lang.python. A vote was even held that found the
52 majority of voters wanted conditional expressions in some form,
53 but there was no syntax that was preferred by a clear majority.
54 Candidates included C's \code{cond ? true_v : false_v},
55 \code{if cond then true_v else false_v}, and 16 other variations.
57 GvR eventually chose a surprising syntax:
59 \begin{verbatim}
60 x = true_value if condition else false_value
61 \end{verbatim}
63 Evaluation is still lazy as in existing Boolean expressions, so the
64 order of evaluation jumps around a bit. The \var{condition}
65 expression in the middle is evaluated first, and the \var{true_value}
66 expression is evaluated only if the condition was true. Similarly,
67 the \var{false_value} expression is only evaluated when the condition
68 is false.
70 This syntax may seem strange and backwards; why does the condition go
71 in the \emph{middle} of the expression, and not in the front as in C's
72 \code{c ? x : y}? The decision was checked by applying the new syntax
73 to the modules in the standard library and seeing how the resulting
74 code read. In many cases where a conditional expression is used, one
75 value seems to be the 'common case' and one value is an 'exceptional
76 case', used only on rarer occasions when the condition isn't met. The
77 conditional syntax makes this pattern a bit more obvious:
79 \begin{verbatim}
80 contents = ((doc + '\n') if doc else '')
81 \end{verbatim}
83 I read the above statement as meaning ``here \var{contents} is
84 usually assigned a value of \code{doc+'\e n'}; sometimes
85 \var{doc} is empty, in which special case an empty string is returned.''
86 I doubt I will use conditional expressions very often where there
87 isn't a clear common and uncommon case.
89 There was some discussion of whether the language should require
90 surrounding conditional expressions with parentheses. The decision
91 was made to \emph{not} require parentheses in the Python language's
92 grammar, but as a matter of style I think you should always use them.
93 Consider these two statements:
95 \begin{verbatim}
96 # First version -- no parens
97 level = 1 if logging else 0
99 # Second version -- with parens
100 level = (1 if logging else 0)
101 \end{verbatim}
103 In the first version, I think a reader's eye might group the statement
104 into 'level = 1', 'if logging', 'else 0', and think that the condition
105 decides whether the assignment to \var{level} is performed. The
106 second version reads better, in my opinion, because it makes it clear
107 that the assignment is always performed and the choice is being made
108 between two values.
110 Another reason for including the brackets: a few odd combinations of
111 list comprehensions and lambdas could look like incorrect conditional
112 expressions. See \pep{308} for some examples. If you put parentheses
113 around your conditional expressions, you won't run into this case.
116 \begin{seealso}
118 \seepep{308}{Conditional Expressions}{PEP written by
119 Guido van~Rossum and Raymond D. Hettinger; implemented by Thomas
120 Wouters.}
122 \end{seealso}
125 %======================================================================
126 \section{PEP 309: Partial Function Application\label{pep-309}}
128 The \module{functional} module is intended to contain tools for
129 functional-style programming. Currently it only contains a
130 \class{partial()} function, but new functions will probably be added
131 in future versions of Python.
133 For programs written in a functional style, it can be useful 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'',
138 and is provided by the \class{partial} class in the new
139 \module{functional} module.
141 The constructor for \class{partial} takes the arguments
142 \code{(\var{function}, \var{arg1}, \var{arg2}, ...
143 \var{kwarg1}=\var{value1}, \var{kwarg2}=\var{value2})}. The resulting
144 object is callable, so you can just call it to invoke \var{function}
145 with the filled-in arguments.
147 Here's a small but realistic example:
149 \begin{verbatim}
150 import functional
152 def log (message, subsystem):
153 "Write the contents of 'message' to the specified subsystem."
154 print '%s: %s' % (subsystem, message)
157 server_log = functional.partial(log, subsystem='server')
158 server_log('Unable to open socket')
159 \end{verbatim}
161 Here's another example, from a program that uses PyGTk. Here a
162 context-sensitive pop-up menu is being constructed dynamically. The
163 callback provided for the menu option is a partially applied version
164 of the \method{open_item()} method, where the first argument has been
165 provided.
167 \begin{verbatim}
169 class Application:
170 def open_item(self, path):
172 def init (self):
173 open_func = functional.partial(self.open_item, item_path)
174 popup_menu.append( ("Open", open_func, 1) )
175 \end{verbatim}
178 \begin{seealso}
180 \seepep{309}{Partial Function Application}{PEP proposed and written by
181 Peter Harris; implemented by Hye-Shik Chang, with adaptations by
182 Raymond Hettinger.}
184 \end{seealso}
187 %======================================================================
188 \section{PEP 314: Metadata for Python Software Packages v1.1\label{pep-314}}
190 Some simple dependency support was added to Distutils. The
191 \function{setup()} function now has \code{requires}, \code{provides},
192 and \code{obsoletes} keyword parameters. When you build a source
193 distribution using the \code{sdist} command, the dependency
194 information will be recorded in the \file{PKG-INFO} file.
196 Another new keyword parameter is \code{download_url}, which should be
197 set to a URL for the package's source code. This means it's now
198 possible to look up an entry in the package index, determine the
199 dependencies for a package, and download the required packages.
201 \begin{verbatim}
202 VERSION = '1.0'
203 setup(name='PyPackage',
204 version=VERSION,
205 requires=['numarray', 'zlib (>=1.1.4)'],
206 obsoletes=['OldPackage']
207 download_url=('http://www.example.com/pypackage/dist/pkg-%s.tar.gz'
208 % VERSION),
210 \end{verbatim}
212 Another new enhancement to the Python package index at
213 \url{http://cheeseshop.python.org} is storing source and binary
214 archives for a package. The new \command{upload} Distutils command
215 will upload a package to the repository.
217 Before a package can be uploaded, you must be able to build a
218 distribution using the \command{sdist} Distutils command. Once that
219 works, you can run \code{python setup.py upload} to add your package
220 to the PyPI archive. Optionally you can GPG-sign the package by
221 supplying the \longprogramopt{sign} and
222 \longprogramopt{identity} options.
224 Package uploading was implemented by Martin von~L\"owis and Richard Jones.
226 \begin{seealso}
228 \seepep{314}{Metadata for Python Software Packages v1.1}{PEP proposed
229 and written by A.M. Kuchling, Richard Jones, and Fred Drake;
230 implemented by Richard Jones and Fred Drake.}
232 \end{seealso}
235 %======================================================================
236 \section{PEP 328: Absolute and Relative Imports\label{pep-328}}
238 The simpler part of PEP 328 was implemented in Python 2.4: parentheses
239 could now be used to enclose the names imported from a module using
240 the \code{from ... import ...} statement, making it easier to import
241 many different names.
243 The more complicated part has been implemented in Python 2.5:
244 importing a module can be specified to use absolute or
245 package-relative imports. The plan is to move toward making absolute
246 imports the default in future versions of Python.
248 Let's say you have a package directory like this:
249 \begin{verbatim}
250 pkg/
251 pkg/__init__.py
252 pkg/main.py
253 pkg/string.py
254 \end{verbatim}
256 This defines a package named \module{pkg} containing the
257 \module{pkg.main} and \module{pkg.string} submodules.
259 Consider the code in the \file{main.py} module. What happens if it
260 executes the statement \code{import string}? In Python 2.4 and
261 earlier, it will first look in the package's directory to perform a
262 relative import, finds \file{pkg/string.py}, imports the contents of
263 that file as the \module{pkg.string} module, and that module is bound
264 to the name \samp{string} in the \module{pkg.main} module's namespace.
266 That's fine if \module{pkg.string} was what you wanted. But what if
267 you wanted Python's standard \module{string} module? There's no clean
268 way to ignore \module{pkg.string} and look for the standard module;
269 generally you had to look at the contents of \code{sys.modules}, which
270 is slightly unclean.
271 Holger Krekel's \module{py.std} package provides a tidier way to perform
272 imports from the standard library, \code{import py ; py.std.string.join()},
273 but that package isn't available on all Python installations.
275 Reading code which relies on relative imports is also less clear,
276 because a reader may be confused about which module, \module{string}
277 or \module{pkg.string}, is intended to be used. Python users soon
278 learned not to duplicate the names of standard library modules in the
279 names of their packages' submodules, but you can't protect against
280 having your submodule's name being used for a new module added in a
281 future version of Python.
283 In Python 2.5, you can switch \keyword{import}'s behaviour to
284 absolute imports using a \code{from __future__ import absolute_import}
285 directive. This absolute-import behaviour will become the default in
286 a future version (probably Python 2.7). Once absolute imports
287 are the default, \code{import string} will
288 always find the standard library's version.
289 It's suggested that users should begin using absolute imports as much
290 as possible, so it's preferable to begin writing \code{from pkg import
291 string} in your code.
293 Relative imports are still possible by adding a leading period
294 to the module name when using the \code{from ... import} form:
296 \begin{verbatim}
297 # Import names from pkg.string
298 from .string import name1, name2
299 # Import pkg.string
300 from . import string
301 \end{verbatim}
303 This imports the \module{string} module relative to the current
304 package, so in \module{pkg.main} this will import \var{name1} and
305 \var{name2} from \module{pkg.string}. Additional leading periods
306 perform the relative import starting from the parent of the current
307 package. For example, code in the \module{A.B.C} module can do:
309 \begin{verbatim}
310 from . import D # Imports A.B.D
311 from .. import E # Imports A.E
312 from ..F import G # Imports A.F.G
313 \end{verbatim}
315 Leading periods cannot be used with the \code{import \var{modname}}
316 form of the import statement, only the \code{from ... import} form.
318 \begin{seealso}
320 \seepep{328}{Imports: Multi-Line and Absolute/Relative}
321 {PEP written by Aahz; implemented by Thomas Wouters.}
323 \seeurl{http://codespeak.net/py/current/doc/index.html}
324 {The py library by Holger Krekel, which contains the \module{py.std} package.}
326 \end{seealso}
329 %======================================================================
330 \section{PEP 338: Executing Modules as Scripts\label{pep-338}}
332 The \programopt{-m} switch added in Python 2.4 to execute a module as
333 a script gained a few more abilities. Instead of being implemented in
334 C code inside the Python interpreter, the switch now uses an
335 implementation in a new module, \module{runpy}.
337 The \module{runpy} module implements a more sophisticated import
338 mechanism so that it's now possible to run modules in a package such
339 as \module{pychecker.checker}. The module also supports alternative
340 import mechanisms such as the \module{zipimport} module. This means
341 you can add a .zip archive's path to \code{sys.path} and then use the
342 \programopt{-m} switch to execute code from the archive.
345 \begin{seealso}
347 \seepep{338}{Executing modules as scripts}{PEP written and
348 implemented by Nick Coghlan.}
350 \end{seealso}
353 %======================================================================
354 \section{PEP 341: Unified try/except/finally\label{pep-341}}
356 Until Python 2.5, the \keyword{try} statement came in two
357 flavours. You could use a \keyword{finally} block to ensure that code
358 is always executed, or one or more \keyword{except} blocks to catch
359 specific exceptions. You couldn't combine both \keyword{except} blocks and a
360 \keyword{finally} block, because generating the right bytecode for the
361 combined version was complicated and it wasn't clear what the
362 semantics of the combined should be.
364 GvR spent some time working with Java, which does support the
365 equivalent of combining \keyword{except} blocks and a
366 \keyword{finally} block, and this clarified what the statement should
367 mean. In Python 2.5, you can now write:
369 \begin{verbatim}
370 try:
371 block-1 ...
372 except Exception1:
373 handler-1 ...
374 except Exception2:
375 handler-2 ...
376 else:
377 else-block
378 finally:
379 final-block
380 \end{verbatim}
382 The code in \var{block-1} is executed. If the code raises an
383 exception, the various \keyword{except} blocks are tested: if the
384 exception is of class \class{Exception1}, \var{handler-1} is executed;
385 otherwise if it's of class \class{Exception2}, \var{handler-2} is
386 executed, and so forth. If no exception is raised, the
387 \var{else-block} is executed.
389 No matter what happened previously, the \var{final-block} is executed
390 once the code block is complete and any raised exceptions handled.
391 Even if there's an error in an exception handler or the
392 \var{else-block} and a new exception is raised, the
393 code in the \var{final-block} is still run.
395 \begin{seealso}
397 \seepep{341}{Unifying try-except and try-finally}{PEP written by Georg Brandl;
398 implementation by Thomas Lee.}
400 \end{seealso}
403 %======================================================================
404 \section{PEP 342: New Generator Features\label{pep-342}}
406 Python 2.5 adds a simple way to pass values \emph{into} a generator.
407 As introduced in Python 2.3, generators only produce output; once a
408 generator's code was invoked to create an iterator, there was no way to
409 pass any new information into the function when its execution is
410 resumed. Sometimes the ability to pass in some information would be
411 useful. Hackish solutions to this include making the generator's code
412 look at a global variable and then changing the global variable's
413 value, or passing in some mutable object that callers then modify.
415 To refresh your memory of basic generators, here's a simple example:
417 \begin{verbatim}
418 def counter (maximum):
419 i = 0
420 while i < maximum:
421 yield i
422 i += 1
423 \end{verbatim}
425 When you call \code{counter(10)}, the result is an iterator that
426 returns the values from 0 up to 9. On encountering the
427 \keyword{yield} statement, the iterator returns the provided value and
428 suspends the function's execution, preserving the local variables.
429 Execution resumes on the following call to the iterator's
430 \method{next()} method, picking up after the \keyword{yield} statement.
432 In Python 2.3, \keyword{yield} was a statement; it didn't return any
433 value. In 2.5, \keyword{yield} is now an expression, returning a
434 value that can be assigned to a variable or otherwise operated on:
436 \begin{verbatim}
437 val = (yield i)
438 \end{verbatim}
440 I recommend that you always put parentheses around a \keyword{yield}
441 expression when you're doing something with the returned value, as in
442 the above example. The parentheses aren't always necessary, but it's
443 easier to always add them instead of having to remember when they're
444 needed.
446 (\pep{342} explains the exact rules, which are that a
447 \keyword{yield}-expression must always be parenthesized except when it
448 occurs at the top-level expression on the right-hand side of an
449 assignment. This means you can write \code{val = yield i} but have to
450 use parentheses when there's an operation, as in \code{val = (yield i)
451 + 12}.)
453 Values are sent into a generator by calling its
454 \method{send(\var{value})} method. The generator's code is then
455 resumed and the \keyword{yield} expression returns the specified
456 \var{value}. If the regular \method{next()} method is called, the
457 \keyword{yield} returns \constant{None}.
459 Here's the previous example, modified to allow changing the value of
460 the internal counter.
462 \begin{verbatim}
463 def counter (maximum):
464 i = 0
465 while i < maximum:
466 val = (yield i)
467 # If value provided, change counter
468 if val is not None:
469 i = val
470 else:
471 i += 1
472 \end{verbatim}
474 And here's an example of changing the counter:
476 \begin{verbatim}
477 >>> it = counter(10)
478 >>> print it.next()
480 >>> print it.next()
482 >>> print it.send(8)
484 >>> print it.next()
486 >>> print it.next()
487 Traceback (most recent call last):
488 File ``t.py'', line 15, in ?
489 print it.next()
490 StopIteration
491 \end{verbatim}
493 Because \keyword{yield} will often be returning \constant{None}, you
494 should always check for this case. Don't just use its value in
495 expressions unless you're sure that the \method{send()} method
496 will be the only method used resume your generator function.
498 In addition to \method{send()}, there are two other new methods on
499 generators:
501 \begin{itemize}
503 \item \method{throw(\var{type}, \var{value}=None,
504 \var{traceback}=None)} is used to raise an exception inside the
505 generator; the exception is raised by the \keyword{yield} expression
506 where the generator's execution is paused.
508 \item \method{close()} raises a new \exception{GeneratorExit}
509 exception inside the generator to terminate the iteration.
510 On receiving this
511 exception, the generator's code must either raise
512 \exception{GeneratorExit} or \exception{StopIteration}; catching the
513 exception and doing anything else is illegal and will trigger
514 a \exception{RuntimeError}. \method{close()} will also be called by
515 Python's garbage collection when the generator is garbage-collected.
517 If you need to run cleanup code in case of a \exception{GeneratorExit},
518 I suggest using a \code{try: ... finally:} suite instead of
519 catching \exception{GeneratorExit}.
521 \end{itemize}
523 The cumulative effect of these changes is to turn generators from
524 one-way producers of information into both producers and consumers.
526 Generators also become \emph{coroutines}, a more generalized form of
527 subroutines. Subroutines are entered at one point and exited at
528 another point (the top of the function, and a \keyword{return}
529 statement), but coroutines can be entered, exited, and resumed at
530 many different points (the \keyword{yield} statements). We'll have to
531 figure out patterns for using coroutines effectively in Python.
533 The addition of the \method{close()} method has one side effect that
534 isn't obvious. \method{close()} is called when a generator is
535 garbage-collected, so this means the generator's code gets one last
536 chance to run before the generator is destroyed. This last chance
537 means that \code{try...finally} statements in generators can now be
538 guaranteed to work; the \keyword{finally} clause will now always get a
539 chance to run. The syntactic restriction that you couldn't mix
540 \keyword{yield} statements with a \code{try...finally} suite has
541 therefore been removed. This seems like a minor bit of language
542 trivia, but using generators and \code{try...finally} is actually
543 necessary in order to implement the \keyword{with} statement
544 described by PEP 343. I'll look at this new statement in the following
545 section.
547 Another even more esoteric effect of this change: previously, the
548 \member{gi_frame} attribute of a generator was always a frame object.
549 It's now possible for \member{gi_frame} to be \code{None}
550 once the generator has been exhausted.
552 \begin{seealso}
554 \seepep{342}{Coroutines via Enhanced Generators}{PEP written by
555 Guido van~Rossum and Phillip J. Eby;
556 implemented by Phillip J. Eby. Includes examples of
557 some fancier uses of generators as coroutines.}
559 \seeurl{http://en.wikipedia.org/wiki/Coroutine}{The Wikipedia entry for
560 coroutines.}
562 \seeurl{http://www.sidhe.org/\~{}dan/blog/archives/000178.html}{An
563 explanation of coroutines from a Perl point of view, written by Dan
564 Sugalski.}
566 \end{seealso}
569 %======================================================================
570 \section{PEP 343: The 'with' statement\label{pep-343}}
572 The '\keyword{with}' statement clarifies code that previously would
573 use \code{try...finally} blocks to ensure that clean-up code is
574 executed. In this section, I'll discuss the statement as it will
575 commonly be used. In the next section, I'll examine the
576 implementation details and show how to write objects for use with this
577 statement.
579 The '\keyword{with}' statement is a new control-flow structure whose
580 basic structure is:
582 \begin{verbatim}
583 with expression [as variable]:
584 with-block
585 \end{verbatim}
587 The expression is evaluated, and it should result in an object that
588 supports the context management protocol. This object may return a
589 value that can optionally be bound to the name \var{variable}. (Note
590 carefully that \var{variable} is \emph{not} assigned the result of
591 \var{expression}.) The object can then run set-up code
592 before \var{with-block} is executed and some clean-up code
593 is executed after the block is done, even if the block raised an exception.
595 To enable the statement in Python 2.5, you need
596 to add the following directive to your module:
598 \begin{verbatim}
599 from __future__ import with_statement
600 \end{verbatim}
602 The statement will always be enabled in Python 2.6.
604 Some standard Python objects now support the context management
605 protocol and can be used with the '\keyword{with}' statement. File
606 objects are one example:
608 \begin{verbatim}
609 with open('/etc/passwd', 'r') as f:
610 for line in f:
611 print line
612 ... more processing code ...
613 \end{verbatim}
615 After this statement has executed, the file object in \var{f} will
616 have been automatically closed, even if the 'for' loop
617 raised an exception part-way through the block.
619 The \module{threading} module's locks and condition variables
620 also support the '\keyword{with}' statement:
622 \begin{verbatim}
623 lock = threading.Lock()
624 with lock:
625 # Critical section of code
627 \end{verbatim}
629 The lock is acquired before the block is executed and always released once
630 the block is complete.
632 The \module{decimal} module's contexts, which encapsulate the desired
633 precision and rounding characteristics for computations, provide a
634 \method{context_manager()} method for getting a context manager:
636 \begin{verbatim}
637 import decimal
639 # Displays with default precision of 28 digits
640 v1 = decimal.Decimal('578')
641 print v1.sqrt()
643 ctx = decimal.Context(prec=16)
644 with ctx.context_manager():
645 # All code in this block uses a precision of 16 digits.
646 # The original context is restored on exiting the block.
647 print v1.sqrt()
648 \end{verbatim}
650 \subsection{Writing Context Managers\label{context-managers}}
652 Under the hood, the '\keyword{with}' statement is fairly complicated.
653 Most people will only use '\keyword{with}' in company with existing
654 objects and don't need to know these details, so you can skip the rest
655 of this section if you like. Authors of new objects will need to
656 understand the details of the underlying implementation and should
657 keep reading.
659 A high-level explanation of the context management protocol is:
661 \begin{itemize}
663 \item The expression is evaluated and should result in an object
664 called a ``context manager''. The context manager must have
665 \method{__enter__()} and \method{__exit__()} methods.
667 \item The context manager's \method{__enter__()} method is called. The value
668 returned is assigned to \var{VAR}. If no \code{'as \var{VAR}'} clause
669 is present, the value is simply discarded.
671 \item The code in \var{BLOCK} is executed.
673 \item If \var{BLOCK} raises an exception, the
674 \method{__exit__(\var{type}, \var{value}, \var{traceback})} is called
675 with the exception details, the same values returned by
676 \function{sys.exc_info()}. The method's return value controls whether
677 the exception is re-raised: any false value re-raises the exception,
678 and \code{True} will result in suppressing it. You'll only rarely
679 want to suppress the exception, because if you do
680 the author of the code containing the
681 '\keyword{with}' statement will never realize anything went wrong.
683 \item If \var{BLOCK} didn't raise an exception,
684 the \method{__exit__()} method is still called,
685 but \var{type}, \var{value}, and \var{traceback} are all \code{None}.
687 \end{itemize}
689 Let's think through an example. I won't present detailed code but
690 will only sketch the methods necessary for a database that supports
691 transactions.
693 (For people unfamiliar with database terminology: a set of changes to
694 the database are grouped into a transaction. Transactions can be
695 either committed, meaning that all the changes are written into the
696 database, or rolled back, meaning that the changes are all discarded
697 and the database is unchanged. See any database textbook for more
698 information.)
699 % XXX find a shorter reference?
701 Let's assume there's an object representing a database connection.
702 Our goal will be to let the user write code like this:
704 \begin{verbatim}
705 db_connection = DatabaseConnection()
706 with db_connection as cursor:
707 cursor.execute('insert into ...')
708 cursor.execute('delete from ...')
709 # ... more operations ...
710 \end{verbatim}
712 The transaction should be committed if the code in the block
713 runs flawlessly or rolled back if there's an exception.
714 Here's the basic interface
715 for \class{DatabaseConnection} that I'll assume:
717 \begin{verbatim}
718 class DatabaseConnection:
719 # Database interface
720 def cursor (self):
721 "Returns a cursor object and starts a new transaction"
722 def commit (self):
723 "Commits current transaction"
724 def rollback (self):
725 "Rolls back current transaction"
726 \end{verbatim}
728 The \method {__enter__()} method is pretty easy, having only to start
729 a new transaction. For this application the resulting cursor object
730 would be a useful result, so the method will return it. The user can
731 then add \code{as cursor} to their '\keyword{with}' statement to bind
732 the cursor to a variable name.
734 \begin{verbatim}
735 class DatabaseConnection:
737 def __enter__ (self):
738 # Code to start a new transaction
739 cursor = self.cursor()
740 return cursor
741 \end{verbatim}
743 The \method{__exit__()} method is the most complicated because it's
744 where most of the work has to be done. The method has to check if an
745 exception occurred. If there was no exception, the transaction is
746 committed. The transaction is rolled back if there was an exception.
748 In the code below, execution will just fall off the end of the
749 function, returning the default value of \code{None}. \code{None} is
750 false, so the exception will be re-raised automatically. If you
751 wished, you could be more explicit and add a \keyword{return}
752 statement at the marked location.
754 \begin{verbatim}
755 class DatabaseConnection:
757 def __exit__ (self, type, value, tb):
758 if tb is None:
759 # No exception, so commit
760 self.commit()
761 else:
762 # Exception occurred, so rollback.
763 self.rollback()
764 # return False
765 \end{verbatim}
768 \subsection{The contextlib module\label{module-contextlib}}
770 The new \module{contextlib} module provides some functions and a
771 decorator that are useful for writing objects for use with the
772 '\keyword{with}' statement.
774 The decorator is called \function{contextfactory}, and lets you write
775 a single generator function instead of defining a new class. The generator
776 should yield exactly one value. The code up to the \keyword{yield}
777 will be executed as the \method{__enter__()} method, and the value
778 yielded will be the method's return value that will get bound to the
779 variable in the '\keyword{with}' statement's \keyword{as} clause, if
780 any. The code after the \keyword{yield} will be executed in the
781 \method{__exit__()} method. Any exception raised in the block will be
782 raised by the \keyword{yield} statement.
784 Our database example from the previous section could be written
785 using this decorator as:
787 \begin{verbatim}
788 from contextlib import contextfactory
790 @contextfactory
791 def db_transaction (connection):
792 cursor = connection.cursor()
793 try:
794 yield cursor
795 except:
796 connection.rollback()
797 raise
798 else:
799 connection.commit()
801 db = DatabaseConnection()
802 with db_transaction(db) as cursor:
804 \end{verbatim}
806 The \module{contextlib} module also has a \function{nested(\var{mgr1},
807 \var{mgr2}, ...)} function that combines a number of context managers so you
808 don't need to write nested '\keyword{with}' statements. In this
809 example, the single '\keyword{with}' statement both starts a database
810 transaction and acquires a thread lock:
812 \begin{verbatim}
813 lock = threading.Lock()
814 with nested (db_transaction(db), lock) as (cursor, locked):
816 \end{verbatim}
818 Finally, the \function{closing(\var{object})} function
819 returns \var{object} so that it can be bound to a variable,
820 and calls \code{\var{object}.close()} at the end of the block.
822 \begin{verbatim}
823 import urllib, sys
824 from contextlib import closing
826 with closing(urllib.urlopen('http://www.yahoo.com')) as f:
827 for line in f:
828 sys.stdout.write(line)
829 \end{verbatim}
831 \begin{seealso}
833 \seepep{343}{The ``with'' statement}{PEP written by Guido van~Rossum
834 and Nick Coghlan; implemented by Mike Bland, Guido van~Rossum, and
835 Neal Norwitz. The PEP shows the code generated for a '\keyword{with}'
836 statement, which can be helpful in learning how the statement works.}
838 \seeurl{../lib/module-contextlib.html}{The documentation
839 for the \module{contextlib} module.}
841 \end{seealso}
844 %======================================================================
845 \section{PEP 352: Exceptions as New-Style Classes\label{pep-352}}
847 Exception classes can now be new-style classes, not just classic
848 classes, and the built-in \exception{Exception} class and all the
849 standard built-in exceptions (\exception{NameError},
850 \exception{ValueError}, etc.) are now new-style classes.
852 The inheritance hierarchy for exceptions has been rearranged a bit.
853 In 2.5, the inheritance relationships are:
855 \begin{verbatim}
856 BaseException # New in Python 2.5
857 |- KeyboardInterrupt
858 |- SystemExit
859 |- Exception
860 |- (all other current built-in exceptions)
861 \end{verbatim}
863 This rearrangement was done because people often want to catch all
864 exceptions that indicate program errors. \exception{KeyboardInterrupt} and
865 \exception{SystemExit} aren't errors, though, and usually represent an explicit
866 action such as the user hitting Control-C or code calling
867 \function{sys.exit()}. A bare \code{except:} will catch all exceptions,
868 so you commonly need to list \exception{KeyboardInterrupt} and
869 \exception{SystemExit} in order to re-raise them. The usual pattern is:
871 \begin{verbatim}
872 try:
874 except (KeyboardInterrupt, SystemExit):
875 raise
876 except:
877 # Log error...
878 # Continue running program...
879 \end{verbatim}
881 In Python 2.5, you can now write \code{except Exception} to achieve
882 the same result, catching all the exceptions that usually indicate errors
883 but leaving \exception{KeyboardInterrupt} and
884 \exception{SystemExit} alone. As in previous versions,
885 a bare \code{except:} still catches all exceptions.
887 The goal for Python 3.0 is to require any class raised as an exception
888 to derive from \exception{BaseException} or some descendant of
889 \exception{BaseException}, and future releases in the
890 Python 2.x series may begin to enforce this constraint. Therefore, I
891 suggest you begin making all your exception classes derive from
892 \exception{Exception} now. It's been suggested that the bare
893 \code{except:} form should be removed in Python 3.0, but Guido van~Rossum
894 hasn't decided whether to do this or not.
896 Raising of strings as exceptions, as in the statement \code{raise
897 "Error occurred"}, is deprecated in Python 2.5 and will trigger a
898 warning. The aim is to be able to remove the string-exception feature
899 in a few releases.
902 \begin{seealso}
904 \seepep{352}{Required Superclass for Exceptions}{PEP written by
905 Brett Cannon and Guido van~Rossum; implemented by Brett Cannon.}
907 \end{seealso}
910 %======================================================================
911 \section{PEP 353: Using ssize_t as the index type\label{pep-353}}
913 A wide-ranging change to Python's C API, using a new
914 \ctype{Py_ssize_t} type definition instead of \ctype{int},
915 will permit the interpreter to handle more data on 64-bit platforms.
916 This change doesn't affect Python's capacity on 32-bit platforms.
918 Various pieces of the Python interpreter used C's \ctype{int} type to
919 store sizes or counts; for example, the number of items in a list or
920 tuple were stored in an \ctype{int}. The C compilers for most 64-bit
921 platforms still define \ctype{int} as a 32-bit type, so that meant
922 that lists could only hold up to \code{2**31 - 1} = 2147483647 items.
923 (There are actually a few different programming models that 64-bit C
924 compilers can use -- see
925 \url{http://www.unix.org/version2/whatsnew/lp64_wp.html} for a
926 discussion -- but the most commonly available model leaves \ctype{int}
927 as 32 bits.)
929 A limit of 2147483647 items doesn't really matter on a 32-bit platform
930 because you'll run out of memory before hitting the length limit.
931 Each list item requires space for a pointer, which is 4 bytes, plus
932 space for a \ctype{PyObject} representing the item. 2147483647*4 is
933 already more bytes than a 32-bit address space can contain.
935 It's possible to address that much memory on a 64-bit platform,
936 however. The pointers for a list that size would only require 16GiB
937 of space, so it's not unreasonable that Python programmers might
938 construct lists that large. Therefore, the Python interpreter had to
939 be changed to use some type other than \ctype{int}, and this will be a
940 64-bit type on 64-bit platforms. The change will cause
941 incompatibilities on 64-bit machines, so it was deemed worth making
942 the transition now, while the number of 64-bit users is still
943 relatively small. (In 5 or 10 years, we may \emph{all} be on 64-bit
944 machines, and the transition would be more painful then.)
946 This change most strongly affects authors of C extension modules.
947 Python strings and container types such as lists and tuples
948 now use \ctype{Py_ssize_t} to store their size.
949 Functions such as \cfunction{PyList_Size()}
950 now return \ctype{Py_ssize_t}. Code in extension modules
951 may therefore need to have some variables changed to
952 \ctype{Py_ssize_t}.
954 The \cfunction{PyArg_ParseTuple()} and \cfunction{Py_BuildValue()} functions
955 have a new conversion code, \samp{n}, for \ctype{Py_ssize_t}.
956 \cfunction{PyArg_ParseTuple()}'s \samp{s\#} and \samp{t\#} still output
957 \ctype{int} by default, but you can define the macro
958 \csimplemacro{PY_SSIZE_T_CLEAN} before including \file{Python.h}
959 to make them return \ctype{Py_ssize_t}.
961 \pep{353} has a section on conversion guidelines that
962 extension authors should read to learn about supporting 64-bit
963 platforms.
965 \begin{seealso}
967 \seepep{353}{Using ssize_t as the index type}{PEP written and implemented by Martin von~L\"owis.}
969 \end{seealso}
972 %======================================================================
973 \section{PEP 357: The '__index__' method\label{pep-357}}
975 The NumPy developers had a problem that could only be solved by adding
976 a new special method, \method{__index__}. When using slice notation,
977 as in \code{[\var{start}:\var{stop}:\var{step}]}, the values of the
978 \var{start}, \var{stop}, and \var{step} indexes must all be either
979 integers or long integers. NumPy defines a variety of specialized
980 integer types corresponding to unsigned and signed integers of 8, 16,
981 32, and 64 bits, but there was no way to signal that these types could
982 be used as slice indexes.
984 Slicing can't just use the existing \method{__int__} method because
985 that method is also used to implement coercion to integers. If
986 slicing used \method{__int__}, floating-point numbers would also
987 become legal slice indexes and that's clearly an undesirable
988 behaviour.
990 Instead, a new special method called \method{__index__} was added. It
991 takes no arguments and returns an integer giving the slice index to
992 use. For example:
994 \begin{verbatim}
995 class C:
996 def __index__ (self):
997 return self.value
998 \end{verbatim}
1000 The return value must be either a Python integer or long integer.
1001 The interpreter will check that the type returned is correct, and
1002 raises a \exception{TypeError} if this requirement isn't met.
1004 A corresponding \member{nb_index} slot was added to the C-level
1005 \ctype{PyNumberMethods} structure to let C extensions implement this
1006 protocol. \cfunction{PyNumber_Index(\var{obj})} can be used in
1007 extension code to call the \method{__index__} function and retrieve
1008 its result.
1010 \begin{seealso}
1012 \seepep{357}{Allowing Any Object to be Used for Slicing}{PEP written
1013 and implemented by Travis Oliphant.}
1015 \end{seealso}
1018 %======================================================================
1019 \section{Other Language Changes\label{other-lang}}
1021 Here are all of the changes that Python 2.5 makes to the core Python
1022 language.
1024 \begin{itemize}
1026 \item The \class{dict} type has a new hook for letting subclasses
1027 provide a default value when a key isn't contained in the dictionary.
1028 When a key isn't found, the dictionary's
1029 \method{__missing__(\var{key})}
1030 method will be called. This hook is used to implement
1031 the new \class{defaultdict} class in the \module{collections}
1032 module. The following example defines a dictionary
1033 that returns zero for any missing key:
1035 \begin{verbatim}
1036 class zerodict (dict):
1037 def __missing__ (self, key):
1038 return 0
1040 d = zerodict({1:1, 2:2})
1041 print d[1], d[2] # Prints 1, 2
1042 print d[3], d[4] # Prints 0, 0
1043 \end{verbatim}
1045 \item The \function{min()} and \function{max()} built-in functions
1046 gained a \code{key} keyword parameter analogous to the \code{key}
1047 argument for \method{sort()}. This parameter supplies a function that
1048 takes a single argument and is called for every value in the list;
1049 \function{min()}/\function{max()} will return the element with the
1050 smallest/largest return value from this function.
1051 For example, to find the longest string in a list, you can do:
1053 \begin{verbatim}
1054 L = ['medium', 'longest', 'short']
1055 # Prints 'longest'
1056 print max(L, key=len)
1057 # Prints 'short', because lexicographically 'short' has the largest value
1058 print max(L)
1059 \end{verbatim}
1061 (Contributed by Steven Bethard and Raymond Hettinger.)
1063 \item Two new built-in functions, \function{any()} and
1064 \function{all()}, evaluate whether an iterator contains any true or
1065 false values. \function{any()} returns \constant{True} if any value
1066 returned by the iterator is true; otherwise it will return
1067 \constant{False}. \function{all()} returns \constant{True} only if
1068 all of the values returned by the iterator evaluate as being true.
1069 (Suggested by GvR, and implemented by Raymond Hettinger.)
1071 \item ASCII is now the default encoding for modules. It's now
1072 a syntax error if a module contains string literals with 8-bit
1073 characters but doesn't have an encoding declaration. In Python 2.4
1074 this triggered a warning, not a syntax error. See \pep{263}
1075 for how to declare a module's encoding; for example, you might add
1076 a line like this near the top of the source file:
1078 \begin{verbatim}
1079 # -*- coding: latin1 -*-
1080 \end{verbatim}
1082 \item One error that Python programmers sometimes make is forgetting
1083 to include an \file{__init__.py} module in a package directory.
1084 Debugging this mistake can be confusing, and usually requires running
1085 Python with the \programopt{-v} switch to log all the paths searched.
1086 In Python 2.5, a new \exception{ImportWarning} warning is raised when
1087 an import would have picked up a directory as a package but no
1088 \file{__init__.py} was found. (Implemented by Thomas Wouters.)
1090 \item The list of base classes in a class definition can now be empty.
1091 As an example, this is now legal:
1093 \begin{verbatim}
1094 class C():
1095 pass
1096 \end{verbatim}
1097 (Implemented by Brett Cannon.)
1099 \end{itemize}
1102 %======================================================================
1103 \subsection{Interactive Interpreter Changes\label{interactive}}
1105 In the interactive interpreter, \code{quit} and \code{exit}
1106 have long been strings so that new users get a somewhat helpful message
1107 when they try to quit:
1109 \begin{verbatim}
1110 >>> quit
1111 'Use Ctrl-D (i.e. EOF) to exit.'
1112 \end{verbatim}
1114 In Python 2.5, \code{quit} and \code{exit} are now objects that still
1115 produce string representations of themselves, but are also callable.
1116 Newbies who try \code{quit()} or \code{exit()} will now exit the
1117 interpreter as they expect. (Implemented by Georg Brandl.)
1120 %======================================================================
1121 \subsection{Optimizations\label{opts}}
1123 Several of the optimizations were developed at the NeedForSpeed
1124 sprint, an event held in Reykjavik, Iceland, from May 21--28 2006.
1125 The sprint focused on speed enhancements to the CPython implementation
1126 and was funded by EWT LLC with local support from CCP Games. Those
1127 optimizations added at this sprint are specially marked in the
1128 following list.
1130 \begin{itemize}
1132 \item When they were introduced
1133 in Python 2.4, the built-in \class{set} and \class{frozenset} types
1134 were built on top of Python's dictionary type.
1135 In 2.5 the internal data structure has been customized for implementing sets,
1136 and as a result sets will use a third less memory and are somewhat faster.
1137 (Implemented by Raymond Hettinger.)
1139 \item The performance of some Unicode operations, such as
1140 finding substrings and character map decoding, has been improved.
1141 (Substring search improvements were added by Fredrik Lundh and Andrew
1142 Dalke at the NeedForSpeed sprint. Character map decoding was improved
1143 by Walter D\"orwald.)
1144 % Patch 1313939
1146 \item The code generator's peephole optimizer now performs
1147 simple constant folding in expressions. If you write something like
1148 \code{a = 2+3}, the code generator will do the arithmetic and produce
1149 code corresponding to \code{a = 5}.
1151 \item Function calls are now faster because code objects now keep
1152 the most recently finished frame (a ``zombie frame'') in an internal
1153 field of the code object, reusing it the next time the code object is
1154 invoked. (Original patch by Michael Hudson, modified by Armin Rigo
1155 and Richard Jones; committed at the NeedForSpeed sprint.)
1156 % Patch 876206
1158 \end{itemize}
1160 The net result of the 2.5 optimizations is that Python 2.5 runs the
1161 pystone benchmark around XXX\% faster than Python 2.4.
1164 %======================================================================
1165 \section{New, Improved, and Removed Modules\label{modules}}
1167 The standard library received many enhancements and bug fixes in
1168 Python 2.5. Here's a partial list of the most notable changes, sorted
1169 alphabetically by module name. Consult the \file{Misc/NEWS} file in
1170 the source tree for a more complete list of changes, or look through
1171 the SVN logs for all the details.
1173 \begin{itemize}
1175 \item The \module{audioop} module now supports the a-LAW encoding,
1176 and the code for u-LAW encoding has been improved. (Contributed by
1177 Lars Immisch.)
1179 \item The \module{codecs} module gained support for incremental
1180 codecs. The \function{codec.lookup()} function now
1181 returns a \class{CodecInfo} instance instead of a tuple.
1182 \class{CodecInfo} instances behave like a 4-tuple to preserve backward
1183 compatibility but also have the attributes \member{encode},
1184 \member{decode}, \member{incrementalencoder}, \member{incrementaldecoder},
1185 \member{streamwriter}, and \member{streamreader}. Incremental codecs
1186 can receive input and produce output in multiple chunks; the output is
1187 the same as if the entire input was fed to the non-incremental codec.
1188 See the \module{codecs} module documentation for details.
1189 (Designed and implemented by Walter D\"orwald.)
1190 % Patch 1436130
1192 \item The \module{collections} module gained a new type,
1193 \class{defaultdict}, that subclasses the standard \class{dict}
1194 type. The new type mostly behaves like a dictionary but constructs a
1195 default value when a key isn't present, automatically adding it to the
1196 dictionary for the requested key value.
1198 The first argument to \class{defaultdict}'s constructor is a factory
1199 function that gets called whenever a key is requested but not found.
1200 This factory function receives no arguments, so you can use built-in
1201 type constructors such as \function{list()} or \function{int()}. For
1202 example,
1203 you can make an index of words based on their initial letter like this:
1205 \begin{verbatim}
1206 words = """Nel mezzo del cammin di nostra vita
1207 mi ritrovai per una selva oscura
1208 che la diritta via era smarrita""".lower().split()
1210 index = defaultdict(list)
1212 for w in words:
1213 init_letter = w[0]
1214 index[init_letter].append(w)
1215 \end{verbatim}
1217 Printing \code{index} results in the following output:
1219 \begin{verbatim}
1220 defaultdict(<type 'list'>, {'c': ['cammin', 'che'], 'e': ['era'],
1221 'd': ['del', 'di', 'diritta'], 'm': ['mezzo', 'mi'],
1222 'l': ['la'], 'o': ['oscura'], 'n': ['nel', 'nostra'],
1223 'p': ['per'], 's': ['selva', 'smarrita'],
1224 'r': ['ritrovai'], 'u': ['una'], 'v': ['vita', 'via']}
1225 \end{verbatim}
1227 The \class{deque} double-ended queue type supplied by the
1228 \module{collections} module now has a \method{remove(\var{value})}
1229 method that removes the first occurrence of \var{value} in the queue,
1230 raising \exception{ValueError} if the value isn't found.
1232 \item New module: The \module{contextlib} module contains helper functions for use
1233 with the new '\keyword{with}' statement. See
1234 section~\ref{module-contextlib} for more about this module.
1236 \item New module: The \module{cProfile} module is a C implementation of
1237 the existing \module{profile} module that has much lower overhead.
1238 The module's interface is the same as \module{profile}: you run
1239 \code{cProfile.run('main()')} to profile a function, can save profile
1240 data to a file, etc. It's not yet known if the Hotshot profiler,
1241 which is also written in C but doesn't match the \module{profile}
1242 module's interface, will continue to be maintained in future versions
1243 of Python. (Contributed by Armin Rigo.)
1245 Also, the \module{pstats} module for analyzing the data measured by
1246 the profiler now supports directing the output to any file object
1247 by supplying a \var{stream} argument to the \class{Stats} constructor.
1248 (Contributed by Skip Montanaro.)
1250 \item The \module{csv} module, which parses files in
1251 comma-separated value format, received several enhancements and a
1252 number of bugfixes. You can now set the maximum size in bytes of a
1253 field by calling the \method{csv.field_size_limit(\var{new_limit})}
1254 function; omitting the \var{new_limit} argument will return the
1255 currently-set limit. The \class{reader} class now has a
1256 \member{line_num} attribute that counts the number of physical lines
1257 read from the source; records can span multiple physical lines, so
1258 \member{line_num} is not the same as the number of records read.
1259 (Contributed by Skip Montanaro and Andrew McNamara.)
1261 \item The \class{datetime} class in the \module{datetime}
1262 module now has a \method{strptime(\var{string}, \var{format})}
1263 method for parsing date strings, contributed by Josh Spoerri.
1264 It uses the same format characters as \function{time.strptime()} and
1265 \function{time.strftime()}:
1267 \begin{verbatim}
1268 from datetime import datetime
1270 ts = datetime.strptime('10:13:15 2006-03-07',
1271 '%H:%M:%S %Y-%m-%d')
1272 \end{verbatim}
1274 \item The \module{doctest} module gained a \code{SKIP} option that
1275 keeps an example from being executed at all. This is intended for
1276 code snippets that are usage examples intended for the reader and
1277 aren't actually test cases.
1279 \item The \module{fileinput} module was made more flexible.
1280 Unicode filenames are now supported, and a \var{mode} parameter that
1281 defaults to \code{"r"} was added to the
1282 \function{input()} function to allow opening files in binary or
1283 universal-newline mode. Another new parameter, \var{openhook},
1284 lets you use a function other than \function{open()}
1285 to open the input files. Once you're iterating over
1286 the set of files, the \class{FileInput} object's new
1287 \method{fileno()} returns the file descriptor for the currently opened file.
1288 (Contributed by Georg Brandl.)
1290 \item In the \module{gc} module, the new \function{get_count()} function
1291 returns a 3-tuple containing the current collection counts for the
1292 three GC generations. This is accounting information for the garbage
1293 collector; when these counts reach a specified threshold, a garbage
1294 collection sweep will be made. The existing \function{gc.collect()}
1295 function now takes an optional \var{generation} argument of 0, 1, or 2
1296 to specify which generation to collect.
1298 \item The \function{nsmallest()} and
1299 \function{nlargest()} functions in the \module{heapq} module
1300 now support a \code{key} keyword parameter similar to the one
1301 provided by the \function{min()}/\function{max()} functions
1302 and the \method{sort()} methods. For example:
1303 Example:
1305 \begin{verbatim}
1306 >>> import heapq
1307 >>> L = ["short", 'medium', 'longest', 'longer still']
1308 >>> heapq.nsmallest(2, L) # Return two lowest elements, lexicographically
1309 ['longer still', 'longest']
1310 >>> heapq.nsmallest(2, L, key=len) # Return two shortest elements
1311 ['short', 'medium']
1312 \end{verbatim}
1314 (Contributed by Raymond Hettinger.)
1316 \item The \function{itertools.islice()} function now accepts
1317 \code{None} for the start and step arguments. This makes it more
1318 compatible with the attributes of slice objects, so that you can now write
1319 the following:
1321 \begin{verbatim}
1322 s = slice(5) # Create slice object
1323 itertools.islice(iterable, s.start, s.stop, s.step)
1324 \end{verbatim}
1326 (Contributed by Raymond Hettinger.)
1328 \item The \module{mailbox} module underwent a massive rewrite to add
1329 the capability to modify mailboxes in addition to reading them. A new
1330 set of classes that include \class{mbox}, \class{MH}, and
1331 \class{Maildir} are used to read mailboxes, and have an
1332 \method{add(\var{message})} method to add messages,
1333 \method{remove(\var{key})} to remove messages, and
1334 \method{lock()}/\method{unlock()} to lock/unlock the mailbox. The
1335 following example converts a maildir-format mailbox into an mbox-format one:
1337 \begin{verbatim}
1338 import mailbox
1340 # 'factory=None' uses email.Message.Message as the class representing
1341 # individual messages.
1342 src = mailbox.Maildir('maildir', factory=None)
1343 dest = mailbox.mbox('/tmp/mbox')
1345 for msg in src:
1346 dest.add(msg)
1347 \end{verbatim}
1349 (Contributed by Gregory K. Johnson. Funding was provided by Google's
1350 2005 Summer of Code.)
1352 \item New module: the \module{msilib} module allows creating
1353 Microsoft Installer \file{.msi} files and CAB files. Some support
1354 for reading the \file{.msi} database is also included.
1355 (Contributed by Martin von~L\"owis.)
1357 \item The \module{nis} module now supports accessing domains other
1358 than the system default domain by supplying a \var{domain} argument to
1359 the \function{nis.match()} and \function{nis.maps()} functions.
1360 (Contributed by Ben Bell.)
1362 \item The \module{operator} module's \function{itemgetter()}
1363 and \function{attrgetter()} functions now support multiple fields.
1364 A call such as \code{operator.attrgetter('a', 'b')}
1365 will return a function
1366 that retrieves the \member{a} and \member{b} attributes. Combining
1367 this new feature with the \method{sort()} method's \code{key} parameter
1368 lets you easily sort lists using multiple fields.
1369 (Contributed by Raymond Hettinger.)
1371 \item The \module{optparse} module was updated to version 1.5.1 of the
1372 Optik library. The \class{OptionParser} class gained an
1373 \member{epilog} attribute, a string that will be printed after the
1374 help message, and a \method{destroy()} method to break reference
1375 cycles created by the object. (Contributed by Greg Ward.)
1377 \item The \module{os} module underwent several changes. The
1378 \member{stat_float_times} variable now defaults to true, meaning that
1379 \function{os.stat()} will now return time values as floats. (This
1380 doesn't necessarily mean that \function{os.stat()} will return times
1381 that are precise to fractions of a second; not all systems support
1382 such precision.)
1384 Constants named \member{os.SEEK_SET}, \member{os.SEEK_CUR}, and
1385 \member{os.SEEK_END} have been added; these are the parameters to the
1386 \function{os.lseek()} function. Two new constants for locking are
1387 \member{os.O_SHLOCK} and \member{os.O_EXLOCK}.
1389 Two new functions, \function{wait3()} and \function{wait4()}, were
1390 added. They're similar the \function{waitpid()} function which waits
1391 for a child process to exit and returns a tuple of the process ID and
1392 its exit status, but \function{wait3()} and \function{wait4()} return
1393 additional information. \function{wait3()} doesn't take a process ID
1394 as input, so it waits for any child process to exit and returns a
1395 3-tuple of \var{process-id}, \var{exit-status}, \var{resource-usage}
1396 as returned from the \function{resource.getrusage()} function.
1397 \function{wait4(\var{pid})} does take a process ID.
1398 (Contributed by Chad J. Schroeder.)
1400 On FreeBSD, the \function{os.stat()} function now returns
1401 times with nanosecond resolution, and the returned object
1402 now has \member{st_gen} and \member{st_birthtime}.
1403 The \member{st_flags} member is also available, if the platform supports it.
1404 (Contributed by Antti Louko and Diego Petten\`o.)
1405 % (Patch 1180695, 1212117)
1407 \item The Python debugger provided by the \module{pdb} module
1408 can now store lists of commands to execute when a breakpoint is
1409 reached and execution stops. Once breakpoint \#1 has been created,
1410 enter \samp{commands 1} and enter a series of commands to be executed,
1411 finishing the list with \samp{end}. The command list can include
1412 commands that resume execution, such as \samp{continue} or
1413 \samp{next}. (Contributed by Gr\'egoire Dooms.)
1414 % Patch 790710
1416 \item The \module{pickle} and \module{cPickle} modules no
1417 longer accept a return value of \code{None} from the
1418 \method{__reduce__()} method; the method must return a tuple of
1419 arguments instead. The ability to return \code{None} was deprecated
1420 in Python 2.4, so this completes the removal of the feature.
1422 \item The \module{pkgutil} module, containing various utility
1423 functions for finding packages, was enhanced to support PEP 302's
1424 import hooks and now also works for packages stored in ZIP-format archives.
1425 (Contributed by Phillip J. Eby.)
1427 \item The pybench benchmark suite by Marc-Andr\'e~Lemburg is now
1428 included in the \file{Tools/pybench} directory. The pybench suite is
1429 an improvement on the commonly used \file{pystone.py} program because
1430 pybench provides a more detailed measurement of the interpreter's
1431 performance. It times particular operations such as function calls,
1432 tuple slicing, method lookups, and numeric operations, instead of
1433 performing many different operations and reducing the result to a
1434 single number as \file{pystone.py} does.
1436 \item The old \module{regex} and \module{regsub} modules, which have been
1437 deprecated ever since Python 2.0, have finally been deleted.
1438 Other deleted modules: \module{statcache}, \module{tzparse},
1439 \module{whrandom}.
1441 \item Also deleted: the \file{lib-old} directory,
1442 which includes ancient modules such as \module{dircmp} and
1443 \module{ni}, was removed. \file{lib-old} wasn't on the default
1444 \code{sys.path}, so unless your programs explicitly added the directory to
1445 \code{sys.path}, this removal shouldn't affect your code.
1447 \item The \module{rlcompleter} module is no longer
1448 dependent on importing the \module{readline} module and
1449 therefore now works on non-{\UNIX} platforms.
1450 (Patch from Robert Kiendl.)
1451 % Patch #1472854
1453 \item The \module{socket} module now supports \constant{AF_NETLINK}
1454 sockets on Linux, thanks to a patch from Philippe Biondi.
1455 Netlink sockets are a Linux-specific mechanism for communications
1456 between a user-space process and kernel code; an introductory
1457 article about them is at \url{http://www.linuxjournal.com/article/7356}.
1458 In Python code, netlink addresses are represented as a tuple of 2 integers,
1459 \code{(\var{pid}, \var{group_mask})}.
1461 Socket objects also gained accessor methods \method{getfamily()},
1462 \method{gettype()}, and \method{getproto()} methods to retrieve the
1463 family, type, and protocol values for the socket.
1465 \item New module: the \module{spwd} module provides functions for
1466 accessing the shadow password database on systems that support
1467 shadow passwords.
1469 \item The Python developers switched from CVS to Subversion during the 2.5
1470 development process. Information about the exact build version is
1471 available as the \code{sys.subversion} variable, a 3-tuple
1472 of \code{(\var{interpreter-name}, \var{branch-name}, \var{revision-range})}.
1473 For example, at the time of writing
1474 my copy of 2.5 was reporting \code{('CPython', 'trunk', '45313:45315')}.
1476 This information is also available to C extensions via the
1477 \cfunction{Py_GetBuildInfo()} function that returns a
1478 string of build information like this:
1479 \code{"trunk:45355:45356M, Apr 13 2006, 07:42:19"}.
1480 (Contributed by Barry Warsaw.)
1482 \item The \class{TarFile} class in the \module{tarfile} module now has
1483 an \method{extractall()} method that extracts all members from the
1484 archive into the current working directory. It's also possible to set
1485 a different directory as the extraction target, and to unpack only a
1486 subset of the archive's members.
1488 A tarfile's compression can be autodetected by
1489 using the mode \code{'r|*'}.
1490 % patch 918101
1491 (Contributed by Lars Gust\"abel.)
1493 \item The \module{unicodedata} module has been updated to use version 4.1.0
1494 of the Unicode character database. Version 3.2.0 is required
1495 by some specifications, so it's still available as
1496 \member{unicodedata.db_3_2_0}.
1498 \item The \module{webbrowser} module received a number of
1499 enhancements.
1500 It's now usable as a script with \code{python -m webbrowser}, taking a
1501 URL as the argument; there are a number of switches
1502 to control the behaviour (\programopt{-n} for a new browser window,
1503 \programopt{-t} for a new tab). New module-level functions,
1504 \function{open_new()} and \function{open_new_tab()}, were added
1505 to support this. The module's \function{open()} function supports an
1506 additional feature, an \var{autoraise} parameter that signals whether
1507 to raise the open window when possible. A number of additional
1508 browsers were added to the supported list such as Firefox, Opera,
1509 Konqueror, and elinks. (Contributed by Oleg Broytmann and George
1510 Brandl.)
1511 % Patch #754022
1514 \item The \module{xmlrpclib} module now supports returning
1515 \class{datetime} objects for the XML-RPC date type. Supply
1516 \code{use_datetime=True} to the \function{loads()} function
1517 or the \class{Unmarshaller} class to enable this feature.
1518 (Contributed by Skip Montanaro.)
1519 % Patch 1120353
1521 \item The \module{zlib} module's \class{Compress} and \class{Decompress}
1522 objects now support a \method{copy()} method that makes a copy of the
1523 object's internal state and returns a new
1524 \class{Compress} or \class{Decompress} object.
1525 (Contributed by Chris AtLee.)
1526 % Patch 1435422
1528 \end{itemize}
1532 %======================================================================
1533 \subsection{The ctypes package\label{module-ctypes}}
1535 The \module{ctypes} package, written by Thomas Heller, has been added
1536 to the standard library. \module{ctypes} lets you call arbitrary functions
1537 in shared libraries or DLLs. Long-time users may remember the \module{dl} module, which
1538 provides functions for loading shared libraries and calling functions in them. The \module{ctypes} package is much fancier.
1540 To load a shared library or DLL, you must create an instance of the
1541 \class{CDLL} class and provide the name or path of the shared library
1542 or DLL. Once that's done, you can call arbitrary functions
1543 by accessing them as attributes of the \class{CDLL} object.
1545 \begin{verbatim}
1546 import ctypes
1548 libc = ctypes.CDLL('libc.so.6')
1549 result = libc.printf("Line of output\n")
1550 \end{verbatim}
1552 Type constructors for the various C types are provided: \function{c_int},
1553 \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
1554 to change the wrapped value. Python integers and strings will be automatically
1555 converted to the corresponding C types, but for other types you
1556 must call the correct type constructor. (And I mean \emph{must};
1557 getting it wrong will often result in the interpreter crashing
1558 with a segmentation fault.)
1560 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
1561 supposed to be immutable; breaking this rule will cause puzzling bugs. When you need a modifiable memory area,
1562 use \function{create_string_buffer()}:
1564 \begin{verbatim}
1565 s = "this is a string"
1566 buf = ctypes.create_string_buffer(s)
1567 libc.strfry(buf)
1568 \end{verbatim}
1570 C functions are assumed to return integers, but you can set
1571 the \member{restype} attribute of the function object to
1572 change this:
1574 \begin{verbatim}
1575 >>> libc.atof('2.71828')
1576 -1783957616
1577 >>> libc.atof.restype = ctypes.c_double
1578 >>> libc.atof('2.71828')
1579 2.71828
1580 \end{verbatim}
1582 \module{ctypes} also provides a wrapper for Python's C API
1583 as the \code{ctypes.pythonapi} object. This object does \emph{not}
1584 release the global interpreter lock before calling a function, because the lock must be held when calling into the interpreter's code.
1585 There's a \class{py_object()} type constructor that will create a
1586 \ctype{PyObject *} pointer. A simple usage:
1588 \begin{verbatim}
1589 import ctypes
1591 d = {}
1592 ctypes.pythonapi.PyObject_SetItem(ctypes.py_object(d),
1593 ctypes.py_object("abc"), ctypes.py_object(1))
1594 # d is now {'abc', 1}.
1595 \end{verbatim}
1597 Don't forget to use \class{py_object()}; if it's omitted you end
1598 up with a segmentation fault.
1600 \module{ctypes} has been around for a while, but people still write
1601 and distribution hand-coded extension modules because you can't rely on \module{ctypes} being present.
1602 Perhaps developers will begin to write
1603 Python wrappers atop a library accessed through \module{ctypes} instead
1604 of extension modules, now that \module{ctypes} is included with core Python.
1606 \begin{seealso}
1608 \seeurl{http://starship.python.net/crew/theller/ctypes/}
1609 {The ctypes web page, with a tutorial, reference, and FAQ.}
1611 \end{seealso}
1614 %======================================================================
1615 \subsection{The ElementTree package\label{module-etree}}
1617 A subset of Fredrik Lundh's ElementTree library for processing XML has
1618 been added to the standard library as \module{xml.etree}. The
1619 available modules are
1620 \module{ElementTree}, \module{ElementPath}, and
1621 \module{ElementInclude} from ElementTree 1.2.6.
1622 The \module{cElementTree} accelerator module is also included.
1624 The rest of this section will provide a brief overview of using
1625 ElementTree. Full documentation for ElementTree is available at
1626 \url{http://effbot.org/zone/element-index.htm}.
1628 ElementTree represents an XML document as a tree of element nodes.
1629 The text content of the document is stored as the \member{.text}
1630 and \member{.tail} attributes of
1631 (This is one of the major differences between ElementTree and
1632 the Document Object Model; in the DOM there are many different
1633 types of node, including \class{TextNode}.)
1635 The most commonly used parsing function is \function{parse()}, that
1636 takes either a string (assumed to contain a filename) or a file-like
1637 object and returns an \class{ElementTree} instance:
1639 \begin{verbatim}
1640 from xml.etree import ElementTree as ET
1642 tree = ET.parse('ex-1.xml')
1644 feed = urllib.urlopen(
1645 'http://planet.python.org/rss10.xml')
1646 tree = ET.parse(feed)
1647 \end{verbatim}
1649 Once you have an \class{ElementTree} instance, you
1650 can call its \method{getroot()} method to get the root \class{Element} node.
1652 There's also an \function{XML()} function that takes a string literal
1653 and returns an \class{Element} node (not an \class{ElementTree}).
1654 This function provides a tidy way to incorporate XML fragments,
1655 approaching the convenience of an XML literal:
1657 \begin{verbatim}
1658 svg = ET.XML("""<svg width="10px" version="1.0">
1659 </svg>""")
1660 svg.set('height', '320px')
1661 svg.append(elem1)
1662 \end{verbatim}
1664 Each XML element supports some dictionary-like and some list-like
1665 access methods. Dictionary-like operations are used to access attribute
1666 values, and list-like operations are used to access child nodes.
1668 \begin{tableii}{c|l}{code}{Operation}{Result}
1669 \lineii{elem[n]}{Returns n'th child element.}
1670 \lineii{elem[m:n]}{Returns list of m'th through n'th child elements.}
1671 \lineii{len(elem)}{Returns number of child elements.}
1672 \lineii{list(elem)}{Returns list of child elements.}
1673 \lineii{elem.append(elem2)}{Adds \var{elem2} as a child.}
1674 \lineii{elem.insert(index, elem2)}{Inserts \var{elem2} at the specified location.}
1675 \lineii{del elem[n]}{Deletes n'th child element.}
1676 \lineii{elem.keys()}{Returns list of attribute names.}
1677 \lineii{elem.get(name)}{Returns value of attribute \var{name}.}
1678 \lineii{elem.set(name, value)}{Sets new value for attribute \var{name}.}
1679 \lineii{elem.attrib}{Retrieves the dictionary containing attributes.}
1680 \lineii{del elem.attrib[name]}{Deletes attribute \var{name}.}
1681 \end{tableii}
1683 Comments and processing instructions are also represented as
1684 \class{Element} nodes. To check if a node is a comment or processing
1685 instructions:
1687 \begin{verbatim}
1688 if elem.tag is ET.Comment:
1690 elif elem.tag is ET.ProcessingInstruction:
1692 \end{verbatim}
1694 To generate XML output, you should call the
1695 \method{ElementTree.write()} method. Like \function{parse()},
1696 it can take either a string or a file-like object:
1698 \begin{verbatim}
1699 # Encoding is US-ASCII
1700 tree.write('output.xml')
1702 # Encoding is UTF-8
1703 f = open('output.xml', 'w')
1704 tree.write(f, encoding='utf-8')
1705 \end{verbatim}
1707 (Caution: the default encoding used for output is ASCII. For general
1708 XML work, where an element's name may contain arbitrary Unicode
1709 characters, ASCII isn't a very useful encoding because it will raise
1710 an exception if an element's name contains any characters with values
1711 greater than 127. Therefore, it's best to specify a different
1712 encoding such as UTF-8 that can handle any Unicode character.)
1714 This section is only a partial description of the ElementTree interfaces.
1715 Please read the package's official documentation for more details.
1717 \begin{seealso}
1719 \seeurl{http://effbot.org/zone/element-index.htm}
1720 {Official documentation for ElementTree.}
1723 \end{seealso}
1726 %======================================================================
1727 \subsection{The hashlib package\label{module-hashlib}}
1729 A new \module{hashlib} module, written by Gregory P. Smith,
1730 has been added to replace the
1731 \module{md5} and \module{sha} modules. \module{hashlib} adds support
1732 for additional secure hashes (SHA-224, SHA-256, SHA-384, and SHA-512).
1733 When available, the module uses OpenSSL for fast platform optimized
1734 implementations of algorithms.
1736 The old \module{md5} and \module{sha} modules still exist as wrappers
1737 around hashlib to preserve backwards compatibility. The new module's
1738 interface is very close to that of the old modules, but not identical.
1739 The most significant difference is that the constructor functions
1740 for creating new hashing objects are named differently.
1742 \begin{verbatim}
1743 # Old versions
1744 h = md5.md5()
1745 h = md5.new()
1747 # New version
1748 h = hashlib.md5()
1750 # Old versions
1751 h = sha.sha()
1752 h = sha.new()
1754 # New version
1755 h = hashlib.sha1()
1757 # Hash that weren't previously available
1758 h = hashlib.sha224()
1759 h = hashlib.sha256()
1760 h = hashlib.sha384()
1761 h = hashlib.sha512()
1763 # Alternative form
1764 h = hashlib.new('md5') # Provide algorithm as a string
1765 \end{verbatim}
1767 Once a hash object has been created, its methods are the same as before:
1768 \method{update(\var{string})} hashes the specified string into the
1769 current digest state, \method{digest()} and \method{hexdigest()}
1770 return the digest value as a binary string or a string of hex digits,
1771 and \method{copy()} returns a new hashing object with the same digest state.
1774 %======================================================================
1775 \subsection{The sqlite3 package\label{module-sqlite}}
1777 The pysqlite module (\url{http://www.pysqlite.org}), a wrapper for the
1778 SQLite embedded database, has been added to the standard library under
1779 the package name \module{sqlite3}.
1781 SQLite is a C library that provides a SQL-language database that
1782 stores data in disk files without requiring a separate server process.
1783 pysqlite was written by Gerhard H\"aring and provides a SQL interface
1784 compliant with the DB-API 2.0 specification described by
1785 \pep{249}. This means that it should be possible to write the first
1786 version of your applications using SQLite for data storage. If
1787 switching to a larger database such as PostgreSQL or Oracle is
1788 later necessary, the switch should be relatively easy.
1790 If you're compiling the Python source yourself, note that the source
1791 tree doesn't include the SQLite code, only the wrapper module.
1792 You'll need to have the SQLite libraries and headers installed before
1793 compiling Python, and the build process will compile the module when
1794 the necessary headers are available.
1796 To use the module, you must first create a \class{Connection} object
1797 that represents the database. Here the data will be stored in the
1798 \file{/tmp/example} file:
1800 \begin{verbatim}
1801 conn = sqlite3.connect('/tmp/example')
1802 \end{verbatim}
1804 You can also supply the special name \samp{:memory:} to create
1805 a database in RAM.
1807 Once you have a \class{Connection}, you can create a \class{Cursor}
1808 object and call its \method{execute()} method to perform SQL commands:
1810 \begin{verbatim}
1811 c = conn.cursor()
1813 # Create table
1814 c.execute('''create table stocks
1815 (date timestamp, trans varchar, symbol varchar,
1816 qty decimal, price decimal)''')
1818 # Insert a row of data
1819 c.execute("""insert into stocks
1820 values ('2006-01-05','BUY','RHAT',100,35.14)""")
1821 \end{verbatim}
1823 Usually your SQL operations will need to use values from Python
1824 variables. You shouldn't assemble your query using Python's string
1825 operations because doing so is insecure; it makes your program
1826 vulnerable to an SQL injection attack.
1828 Instead, use SQLite's parameter substitution. Put \samp{?} as a
1829 placeholder wherever you want to use a value, and then provide a tuple
1830 of values as the second argument to the cursor's \method{execute()}
1831 method. For example:
1833 \begin{verbatim}
1834 # Never do this -- insecure!
1835 symbol = 'IBM'
1836 c.execute("... where symbol = '%s'" % symbol)
1838 # Do this instead
1839 t = (symbol,)
1840 c.execute('select * from stocks where symbol=?', t)
1842 # Larger example
1843 for t in (('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
1844 ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
1845 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
1847 c.execute('insert into stocks values (?,?,?,?,?)', t)
1848 \end{verbatim}
1850 To retrieve data after executing a SELECT statement, you can either
1851 treat the cursor as an iterator, call the cursor's \method{fetchone()}
1852 method to retrieve a single matching row,
1853 or call \method{fetchall()} to get a list of the matching rows.
1855 This example uses the iterator form:
1857 \begin{verbatim}
1858 >>> c = conn.cursor()
1859 >>> c.execute('select * from stocks order by price')
1860 >>> for row in c:
1861 ... print row
1863 (u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001)
1864 (u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
1865 (u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
1866 (u'2006-04-05', u'BUY', u'MSOFT', 1000, 72.0)
1868 \end{verbatim}
1870 For more information about the SQL dialect supported by SQLite, see
1871 \url{http://www.sqlite.org}.
1873 \begin{seealso}
1875 \seeurl{http://www.pysqlite.org}
1876 {The pysqlite web page.}
1878 \seeurl{http://www.sqlite.org}
1879 {The SQLite web page; the documentation describes the syntax and the
1880 available data types for the supported SQL dialect.}
1882 \seepep{249}{Database API Specification 2.0}{PEP written by
1883 Marc-Andr\'e Lemburg.}
1885 \end{seealso}
1888 % ======================================================================
1889 \section{Build and C API Changes\label{build-api}}
1891 Changes to Python's build process and to the C API include:
1893 \begin{itemize}
1895 \item The largest change to the C API came from \pep{353},
1896 which modifies the interpreter to use a \ctype{Py_ssize_t} type
1897 definition instead of \ctype{int}. See the earlier
1898 section~\ref{pep-353} for a discussion of this change.
1900 \item The design of the bytecode compiler has changed a great deal, to
1901 no longer generate bytecode by traversing the parse tree. Instead
1902 the parse tree is converted to an abstract syntax tree (or AST), and it is
1903 the abstract syntax tree that's traversed to produce the bytecode.
1905 It's possible for Python code to obtain AST objects by using the
1906 \function{compile()} built-in and specifying \code{_ast.PyCF_ONLY_AST}
1907 as the value of the
1908 \var{flags} parameter:
1910 \begin{verbatim}
1911 from _ast import PyCF_ONLY_AST
1912 ast = compile("""a=0
1913 for i in range(10):
1914 a += i
1915 """, "<string>", 'exec', PyCF_ONLY_AST)
1917 assignment = ast.body[0]
1918 for_loop = ast.body[1]
1919 \end{verbatim}
1921 No documentation has been written for the AST code yet. To start
1922 learning about it, read the definition of the various AST nodes in
1923 \file{Parser/Python.asdl}. A Python script reads this file and
1924 generates a set of C structure definitions in
1925 \file{Include/Python-ast.h}. The \cfunction{PyParser_ASTFromString()}
1926 and \cfunction{PyParser_ASTFromFile()}, defined in
1927 \file{Include/pythonrun.h}, take Python source as input and return the
1928 root of an AST representing the contents. This AST can then be turned
1929 into a code object by \cfunction{PyAST_Compile()}. For more
1930 information, read the source code, and then ask questions on
1931 python-dev.
1933 % List of names taken from Jeremy's python-dev post at
1934 % http://mail.python.org/pipermail/python-dev/2005-October/057500.html
1935 The AST code was developed under Jeremy Hylton's management, and
1936 implemented by (in alphabetical order) Brett Cannon, Nick Coghlan,
1937 Grant Edwards, John Ehresman, Kurt Kaiser, Neal Norwitz, Tim Peters,
1938 Armin Rigo, and Neil Schemenauer, plus the participants in a number of
1939 AST sprints at conferences such as PyCon.
1941 \item The built-in set types now have an official C API. Call
1942 \cfunction{PySet_New()} and \cfunction{PyFrozenSet_New()} to create a
1943 new set, \cfunction{PySet_Add()} and \cfunction{PySet_Discard()} to
1944 add and remove elements, and \cfunction{PySet_Contains} and
1945 \cfunction{PySet_Size} to examine the set's state.
1946 (Contributed by Raymond Hettinger.)
1948 \item C code can now obtain information about the exact revision
1949 of the Python interpreter by calling the
1950 \cfunction{Py_GetBuildInfo()} function that returns a
1951 string of build information like this:
1952 \code{"trunk:45355:45356M, Apr 13 2006, 07:42:19"}.
1953 (Contributed by Barry Warsaw.)
1955 \item \cfunction{PyErr_NewException(\var{name}, \var{base},
1956 \var{dict})} can now accept a tuple of base classes as its \var{base}
1957 argument. (Contributed by Georg Brandl.)
1959 \item The CPython interpreter is still written in C, but
1960 the code can now be compiled with a {\Cpp} compiler without errors.
1961 (Implemented by Anthony Baxter, Martin von~L\"owis, Skip Montanaro.)
1963 \item The \cfunction{PyRange_New()} function was removed. It was
1964 never documented, never used in the core code, and had dangerously lax
1965 error checking.
1967 \end{itemize}
1970 %======================================================================
1971 \subsection{Port-Specific Changes\label{ports}}
1973 \begin{itemize}
1975 \item MacOS X (10.3 and higher): dynamic loading of modules
1976 now uses the \cfunction{dlopen()} function instead of MacOS-specific
1977 functions.
1979 \item MacOS X: a \longprogramopt{enable-universalsdk} switch was added
1980 to the \program{configure} script that compiles the interpreter as a
1981 universal binary able to run on both PowerPC and Intel processors.
1982 (Contributed by Ronald Oussoren.)
1984 \item Windows: \file{.dll} is no longer supported as a filename extension for
1985 extension modules. \file{.pyd} is now the only filename extension that will
1986 be searched for.
1988 \end{itemize}
1991 %======================================================================
1992 \section{Other Changes and Fixes \label{section-other}}
1994 As usual, there were a bunch of other improvements and bugfixes
1995 scattered throughout the source tree. A search through the SVN change
1996 logs finds there were XXX patches applied and YYY bugs fixed between
1997 Python 2.4 and 2.5. Both figures are likely to be underestimates.
1999 Some of the more notable changes are:
2001 \begin{itemize}
2003 \item Evan Jones's patch to obmalloc, first described in a talk
2004 at PyCon DC 2005, was applied. Python 2.4 allocated small objects in
2005 256K-sized arenas, but never freed arenas. With this patch, Python
2006 will free arenas when they're empty. The net effect is that on some
2007 platforms, when you allocate many objects, Python's memory usage may
2008 actually drop when you delete them, and the memory may be returned to
2009 the operating system. (Implemented by Evan Jones, and reworked by Tim
2010 Peters.)
2012 Note that this change means extension modules need to be more careful
2013 with how they allocate memory. Python's API has many different
2014 functions for allocating memory that are grouped into families. For
2015 example, \cfunction{PyMem_Malloc()}, \cfunction{PyMem_Realloc()}, and
2016 \cfunction{PyMem_Free()} are one family that allocates raw memory,
2017 while \cfunction{PyObject_Malloc()}, \cfunction{PyObject_Realloc()},
2018 and \cfunction{PyObject_Free()} are another family that's supposed to
2019 be used for creating Python objects.
2021 Previously these different families all reduced to the platform's
2022 \cfunction{malloc()} and \cfunction{free()} functions. This meant
2023 it didn't matter if you got things wrong and allocated memory with the
2024 \cfunction{PyMem} function but freed it with the \cfunction{PyObject}
2025 function. With the obmalloc change, these families now do different
2026 things, and mismatches will probably result in a segfault. You should
2027 carefully test your C extension modules with Python 2.5.
2029 \item Coverity, a company that markets a source code analysis tool
2030 called Prevent, provided the results of their examination of the Python
2031 source code. The analysis found about 60 bugs that
2032 were quickly fixed. Many of the bugs were refcounting problems, often
2033 occurring in error-handling code. See
2034 \url{http://scan.coverity.com} for the statistics.
2036 \end{itemize}
2039 %======================================================================
2040 \section{Porting to Python 2.5\label{porting}}
2042 This section lists previously described changes that may require
2043 changes to your code:
2045 \begin{itemize}
2047 \item ASCII is now the default encoding for modules. It's now
2048 a syntax error if a module contains string literals with 8-bit
2049 characters but doesn't have an encoding declaration. In Python 2.4
2050 this triggered a warning, not a syntax error.
2052 \item Previously, the \member{gi_frame} attribute of a generator
2053 was always a frame object. Because of the \pep{342} changes
2054 described in section~\ref{pep-342}, it's now possible
2055 for \member{gi_frame} to be \code{None}.
2058 \item Library: The \module{pickle} and \module{cPickle} modules no
2059 longer accept a return value of \code{None} from the
2060 \method{__reduce__()} method; the method must return a tuple of
2061 arguments instead. The modules also no longer accept the deprecated
2062 \var{bin} keyword parameter.
2064 \item C API: Many functions now use \ctype{Py_ssize_t}
2065 instead of \ctype{int} to allow processing more data on 64-bit
2066 machines. Extension code may need to make the same change to avoid
2067 warnings and to support 64-bit machines. See the earlier
2068 section~\ref{pep-353} for a discussion of this change.
2070 \item C API:
2071 The obmalloc changes mean that
2072 you must be careful to not mix usage
2073 of the \cfunction{PyMem_*()} and \cfunction{PyObject_*()}
2074 families of functions. Memory allocated with
2075 one family's \cfunction{*_Malloc()} must be
2076 freed with the corresponding family's \cfunction{*_Free()} function.
2078 \end{itemize}
2081 %======================================================================
2082 \section{Acknowledgements \label{acks}}
2084 The author would like to thank the following people for offering
2085 suggestions, corrections and assistance with various drafts of this
2086 article: Phillip J. Eby, Kent Johnson, Martin von~L\"owis, Fredrik Lundh,
2087 Gustavo Niemeyer, James Pryor, Mike Rovner, Scott Weikart, Thomas Wouters.
2089 \end{document}