Fred Drake | 2db7680 | 2004-12-01 05:05:47 +0000 | [diff] [blame] | 1 | \documentclass{howto} |
| 2 | \usepackage{distutils} |
| 3 | % $Id$ |
| 4 | |
Fred Drake | 2db7680 | 2004-12-01 05:05:47 +0000 | [diff] [blame] | 5 | |
| 6 | \title{What's New in Python 2.5} |
| 7 | \release{0.0} |
Andrew M. Kuchling | 92e2495 | 2004-12-03 13:54:09 +0000 | [diff] [blame] | 8 | \author{A.M. Kuchling} |
| 9 | \authoraddress{\email{amk@amk.ca}} |
Fred Drake | 2db7680 | 2004-12-01 05:05:47 +0000 | [diff] [blame] | 10 | |
| 11 | \begin{document} |
| 12 | \maketitle |
| 13 | \tableofcontents |
| 14 | |
| 15 | 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] | 16 | for Python 2.5 has been set; it will probably be released in the |
| 17 | autumn of 2006. |
Fred Drake | 2db7680 | 2004-12-01 05:05:47 +0000 | [diff] [blame] | 18 | |
Andrew M. Kuchling | 437567c | 2006-03-07 20:48:55 +0000 | [diff] [blame] | 19 | % XXX Compare with previous release in 2 - 3 sentences here. |
Fred Drake | 2db7680 | 2004-12-01 05:05:47 +0000 | [diff] [blame] | 20 | |
| 21 | This article doesn't attempt to provide a complete specification of |
| 22 | the new features, but instead provides a convenient overview. For |
| 23 | 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] | 24 | % XXX add hyperlink when the documentation becomes available online. |
Fred Drake | 2db7680 | 2004-12-01 05:05:47 +0000 | [diff] [blame] | 25 | If you want to understand the complete implementation and design |
| 26 | rationale, refer to the PEP for a particular new feature. |
| 27 | |
| 28 | |
| 29 | %====================================================================== |
Andrew M. Kuchling | 437567c | 2006-03-07 20:48:55 +0000 | [diff] [blame] | 30 | \section{PEP 308: Conditional Expressions} |
| 31 | |
Andrew M. Kuchling | e362d93 | 2006-03-09 13:56:25 +0000 | [diff] [blame] | 32 | For a long time, people have been requesting a way to write |
| 33 | conditional expressions, expressions that return value A or value B |
| 34 | depending on whether a Boolean value is true or false. A conditional |
| 35 | expression lets you write a single assignment statement that has the |
| 36 | same effect as the following: |
| 37 | |
| 38 | \begin{verbatim} |
| 39 | if condition: |
| 40 | x = true_value |
| 41 | else: |
| 42 | x = false_value |
| 43 | \end{verbatim} |
| 44 | |
| 45 | There have been endless tedious discussions of syntax on both |
| 46 | python-dev and comp.lang.python, and even a vote that found the |
| 47 | majority of voters wanted some way to write conditional expressions, |
| 48 | but there was no syntax that was clearly preferred by a majority. |
| 49 | Candidates include C's \code{cond ? true_v : false_v}, |
| 50 | \code{if cond then true_v else false_v}, and 16 other variations. |
| 51 | |
| 52 | GvR eventually chose a surprising syntax: |
| 53 | |
| 54 | \begin{verbatim} |
| 55 | x = true_value if condition else false_value |
| 56 | \end{verbatim} |
| 57 | |
| 58 | Evaluation is still lazy as in existing Boolean expression, so the |
| 59 | evaluation jumps around a bit. The \var{condition} expression is |
| 60 | evaluated first, and the \var{true_value} expression is evaluated only |
| 61 | if the condition was true. Similarly, the \var{false_value} |
| 62 | expression is only evaluated when the condition is false. |
| 63 | |
| 64 | This syntax may seem strange and backwards; why does the condition go |
| 65 | in the \emph{middle} of the expression, and not in the front as in C's |
| 66 | \code{c ? x : y}? The decision was checked by applying the new syntax |
| 67 | to the modules in the standard library and seeing how the resulting |
| 68 | code read. In many cases where a conditional expression is used, one |
| 69 | value seems to be the 'common case' and one value is an 'exceptional |
| 70 | case', used only on rarer occasions when the condition isn't met. The |
| 71 | conditional syntax makes this pattern a bit more obvious: |
| 72 | |
| 73 | \begin{verbatim} |
| 74 | contents = ((doc + '\n') if doc else '') |
| 75 | \end{verbatim} |
| 76 | |
| 77 | I read the above statement as meaning ``here \var{contents} is |
Andrew M. Kuchling | d0fcc02 | 2006-03-09 13:57:28 +0000 | [diff] [blame] | 78 | usually assigned a value of \code{doc+'\e n'}; sometimes |
Andrew M. Kuchling | e362d93 | 2006-03-09 13:56:25 +0000 | [diff] [blame] | 79 | \var{doc} is empty, in which special case an empty string is returned.'' |
| 80 | I doubt I will use conditional expressions very often where there |
| 81 | isn't a clear common and uncommon case. |
| 82 | |
| 83 | There was some discussion of whether the language should require |
| 84 | surrounding conditional expressions with parentheses. The decision |
| 85 | was made to \emph{not} require parentheses in the Python language's |
| 86 | grammar, but as a matter of style I think you should always use them. |
| 87 | Consider these two statements: |
| 88 | |
| 89 | \begin{verbatim} |
| 90 | # First version -- no parens |
| 91 | level = 1 if logging else 0 |
| 92 | |
| 93 | # Second version -- with parens |
| 94 | level = (1 if logging else 0) |
| 95 | \end{verbatim} |
| 96 | |
| 97 | In the first version, I think a reader's eye might group the statement |
| 98 | into 'level = 1', 'if logging', 'else 0', and think that the condition |
| 99 | decides whether the assignment to \var{level} is performed. The |
| 100 | second version reads better, in my opinion, because it makes it clear |
| 101 | that the assignment is always performed and the choice is being made |
| 102 | between two values. |
| 103 | |
| 104 | Another reason for including the brackets: a few odd combinations of |
| 105 | list comprehensions and lambdas could look like incorrect conditional |
| 106 | expressions. See \pep{308} for some examples. If you put parentheses |
| 107 | around your conditional expressions, you won't run into this case. |
| 108 | |
| 109 | |
| 110 | \begin{seealso} |
| 111 | |
| 112 | \seepep{308}{Conditional Expressions}{PEP written by |
| 113 | Guido van Rossum and Raymond D. Hettinger; implemented by Thomas |
| 114 | Wouters.} |
| 115 | |
| 116 | \end{seealso} |
Andrew M. Kuchling | 437567c | 2006-03-07 20:48:55 +0000 | [diff] [blame] | 117 | |
| 118 | |
| 119 | %====================================================================== |
Andrew M. Kuchling | 3e41b05 | 2005-03-01 00:53:46 +0000 | [diff] [blame] | 120 | \section{PEP 309: Partial Function Application} |
Fred Drake | 2db7680 | 2004-12-01 05:05:47 +0000 | [diff] [blame] | 121 | |
Andrew M. Kuchling | b1c96fd | 2005-03-20 21:42:04 +0000 | [diff] [blame] | 122 | The \module{functional} module is intended to contain tools for |
Andrew M. Kuchling | 437567c | 2006-03-07 20:48:55 +0000 | [diff] [blame] | 123 | functional-style programming. Currently it only contains a |
| 124 | \class{partial()} function, but new functions will probably be added |
| 125 | in future versions of Python. |
Andrew M. Kuchling | b1c96fd | 2005-03-20 21:42:04 +0000 | [diff] [blame] | 126 | |
Andrew M. Kuchling | 4b000cd | 2005-04-09 15:51:44 +0000 | [diff] [blame] | 127 | For programs written in a functional style, it can be useful to |
| 128 | construct variants of existing functions that have some of the |
| 129 | parameters filled in. Consider a Python function \code{f(a, b, c)}; |
| 130 | you could create a new function \code{g(b, c)} that was equivalent to |
| 131 | \code{f(1, b, c)}. This is called ``partial function application'', |
| 132 | and is provided by the \class{partial} class in the new |
| 133 | \module{functional} module. |
| 134 | |
| 135 | The constructor for \class{partial} takes the arguments |
| 136 | \code{(\var{function}, \var{arg1}, \var{arg2}, ... |
| 137 | \var{kwarg1}=\var{value1}, \var{kwarg2}=\var{value2})}. The resulting |
| 138 | object is callable, so you can just call it to invoke \var{function} |
| 139 | with the filled-in arguments. |
| 140 | |
| 141 | Here's a small but realistic example: |
| 142 | |
| 143 | \begin{verbatim} |
| 144 | import functional |
| 145 | |
| 146 | def log (message, subsystem): |
| 147 | "Write the contents of 'message' to the specified subsystem." |
| 148 | print '%s: %s' % (subsystem, message) |
| 149 | ... |
| 150 | |
| 151 | server_log = functional.partial(log, subsystem='server') |
Andrew M. Kuchling | 437567c | 2006-03-07 20:48:55 +0000 | [diff] [blame] | 152 | server_log('Unable to open socket') |
Andrew M. Kuchling | 4b000cd | 2005-04-09 15:51:44 +0000 | [diff] [blame] | 153 | \end{verbatim} |
| 154 | |
Andrew M. Kuchling | 6af7fe0 | 2005-08-02 17:20:36 +0000 | [diff] [blame] | 155 | Here's another example, from a program that uses PyGTk. Here a |
| 156 | context-sensitive pop-up menu is being constructed dynamically. The |
| 157 | callback provided for the menu option is a partially applied version |
| 158 | of the \method{open_item()} method, where the first argument has been |
| 159 | provided. |
Andrew M. Kuchling | 4b000cd | 2005-04-09 15:51:44 +0000 | [diff] [blame] | 160 | |
Andrew M. Kuchling | 6af7fe0 | 2005-08-02 17:20:36 +0000 | [diff] [blame] | 161 | \begin{verbatim} |
| 162 | ... |
| 163 | class Application: |
| 164 | def open_item(self, path): |
| 165 | ... |
| 166 | def init (self): |
| 167 | open_func = functional.partial(self.open_item, item_path) |
| 168 | popup_menu.append( ("Open", open_func, 1) ) |
| 169 | \end{verbatim} |
Andrew M. Kuchling | b1c96fd | 2005-03-20 21:42:04 +0000 | [diff] [blame] | 170 | |
| 171 | |
| 172 | \begin{seealso} |
| 173 | |
| 174 | \seepep{309}{Partial Function Application}{PEP proposed and written by |
| 175 | Peter Harris; implemented by Hye-Shik Chang, with adaptations by |
| 176 | Raymond Hettinger.} |
| 177 | |
| 178 | \end{seealso} |
Fred Drake | 2db7680 | 2004-12-01 05:05:47 +0000 | [diff] [blame] | 179 | |
| 180 | |
| 181 | %====================================================================== |
Fred Drake | db7b002 | 2005-03-20 22:19:47 +0000 | [diff] [blame] | 182 | \section{PEP 314: Metadata for Python Software Packages v1.1} |
| 183 | |
Andrew M. Kuchling | d8d732e | 2005-04-09 23:59:41 +0000 | [diff] [blame] | 184 | Some simple dependency support was added to Distutils. The |
Andrew M. Kuchling | 437567c | 2006-03-07 20:48:55 +0000 | [diff] [blame] | 185 | \function{setup()} function now has \code{requires}, \code{provides}, |
| 186 | and \code{obsoletes} keyword parameters. When you build a source |
| 187 | distribution using the \code{sdist} command, the dependency |
| 188 | information will be recorded in the \file{PKG-INFO} file. |
Andrew M. Kuchling | d8d732e | 2005-04-09 23:59:41 +0000 | [diff] [blame] | 189 | |
Andrew M. Kuchling | 437567c | 2006-03-07 20:48:55 +0000 | [diff] [blame] | 190 | Another new keyword parameter is \code{download_url}, which should be |
| 191 | set to a URL for the package's source code. This means it's now |
| 192 | possible to look up an entry in the package index, determine the |
| 193 | dependencies for a package, and download the required packages. |
Andrew M. Kuchling | d8d732e | 2005-04-09 23:59:41 +0000 | [diff] [blame] | 194 | |
| 195 | % XXX put example here |
| 196 | |
| 197 | \begin{seealso} |
| 198 | |
| 199 | \seepep{314}{Metadata for Python Software Packages v1.1}{PEP proposed |
| 200 | and written by A.M. Kuchling, Richard Jones, and Fred Drake; |
| 201 | implemented by Richard Jones and Fred Drake.} |
| 202 | |
| 203 | \end{seealso} |
Fred Drake | db7b002 | 2005-03-20 22:19:47 +0000 | [diff] [blame] | 204 | |
| 205 | |
| 206 | %====================================================================== |
Andrew M. Kuchling | 437567c | 2006-03-07 20:48:55 +0000 | [diff] [blame] | 207 | \section{PEP 328: Absolute and Relative Imports} |
| 208 | |
| 209 | % XXX write this |
| 210 | |
| 211 | |
| 212 | %====================================================================== |
Andrew M. Kuchling | 21d3a7c | 2006-03-15 11:53:09 +0000 | [diff] [blame^] | 213 | \section{PEP 338: Executing Modules as Scripts} |
| 214 | |
| 215 | % XXX write this |
| 216 | |
| 217 | |
| 218 | %====================================================================== |
Andrew M. Kuchling | 437567c | 2006-03-07 20:48:55 +0000 | [diff] [blame] | 219 | \section{PEP 341: Unified try/except/finally} |
| 220 | |
| 221 | % XXX write this |
| 222 | |
| 223 | |
| 224 | %====================================================================== |
Andrew M. Kuchling | a2e21cb | 2005-08-02 17:13:21 +0000 | [diff] [blame] | 225 | \section{PEP 342: New Generator Features} |
| 226 | |
Andrew M. Kuchling | 150e349 | 2005-08-23 00:56:06 +0000 | [diff] [blame] | 227 | 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] | 228 | generator's code is invoked to create an iterator, there's no way to |
| 229 | pass any new information into the function when its execution is |
| 230 | resumed. Hackish solutions to this include making the generator's |
| 231 | code look at a global variable and then changing the global variable's |
| 232 | value, or passing in some mutable object that callers then modify. |
| 233 | Python 2.5 adds the ability to pass values \emph{into} a generator. |
Andrew M. Kuchling | 150e349 | 2005-08-23 00:56:06 +0000 | [diff] [blame] | 234 | |
| 235 | To refresh your memory of basic generators, here's a simple example: |
| 236 | |
| 237 | \begin{verbatim} |
| 238 | def counter (maximum): |
| 239 | i = 0 |
| 240 | while i < maximum: |
| 241 | yield i |
| 242 | i += 1 |
| 243 | \end{verbatim} |
| 244 | |
Andrew M. Kuchling | 0738206 | 2005-08-27 18:45:47 +0000 | [diff] [blame] | 245 | When you call \code{counter(10)}, the result is an iterator that |
| 246 | returns the values from 0 up to 9. On encountering the |
| 247 | \keyword{yield} statement, the iterator returns the provided value and |
| 248 | suspends the function's execution, preserving the local variables. |
| 249 | Execution resumes on the following call to the iterator's |
Andrew M. Kuchling | 437567c | 2006-03-07 20:48:55 +0000 | [diff] [blame] | 250 | \method{next()} method, picking up after the \keyword{yield} statement. |
Andrew M. Kuchling | 150e349 | 2005-08-23 00:56:06 +0000 | [diff] [blame] | 251 | |
Andrew M. Kuchling | 0738206 | 2005-08-27 18:45:47 +0000 | [diff] [blame] | 252 | In Python 2.3, \keyword{yield} was a statement; it didn't return any |
| 253 | value. In 2.5, \keyword{yield} is now an expression, returning a |
| 254 | 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] | 255 | |
Andrew M. Kuchling | 0738206 | 2005-08-27 18:45:47 +0000 | [diff] [blame] | 256 | \begin{verbatim} |
| 257 | val = (yield i) |
| 258 | \end{verbatim} |
| 259 | |
| 260 | I recommend that you always put parentheses around a \keyword{yield} |
| 261 | expression when you're doing something with the returned value, as in |
| 262 | the above example. The parentheses aren't always necessary, but it's |
| 263 | 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] | 264 | 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] | 265 | always be parenthesized except when it occurs at the top-level |
Andrew M. Kuchling | 437567c | 2006-03-07 20:48:55 +0000 | [diff] [blame] | 266 | expression on the right-hand side of an assignment, meaning you can |
| 267 | write \code{val = yield i} but have to use parentheses when there's an |
| 268 | operation, as in \code{val = (yield i) + 12}.} |
Andrew M. Kuchling | 0738206 | 2005-08-27 18:45:47 +0000 | [diff] [blame] | 269 | |
| 270 | Values are sent into a generator by calling its |
| 271 | \method{send(\var{value})} method. The generator's code is then |
Andrew M. Kuchling | 437567c | 2006-03-07 20:48:55 +0000 | [diff] [blame] | 272 | resumed and the \keyword{yield} expression returns the specified |
| 273 | \var{value}. If the regular \method{next()} method is called, the |
| 274 | \keyword{yield} returns \constant{None}. |
Andrew M. Kuchling | 0738206 | 2005-08-27 18:45:47 +0000 | [diff] [blame] | 275 | |
| 276 | Here's the previous example, modified to allow changing the value of |
| 277 | the internal counter. |
| 278 | |
| 279 | \begin{verbatim} |
| 280 | def counter (maximum): |
| 281 | i = 0 |
| 282 | while i < maximum: |
| 283 | val = (yield i) |
| 284 | # If value provided, change counter |
| 285 | if val is not None: |
| 286 | i = val |
| 287 | else: |
| 288 | i += 1 |
| 289 | \end{verbatim} |
| 290 | |
| 291 | And here's an example of changing the counter: |
| 292 | |
| 293 | \begin{verbatim} |
| 294 | >>> it = counter(10) |
| 295 | >>> print it.next() |
| 296 | 0 |
| 297 | >>> print it.next() |
| 298 | 1 |
| 299 | >>> print it.send(8) |
| 300 | 8 |
| 301 | >>> print it.next() |
| 302 | 9 |
| 303 | >>> print it.next() |
| 304 | Traceback (most recent call last): |
| 305 | File ``t.py'', line 15, in ? |
| 306 | print it.next() |
| 307 | StopIteration |
Andrew M. Kuchling | c203370 | 2005-08-29 13:30:12 +0000 | [diff] [blame] | 308 | \end{verbatim} |
Andrew M. Kuchling | 0738206 | 2005-08-27 18:45:47 +0000 | [diff] [blame] | 309 | |
Andrew M. Kuchling | 437567c | 2006-03-07 20:48:55 +0000 | [diff] [blame] | 310 | Because \keyword{yield} will often be returning \constant{None}, you |
| 311 | should always check for this case. Don't just use its value in |
| 312 | expressions unless you're sure that the \method{send()} method |
| 313 | will be the only method used resume your generator function. |
Andrew M. Kuchling | 0738206 | 2005-08-27 18:45:47 +0000 | [diff] [blame] | 314 | |
Andrew M. Kuchling | 437567c | 2006-03-07 20:48:55 +0000 | [diff] [blame] | 315 | In addition to \method{send()}, there are two other new methods on |
| 316 | generators: |
Andrew M. Kuchling | 0738206 | 2005-08-27 18:45:47 +0000 | [diff] [blame] | 317 | |
| 318 | \begin{itemize} |
| 319 | |
| 320 | \item \method{throw(\var{type}, \var{value}=None, |
| 321 | \var{traceback}=None)} is used to raise an exception inside the |
| 322 | generator; the exception is raised by the \keyword{yield} expression |
| 323 | where the generator's execution is paused. |
| 324 | |
| 325 | \item \method{close()} raises a new \exception{GeneratorExit} |
| 326 | exception inside the generator to terminate the iteration. |
| 327 | On receiving this |
| 328 | exception, the generator's code must either raise |
| 329 | \exception{GeneratorExit} or \exception{StopIteration}; catching the |
| 330 | exception and doing anything else is illegal and will trigger |
| 331 | a \exception{RuntimeError}. \method{close()} will also be called by |
| 332 | Python's garbage collection when the generator is garbage-collected. |
| 333 | |
| 334 | If you need to run cleanup code in case of a \exception{GeneratorExit}, |
| 335 | I suggest using a \code{try: ... finally:} suite instead of |
| 336 | catching \exception{GeneratorExit}. |
| 337 | |
| 338 | \end{itemize} |
| 339 | |
| 340 | The cumulative effect of these changes is to turn generators from |
| 341 | one-way producers of information into both producers and consumers. |
Andrew M. Kuchling | 437567c | 2006-03-07 20:48:55 +0000 | [diff] [blame] | 342 | |
Andrew M. Kuchling | 0738206 | 2005-08-27 18:45:47 +0000 | [diff] [blame] | 343 | Generators also become \emph{coroutines}, a more generalized form of |
Andrew M. Kuchling | 437567c | 2006-03-07 20:48:55 +0000 | [diff] [blame] | 344 | subroutines. Subroutines are entered at one point and exited at |
Andrew M. Kuchling | 0738206 | 2005-08-27 18:45:47 +0000 | [diff] [blame] | 345 | another point (the top of the function, and a \keyword{return |
| 346 | statement}), but coroutines can be entered, exited, and resumed at |
Andrew M. Kuchling | 437567c | 2006-03-07 20:48:55 +0000 | [diff] [blame] | 347 | many different points (the \keyword{yield} statements). |
Andrew M. Kuchling | 0738206 | 2005-08-27 18:45:47 +0000 | [diff] [blame] | 348 | |
Andrew M. Kuchling | 437567c | 2006-03-07 20:48:55 +0000 | [diff] [blame] | 349 | |
Andrew M. Kuchling | a2e21cb | 2005-08-02 17:13:21 +0000 | [diff] [blame] | 350 | \begin{seealso} |
| 351 | |
| 352 | \seepep{342}{Coroutines via Enhanced Generators}{PEP written by |
| 353 | Guido van Rossum and Phillip J. Eby; |
Andrew M. Kuchling | 0738206 | 2005-08-27 18:45:47 +0000 | [diff] [blame] | 354 | implemented by Phillip J. Eby. Includes examples of |
| 355 | some fancier uses of generators as coroutines.} |
| 356 | |
| 357 | \seeurl{http://en.wikipedia.org/wiki/Coroutine}{The Wikipedia entry for |
| 358 | coroutines.} |
| 359 | |
Neal Norwitz | 0917988 | 2006-03-04 23:31:45 +0000 | [diff] [blame] | 360 | \seeurl{http://www.sidhe.org/\~{}dan/blog/archives/000178.html}{An |
Andrew M. Kuchling | 0738206 | 2005-08-27 18:45:47 +0000 | [diff] [blame] | 361 | explanation of coroutines from a Perl point of view, written by Dan |
| 362 | Sugalski.} |
Andrew M. Kuchling | a2e21cb | 2005-08-02 17:13:21 +0000 | [diff] [blame] | 363 | |
| 364 | \end{seealso} |
| 365 | |
| 366 | |
| 367 | %====================================================================== |
Andrew M. Kuchling | 437567c | 2006-03-07 20:48:55 +0000 | [diff] [blame] | 368 | \section{PEP 343: The 'with' statement} |
| 369 | |
| 370 | % XXX write this |
| 371 | |
| 372 | |
| 373 | %====================================================================== |
Andrew M. Kuchling | 8f4d255 | 2006-03-08 01:50:20 +0000 | [diff] [blame] | 374 | \section{PEP 352: Exceptions as New-Style Classes} |
| 375 | |
Andrew M. Kuchling | aeadf95 | 2006-03-09 19:06:05 +0000 | [diff] [blame] | 376 | Exception classes can now be new-style classes, not just classic classes, |
| 377 | and the built-in \exception{Exception} class and all |
| 378 | |
| 379 | The inheritance hierarchy for exceptions has been rearranged a bit. |
| 380 | In 2.5, the inheritance relationships are: |
| 381 | |
| 382 | \begin{verbatim} |
| 383 | BaseException # New in Python 2.5 |
| 384 | |- KeyboardInterrupt |
| 385 | |- SystemExit |
| 386 | |- Exception |
| 387 | |- (all other current built-in exceptions) |
| 388 | \end{verbatim} |
| 389 | |
| 390 | This rearrangement was done because people often want to catch all |
| 391 | exceptions that indicate program errors. \exception{KeyboardInterrupt} and |
| 392 | \exception{SystemExit} aren't errors, though, and usually represent an explicit |
| 393 | action such as the user hitting Control-C or code calling |
| 394 | \function{sys.exit()}. A bare \code{except:} will catch all exceptions, |
| 395 | so you commonly need to list \exception{KeyboardInterrupt} and |
| 396 | \exception{SystemExit} in order to re-raise them. The usual pattern is: |
| 397 | |
| 398 | \begin{verbatim} |
| 399 | try: |
| 400 | ... |
| 401 | except (KeyboardInterrupt, SystemExit): |
| 402 | raise |
| 403 | except: |
| 404 | # Log error... |
| 405 | # Continue running program... |
| 406 | \end{verbatim} |
| 407 | |
| 408 | In Python 2.5, you can now write \code{except Exception} to achieve |
| 409 | the same result, catching all the exceptions that usually indicate errors |
| 410 | but leaving \exception{KeyboardInterrupt} and |
| 411 | \exception{SystemExit} alone. As in previous versions, |
| 412 | a bare \code{except:} still catches all exceptions. |
| 413 | |
| 414 | The goal for Python 3.0 is to require any class raised as an exception |
| 415 | to derive from \exception{BaseException} or some descendant of |
| 416 | \exception{BaseException}, and future releases in the |
| 417 | Python 2.x series may begin to enforce this constraint. Therefore, I |
| 418 | suggest you begin making all your exception classes derive from |
| 419 | \exception{Exception} now. It's been suggested that the bare |
| 420 | \code{except:} form should be removed in Python 3.0, but Guido van~Rossum |
| 421 | hasn't decided whether to do this or not. |
| 422 | |
| 423 | Raising of strings as exceptions, as in the statement \code{raise |
| 424 | "Error occurred"}, is deprecated in Python 2.5 and will trigger a |
| 425 | warning. The aim is to be able to remove the string-exception feature |
| 426 | in a few releases. |
| 427 | |
| 428 | |
| 429 | \begin{seealso} |
| 430 | |
| 431 | \seepep{352}{}{PEP written by |
| 432 | Brett Cannon and Guido van Rossum; implemented by Brett Cannon.} |
| 433 | |
| 434 | \end{seealso} |
Andrew M. Kuchling | 8f4d255 | 2006-03-08 01:50:20 +0000 | [diff] [blame] | 435 | |
| 436 | |
| 437 | %====================================================================== |
Andrew M. Kuchling | 437567c | 2006-03-07 20:48:55 +0000 | [diff] [blame] | 438 | \section{PEP 357: The '__index__' method} |
| 439 | |
| 440 | % XXX write this |
| 441 | |
| 442 | |
| 443 | %====================================================================== |
Fred Drake | 2db7680 | 2004-12-01 05:05:47 +0000 | [diff] [blame] | 444 | \section{Other Language Changes} |
| 445 | |
| 446 | Here are all of the changes that Python 2.5 makes to the core Python |
| 447 | language. |
| 448 | |
| 449 | \begin{itemize} |
Andrew M. Kuchling | 1cae3f5 | 2004-12-03 14:57:21 +0000 | [diff] [blame] | 450 | |
| 451 | \item The \function{min()} and \function{max()} built-in functions |
| 452 | gained a \code{key} keyword argument analogous to the \code{key} |
Andrew M. Kuchling | e9b1bf4 | 2005-03-20 19:26:30 +0000 | [diff] [blame] | 453 | argument for \method{sort()}. This argument supplies a function |
Andrew M. Kuchling | 1cae3f5 | 2004-12-03 14:57:21 +0000 | [diff] [blame] | 454 | that takes a single argument and is called for every value in the list; |
| 455 | \function{min()}/\function{max()} will return the element with the |
| 456 | smallest/largest return value from this function. |
| 457 | For example, to find the longest string in a list, you can do: |
| 458 | |
| 459 | \begin{verbatim} |
| 460 | L = ['medium', 'longest', 'short'] |
| 461 | # Prints 'longest' |
| 462 | print max(L, key=len) |
| 463 | # Prints 'short', because lexicographically 'short' has the largest value |
| 464 | print max(L) |
| 465 | \end{verbatim} |
| 466 | |
| 467 | (Contributed by Steven Bethard and Raymond Hettinger.) |
Fred Drake | 2db7680 | 2004-12-01 05:05:47 +0000 | [diff] [blame] | 468 | |
Andrew M. Kuchling | 150e349 | 2005-08-23 00:56:06 +0000 | [diff] [blame] | 469 | \item Two new built-in functions, \function{any()} and |
| 470 | \function{all()}, evaluate whether an iterator contains any true or |
| 471 | false values. \function{any()} returns \constant{True} if any value |
| 472 | returned by the iterator is true; otherwise it will return |
| 473 | \constant{False}. \function{all()} returns \constant{True} only if |
| 474 | all of the values returned by the iterator evaluate as being true. |
| 475 | |
| 476 | % XXX who added? |
| 477 | |
| 478 | |
Andrew M. Kuchling | e9b1bf4 | 2005-03-20 19:26:30 +0000 | [diff] [blame] | 479 | \item The list of base classes in a class definition can now be empty. |
| 480 | As an example, this is now legal: |
| 481 | |
| 482 | \begin{verbatim} |
| 483 | class C(): |
| 484 | pass |
| 485 | \end{verbatim} |
| 486 | (Implemented by Brett Cannon.) |
| 487 | |
Fred Drake | 2db7680 | 2004-12-01 05:05:47 +0000 | [diff] [blame] | 488 | \end{itemize} |
| 489 | |
| 490 | |
| 491 | %====================================================================== |
| 492 | \subsection{Optimizations} |
| 493 | |
| 494 | \begin{itemize} |
| 495 | |
Andrew M. Kuchling | 150e349 | 2005-08-23 00:56:06 +0000 | [diff] [blame] | 496 | \item When they were introduced |
| 497 | in Python 2.4, the built-in \class{set} and \class{frozenset} types |
| 498 | were built on top of Python's dictionary type. |
| 499 | In 2.5 the internal data structure has been customized for implementing sets, |
| 500 | and as a result sets will use a third less memory and are somewhat faster. |
| 501 | (Implemented by Raymond Hettinger.) |
Fred Drake | 2db7680 | 2004-12-01 05:05:47 +0000 | [diff] [blame] | 502 | |
| 503 | \end{itemize} |
| 504 | |
| 505 | The net result of the 2.5 optimizations is that Python 2.5 runs the |
Andrew M. Kuchling | 92e2495 | 2004-12-03 13:54:09 +0000 | [diff] [blame] | 506 | pystone benchmark around XX\% faster than Python 2.4. |
Fred Drake | 2db7680 | 2004-12-01 05:05:47 +0000 | [diff] [blame] | 507 | |
| 508 | |
| 509 | %====================================================================== |
| 510 | \section{New, Improved, and Deprecated Modules} |
| 511 | |
| 512 | As usual, Python's standard library received a number of enhancements and |
| 513 | bug fixes. Here's a partial list of the most notable changes, sorted |
| 514 | alphabetically by module name. Consult the |
| 515 | \file{Misc/NEWS} file in the source tree for a more |
Andrew M. Kuchling | f688cc5 | 2006-03-10 18:50:08 +0000 | [diff] [blame] | 516 | complete list of changes, or look through the SVN logs for all the |
Fred Drake | 2db7680 | 2004-12-01 05:05:47 +0000 | [diff] [blame] | 517 | details. |
| 518 | |
| 519 | \begin{itemize} |
| 520 | |
Andrew M. Kuchling | aeadf95 | 2006-03-09 19:06:05 +0000 | [diff] [blame] | 521 | % ctypes added |
| 522 | |
Andrew M. Kuchling | 150e349 | 2005-08-23 00:56:06 +0000 | [diff] [blame] | 523 | % collections.deque now has .remove() |
| 524 | |
Andrew M. Kuchling | 3e41b05 | 2005-03-01 00:53:46 +0000 | [diff] [blame] | 525 | % the cPickle module no longer accepts the deprecated None option in the |
| 526 | % args tuple returned by __reduce__(). |
| 527 | |
| 528 | % csv module improvements |
| 529 | |
| 530 | % datetime.datetime() now has a strptime class method which can be used to |
| 531 | % create datetime object using a string and format. |
| 532 | |
Andrew M. Kuchling | 150e349 | 2005-08-23 00:56:06 +0000 | [diff] [blame] | 533 | \item A new \module{hashlib} module has been added to replace the |
| 534 | \module{md5} and \module{sha} modules. \module{hashlib} adds support |
| 535 | for additional secure hashes (SHA-224, SHA-256, SHA-384, and SHA-512). |
| 536 | When available, the module uses OpenSSL for fast platform optimized |
| 537 | implementations of algorithms. The old \module{md5} and \module{sha} |
| 538 | modules still exist as wrappers around hashlib to preserve backwards |
| 539 | compatibility. (Contributed by Gregory P. Smith.) |
| 540 | |
Andrew M. Kuchling | e9b1bf4 | 2005-03-20 19:26:30 +0000 | [diff] [blame] | 541 | \item The \function{nsmallest()} and |
| 542 | \function{nlargest()} functions in the \module{heapq} module |
| 543 | now support a \code{key} keyword argument similar to the one |
| 544 | provided by the \function{min()}/\function{max()} functions |
| 545 | and the \method{sort()} methods. For example: |
| 546 | Example: |
| 547 | |
| 548 | \begin{verbatim} |
| 549 | >>> import heapq |
| 550 | >>> L = ["short", 'medium', 'longest', 'longer still'] |
| 551 | >>> heapq.nsmallest(2, L) # Return two lowest elements, lexicographically |
| 552 | ['longer still', 'longest'] |
| 553 | >>> heapq.nsmallest(2, L, key=len) # Return two shortest elements |
| 554 | ['short', 'medium'] |
| 555 | \end{verbatim} |
| 556 | |
| 557 | (Contributed by Raymond Hettinger.) |
| 558 | |
Andrew M. Kuchling | 511a3a8 | 2005-03-20 19:52:18 +0000 | [diff] [blame] | 559 | \item The \function{itertools.islice()} function now accepts |
| 560 | \code{None} for the start and step arguments. This makes it more |
| 561 | compatible with the attributes of slice objects, so that you can now write |
| 562 | the following: |
| 563 | |
| 564 | \begin{verbatim} |
| 565 | s = slice(5) # Create slice object |
| 566 | itertools.islice(iterable, s.start, s.stop, s.step) |
| 567 | \end{verbatim} |
| 568 | |
| 569 | (Contributed by Raymond Hettinger.) |
Andrew M. Kuchling | 3e41b05 | 2005-03-01 00:53:46 +0000 | [diff] [blame] | 570 | |
Andrew M. Kuchling | 150e349 | 2005-08-23 00:56:06 +0000 | [diff] [blame] | 571 | \item The \module{operator} module's \function{itemgetter()} |
| 572 | and \function{attrgetter()} functions now support multiple fields. |
| 573 | A call such as \code{operator.attrgetter('a', 'b')} |
| 574 | will return a function |
| 575 | that retrieves the \member{a} and \member{b} attributes. Combining |
| 576 | this new feature with the \method{sort()} method's \code{key} parameter |
| 577 | lets you easily sort lists using multiple fields. |
| 578 | |
| 579 | % XXX who added? |
| 580 | |
Andrew M. Kuchling | 3e41b05 | 2005-03-01 00:53:46 +0000 | [diff] [blame] | 581 | |
Andrew M. Kuchling | e9b1bf4 | 2005-03-20 19:26:30 +0000 | [diff] [blame] | 582 | \item The \module{os} module underwent a number of changes. The |
| 583 | \member{stat_float_times} variable now defaults to true, meaning that |
| 584 | \function{os.stat()} will now return time values as floats. (This |
| 585 | doesn't necessarily mean that \function{os.stat()} will return times |
| 586 | that are precise to fractions of a second; not all systems support |
| 587 | such precision.) |
Andrew M. Kuchling | 3e41b05 | 2005-03-01 00:53:46 +0000 | [diff] [blame] | 588 | |
Andrew M. Kuchling | 150e349 | 2005-08-23 00:56:06 +0000 | [diff] [blame] | 589 | Constants named \member{os.SEEK_SET}, \member{os.SEEK_CUR}, and |
Andrew M. Kuchling | e9b1bf4 | 2005-03-20 19:26:30 +0000 | [diff] [blame] | 590 | \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] | 591 | \function{os.lseek()} function. Two new constants for locking are |
| 592 | \member{os.O_SHLOCK} and \member{os.O_EXLOCK}. |
| 593 | |
| 594 | On FreeBSD, the \function{os.stat()} function now returns |
| 595 | times with nanosecond resolution, and the returned object |
| 596 | now has \member{st_gen} and \member{st_birthtime}. |
| 597 | The \member{st_flags} member is also available, if the platform supports it. |
| 598 | % XXX patch 1180695, 1212117 |
| 599 | |
Andrew M. Kuchling | 4678dc8 | 2006-01-15 16:11:28 +0000 | [diff] [blame] | 600 | \item The \module{socket} module now supports \constant{AF_NETLINK} |
| 601 | sockets on Linux, thanks to a patch from Philippe Biondi. |
| 602 | Netlink sockets are a Linux-specific mechanism for communications |
| 603 | between a user-space process and kernel code; an introductory |
| 604 | article about them is at \url{http://www.linuxjournal.com/article/7356}. |
| 605 | In Python code, netlink addresses are represented as a tuple of 2 integers, |
| 606 | \code{(\var{pid}, \var{group_mask})}. |
| 607 | |
Andrew M. Kuchling | 150e349 | 2005-08-23 00:56:06 +0000 | [diff] [blame] | 608 | \item New module: \module{spwd} provides functions for accessing the |
| 609 | shadow password database on systems that support it. |
| 610 | % XXX give example |
Fred Drake | 2db7680 | 2004-12-01 05:05:47 +0000 | [diff] [blame] | 611 | |
Andrew M. Kuchling | e9b1bf4 | 2005-03-20 19:26:30 +0000 | [diff] [blame] | 612 | \item The \class{TarFile} class in the \module{tarfile} module now has |
Georg Brandl | 08c02db | 2005-07-22 18:39:19 +0000 | [diff] [blame] | 613 | an \method{extractall()} method that extracts all members from the |
Andrew M. Kuchling | e9b1bf4 | 2005-03-20 19:26:30 +0000 | [diff] [blame] | 614 | archive into the current working directory. It's also possible to set |
| 615 | 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] | 616 | subset of the archive's members. |
Andrew M. Kuchling | e9b1bf4 | 2005-03-20 19:26:30 +0000 | [diff] [blame] | 617 | |
Andrew M. Kuchling | 150e349 | 2005-08-23 00:56:06 +0000 | [diff] [blame] | 618 | A tarfile's compression can be autodetected by |
| 619 | using the mode \code{'r|*'}. |
| 620 | % patch 918101 |
| 621 | (Contributed by Lars Gust\"abel.) |
Gregory P. Smith | f21a5f7 | 2005-08-21 18:45:59 +0000 | [diff] [blame] | 622 | |
Andrew M. Kuchling | f688cc5 | 2006-03-10 18:50:08 +0000 | [diff] [blame] | 623 | \item The \module{unicodedata} module has been updated to use version 4.1.0 |
| 624 | of the Unicode character database. Version 3.2.0 is required |
| 625 | by some specifications, so it's still available as |
| 626 | \member{unicodedata.db_3_2_0}. |
| 627 | |
Fredrik Lundh | 7e0aef0 | 2005-12-12 18:54:55 +0000 | [diff] [blame] | 628 | \item A new package \module{xml.etree} has been added, which contains |
| 629 | a subset of the ElementTree XML library. Available modules are |
| 630 | \module{ElementTree}, \module{ElementPath}, and |
| 631 | \module{ElementInclude}, from ElementTree 1.2.6. (Contributed by |
| 632 | Fredrik Lundh.) |
| 633 | |
Andrew M. Kuchling | 150e349 | 2005-08-23 00:56:06 +0000 | [diff] [blame] | 634 | \item The \module{xmlrpclib} module now supports returning |
| 635 | \class{datetime} objects for the XML-RPC date type. Supply |
| 636 | \code{use_datetime=True} to the \function{loads()} function |
| 637 | or the \class{Unmarshaller} class to enable this feature. |
| 638 | % XXX patch 1120353 |
| 639 | |
Gregory P. Smith | f21a5f7 | 2005-08-21 18:45:59 +0000 | [diff] [blame] | 640 | |
Fred Drake | 114b8ca | 2005-03-21 05:47:11 +0000 | [diff] [blame] | 641 | \end{itemize} |
Andrew M. Kuchling | e9b1bf4 | 2005-03-20 19:26:30 +0000 | [diff] [blame] | 642 | |
Fred Drake | 2db7680 | 2004-12-01 05:05:47 +0000 | [diff] [blame] | 643 | |
| 644 | |
| 645 | %====================================================================== |
| 646 | % whole new modules get described in \subsections here |
| 647 | |
Andrew M. Kuchling | 150e349 | 2005-08-23 00:56:06 +0000 | [diff] [blame] | 648 | % XXX new distutils features: upload |
| 649 | |
Fredrik Lundh | 7e0aef0 | 2005-12-12 18:54:55 +0000 | [diff] [blame] | 650 | % XXX should hashlib perhaps be described here instead? |
| 651 | % XXX should xml.etree perhaps be described here instead? |
Andrew M. Kuchling | 150e349 | 2005-08-23 00:56:06 +0000 | [diff] [blame] | 652 | |
| 653 | |
Fred Drake | 2db7680 | 2004-12-01 05:05:47 +0000 | [diff] [blame] | 654 | |
| 655 | % ====================================================================== |
| 656 | \section{Build and C API Changes} |
| 657 | |
| 658 | Changes to Python's build process and to the C API include: |
| 659 | |
| 660 | \begin{itemize} |
| 661 | |
Andrew M. Kuchling | db85ed5 | 2005-10-23 21:52:59 +0000 | [diff] [blame] | 662 | \item The design of the bytecode compiler has changed a great deal, no |
| 663 | longer generating bytecode by traversing the parse tree. Instead |
| 664 | the parse tree is converted to an abstract syntax tree (or AST), and it is |
| 665 | the abstract syntax tree that's traversed to produce the bytecode. |
| 666 | |
| 667 | No documentation has been written for the AST code yet. To start |
| 668 | learning about it, read the definition of the various AST nodes in |
| 669 | \file{Parser/Python.asdl}. A Python script reads this file and |
| 670 | generates a set of C structure definitions in |
| 671 | \file{Include/Python-ast.h}. The \cfunction{PyParser_ASTFromString()} |
| 672 | and \cfunction{PyParser_ASTFromFile()}, defined in |
| 673 | \file{Include/pythonrun.h}, take Python source as input and return the |
| 674 | root of an AST representing the contents. This AST can then be turned |
| 675 | into a code object by \cfunction{PyAST_Compile()}. For more |
| 676 | information, read the source code, and then ask questions on |
| 677 | python-dev. |
| 678 | |
| 679 | % List of names taken from Jeremy's python-dev post at |
| 680 | % http://mail.python.org/pipermail/python-dev/2005-October/057500.html |
| 681 | The AST code was developed under Jeremy Hylton's management, and |
| 682 | implemented by (in alphabetical order) Brett Cannon, Nick Coghlan, |
| 683 | Grant Edwards, John Ehresman, Kurt Kaiser, Neal Norwitz, Tim Peters, |
| 684 | Armin Rigo, and Neil Schemenauer, plus the participants in a number of |
| 685 | AST sprints at conferences such as PyCon. |
| 686 | |
Andrew M. Kuchling | 150e349 | 2005-08-23 00:56:06 +0000 | [diff] [blame] | 687 | \item The built-in set types now have an official C API. Call |
| 688 | \cfunction{PySet_New()} and \cfunction{PyFrozenSet_New()} to create a |
| 689 | new set, \cfunction{PySet_Add()} and \cfunction{PySet_Discard()} to |
| 690 | add and remove elements, and \cfunction{PySet_Contains} and |
| 691 | \cfunction{PySet_Size} to examine the set's state. |
| 692 | |
| 693 | \item The \cfunction{PyRange_New()} function was removed. It was |
| 694 | never documented, never used in the core code, and had dangerously lax |
| 695 | error checking. |
Fred Drake | 2db7680 | 2004-12-01 05:05:47 +0000 | [diff] [blame] | 696 | |
| 697 | \end{itemize} |
| 698 | |
| 699 | |
| 700 | %====================================================================== |
| 701 | \subsection{Port-Specific Changes} |
| 702 | |
| 703 | Platform-specific changes go here. |
| 704 | |
| 705 | |
| 706 | %====================================================================== |
| 707 | \section{Other Changes and Fixes \label{section-other}} |
| 708 | |
| 709 | As usual, there were a bunch of other improvements and bugfixes |
Andrew M. Kuchling | f688cc5 | 2006-03-10 18:50:08 +0000 | [diff] [blame] | 710 | scattered throughout the source tree. A search through the SVN change |
Fred Drake | 2db7680 | 2004-12-01 05:05:47 +0000 | [diff] [blame] | 711 | 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] | 712 | 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] | 713 | |
| 714 | Some of the more notable changes are: |
| 715 | |
| 716 | \begin{itemize} |
| 717 | |
| 718 | \item Details go here. |
| 719 | |
| 720 | \end{itemize} |
| 721 | |
| 722 | |
| 723 | %====================================================================== |
| 724 | \section{Porting to Python 2.5} |
| 725 | |
| 726 | This section lists previously described changes that may require |
| 727 | changes to your code: |
| 728 | |
| 729 | \begin{itemize} |
| 730 | |
Andrew M. Kuchling | 3e41b05 | 2005-03-01 00:53:46 +0000 | [diff] [blame] | 731 | \item Some old deprecated modules (\module{statcache}, \module{tzparse}, |
| 732 | \module{whrandom}) have been moved to \file{Lib/lib-old}. |
Andrew M. Kuchling | 0c35db9 | 2005-03-20 20:06:49 +0000 | [diff] [blame] | 733 | You can get access to these modules again by adding the directory |
| 734 | to your \code{sys.path}: |
| 735 | |
| 736 | \begin{verbatim} |
| 737 | import os |
| 738 | from distutils import sysconfig |
| 739 | |
| 740 | lib_dir = sysconfig.get_python_lib(standard_lib=True) |
| 741 | old_dir = os.path.join(lib_dir, 'lib-old') |
| 742 | sys.path.append(old_dir) |
| 743 | \end{verbatim} |
| 744 | |
| 745 | Doing so is discouraged, however; it's better to update any code that |
| 746 | still uses these modules. |
Andrew M. Kuchling | 3e41b05 | 2005-03-01 00:53:46 +0000 | [diff] [blame] | 747 | |
| 748 | % the pickle module no longer uses the deprecated bin parameter. |
Fred Drake | 2db7680 | 2004-12-01 05:05:47 +0000 | [diff] [blame] | 749 | |
| 750 | \end{itemize} |
| 751 | |
| 752 | |
| 753 | %====================================================================== |
| 754 | \section{Acknowledgements \label{acks}} |
| 755 | |
| 756 | The author would like to thank the following people for offering |
| 757 | suggestions, corrections and assistance with various drafts of this |
| 758 | article: . |
| 759 | |
| 760 | \end{document} |