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