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