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