blob: 2f1a500da7547eaf50eecebaff9016d716dd7b6c [file] [log] [blame]
Fred Drake2db76802004-12-01 05:05:47 +00001\documentclass{howto}
2\usepackage{distutils}
3% $Id$
4
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00005% Fix XXX comments
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00006% The easy_install stuff
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00007% Stateful codec changes
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00008% Write ctypes examples
9% Count up the patches and bugs
Fred Drake2db76802004-12-01 05:05:47 +000010
11\title{What's New in Python 2.5}
Andrew M. Kuchling2cdb23e2006-04-05 13:59:01 +000012\release{0.1}
Andrew M. Kuchling92e24952004-12-03 13:54:09 +000013\author{A.M. Kuchling}
14\authoraddress{\email{amk@amk.ca}}
Fred Drake2db76802004-12-01 05:05:47 +000015
16\begin{document}
17\maketitle
18\tableofcontents
19
20This article explains the new features in Python 2.5. No release date
Andrew M. Kuchling5eefdca2006-02-08 11:36:09 +000021for Python 2.5 has been set; it will probably be released in the
Andrew M. Kuchlingd96a6ac2006-04-04 19:17:34 +000022autumn of 2006. \pep{356} describes the planned release schedule.
Fred Drake2db76802004-12-01 05:05:47 +000023
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +000024(This is still an early draft, and some sections are still skeletal or
25completely missing. Comments on the present material will still be
26welcomed.)
27
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000028% XXX Compare with previous release in 2 - 3 sentences here.
Fred Drake2db76802004-12-01 05:05:47 +000029
30This article doesn't attempt to provide a complete specification of
31the new features, but instead provides a convenient overview. For
32full details, you should refer to the documentation for Python 2.5.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000033% XXX add hyperlink when the documentation becomes available online.
Fred Drake2db76802004-12-01 05:05:47 +000034If you want to understand the complete implementation and design
35rationale, refer to the PEP for a particular new feature.
36
37
38%======================================================================
Andrew M. Kuchling6a67e4e2006-04-12 13:03:35 +000039\section{PEP 243: Uploading Modules to PyPI}
40
41PEP 243 describes an HTTP-based protocol for submitting software
42packages to a central archive. The Python package index at
43\url{http://cheeseshop.python.org} now supports package uploads, and
44the new \command{upload} Distutils command will upload a package to the
45repository.
46
47Before a package can be uploaded, you must be able to build a
48distribution using the \command{sdist} Distutils command. Once that
49works, you can run \code{python setup.py upload} to add your package
50to the PyPI archive. Optionally you can GPG-sign the package by
51supplying the \programopt{--sign} and
52\programopt{--identity} options.
53
54\begin{seealso}
55
56\seepep{243}{Module Repository Upload Mechanism}{PEP written by
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +000057Sean Reifschneider; implemented by Martin von~L\"owis
Andrew M. Kuchling6a67e4e2006-04-12 13:03:35 +000058and Richard Jones. Note that the PEP doesn't exactly
59describe what's implemented in PyPI.}
60
61\end{seealso}
62
63
64%======================================================================
Andrew M. Kuchling437567c2006-03-07 20:48:55 +000065\section{PEP 308: Conditional Expressions}
66
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000067For a long time, people have been requesting a way to write
68conditional expressions, expressions that return value A or value B
69depending on whether a Boolean value is true or false. A conditional
70expression lets you write a single assignment statement that has the
71same effect as the following:
72
73\begin{verbatim}
74if condition:
75 x = true_value
76else:
77 x = false_value
78\end{verbatim}
79
80There have been endless tedious discussions of syntax on both
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +000081python-dev and comp.lang.python. A vote was even held that found the
82majority of voters wanted conditional expressions in some form,
83but there was no syntax that was preferred by a clear majority.
84Candidates included C's \code{cond ? true_v : false_v},
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000085\code{if cond then true_v else false_v}, and 16 other variations.
86
87GvR eventually chose a surprising syntax:
88
89\begin{verbatim}
90x = true_value if condition else false_value
91\end{verbatim}
92
Andrew M. Kuchling38f85072006-04-02 01:46:32 +000093Evaluation is still lazy as in existing Boolean expressions, so the
94order of evaluation jumps around a bit. The \var{condition}
95expression in the middle is evaluated first, and the \var{true_value}
96expression is evaluated only if the condition was true. Similarly,
97the \var{false_value} expression is only evaluated when the condition
98is false.
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +000099
100This syntax may seem strange and backwards; why does the condition go
101in the \emph{middle} of the expression, and not in the front as in C's
102\code{c ? x : y}? The decision was checked by applying the new syntax
103to the modules in the standard library and seeing how the resulting
104code read. In many cases where a conditional expression is used, one
105value seems to be the 'common case' and one value is an 'exceptional
106case', used only on rarer occasions when the condition isn't met. The
107conditional syntax makes this pattern a bit more obvious:
108
109\begin{verbatim}
110contents = ((doc + '\n') if doc else '')
111\end{verbatim}
112
113I read the above statement as meaning ``here \var{contents} is
Andrew M. Kuchlingd0fcc022006-03-09 13:57:28 +0000114usually assigned a value of \code{doc+'\e n'}; sometimes
Andrew M. Kuchlinge362d932006-03-09 13:56:25 +0000115\var{doc} is empty, in which special case an empty string is returned.''
116I doubt I will use conditional expressions very often where there
117isn't a clear common and uncommon case.
118
119There was some discussion of whether the language should require
120surrounding conditional expressions with parentheses. The decision
121was made to \emph{not} require parentheses in the Python language's
122grammar, but as a matter of style I think you should always use them.
123Consider these two statements:
124
125\begin{verbatim}
126# First version -- no parens
127level = 1 if logging else 0
128
129# Second version -- with parens
130level = (1 if logging else 0)
131\end{verbatim}
132
133In the first version, I think a reader's eye might group the statement
134into 'level = 1', 'if logging', 'else 0', and think that the condition
135decides whether the assignment to \var{level} is performed. The
136second version reads better, in my opinion, because it makes it clear
137that the assignment is always performed and the choice is being made
138between two values.
139
140Another reason for including the brackets: a few odd combinations of
141list comprehensions and lambdas could look like incorrect conditional
142expressions. See \pep{308} for some examples. If you put parentheses
143around your conditional expressions, you won't run into this case.
144
145
146\begin{seealso}
147
148\seepep{308}{Conditional Expressions}{PEP written by
149Guido van Rossum and Raymond D. Hettinger; implemented by Thomas
150Wouters.}
151
152\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000153
154
155%======================================================================
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +0000156\section{PEP 309: Partial Function Application}
Fred Drake2db76802004-12-01 05:05:47 +0000157
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000158The \module{functional} module is intended to contain tools for
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000159functional-style programming. Currently it only contains a
160\class{partial()} function, but new functions will probably be added
161in future versions of Python.
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000162
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000163For programs written in a functional style, it can be useful to
164construct variants of existing functions that have some of the
165parameters filled in. Consider a Python function \code{f(a, b, c)};
166you could create a new function \code{g(b, c)} that was equivalent to
167\code{f(1, b, c)}. This is called ``partial function application'',
168and is provided by the \class{partial} class in the new
169\module{functional} module.
170
171The constructor for \class{partial} takes the arguments
172\code{(\var{function}, \var{arg1}, \var{arg2}, ...
173\var{kwarg1}=\var{value1}, \var{kwarg2}=\var{value2})}. The resulting
174object is callable, so you can just call it to invoke \var{function}
175with the filled-in arguments.
176
177Here's a small but realistic example:
178
179\begin{verbatim}
180import functional
181
182def log (message, subsystem):
183 "Write the contents of 'message' to the specified subsystem."
184 print '%s: %s' % (subsystem, message)
185 ...
186
187server_log = functional.partial(log, subsystem='server')
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000188server_log('Unable to open socket')
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000189\end{verbatim}
190
Andrew M. Kuchling6af7fe02005-08-02 17:20:36 +0000191Here's another example, from a program that uses PyGTk. Here a
192context-sensitive pop-up menu is being constructed dynamically. The
193callback provided for the menu option is a partially applied version
194of the \method{open_item()} method, where the first argument has been
195provided.
Andrew M. Kuchling4b000cd2005-04-09 15:51:44 +0000196
Andrew M. Kuchling6af7fe02005-08-02 17:20:36 +0000197\begin{verbatim}
198...
199class Application:
200 def open_item(self, path):
201 ...
202 def init (self):
203 open_func = functional.partial(self.open_item, item_path)
204 popup_menu.append( ("Open", open_func, 1) )
205\end{verbatim}
Andrew M. Kuchlingb1c96fd2005-03-20 21:42:04 +0000206
207
208\begin{seealso}
209
210\seepep{309}{Partial Function Application}{PEP proposed and written by
211Peter Harris; implemented by Hye-Shik Chang, with adaptations by
212Raymond Hettinger.}
213
214\end{seealso}
Fred Drake2db76802004-12-01 05:05:47 +0000215
216
217%======================================================================
Fred Drakedb7b0022005-03-20 22:19:47 +0000218\section{PEP 314: Metadata for Python Software Packages v1.1}
219
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000220Some simple dependency support was added to Distutils. The
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000221\function{setup()} function now has \code{requires}, \code{provides},
222and \code{obsoletes} keyword parameters. When you build a source
223distribution using the \code{sdist} command, the dependency
224information will be recorded in the \file{PKG-INFO} file.
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000225
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000226Another new keyword parameter is \code{download_url}, which should be
227set to a URL for the package's source code. This means it's now
228possible to look up an entry in the package index, determine the
229dependencies for a package, and download the required packages.
Andrew M. Kuchlingd8d732e2005-04-09 23:59:41 +0000230
231% XXX put example here
232
233\begin{seealso}
234
235\seepep{314}{Metadata for Python Software Packages v1.1}{PEP proposed
236and written by A.M. Kuchling, Richard Jones, and Fred Drake;
237implemented by Richard Jones and Fred Drake.}
238
239\end{seealso}
Fred Drakedb7b0022005-03-20 22:19:47 +0000240
241
242%======================================================================
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000243\section{PEP 328: Absolute and Relative Imports}
244
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000245The simpler part of PEP 328 was implemented in Python 2.4: parentheses
246could now be used to enclose the names imported from a module using
247the \code{from ... import ...} statement, making it easier to import
248many different names.
249
250The more complicated part has been implemented in Python 2.5:
251importing a module can be specified to use absolute or
252package-relative imports. The plan is to move toward making absolute
253imports the default in future versions of Python.
254
255Let's say you have a package directory like this:
256\begin{verbatim}
257pkg/
258pkg/__init__.py
259pkg/main.py
260pkg/string.py
261\end{verbatim}
262
263This defines a package named \module{pkg} containing the
264\module{pkg.main} and \module{pkg.string} submodules.
265
266Consider the code in the \file{main.py} module. What happens if it
267executes the statement \code{import string}? In Python 2.4 and
268earlier, it will first look in the package's directory to perform a
269relative import, finds \file{pkg/string.py}, imports the contents of
270that file as the \module{pkg.string} module, and that module is bound
271to the name \samp{string} in the \module{pkg.main} module's namespace.
272
273That's fine if \module{pkg.string} was what you wanted. But what if
274you wanted Python's standard \module{string} module? There's no clean
275way to ignore \module{pkg.string} and look for the standard module;
276generally you had to look at the contents of \code{sys.modules}, which
277is slightly unclean.
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000278Holger Krekel's \module{py.std} package provides a tidier way to perform
279imports from the standard library, \code{import py ; py.std.string.join()},
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000280but that package isn't available on all Python installations.
281
282Reading code which relies on relative imports is also less clear,
283because a reader may be confused about which module, \module{string}
284or \module{pkg.string}, is intended to be used. Python users soon
285learned not to duplicate the names of standard library modules in the
286names of their packages' submodules, but you can't protect against
287having your submodule's name being used for a new module added in a
288future version of Python.
289
290In Python 2.5, you can switch \keyword{import}'s behaviour to
291absolute imports using a \code{from __future__ import absolute_import}
292directive. This absolute-import behaviour will become the default in
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000293a future version (probably Python 2.7). Once absolute imports
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000294are the default, \code{import string} will
295always find the standard library's version.
296It's suggested that users should begin using absolute imports as much
297as possible, so it's preferable to begin writing \code{from pkg import
298string} in your code.
299
300Relative imports are still possible by adding a leading period
301to the module name when using the \code{from ... import} form:
302
303\begin{verbatim}
304# Import names from pkg.string
305from .string import name1, name2
306# Import pkg.string
307from . import string
308\end{verbatim}
309
310This imports the \module{string} module relative to the current
311package, so in \module{pkg.main} this will import \var{name1} and
312\var{name2} from \module{pkg.string}. Additional leading periods
313perform the relative import starting from the parent of the current
314package. For example, code in the \module{A.B.C} module can do:
315
316\begin{verbatim}
317from . import D # Imports A.B.D
318from .. import E # Imports A.E
319from ..F import G # Imports A.F.G
320\end{verbatim}
321
322Leading periods cannot be used with the \code{import \var{modname}}
323form of the import statement, only the \code{from ... import} form.
324
325\begin{seealso}
326
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000327\seepep{328}{Imports: Multi-Line and Absolute/Relative}
328{PEP written by Aahz; implemented by Thomas Wouters.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000329
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000330\seeurl{http://codespeak.net/py/current/doc/index.html}
331{The py library by Holger Krekel, which contains the \module{py.std} package.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000332
333\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000334
335
336%======================================================================
Andrew M. Kuchling21d3a7c2006-03-15 11:53:09 +0000337\section{PEP 338: Executing Modules as Scripts}
338
Andrew M. Kuchlingb182db42006-03-17 21:48:46 +0000339The \programopt{-m} switch added in Python 2.4 to execute a module as
340a script gained a few more abilities. Instead of being implemented in
341C code inside the Python interpreter, the switch now uses an
342implementation in a new module, \module{runpy}.
343
344The \module{runpy} module implements a more sophisticated import
345mechanism so that it's now possible to run modules in a package such
346as \module{pychecker.checker}. The module also supports alternative
347import mechanisms such as the \module{zipimport} module. (This means
348you can add a .zip archive's path to \code{sys.path} and then use the
349\programopt{-m} switch to execute code from the archive.
350
351
352\begin{seealso}
353
354\seepep{338}{Executing modules as scripts}{PEP written and
355implemented by Nick Coghlan.}
356
357\end{seealso}
Andrew M. Kuchling21d3a7c2006-03-15 11:53:09 +0000358
359
360%======================================================================
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000361\section{PEP 341: Unified try/except/finally}
362
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000363Until Python 2.5, the \keyword{try} statement came in two
364flavours. You could use a \keyword{finally} block to ensure that code
365is always executed, or a number of \keyword{except} blocks to catch an
366exception. You couldn't combine both \keyword{except} blocks and a
367\keyword{finally} block, because generating the right bytecode for the
368combined version was complicated and it wasn't clear what the
369semantics of the combined should be.
370
371GvR spent some time working with Java, which does support the
372equivalent of combining \keyword{except} blocks and a
373\keyword{finally} block, and this clarified what the statement should
374mean. In Python 2.5, you can now write:
375
376\begin{verbatim}
377try:
378 block-1 ...
379except Exception1:
380 handler-1 ...
381except Exception2:
382 handler-2 ...
383else:
384 else-block
385finally:
386 final-block
387\end{verbatim}
388
389The code in \var{block-1} is executed. If the code raises an
390exception, the handlers are tried in order: \var{handler-1},
391\var{handler-2}, ... If no exception is raised, the \var{else-block}
392is executed. No matter what happened previously, the
393\var{final-block} is executed once the code block is complete and any
394raised exceptions handled. Even if there's an error in an exception
395handler or the \var{else-block} and a new exception is raised, the
396\var{final-block} is still executed.
397
398\begin{seealso}
399
400\seepep{341}{Unifying try-except and try-finally}{PEP written by Georg Brandl;
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000401implementation by Thomas Lee.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000402
403\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000404
405
406%======================================================================
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000407\section{PEP 342: New Generator Features}
408
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000409Python 2.5 adds a simple way to pass values \emph{into} a generator.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000410As introduced in Python 2.3, generators only produce output; once a
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000411generator's code is invoked to create an iterator, there's no way to
412pass any new information into the function when its execution is
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000413resumed. Sometimes the ability to pass in some information would be
414useful. Hackish solutions to this include making the generator's code
415look at a global variable and then changing the global variable's
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000416value, or passing in some mutable object that callers then modify.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000417
418To refresh your memory of basic generators, here's a simple example:
419
420\begin{verbatim}
421def counter (maximum):
422 i = 0
423 while i < maximum:
424 yield i
425 i += 1
426\end{verbatim}
427
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000428When you call \code{counter(10)}, the result is an iterator that
429returns the values from 0 up to 9. On encountering the
430\keyword{yield} statement, the iterator returns the provided value and
431suspends the function's execution, preserving the local variables.
432Execution resumes on the following call to the iterator's
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000433\method{next()} method, picking up after the \keyword{yield} statement.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000434
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000435In Python 2.3, \keyword{yield} was a statement; it didn't return any
436value. In 2.5, \keyword{yield} is now an expression, returning a
437value that can be assigned to a variable or otherwise operated on:
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000438
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000439\begin{verbatim}
440val = (yield i)
441\end{verbatim}
442
443I recommend that you always put parentheses around a \keyword{yield}
444expression when you're doing something with the returned value, as in
445the above example. The parentheses aren't always necessary, but it's
446easier to always add them instead of having to remember when they're
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000447needed.\footnote{The exact rules are that a \keyword{yield}-expression must
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000448always be parenthesized except when it occurs at the top-level
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000449expression on the right-hand side of an assignment, meaning you can
450write \code{val = yield i} but have to use parentheses when there's an
451operation, as in \code{val = (yield i) + 12}.}
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000452
453Values are sent into a generator by calling its
454\method{send(\var{value})} method. The generator's code is then
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000455resumed and the \keyword{yield} expression returns the specified
456\var{value}. If the regular \method{next()} method is called, the
457\keyword{yield} returns \constant{None}.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000458
459Here's the previous example, modified to allow changing the value of
460the internal counter.
461
462\begin{verbatim}
463def counter (maximum):
464 i = 0
465 while i < maximum:
466 val = (yield i)
467 # If value provided, change counter
468 if val is not None:
469 i = val
470 else:
471 i += 1
472\end{verbatim}
473
474And here's an example of changing the counter:
475
476\begin{verbatim}
477>>> it = counter(10)
478>>> print it.next()
4790
480>>> print it.next()
4811
482>>> print it.send(8)
4838
484>>> print it.next()
4859
486>>> print it.next()
487Traceback (most recent call last):
488 File ``t.py'', line 15, in ?
489 print it.next()
490StopIteration
Andrew M. Kuchlingc2033702005-08-29 13:30:12 +0000491\end{verbatim}
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000492
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000493Because \keyword{yield} will often be returning \constant{None}, you
494should always check for this case. Don't just use its value in
495expressions unless you're sure that the \method{send()} method
496will be the only method used resume your generator function.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000497
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000498In addition to \method{send()}, there are two other new methods on
499generators:
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000500
501\begin{itemize}
502
503 \item \method{throw(\var{type}, \var{value}=None,
504 \var{traceback}=None)} is used to raise an exception inside the
505 generator; the exception is raised by the \keyword{yield} expression
506 where the generator's execution is paused.
507
508 \item \method{close()} raises a new \exception{GeneratorExit}
509 exception inside the generator to terminate the iteration.
510 On receiving this
511 exception, the generator's code must either raise
512 \exception{GeneratorExit} or \exception{StopIteration}; catching the
513 exception and doing anything else is illegal and will trigger
514 a \exception{RuntimeError}. \method{close()} will also be called by
515 Python's garbage collection when the generator is garbage-collected.
516
517 If you need to run cleanup code in case of a \exception{GeneratorExit},
518 I suggest using a \code{try: ... finally:} suite instead of
519 catching \exception{GeneratorExit}.
520
521\end{itemize}
522
523The cumulative effect of these changes is to turn generators from
524one-way producers of information into both producers and consumers.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000525
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000526Generators also become \emph{coroutines}, a more generalized form of
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000527subroutines. Subroutines are entered at one point and exited at
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000528another point (the top of the function, and a \keyword{return
529statement}), but coroutines can be entered, exited, and resumed at
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000530many different points (the \keyword{yield} statements). We'll have to
531figure out patterns for using coroutines effectively in Python.
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000532
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000533The addition of the \method{close()} method has one side effect that
534isn't obvious. \method{close()} is called when a generator is
535garbage-collected, so this means the generator's code gets one last
536chance to run before the generator is destroyed, and this last chance
537means that \code{try...finally} statements in generators can now be
538guaranteed to work; the \keyword{finally} clause will now always get a
539chance to run. The syntactic restriction that you couldn't mix
540\keyword{yield} statements with a \code{try...finally} suite has
541therefore been removed. This seems like a minor bit of language
542trivia, but using generators and \code{try...finally} is actually
543necessary in order to implement the \keyword{with} statement
544described by PEP 343. We'll look at this new statement in the following
545section.
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000546
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000547\begin{seealso}
548
549\seepep{342}{Coroutines via Enhanced Generators}{PEP written by
550Guido van Rossum and Phillip J. Eby;
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000551implemented by Phillip J. Eby. Includes examples of
552some fancier uses of generators as coroutines.}
553
554\seeurl{http://en.wikipedia.org/wiki/Coroutine}{The Wikipedia entry for
555coroutines.}
556
Neal Norwitz09179882006-03-04 23:31:45 +0000557\seeurl{http://www.sidhe.org/\~{}dan/blog/archives/000178.html}{An
Andrew M. Kuchling07382062005-08-27 18:45:47 +0000558explanation of coroutines from a Perl point of view, written by Dan
559Sugalski.}
Andrew M. Kuchlinga2e21cb2005-08-02 17:13:21 +0000560
561\end{seealso}
562
563
564%======================================================================
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000565\section{PEP 343: The 'with' statement}
566
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000567The \keyword{with} statement allows a clearer
568version of code that uses \code{try...finally} blocks
569
570First, I'll discuss the statement as it will commonly be used, and
571then I'll discuss the detailed implementation and how to write objects
572(called ``context managers'') that can be used with this statement.
573Most people, who will only use \keyword{with} in company with an
Andrew M. Kuchlinga4d651f2006-04-06 13:24:58 +0000574existing object, don't need to know these details and can
575just use objects that are documented to work as context managers.
576Authors of new context managers will need to understand the details of
577the underlying implementation.
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000578
579The \keyword{with} statement is a new control-flow structure whose
580basic structure is:
581
582\begin{verbatim}
583with expression as variable:
584 with-block
585\end{verbatim}
586
587The expression is evaluated, and it should result in a type of object
588that's called a context manager. The context manager can return a
589value that will be bound to the name \var{variable}. (Note carefully:
590\var{variable} is \emph{not} assigned the result of \var{expression}.
591One method of the context manager is run before \var{with-block} is
592executed, and another method is run after the block is done, even if
593the block raised an exception.
594
595To enable the statement in Python 2.5, you need
596to add the following directive to your module:
597
598\begin{verbatim}
599from __future__ import with_statement
600\end{verbatim}
601
602Some standard Python objects can now behave as context managers. For
603example, file objects:
604
605\begin{verbatim}
606with open('/etc/passwd', 'r') as f:
607 for line in f:
608 print line
609
610# f has been automatically closed at this point.
611\end{verbatim}
612
613The \module{threading} module's locks and condition variables
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000614also support the \keyword{with} statement:
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000615
616\begin{verbatim}
617lock = threading.Lock()
618with lock:
619 # Critical section of code
620 ...
621\end{verbatim}
622
623The lock is acquired before the block is executed, and released once
624the block is complete.
625
626The \module{decimal} module's contexts, which encapsulate the desired
627precision and rounding characteristics for computations, can also be
628used as context managers.
629
630\begin{verbatim}
631import decimal
632
633v1 = decimal.Decimal('578')
634
635# Displays with default precision of 28 digits
636print v1.sqrt()
637
638with decimal.Context(prec=16):
639 # All code in this block uses a precision of 16 digits.
640 # The original context is restored on exiting the block.
641 print v1.sqrt()
642\end{verbatim}
643
644\subsection{Writing Context Managers}
645
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000646% XXX write this
647
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000648This section still needs to be written.
649
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000650The new \module{contextlib} module provides some functions and a
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000651decorator that are useful for writing context managers.
652Future versions will go into more detail.
653
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000654% XXX describe further
655
656\begin{seealso}
657
658\seepep{343}{The ``with'' statement}{PEP written by
659Guido van Rossum and Nick Coghlan. }
660
661\end{seealso}
662
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000663
664%======================================================================
Andrew M. Kuchling8f4d2552006-03-08 01:50:20 +0000665\section{PEP 352: Exceptions as New-Style Classes}
666
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000667Exception classes can now be new-style classes, not just classic
668classes, and the built-in \exception{Exception} class and all the
669standard built-in exceptions (\exception{NameError},
670\exception{ValueError}, etc.) are now new-style classes.
Andrew M. Kuchlingaeadf952006-03-09 19:06:05 +0000671
672The inheritance hierarchy for exceptions has been rearranged a bit.
673In 2.5, the inheritance relationships are:
674
675\begin{verbatim}
676BaseException # New in Python 2.5
677|- KeyboardInterrupt
678|- SystemExit
679|- Exception
680 |- (all other current built-in exceptions)
681\end{verbatim}
682
683This rearrangement was done because people often want to catch all
684exceptions that indicate program errors. \exception{KeyboardInterrupt} and
685\exception{SystemExit} aren't errors, though, and usually represent an explicit
686action such as the user hitting Control-C or code calling
687\function{sys.exit()}. A bare \code{except:} will catch all exceptions,
688so you commonly need to list \exception{KeyboardInterrupt} and
689\exception{SystemExit} in order to re-raise them. The usual pattern is:
690
691\begin{verbatim}
692try:
693 ...
694except (KeyboardInterrupt, SystemExit):
695 raise
696except:
697 # Log error...
698 # Continue running program...
699\end{verbatim}
700
701In Python 2.5, you can now write \code{except Exception} to achieve
702the same result, catching all the exceptions that usually indicate errors
703but leaving \exception{KeyboardInterrupt} and
704\exception{SystemExit} alone. As in previous versions,
705a bare \code{except:} still catches all exceptions.
706
707The goal for Python 3.0 is to require any class raised as an exception
708to derive from \exception{BaseException} or some descendant of
709\exception{BaseException}, and future releases in the
710Python 2.x series may begin to enforce this constraint. Therefore, I
711suggest you begin making all your exception classes derive from
712\exception{Exception} now. It's been suggested that the bare
713\code{except:} form should be removed in Python 3.0, but Guido van~Rossum
714hasn't decided whether to do this or not.
715
716Raising of strings as exceptions, as in the statement \code{raise
717"Error occurred"}, is deprecated in Python 2.5 and will trigger a
718warning. The aim is to be able to remove the string-exception feature
719in a few releases.
720
721
722\begin{seealso}
723
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000724\seepep{352}{Required Superclass for Exceptions}{PEP written by
Andrew M. Kuchlingaeadf952006-03-09 19:06:05 +0000725Brett Cannon and Guido van Rossum; implemented by Brett Cannon.}
726
727\end{seealso}
Andrew M. Kuchling8f4d2552006-03-08 01:50:20 +0000728
729
730%======================================================================
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000731\section{PEP 353: Using ssize_t as the index type\label{section-353}}
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000732
733A wide-ranging change to Python's C API, using a new
734\ctype{Py_ssize_t} type definition instead of \ctype{int},
735will permit the interpreter to handle more data on 64-bit platforms.
736This change doesn't affect Python's capacity on 32-bit platforms.
737
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000738Various pieces of the Python interpreter used C's \ctype{int} type to
739store sizes or counts; for example, the number of items in a list or
740tuple were stored in an \ctype{int}. The C compilers for most 64-bit
741platforms still define \ctype{int} as a 32-bit type, so that meant
742that lists could only hold up to \code{2**31 - 1} = 2147483647 items.
743(There are actually a few different programming models that 64-bit C
744compilers can use -- see
745\url{http://www.unix.org/version2/whatsnew/lp64_wp.html} for a
746discussion -- but the most commonly available model leaves \ctype{int}
747as 32 bits.)
748
749A limit of 2147483647 items doesn't really matter on a 32-bit platform
750because you'll run out of memory before hitting the length limit.
751Each list item requires space for a pointer, which is 4 bytes, plus
752space for a \ctype{PyObject} representing the item. 2147483647*4 is
753already more bytes than a 32-bit address space can contain.
754
755It's possible to address that much memory on a 64-bit platform,
756however. The pointers for a list that size would only require 16GiB
757of space, so it's not unreasonable that Python programmers might
758construct lists that large. Therefore, the Python interpreter had to
759be changed to use some type other than \ctype{int}, and this will be a
76064-bit type on 64-bit platforms. The change will cause
761incompatibilities on 64-bit machines, so it was deemed worth making
762the transition now, while the number of 64-bit users is still
763relatively small. (In 5 or 10 years, we may \emph{all} be on 64-bit
764machines, and the transition would be more painful then.)
765
766This change most strongly affects authors of C extension modules.
767Python strings and container types such as lists and tuples
768now use \ctype{Py_ssize_t} to store their size.
769Functions such as \cfunction{PyList_Size()}
770now return \ctype{Py_ssize_t}. Code in extension modules
771may therefore need to have some variables changed to
772\ctype{Py_ssize_t}.
773
774The \cfunction{PyArg_ParseTuple()} and \cfunction{Py_BuildValue()} functions
775have a new conversion code, \samp{n}, for \ctype{Py_ssize_t}.
Andrew M. Kuchlinga4d651f2006-04-06 13:24:58 +0000776\cfunction{PyArg_ParseTuple()}'s \samp{s\#} and \samp{t\#} still output
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000777\ctype{int} by default, but you can define the macro
778\csimplemacro{PY_SSIZE_T_CLEAN} before including \file{Python.h}
779to make them return \ctype{Py_ssize_t}.
780
781\pep{353} has a section on conversion guidelines that
782extension authors should read to learn about supporting 64-bit
783platforms.
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000784
785\begin{seealso}
786
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +0000787\seepep{353}{Using ssize_t as the index type}{PEP written and implemented by Martin von~L\"owis.}
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000788
789\end{seealso}
790
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +0000791
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +0000792%======================================================================
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000793\section{PEP 357: The '__index__' method}
794
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000795The NumPy developers had a problem that could only be solved by adding
796a new special method, \method{__index__}. When using slice notation,
Fred Drake1c0e3282006-04-02 03:30:06 +0000797as in \code{[\var{start}:\var{stop}:\var{step}]}, the values of the
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000798\var{start}, \var{stop}, and \var{step} indexes must all be either
799integers or long integers. NumPy defines a variety of specialized
800integer types corresponding to unsigned and signed integers of 8, 16,
80132, and 64 bits, but there was no way to signal that these types could
802be used as slice indexes.
803
804Slicing can't just use the existing \method{__int__} method because
805that method is also used to implement coercion to integers. If
806slicing used \method{__int__}, floating-point numbers would also
807become legal slice indexes and that's clearly an undesirable
808behaviour.
809
810Instead, a new special method called \method{__index__} was added. It
811takes no arguments and returns an integer giving the slice index to
812use. For example:
813
814\begin{verbatim}
815class C:
816 def __index__ (self):
817 return self.value
818\end{verbatim}
819
820The return value must be either a Python integer or long integer.
821The interpreter will check that the type returned is correct, and
822raises a \exception{TypeError} if this requirement isn't met.
823
824A corresponding \member{nb_index} slot was added to the C-level
825\ctype{PyNumberMethods} structure to let C extensions implement this
826protocol. \cfunction{PyNumber_Index(\var{obj})} can be used in
827extension code to call the \method{__index__} function and retrieve
828its result.
829
830\begin{seealso}
831
832\seepep{357}{Allowing Any Object to be Used for Slicing}{PEP written
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000833and implemented by Travis Oliphant.}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000834
835\end{seealso}
Andrew M. Kuchling437567c2006-03-07 20:48:55 +0000836
837
838%======================================================================
Fred Drake2db76802004-12-01 05:05:47 +0000839\section{Other Language Changes}
840
841Here are all of the changes that Python 2.5 makes to the core Python
842language.
843
844\begin{itemize}
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +0000845
846\item The \function{min()} and \function{max()} built-in functions
847gained a \code{key} keyword argument analogous to the \code{key}
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +0000848argument for \method{sort()}. This argument supplies a function
Andrew M. Kuchling1cae3f52004-12-03 14:57:21 +0000849that takes a single argument and is called for every value in the list;
850\function{min()}/\function{max()} will return the element with the
851smallest/largest return value from this function.
852For example, to find the longest string in a list, you can do:
853
854\begin{verbatim}
855L = ['medium', 'longest', 'short']
856# Prints 'longest'
857print max(L, key=len)
858# Prints 'short', because lexicographically 'short' has the largest value
859print max(L)
860\end{verbatim}
861
862(Contributed by Steven Bethard and Raymond Hettinger.)
Fred Drake2db76802004-12-01 05:05:47 +0000863
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000864\item Two new built-in functions, \function{any()} and
865\function{all()}, evaluate whether an iterator contains any true or
866false values. \function{any()} returns \constant{True} if any value
867returned by the iterator is true; otherwise it will return
868\constant{False}. \function{all()} returns \constant{True} only if
869all of the values returned by the iterator evaluate as being true.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +0000870(Suggested by GvR, and implemented by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000871
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +0000872\item ASCII is now the default encoding for modules. It's now
873a syntax error if a module contains string literals with 8-bit
874characters but doesn't have an encoding declaration. In Python 2.4
875this triggered a warning, not a syntax error. See \pep{263}
876for how to declare a module's encoding; for example, you might add
877a line like this near the top of the source file:
878
879\begin{verbatim}
880# -*- coding: latin1 -*-
881\end{verbatim}
882
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +0000883\item The list of base classes in a class definition can now be empty.
884As an example, this is now legal:
885
886\begin{verbatim}
887class C():
888 pass
889\end{verbatim}
890(Implemented by Brett Cannon.)
891
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000892% XXX __missing__ hook in dictionaries
893
Fred Drake2db76802004-12-01 05:05:47 +0000894\end{itemize}
895
896
897%======================================================================
Andrew M. Kuchlingda376042006-03-17 15:56:41 +0000898\subsection{Interactive Interpreter Changes}
899
900In the interactive interpreter, \code{quit} and \code{exit}
901have long been strings so that new users get a somewhat helpful message
902when they try to quit:
903
904\begin{verbatim}
905>>> quit
906'Use Ctrl-D (i.e. EOF) to exit.'
907\end{verbatim}
908
909In Python 2.5, \code{quit} and \code{exit} are now objects that still
910produce string representations of themselves, but are also callable.
911Newbies who try \code{quit()} or \code{exit()} will now exit the
912interpreter as they expect. (Implemented by Georg Brandl.)
913
914
915%======================================================================
Fred Drake2db76802004-12-01 05:05:47 +0000916\subsection{Optimizations}
917
918\begin{itemize}
919
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000920\item When they were introduced
921in Python 2.4, the built-in \class{set} and \class{frozenset} types
922were built on top of Python's dictionary type.
923In 2.5 the internal data structure has been customized for implementing sets,
924and as a result sets will use a third less memory and are somewhat faster.
925(Implemented by Raymond Hettinger.)
Fred Drake2db76802004-12-01 05:05:47 +0000926
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000927\item The performance of some Unicode operations has been improved.
928% XXX provide details?
929
930\item The code generator's peephole optimizer now performs
931simple constant folding in expressions. If you write something like
932\code{a = 2+3}, the code generator will do the arithmetic and produce
933code corresponding to \code{a = 5}.
934
Fred Drake2db76802004-12-01 05:05:47 +0000935\end{itemize}
936
937The net result of the 2.5 optimizations is that Python 2.5 runs the
Andrew M. Kuchling9c67ee02006-04-04 19:07:27 +0000938pystone benchmark around XXX\% faster than Python 2.4.
Fred Drake2db76802004-12-01 05:05:47 +0000939
940
941%======================================================================
942\section{New, Improved, and Deprecated Modules}
943
944As usual, Python's standard library received a number of enhancements and
945bug fixes. Here's a partial list of the most notable changes, sorted
946alphabetically by module name. Consult the
947\file{Misc/NEWS} file in the source tree for a more
Andrew M. Kuchlingf688cc52006-03-10 18:50:08 +0000948complete list of changes, or look through the SVN logs for all the
Fred Drake2db76802004-12-01 05:05:47 +0000949details.
950
951\begin{itemize}
952
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000953% collections.deque now has .remove()
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000954% collections.defaultdict
Andrew M. Kuchling150e3492005-08-23 00:56:06 +0000955
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +0000956% the cPickle module no longer accepts the deprecated None option in the
957% args tuple returned by __reduce__().
958
959% csv module improvements
960
961% datetime.datetime() now has a strptime class method which can be used to
962% create datetime object using a string and format.
963
Andrew M. Kuchling38f85072006-04-02 01:46:32 +0000964% fileinput: opening hook used to control how files are opened.
965% .input() now has a mode parameter
966% now has a fileno() function
967% accepts Unicode filenames
968
Andrew M. Kuchlingda376042006-03-17 15:56:41 +0000969\item In the \module{gc} module, the new \function{get_count()} function
970returns a 3-tuple containing the current collection counts for the
971three GC generations. This is accounting information for the garbage
972collector; when these counts reach a specified threshold, a garbage
973collection sweep will be made. The existing \function{gc.collect()}
974function now takes an optional \var{generation} argument of 0, 1, or 2
975to specify which generation to collect.
976
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +0000977\item The \function{nsmallest()} and
978\function{nlargest()} functions in the \module{heapq} module
979now support a \code{key} keyword argument similar to the one
980provided by the \function{min()}/\function{max()} functions
981and the \method{sort()} methods. For example:
982Example:
983
984\begin{verbatim}
985>>> import heapq
986>>> L = ["short", 'medium', 'longest', 'longer still']
987>>> heapq.nsmallest(2, L) # Return two lowest elements, lexicographically
988['longer still', 'longest']
989>>> heapq.nsmallest(2, L, key=len) # Return two shortest elements
990['short', 'medium']
991\end{verbatim}
992
993(Contributed by Raymond Hettinger.)
994
Andrew M. Kuchling511a3a82005-03-20 19:52:18 +0000995\item The \function{itertools.islice()} function now accepts
996\code{None} for the start and step arguments. This makes it more
997compatible with the attributes of slice objects, so that you can now write
998the following:
999
1000\begin{verbatim}
1001s = slice(5) # Create slice object
1002itertools.islice(iterable, s.start, s.stop, s.step)
1003\end{verbatim}
1004
1005(Contributed by Raymond Hettinger.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001006
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001007\item The \module{operator} module's \function{itemgetter()}
1008and \function{attrgetter()} functions now support multiple fields.
1009A call such as \code{operator.attrgetter('a', 'b')}
1010will return a function
1011that retrieves the \member{a} and \member{b} attributes. Combining
1012this new feature with the \method{sort()} method's \code{key} parameter
1013lets you easily sort lists using multiple fields.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001014(Contributed by Raymond Hettinger.)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001015
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001016
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001017\item The \module{os} module underwent a number of changes. The
1018\member{stat_float_times} variable now defaults to true, meaning that
1019\function{os.stat()} will now return time values as floats. (This
1020doesn't necessarily mean that \function{os.stat()} will return times
1021that are precise to fractions of a second; not all systems support
1022such precision.)
Andrew M. Kuchling3e41b052005-03-01 00:53:46 +00001023
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001024Constants named \member{os.SEEK_SET}, \member{os.SEEK_CUR}, and
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001025\member{os.SEEK_END} have been added; these are the parameters to the
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001026\function{os.lseek()} function. Two new constants for locking are
1027\member{os.O_SHLOCK} and \member{os.O_EXLOCK}.
1028
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001029Two new functions, \function{wait3()} and \function{wait4()}, were
1030added. They're similar the \function{waitpid()} function which waits
1031for a child process to exit and returns a tuple of the process ID and
1032its exit status, but \function{wait3()} and \function{wait4()} return
1033additional information. \function{wait3()} doesn't take a process ID
1034as input, so it waits for any child process to exit and returns a
10353-tuple of \var{process-id}, \var{exit-status}, \var{resource-usage}
1036as returned from the \function{resource.getrusage()} function.
1037\function{wait4(\var{pid})} does take a process ID.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001038(Contributed by Chad J. Schroeder.)
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001039
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001040On FreeBSD, the \function{os.stat()} function now returns
1041times with nanosecond resolution, and the returned object
1042now has \member{st_gen} and \member{st_birthtime}.
1043The \member{st_flags} member is also available, if the platform supports it.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001044(Contributed by Antti Louko and Diego Petten\`o.)
1045% (Patch 1180695, 1212117)
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001046
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001047\item The old \module{regex} and \module{regsub} modules, which have been
1048deprecated ever since Python 2.0, have finally been deleted.
Andrew M. Kuchlingf4b06602006-03-17 15:39:52 +00001049Other deleted modules: \module{statcache}, \module{tzparse},
1050\module{whrandom}.
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001051
1052\item The \file{lib-old} directory,
1053which includes ancient modules such as \module{dircmp} and
1054\module{ni}, was also deleted. \file{lib-old} wasn't on the default
1055\code{sys.path}, so unless your programs explicitly added the directory to
1056\code{sys.path}, this removal shouldn't affect your code.
1057
Andrew M. Kuchling4678dc82006-01-15 16:11:28 +00001058\item The \module{socket} module now supports \constant{AF_NETLINK}
1059sockets on Linux, thanks to a patch from Philippe Biondi.
1060Netlink sockets are a Linux-specific mechanism for communications
1061between a user-space process and kernel code; an introductory
1062article about them is at \url{http://www.linuxjournal.com/article/7356}.
1063In Python code, netlink addresses are represented as a tuple of 2 integers,
1064\code{(\var{pid}, \var{group_mask})}.
1065
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001066Socket objects also gained accessor methods \method{getfamily()},
1067\method{gettype()}, and \method{getproto()} methods to retrieve the
1068family, type, and protocol values for the socket.
1069
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001070\item New module: \module{spwd} provides functions for accessing the
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001071shadow password database on systems that support it.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001072% XXX give example
Fred Drake2db76802004-12-01 05:05:47 +00001073
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001074% XXX patch #1382163: sys.subversion, Py_GetBuildNumber()
1075
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001076\item The \class{TarFile} class in the \module{tarfile} module now has
Georg Brandl08c02db2005-07-22 18:39:19 +00001077an \method{extractall()} method that extracts all members from the
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001078archive into the current working directory. It's also possible to set
1079a different directory as the extraction target, and to unpack only a
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001080subset of the archive's members.
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001081
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001082A tarfile's compression can be autodetected by
1083using the mode \code{'r|*'}.
1084% patch 918101
1085(Contributed by Lars Gust\"abel.)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001086
Andrew M. Kuchlingf688cc52006-03-10 18:50:08 +00001087\item The \module{unicodedata} module has been updated to use version 4.1.0
1088of the Unicode character database. Version 3.2.0 is required
1089by some specifications, so it's still available as
1090\member{unicodedata.db_3_2_0}.
1091
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001092% patch #754022: Greatly enhanced webbrowser.py (by Oleg Broytmann).
1093
Fredrik Lundh7e0aef02005-12-12 18:54:55 +00001094
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001095\item The \module{xmlrpclib} module now supports returning
1096 \class{datetime} objects for the XML-RPC date type. Supply
1097 \code{use_datetime=True} to the \function{loads()} function
1098 or the \class{Unmarshaller} class to enable this feature.
Andrew M. Kuchling6e3a66d2006-04-07 12:46:06 +00001099 (Contributed by Skip Montanaro.)
1100% Patch 1120353
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001101
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001102
Fred Drake114b8ca2005-03-21 05:47:11 +00001103\end{itemize}
Andrew M. Kuchlinge9b1bf42005-03-20 19:26:30 +00001104
Fred Drake2db76802004-12-01 05:05:47 +00001105
1106
1107%======================================================================
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001108% whole new modules get described in subsections here
Fred Drake2db76802004-12-01 05:05:47 +00001109
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001110\subsection{The ctypes package}
1111
1112The \module{ctypes} package, written by Thomas Heller, has been added
1113to the standard library. \module{ctypes} lets you call arbitrary functions
1114in shared libraries or DLLs.
1115
1116In subsequent alpha releases of Python 2.5, I'll add a brief
1117introduction that shows some basic usage of the module.
1118
1119% XXX write introduction
1120
1121
1122\subsection{The ElementTree package}
1123
1124A subset of Fredrik Lundh's ElementTree library for processing XML has
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001125been added to the standard library as \module{xmlcore.etree}. The
Georg Brandlce27a062006-04-11 06:27:12 +00001126available modules are
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001127\module{ElementTree}, \module{ElementPath}, and
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00001128\module{ElementInclude} from ElementTree 1.2.6.
1129The \module{cElementTree} accelerator module is also included.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001130
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001131The rest of this section will provide a brief overview of using
1132ElementTree. Full documentation for ElementTree is available at
1133\url{http://effbot.org/zone/element-index.htm}.
1134
1135ElementTree represents an XML document as a tree of element nodes.
1136The text content of the document is stored as the \member{.text}
1137and \member{.tail} attributes of
1138(This is one of the major differences between ElementTree and
1139the Document Object Model; in the DOM there are many different
1140types of node, including \class{TextNode}.)
1141
1142The most commonly used parsing function is \function{parse()}, that
1143takes either a string (assumed to contain a filename) or a file-like
1144object and returns an \class{ElementTree} instance:
1145
1146\begin{verbatim}
1147from xmlcore.etree import ElementTree as ET
1148
1149tree = ET.parse('ex-1.xml')
1150
1151feed = urllib.urlopen(
1152 'http://planet.python.org/rss10.xml')
1153tree = ET.parse(feed)
1154\end{verbatim}
1155
1156Once you have an \class{ElementTree} instance, you
1157can call its \method{getroot()} method to get the root \class{Element} node.
1158
1159There's also an \function{XML()} function that takes a string literal
1160and returns an \class{Element} node (not an \class{ElementTree}).
1161This function provides a tidy way to incorporate XML fragments,
1162approaching the convenience of an XML literal:
1163
1164\begin{verbatim}
1165svg = et.XML("""<svg width="10px" version="1.0">
1166 </svg>""")
1167svg.set('height', '320px')
1168svg.append(elem1)
1169\end{verbatim}
1170
1171Each XML element supports some dictionary-like and some list-like
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001172access methods. Dictionary-like operations are used to access attribute
1173values, and list-like operations are used to access child nodes.
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001174
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001175\begin{tableii}{c|l}{code}{Operation}{Result}
1176 \lineii{elem[n]}{Returns n'th child element.}
1177 \lineii{elem[m:n]}{Returns list of m'th through n'th child elements.}
1178 \lineii{len(elem)}{Returns number of child elements.}
1179 \lineii{elem.getchildren()}{Returns list of child elements.}
1180 \lineii{elem.append(elem2)}{Adds \var{elem2} as a child.}
1181 \lineii{elem.insert(index, elem2)}{Inserts \var{elem2} at the specified location.}
1182 \lineii{del elem[n]}{Deletes n'th child element.}
1183 \lineii{elem.keys()}{Returns list of attribute names.}
1184 \lineii{elem.get(name)}{Returns value of attribute \var{name}.}
1185 \lineii{elem.set(name, value)}{Sets new value for attribute \var{name}.}
1186 \lineii{elem.attrib}{Retrieves the dictionary containing attributes.}
1187 \lineii{del elem.attrib[name]}{Deletes attribute \var{name}.}
1188\end{tableii}
1189
1190Comments and processing instructions are also represented as
1191\class{Element} nodes. To check if a node is a comment or processing
1192instructions:
1193
1194\begin{verbatim}
1195if elem.tag is ET.Comment:
1196 ...
1197elif elem.tag is ET.ProcessingInstruction:
1198 ...
1199\end{verbatim}
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001200
1201To generate XML output, you should call the
1202\method{ElementTree.write()} method. Like \function{parse()},
1203it can take either a string or a file-like object:
1204
1205\begin{verbatim}
1206# Encoding is US-ASCII
1207tree.write('output.xml')
1208
1209# Encoding is UTF-8
1210f = open('output.xml', 'w')
1211tree.write(f, 'utf-8')
1212\end{verbatim}
1213
1214(Caution: the default encoding used for output is ASCII, which isn't
1215very useful for general XML work, raising an exception if there are
1216any characters with values greater than 127. You should always
1217specify a different encoding such as UTF-8 that can handle any Unicode
1218character.)
1219
Andrew M. Kuchling075e0232006-04-11 13:14:56 +00001220This section is only a partial description of the ElementTree interfaces.
1221Please read the package's official documentation for more details.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001222
Andrew M. Kuchling16ed5212006-04-10 22:28:11 +00001223\begin{seealso}
1224
1225\seeurl{http://effbot.org/zone/element-index.htm}
1226{Official documentation for ElementTree.}
1227
1228
1229\end{seealso}
1230
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001231
1232\subsection{The hashlib package}
1233
1234A new \module{hashlib} module has been added to replace the
1235\module{md5} and \module{sha} modules. \module{hashlib} adds support
1236for additional secure hashes (SHA-224, SHA-256, SHA-384, and SHA-512).
1237When available, the module uses OpenSSL for fast platform optimized
1238implementations of algorithms.
1239
1240The old \module{md5} and \module{sha} modules still exist as wrappers
1241around hashlib to preserve backwards compatibility. The new module's
1242interface is very close to that of the old modules, but not identical.
1243The most significant difference is that the constructor functions
1244for creating new hashing objects are named differently.
1245
1246\begin{verbatim}
1247# Old versions
1248h = md5.md5()
1249h = md5.new()
1250
1251# New version
1252h = hashlib.md5()
1253
1254# Old versions
1255h = sha.sha()
1256h = sha.new()
1257
1258# New version
1259h = hashlib.sha1()
1260
1261# Hash that weren't previously available
1262h = hashlib.sha224()
1263h = hashlib.sha256()
1264h = hashlib.sha384()
1265h = hashlib.sha512()
1266
1267# Alternative form
1268h = hashlib.new('md5') # Provide algorithm as a string
1269\end{verbatim}
1270
1271Once a hash object has been created, its methods are the same as before:
1272\method{update(\var{string})} hashes the specified string into the
1273current digest state, \method{digest()} and \method{hexdigest()}
1274return the digest value as a binary string or a string of hex digits,
1275and \method{copy()} returns a new hashing object with the same digest state.
1276
1277This module was contributed by Gregory P. Smith.
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001278
1279
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001280\subsection{The sqlite3 package}
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001281
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001282The pysqlite module (\url{http://www.pysqlite.org}), a wrapper for the
1283SQLite embedded database, has been added to the standard library under
1284the package name \module{sqlite3}. SQLite is a C library that
1285provides a SQL-language database that stores data in disk files
1286without requiring a separate server process. pysqlite was written by
1287Gerhard H\"aring, and provides a SQL interface that complies with the
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001288DB-API 2.0 specification described by \pep{249}. This means that it
1289should be possible to write the first version of your applications
1290using SQLite for data storage and, if switching to a larger database
1291such as PostgreSQL or Oracle is necessary, the switch should be
1292relatively easy.
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001293
1294If you're compiling the Python source yourself, note that the source
1295tree doesn't include the SQLite code itself, only the wrapper module.
1296You'll need to have the SQLite libraries and headers installed before
1297compiling Python, and the build process will compile the module when
1298the necessary headers are available.
1299
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001300To use the module, you must first create a \class{Connection} object
1301that represents the database. Here the data will be stored in the
1302\file{/tmp/example} file:
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001303
Andrew M. Kuchlingd58baf82006-04-10 21:40:16 +00001304\begin{verbatim}
1305conn = sqlite3.connect('/tmp/example')
1306\end{verbatim}
1307
1308You can also supply the special name \samp{:memory:} to create
1309a database in RAM.
1310
1311Once you have a \class{Connection}, you can create a \class{Cursor}
1312object and call its \method{execute()} method to perform SQL commands:
1313
1314\begin{verbatim}
1315c = conn.cursor()
1316
1317# Create table
1318c.execute('''create table stocks
1319(date timestamp, trans varchar, symbol varchar,
1320 qty decimal, price decimal)''')
1321
1322# Insert a row of data
1323c.execute("""insert into stocks
1324 values ('2006-01-05','BUY','RHAT',100, 35.14)""")
1325\end{verbatim}
1326
1327Usually your SQL queries will need to reflect the value of Python
1328variables. You shouldn't assemble your query using Python's string
1329operations because doing so is insecure; it makes your program
1330vulnerable to what's called an SQL injection attack. Instead, use
1331SQLite's parameter substitution, putting \samp{?} as a placeholder
1332wherever you want to use a value, and then provide a tuple of values
1333as the second argument to the cursor's \method{execute()} method. For
1334example:
1335
1336\begin{verbatim}
1337# Never do this -- insecure!
1338symbol = 'IBM'
1339c.execute("... where symbol = '%s'" % symbol)
1340
1341# Do this instead
1342t = (symbol,)
1343c.execute("... where symbol = '?'", t)
1344
1345# Larger example
1346for t in (('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
1347 ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
1348 ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
1349 ):
1350 c.execute('insert into stocks values (?,?,?,?,?)', t)
1351\end{verbatim}
1352
1353To retrieve data after executing a SELECT statement, you can either
1354treat the cursor as an iterator, call the cursor's \method{fetchone()}
1355method to retrieve a single matching row,
1356or call \method{fetchall()} to get a list of the matching rows.
1357
1358This example uses the iterator form:
1359
1360\begin{verbatim}
1361>>> c = conn.cursor()
1362>>> c.execute('select * from stocks order by price')
1363>>> for row in c:
1364... print row
1365...
1366(u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001)
1367(u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
1368(u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
1369(u'2006-04-05', u'BUY', u'MSOFT', 1000, 72.0)
1370>>>
1371\end{verbatim}
1372
1373You should also use parameter substitution with SELECT statements:
1374
1375\begin{verbatim}
1376>>> c.execute('select * from stocks where symbol=?', ('IBM',))
1377>>> print c.fetchall()
1378[(u'2006-03-28', u'BUY', u'IBM', 1000, 45.0),
1379 (u'2006-04-06', u'SELL', u'IBM', 500, 53.0)]
1380\end{verbatim}
1381
1382For more information about the SQL dialect supported by SQLite, see
1383\url{http://www.sqlite.org}.
1384
1385\begin{seealso}
1386
1387\seeurl{http://www.pysqlite.org}
1388{The pysqlite web page.}
1389
1390\seeurl{http://www.sqlite.org}
1391{The SQLite web page; the documentation describes the syntax and the
1392available data types for the supported SQL dialect.}
1393
1394\seepep{249}{Database API Specification 2.0}{PEP written by
1395Marc-Andr\'e Lemburg.}
1396
1397\end{seealso}
Andrew M. Kuchlingaf7ee992006-04-03 12:41:37 +00001398
Fred Drake2db76802004-12-01 05:05:47 +00001399
1400% ======================================================================
1401\section{Build and C API Changes}
1402
1403Changes to Python's build process and to the C API include:
1404
1405\begin{itemize}
1406
Andrew M. Kuchling4d8cd892006-04-06 13:03:04 +00001407\item The largest change to the C API came from \pep{353},
1408which modifies the interpreter to use a \ctype{Py_ssize_t} type
1409definition instead of \ctype{int}. See the earlier
1410section~ref{section-353} for a discussion of this change.
1411
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001412\item The design of the bytecode compiler has changed a great deal, to
1413no longer generate bytecode by traversing the parse tree. Instead
Andrew M. Kuchlingdb85ed52005-10-23 21:52:59 +00001414the parse tree is converted to an abstract syntax tree (or AST), and it is
1415the abstract syntax tree that's traversed to produce the bytecode.
1416
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00001417It's possible for Python code to obtain AST objects by using the
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001418\function{compile()} built-in and specifying \code{_ast.PyCF_ONLY_AST}
1419as the value of the
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00001420\var{flags} parameter:
1421
1422\begin{verbatim}
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001423from _ast import PyCF_ONLY_AST
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00001424ast = compile("""a=0
1425for i in range(10):
1426 a += i
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001427""", "<string>", 'exec', PyCF_ONLY_AST)
Andrew M. Kuchling4e861952006-04-12 12:16:31 +00001428
1429assignment = ast.body[0]
1430for_loop = ast.body[1]
1431\end{verbatim}
1432
Andrew M. Kuchlingdb85ed52005-10-23 21:52:59 +00001433No documentation has been written for the AST code yet. To start
1434learning about it, read the definition of the various AST nodes in
1435\file{Parser/Python.asdl}. A Python script reads this file and
1436generates a set of C structure definitions in
1437\file{Include/Python-ast.h}. The \cfunction{PyParser_ASTFromString()}
1438and \cfunction{PyParser_ASTFromFile()}, defined in
1439\file{Include/pythonrun.h}, take Python source as input and return the
1440root of an AST representing the contents. This AST can then be turned
1441into a code object by \cfunction{PyAST_Compile()}. For more
1442information, read the source code, and then ask questions on
1443python-dev.
1444
1445% List of names taken from Jeremy's python-dev post at
1446% http://mail.python.org/pipermail/python-dev/2005-October/057500.html
1447The AST code was developed under Jeremy Hylton's management, and
1448implemented by (in alphabetical order) Brett Cannon, Nick Coghlan,
1449Grant Edwards, John Ehresman, Kurt Kaiser, Neal Norwitz, Tim Peters,
1450Armin Rigo, and Neil Schemenauer, plus the participants in a number of
1451AST sprints at conferences such as PyCon.
1452
Andrew M. Kuchling150e3492005-08-23 00:56:06 +00001453\item The built-in set types now have an official C API. Call
1454\cfunction{PySet_New()} and \cfunction{PyFrozenSet_New()} to create a
1455new set, \cfunction{PySet_Add()} and \cfunction{PySet_Discard()} to
1456add and remove elements, and \cfunction{PySet_Contains} and
1457\cfunction{PySet_Size} to examine the set's state.
1458
1459\item The \cfunction{PyRange_New()} function was removed. It was
1460never documented, never used in the core code, and had dangerously lax
1461error checking.
Fred Drake2db76802004-12-01 05:05:47 +00001462
1463\end{itemize}
1464
1465
1466%======================================================================
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001467%\subsection{Port-Specific Changes}
Fred Drake2db76802004-12-01 05:05:47 +00001468
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001469%Platform-specific changes go here.
Fred Drake2db76802004-12-01 05:05:47 +00001470
1471
1472%======================================================================
1473\section{Other Changes and Fixes \label{section-other}}
1474
1475As usual, there were a bunch of other improvements and bugfixes
Andrew M. Kuchlingf688cc52006-03-10 18:50:08 +00001476scattered throughout the source tree. A search through the SVN change
Fred Drake2db76802004-12-01 05:05:47 +00001477logs finds there were XXX patches applied and YYY bugs fixed between
Andrew M. Kuchling92e24952004-12-03 13:54:09 +00001478Python 2.4 and 2.5. Both figures are likely to be underestimates.
Fred Drake2db76802004-12-01 05:05:47 +00001479
1480Some of the more notable changes are:
1481
1482\begin{itemize}
1483
Andrew M. Kuchling01e3d262006-03-17 15:38:39 +00001484\item Evan Jones's patch to obmalloc, first described in a talk
1485at PyCon DC 2005, was applied. Python 2.4 allocated small objects in
1486256K-sized arenas, but never freed arenas. With this patch, Python
1487will free arenas when they're empty. The net effect is that on some
1488platforms, when you allocate many objects, Python's memory usage may
1489actually drop when you delete them, and the memory may be returned to
1490the operating system. (Implemented by Evan Jones, and reworked by Tim
1491Peters.)
Fred Drake2db76802004-12-01 05:05:47 +00001492
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00001493Note that this change means extension modules need to be more careful
1494with how they allocate memory. Python's API has a number of different
1495functions for allocating memory that are grouped into families. For
1496example, \cfunction{PyMem_Malloc()}, \cfunction{PyMem_Realloc()}, and
1497\cfunction{PyMem_Free()} are one family that allocates raw memory,
1498while \cfunction{PyObject_Malloc()}, \cfunction{PyObject_Realloc()},
1499and \cfunction{PyObject_Free()} are another family that's supposed to
1500be used for creating Python objects.
1501
1502Previously these different families all reduced to the platform's
1503\cfunction{malloc()} and \cfunction{free()} functions. This meant
1504it didn't matter if you got things wrong and allocated memory with the
1505\cfunction{PyMem} function but freed it with the \cfunction{PyObject}
1506function. With the obmalloc change, these families now do different
1507things, and mismatches will probably result in a segfault. You should
1508carefully test your C extension modules with Python 2.5.
1509
Andrew M. Kuchling38f85072006-04-02 01:46:32 +00001510\item Coverity, a company that markets a source code analysis tool
1511 called Prevent, provided the results of their examination of the Python
1512 source code. The analysis found a number of refcounting bugs, often
1513 in error-handling code. These bugs have been fixed.
1514 % XXX provide reference?
1515
Fred Drake2db76802004-12-01 05:05:47 +00001516\end{itemize}
1517
1518
1519%======================================================================
1520\section{Porting to Python 2.5}
1521
1522This section lists previously described changes that may require
1523changes to your code:
1524
1525\begin{itemize}
1526
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001527\item ASCII is now the default encoding for modules. It's now
1528a syntax error if a module contains string literals with 8-bit
1529characters but doesn't have an encoding declaration. In Python 2.4
1530this triggered a warning, not a syntax error.
1531
Andrew M. Kuchlingc3749a92006-04-04 19:14:41 +00001532\item The \module{pickle} module no longer uses the deprecated \var{bin} parameter.
Fred Drake2db76802004-12-01 05:05:47 +00001533
Andrew M. Kuchlingf7c62902006-04-12 12:27:50 +00001534\item C API: Many functions now use \ctype{Py_ssize_t}
1535instead of \ctype{int} to allow processing more data
1536on 64-bit machines. Extension code may need to make
1537the same change to avoid warnings and to support 64-bit machines.
1538See the earlier
1539section~ref{section-353} for a discussion of this change.
1540
1541\item C API:
1542The obmalloc changes mean that
1543you must be careful to not mix usage
1544of the \cfunction{PyMem_*()} and \cfunction{PyObject_*()}
1545families of functions. Memory allocated with
1546one family's \cfunction{*_Malloc()} must be
1547freed with the corresponding family's \cfunction{*_Free()} function.
1548
Fred Drake2db76802004-12-01 05:05:47 +00001549\end{itemize}
1550
1551
1552%======================================================================
1553\section{Acknowledgements \label{acks}}
1554
1555The author would like to thank the following people for offering
1556suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchling5f445bf2006-04-12 18:54:00 +00001557article: Martin von~L\"owis, Mike Rovner, Thomas Wouters.
Fred Drake2db76802004-12-01 05:05:47 +00001558
1559\end{document}