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