blob: d493d9aecde6fee267f89ff5fd368da54244d79a [file] [log] [blame]
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001****************************
2 What's New in Python 2.7
3****************************
4
5:Author: A.M. Kuchling (amk at amk.ca)
6:Release: |release|
7:Date: |today|
8
Andrew M. Kuchling6d7dfa22010-04-11 12:49:37 +00009.. hyperlink all the methods & functions.
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +000010
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +000011.. T_STRING_INPLACE not described in main docs
Andrew M. Kuchling0efe18a2010-05-08 15:39:46 +000012.. "Format String Syntax" in string.rst could use many more examples.
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +000013
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000014.. $Id$
15 Rules for maintenance:
16
17 * Anyone can add text to this document. Do not spend very much time
18 on the wording of your changes, because your text will probably
19 get rewritten to some degree.
20
21 * The maintainer will go through Misc/NEWS periodically and add
22 changes; it's therefore more important to add your changes to
23 Misc/NEWS than to this file.
24
25 * This is not a complete list of every single change; completeness
26 is the purpose of Misc/NEWS. Some changes I consider too small
27 or esoteric to include. If such a change is added to the text,
28 I'll just remove it. (This is another reason you shouldn't spend
29 too much time on writing your addition.)
30
31 * If you want to draw your new text to the attention of the
32 maintainer, add 'XXX' to the beginning of the paragraph or
33 section.
34
35 * It's OK to just add a fragmentary note about a change. For
36 example: "XXX Describe the transmogrify() function added to the
37 socket module." The maintainer will research the change and
38 write the necessary text.
39
40 * You can comment out your additions if you like, but it's not
41 necessary (especially when a final release is some months away).
42
Ezio Melotti021f3342010-04-06 03:26:49 +000043 * Credit the author of a patch or bugfix. Just the name is
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000044 sufficient; the e-mail address isn't necessary.
45
46 * It's helpful to add the bug/patch number in a parenthetical comment.
47
48 XXX Describe the transmogrify() function added to the socket
49 module.
50 (Contributed by P.Y. Developer; :issue:`12345`.)
51
52 This saves the maintainer some effort going through the SVN logs
53 when researching a change.
54
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +000055This article explains the new features in Python 2.7. The final
Andrew M. Kuchling837a5382010-05-06 17:21:59 +000056release of 2.7 is currently scheduled for July 2010; the detailed
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +000057schedule is described in :pep:`373`.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000058
Andrew M. Kuchling27024912010-05-12 00:38:44 +000059Numeric handling has been improved in many ways, for both
Andrew M. Kuchling0efe18a2010-05-08 15:39:46 +000060floating-point numbers and for the :class:`Decimal` class. There are
61some useful additions to the standard library, such as a greatly
62enhanced :mod:`unittest` module, the :mod:`argparse` module for
63parsing command-line options, convenient ordered-dictionary and
64:class:`Counter` classes in the :mod:`collections` module, and many
65other improvements.
66
Andrew M. Kuchling27024912010-05-12 00:38:44 +000067Python 2.7 is planned to be the last of the 2.x releases, so we worked
68on making it a good release for the long term. To help with porting
69to Python 3, several new features from the Python 3.x series have been
70included in 2.7.
71
Andrew M. Kuchling0efe18a2010-05-08 15:39:46 +000072This article doesn't attempt to provide a complete specification of
73the new features, but instead provides a convenient overview. For
74full details, you should refer to the documentation for Python 2.7 at
75http://docs.python.org. If you want to understand the rationale for
76the design and implementation, refer to the PEP for a particular new
77feature or the issue on http://bugs.python.org in which a change was
78discussed. Whenever possible, "What's New in Python" links to the
79bug/patch item for each change.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000080
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +000081.. _whatsnew27-python31:
82
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +000083The Future for Python 2.x
84=========================
85
86Python 2.7 is intended to be the last major release in the 2.x series.
Andrew M. Kuchlingd1e696b2010-05-07 11:30:47 +000087The Python maintainers are planning to focus their future efforts on
88the Python 3.x series.
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +000089
90This means that 2.7 will remain in place for a long time, running
91production systems that have not been ported to Python 3.x.
92Two consequences of the long-term significance of 2.7 are:
93
94* It's very likely the 2.7 release will have a longer period of
95 maintenance compared to earlier 2.x versions. Python 2.7 will
Andrew M. Kuchling0efe18a2010-05-08 15:39:46 +000096 continue to be maintained while the transition to 3.x continues, and
97 the developers are planning to support Python 2.7 with bug-fix
98 releases beyond the typical two years.
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +000099
Andrew M. Kuchlingd1e696b2010-05-07 11:30:47 +0000100* A policy decision was made to silence warnings only of interest to
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000101 developers. :exc:`DeprecationWarning` and its
Andrew M. Kuchlingd1e696b2010-05-07 11:30:47 +0000102 descendants are now ignored unless otherwise requested, preventing
Andrew M. Kuchling0efe18a2010-05-08 15:39:46 +0000103 users from seeing warnings triggered by an application. This change
104 was also made in the branch that will become Python 3.2. (Discussed
105 on stdlib-sig and carried out in :issue:`7319`.)
Andrew M. Kuchlingd1e696b2010-05-07 11:30:47 +0000106
107 In previous releases, :exc:`DeprecationWarning` messages were
108 enabled by default, providing Python developers with a clear
109 indication of where their code may break in a future major version
110 of Python.
111
112 However, there are increasingly many users of Python-based
113 applications who are not directly involved in the development of
114 those applications. :exc:`DeprecationWarning` messages are
115 irrelevant to such users, making them worry about an application
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000116 that's actually working correctly and burdening application developers
117 with responding to these concerns.
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +0000118
119 You can re-enable display of :exc:`DeprecationWarning` messages by
120 running Python with the :option:`-Wdefault` (short form:
Andrew M. Kuchling0efe18a2010-05-08 15:39:46 +0000121 :option:`-Wd`) switch, or by setting the :envvar:`PYTHONWARNINGS`
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000122 environment variable to ``"default"`` (or ``"d"``) before running
Andrew M. Kuchling0efe18a2010-05-08 15:39:46 +0000123 Python. Python code can also re-enable them
124 by calling ``warnings.simplefilter('default')``.
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +0000125
126
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000127Python 3.1 Features
128=======================
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000129
130Much as Python 2.6 incorporated features from Python 3.0,
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000131version 2.7 incorporates some of the new features
132in Python 3.1. The 2.x series continues to provide tools
133for migrating to the 3.x series.
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000134
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000135A partial list of 3.1 features that were backported to 2.7:
136
Andrew M. Kuchling0efe18a2010-05-08 15:39:46 +0000137* The syntax for set literals (``{1,2,3}`` is a mutable set).
138* Dictionary and set comprehensions (``{ i: i*2 for i in range(3)}``).
Andrew M. Kuchling93c40d42010-05-10 14:18:27 +0000139* Multiple context managers in a single :keyword:`with` statement.
Andrew M. Kuchling837a5382010-05-06 17:21:59 +0000140* A new version of the :mod:`io` library, rewritten in C for performance.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000141* The ordered-dictionary type described in :ref:`pep-0372`.
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000142* The new ``","`` format specifier described in :ref:`pep-0378`.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000143* The :class:`memoryview` object.
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000144* A small subset of the :mod:`importlib` module,
145 `described below <#importlib-section>`__.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000146* Float-to-string and string-to-float conversions now round their
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000147 results more correctly, and :func:`repr` of a floating-point
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000148 number *x* returns a result that's guaranteed to round back to the
149 same number when converted back to a string.
Andrew M. Kuchling93c40d42010-05-10 14:18:27 +0000150* The :ctype:`PyCapsule` type, used to provide a C API for extension modules.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000151* The :cfunc:`PyLong_AsLongAndOverflow` C API function.
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000152
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000153Other new Python3-mode warnings include:
154
155* :func:`operator.isCallable` and :func:`operator.sequenceIncludes`,
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000156 which are not supported in 3.x, now trigger warnings.
157* The :option:`-3` switch now automatically
158 enables the :option:`-Qwarn` switch that causes warnings
159 about using classic division with integers and long integers.
160
161
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000162
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000163.. ========================================================================
164.. Large, PEP-level features and changes should be described here.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000165.. ========================================================================
166
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000167.. _pep-0372:
168
Andrew M. Kuchling10595a62010-05-10 14:20:12 +0000169PEP 372: Adding an Ordered Dictionary to collections
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000170====================================================
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000171
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000172Regular Python dictionaries iterate over key/value pairs in arbitrary order.
173Over the years, a number of authors have written alternative implementations
174that remember the order that the keys were originally inserted. Based on
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000175the experiences from those implementations, 2.7 introduces a new
176:class:`~collections.OrderedDict` class in the :mod:`collections` module.
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000177
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000178The :class:`~collections.OrderedDict` API provides the same interface as regular
179dictionaries but iterates over keys and values in a guaranteed order
Ezio Melotti021f3342010-04-06 03:26:49 +0000180depending on when a key was first inserted::
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000181
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000182 >>> from collections import OrderedDict
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000183 >>> d = OrderedDict([('first', 1),
184 ... ('second', 2),
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000185 ... ('third', 3)])
186 >>> d.items()
187 [('first', 1), ('second', 2), ('third', 3)]
188
189If a new entry overwrites an existing entry, the original insertion
190position is left unchanged::
191
192 >>> d['second'] = 4
193 >>> d.items()
194 [('first', 1), ('second', 4), ('third', 3)]
195
196Deleting an entry and reinserting it will move it to the end::
197
198 >>> del d['second']
199 >>> d['second'] = 5
200 >>> d.items()
201 [('first', 1), ('third', 3), ('second', 5)]
202
Ezio Melotti021f3342010-04-06 03:26:49 +0000203The :meth:`~collections.OrderedDict.popitem` method has an optional *last*
204argument that defaults to True. If *last* is True, the most recently
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000205added key is returned and removed; if it's False, the
206oldest key is selected::
207
208 >>> od = OrderedDict([(x,0) for x in range(20)])
209 >>> od.popitem()
210 (19, 0)
211 >>> od.popitem()
212 (18, 0)
Ezio Melotti021f3342010-04-06 03:26:49 +0000213 >>> od.popitem(last=False)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000214 (0, 0)
Ezio Melotti021f3342010-04-06 03:26:49 +0000215 >>> od.popitem(last=False)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000216 (1, 0)
217
218Comparing two ordered dictionaries checks both the keys and values,
219and requires that the insertion order was the same::
220
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000221 >>> od1 = OrderedDict([('first', 1),
222 ... ('second', 2),
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000223 ... ('third', 3)])
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000224 >>> od2 = OrderedDict([('third', 3),
225 ... ('first', 1),
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000226 ... ('second', 2)])
Ezio Melotti021f3342010-04-06 03:26:49 +0000227 >>> od1 == od2
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000228 False
229 >>> # Move 'third' key to the end
Ezio Melotti021f3342010-04-06 03:26:49 +0000230 >>> del od2['third']; od2['third'] = 3
231 >>> od1 == od2
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000232 True
233
Ezio Melotti021f3342010-04-06 03:26:49 +0000234Comparing an :class:`~collections.OrderedDict` with a regular dictionary
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000235ignores the insertion order and just compares the keys and values.
236
Ezio Melotti021f3342010-04-06 03:26:49 +0000237How does the :class:`~collections.OrderedDict` work? It maintains a
238doubly-linked list of keys, appending new keys to the list as they're inserted.
239A secondary dictionary maps keys to their corresponding list node, so
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000240deletion doesn't have to traverse the entire linked list and therefore
241remains O(1).
242
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000243The standard library now supports use of ordered dictionaries in several
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +0000244modules.
245
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000246* The :mod:`ConfigParser` module uses them by default, meaning that
247 configuration files can now read, modified, and then written back
248 in their original order.
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +0000249
250* The :meth:`~collections.somenamedtuple._asdict()` method for
251 :func:`collections.namedtuple` now returns an ordered dictionary with the
252 values appearing in the same order as the underlying tuple indices.
253
254* The :mod:`json` module's :class:`~json.JSONDecoder` class
255 constructor was extended with an *object_pairs_hook* parameter to
256 allow :class:`OrderedDict` instances to be built by the decoder.
257 Support was also added for third-party tools like
258 `PyYAML <http://pyyaml.org/>`_.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000259
Andrew M. Kuchling7fe65a02009-10-13 15:49:33 +0000260.. seealso::
261
262 :pep:`372` - Adding an ordered dictionary to collections
263 PEP written by Armin Ronacher and Raymond Hettinger;
264 implemented by Raymond Hettinger.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000265
266.. _pep-0378:
267
268PEP 378: Format Specifier for Thousands Separator
Ezio Melotti021f3342010-04-06 03:26:49 +0000269=================================================
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000270
271To make program output more readable, it can be useful to add
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000272separators to large numbers, rendering them as
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +000027318,446,744,073,709,551,616 instead of 18446744073709551616.
274
275The fully general solution for doing this is the :mod:`locale` module,
276which can use different separators ("," in North America, "." in
277Europe) and different grouping sizes, but :mod:`locale` is complicated
278to use and unsuitable for multi-threaded applications where different
279threads are producing output for different locales.
280
281Therefore, a simple comma-grouping mechanism has been added to the
Ezio Melotti021f3342010-04-06 03:26:49 +0000282mini-language used by the :meth:`str.format` method. When
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000283formatting a floating-point number, simply include a comma between the
284width and the precision::
285
Eric Smithc4663852010-04-06 14:30:15 +0000286 >>> '{:20,.2f}'.format(18446744073709551616.0)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000287 '18,446,744,073,709,551,616.00'
288
Eric Smith6a928602010-04-06 15:17:33 +0000289When formatting an integer, include the comma after the width:
290
291 >>> '{:20,d}'.format(18446744073709551616)
292 '18,446,744,073,709,551,616'
293
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000294This mechanism is not adaptable at all; commas are always used as the
295separator and the grouping is always into three-digit groups. The
296comma-formatting mechanism isn't as general as the :mod:`locale`
297module, but it's easier to use.
298
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000299.. seealso::
300
301 :pep:`378` - Format Specifier for Thousands Separator
302 PEP written by Raymond Hettinger; implemented by Eric Smith.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000303
Andrew M. Kuchlingab21f752010-03-02 13:55:33 +0000304PEP 389: The argparse Module for Parsing Command Lines
305======================================================
306
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000307The :mod:`argparse` module for parsing command-line arguments was
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000308added as a more powerful replacement for the
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000309:mod:`optparse` module.
310
311This means Python now supports three different modules for parsing
312command-line arguments: :mod:`getopt`, :mod:`optparse`, and
313:mod:`argparse`. The :mod:`getopt` module closely resembles the C
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000314library's :cfunc:`getopt` function, so it remains useful if you're writing a
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000315Python prototype that will eventually be rewritten in C.
316:mod:`optparse` becomes redundant, but there are no plans to remove it
317because there are many scripts still using it, and there's no
318automated way to update these scripts. (Making the :mod:`argparse`
319API consistent with :mod:`optparse`'s interface was discussed but
320rejected as too messy and difficult.)
321
Andrew M. Kuchlingf03641a2010-04-14 01:14:59 +0000322In short, if you're writing a new script and don't need to worry
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000323about compatibility with earlier versions of Python, use
324:mod:`argparse` instead of :mod:`optparse`.
325
Andrew M. Kuchlingf03641a2010-04-14 01:14:59 +0000326Here's an example::
327
328 import argparse
329
330 parser = argparse.ArgumentParser(description='Command-line example.')
331
332 # Add optional switches
333 parser.add_argument('-v', action='store_true', dest='is_verbose',
334 help='produce verbose output')
335 parser.add_argument('-o', action='store', dest='output',
336 metavar='FILE',
337 help='direct output to FILE instead of stdout')
338 parser.add_argument('-C', action='store', type=int, dest='context',
339 metavar='NUM', default=0,
340 help='display NUM lines of added context')
341
342 # Allow any number of additional arguments.
343 parser.add_argument(nargs='*', action='store', dest='inputs',
344 help='input filenames (default is stdin)')
345
346 args = parser.parse_args()
347 print args.__dict__
348
349Unless you override it, :option:`-h` and :option:`--help` switches
350are automatically added, and produce neatly formatted output::
351
352 -> ./python.exe argparse-example.py --help
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +0000353 usage: argparse-example.py [-h] [-v] [-o FILE] [-C NUM] [inputs [inputs ...]]
Andrew M. Kuchlingf03641a2010-04-14 01:14:59 +0000354
355 Command-line example.
356
357 positional arguments:
358 inputs input filenames (default is stdin)
359
360 optional arguments:
361 -h, --help show this help message and exit
362 -v produce verbose output
363 -o FILE direct output to FILE instead of stdout
364 -C NUM display NUM lines of added context
365
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000366As with :mod:`optparse`, the command-line switches and arguments
Andrew M. Kuchlingf03641a2010-04-14 01:14:59 +0000367are returned as an object with attributes named by the *dest* parameters::
368
369 -> ./python.exe argparse-example.py -v
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000370 {'output': None,
371 'is_verbose': True,
372 'context': 0,
373 'inputs': []}
Andrew M. Kuchlingf03641a2010-04-14 01:14:59 +0000374
375 -> ./python.exe argparse-example.py -v -o /tmp/output -C 4 file1 file2
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000376 {'output': '/tmp/output',
377 'is_verbose': True,
378 'context': 4,
Andrew M. Kuchlingf03641a2010-04-14 01:14:59 +0000379 'inputs': ['file1', 'file2']}
380
381:mod:`argparse` has much fancier validation than :mod:`optparse`; you
382can specify an exact number of arguments as an integer, 0 or more
383arguments by passing ``'*'``, 1 or more by passing ``'+'``, or an
384optional argument with ``'?'``. A top-level parser can contain
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000385sub-parsers to define subcommands that have different sets of
Andrew M. Kuchlingf03641a2010-04-14 01:14:59 +0000386switches, as in ``svn commit``, ``svn checkout``, etc. You can
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000387specify an argument's type as :class:`~argparse.FileType`, which will
Andrew M. Kuchlingf03641a2010-04-14 01:14:59 +0000388automatically open files for you and understands that ``'-'`` means
389standard input or output.
Andrew M. Kuchlingab21f752010-03-02 13:55:33 +0000390
391.. seealso::
392
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000393 `argparse module documentation <http://docs.python.org/dev/library/argparse.html>`__
394
395 `Upgrading optparse code to use argparse <http://docs.python.org/dev/library/argparse.html#upgrading-optparse-code>`__
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000396 Part of the Python documentation, describing how to convert
397 code that uses :mod:`optparse`.
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000398
Andrew M. Kuchlingab21f752010-03-02 13:55:33 +0000399 :pep:`389` - argparse - New Command Line Parsing Module
400 PEP written and implemented by Steven Bethard.
401
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000402PEP 391: Dictionary-Based Configuration For Logging
403====================================================
404
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000405.. XXX not documented in library reference yet; add link here once it's added.
Andrew M. Kuchlingb6c1aeb2010-04-14 14:28:31 +0000406
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000407The :mod:`logging` module is very flexible; applications can define
Andrew M. Kuchlingb6c1aeb2010-04-14 14:28:31 +0000408a tree of logging subsystems, and each logger in this tree can filter
409out certain messages, format them differently, and direct messages to
410a varying number of handlers.
411
412All this flexibility can require a lot of configuration. You can
413write Python statements to create objects and set their properties,
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000414but a complex set-up requires verbose but boring code.
Andrew M. Kuchlingb6c1aeb2010-04-14 14:28:31 +0000415:mod:`logging` also supports a :func:`~logging.config.fileConfig`
416function that parses a file, but the file format doesn't support
417configuring filters, and it's messier to generate programmatically.
418
419Python 2.7 adds a :func:`~logging.config.dictConfig` function that
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000420uses a dictionary to configure logging. There are many ways to
421produce a dictionary from different sources: construct one with code;
422parse a file containing JSON; or use a YAML parsing library if one is
423installed.
Andrew M. Kuchlingb6c1aeb2010-04-14 14:28:31 +0000424
Andrew M. Kuchling8e343862010-05-08 13:28:03 +0000425The following example configures two loggers, the root logger and a
426logger named "network". Messages sent to the root logger will be
427sent to the system log using the syslog protocol, and messages
428to the "network" logger will be written to a :file:`network.log` file
429that will be rotated once the log reaches 1Mb.
430
431::
432
433 import logging
434 import logging.config
435
436 configdict = {
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000437 'version': 1, # Configuration schema in use; must be 1 for now
Andrew M. Kuchling8e343862010-05-08 13:28:03 +0000438 'formatters': {
439 'standard': {
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000440 'format': ('%(asctime)s %(name)-15s '
441 '%(levelname)-8s %(message)s')}},
Andrew M. Kuchling8e343862010-05-08 13:28:03 +0000442
443 'handlers': {'netlog': {'backupCount': 10,
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000444 'class': 'logging.handlers.RotatingFileHandler',
445 'filename': '/logs/network.log',
446 'formatter': 'standard',
447 'level': 'INFO',
448 'maxBytes': 1024*1024},
Andrew M. Kuchling8e343862010-05-08 13:28:03 +0000449 'syslog': {'class': 'logging.handlers.SysLogHandler',
450 'formatter': 'standard',
451 'level': 'ERROR'}},
452
453 # Specify all the subordinate loggers
454 'loggers': {
455 'network': {
456 'handlers': ['netlog']
457 }
458 },
459 # Specify properties of the root logger
460 'root': {
461 'handlers': ['syslog']
462 },
463 }
464
465 # Set up configuration
466 logging.config.dictConfig(configdict)
467
468 # As an example, log two error messages
469 logger = logging.getLogger('/')
470 logger.error('Database not found')
471
472 netlogger = logging.getLogger('network')
473 netlogger.error('Connection failed')
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000474
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +0000475Three smaller enhancements to the :mod:`logging` module, all
476implemented by Vinay Sajip, are:
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000477
478.. rev79293
479
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +0000480* The :class:`~logging.handlers.SysLogHandler` class now supports
481 syslogging over TCP. The constructor has a *socktype* parameter
482 giving the type of socket to use, either :const:`socket.SOCK_DGRAM`
483 for UDP or :const:`socket.SOCK_STREAM` for TCP. The default
484 protocol remains UDP.
485
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +0000486* :class:`Logger` instances gained a :meth:`getChild` method that retrieves a
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000487 descendant logger using a relative path. For example,
488 once you retrieve a logger by doing ``log = getLogger('app')``,
489 calling ``log.getChild('network.listen')`` is equivalent to
490 ``getLogger('app.network.listen')``.
491
492* The :class:`LoggerAdapter` class gained a :meth:`isEnabledFor` method
493 that takes a *level* and returns whether the underlying logger would
494 process a message of that level of importance.
495
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000496.. seealso::
497
498 :pep:`391` - Dictionary-Based Configuration For Logging
499 PEP written and implemented by Vinay Sajip.
500
501PEP 3106: Dictionary Views
502====================================================
503
Andrew M. Kuchling85f928a2010-04-15 01:42:27 +0000504The dictionary methods :meth:`keys`, :meth:`values`, and :meth:`items`
505are different in Python 3.x. They return an object called a :dfn:`view`
506instead of a fully materialized list.
507
Andrew M. Kuchling85f928a2010-04-15 01:42:27 +0000508It's not possible to change the return values of :meth:`keys`,
509:meth:`values`, and :meth:`items` in Python 2.7 because too much code
510would break. Instead the 3.x versions were added under the new names
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000511:meth:`viewkeys`, :meth:`viewvalues`, and :meth:`viewitems`.
Andrew M. Kuchling85f928a2010-04-15 01:42:27 +0000512
513::
514
515 >>> d = dict((i*10, chr(65+i)) for i in range(26))
516 >>> d
517 {0: 'A', 130: 'N', 10: 'B', 140: 'O', 20: ..., 250: 'Z'}
518 >>> d.viewkeys()
519 dict_keys([0, 130, 10, 140, 20, 150, 30, ..., 250])
520
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000521Views can be iterated over, but the key and item views also behave
522like sets. The ``&`` operator performs intersection, and ``|``
523performs a union::
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +0000524
525 >>> d1 = dict((i*10, chr(65+i)) for i in range(26))
526 >>> d2 = dict((i**.5, i) for i in range(1000))
527 >>> d1.viewkeys() & d2.viewkeys()
528 set([0.0, 10.0, 20.0, 30.0])
529 >>> d1.viewkeys() | range(0, 30)
530 set([0, 1, 130, 3, 4, 5, 6, ..., 120, 250])
531
Andrew M. Kuchling85f928a2010-04-15 01:42:27 +0000532The view keeps track of the dictionary and its contents change as the
533dictionary is modified::
534
535 >>> vk = d.viewkeys()
536 >>> vk
537 dict_keys([0, 130, 10, ..., 250])
538 >>> d[260] = '&'
539 >>> vk
540 dict_keys([0, 130, 260, 10, ..., 250])
541
542However, note that you can't add or remove keys while you're iterating
543over the view::
544
545 >>> for k in vk:
546 ... d[k*2] = k
547 ...
548 Traceback (most recent call last):
549 File "<stdin>", line 1, in <module>
550 RuntimeError: dictionary changed size during iteration
551
552You can use the view methods in Python 2.x code, and the 2to3
553converter will change them to the standard :meth:`keys`,
554:meth:`values`, and :meth:`items` methods.
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000555
556.. seealso::
557
558 :pep:`3106` - Revamping dict.keys(), .values() and .items()
559 PEP written by Guido van Rossum.
560 Backported to 2.7 by Alexandre Vassalotti; :issue:`1967`.
561
562
Andrew M. Kuchling9fbbd3b2010-05-01 12:06:51 +0000563PEP 3137: The memoryview Object
564====================================================
565
566The :class:`memoryview` object provides a view of another object's
567memory content that matches the :class:`bytes` type's interface.
568
569 >>> import string
570 >>> m = memoryview(string.letters)
571 >>> m
572 <memory at 0x37f850>
573 >>> len(m) # Returns length of underlying object
574 52
575 >>> m[0], m[25], m[26] # Indexing returns one byte
576 ('a', 'z', 'A')
577 >>> m2 = m[0:26] # Slicing returns another memoryview
578 >>> m2
579 <memory at 0x37f080>
580
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000581The content of the view can be converted to a string of bytes or
Andrew M. Kuchling9fbbd3b2010-05-01 12:06:51 +0000582a list of integers:
583
584 >>> m2.tobytes()
585 'abcdefghijklmnopqrstuvwxyz'
586 >>> m2.tolist()
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000587 [97, 98, 99, 100, 101, 102, 103, ... 121, 122]
Andrew M. Kuchling9fbbd3b2010-05-01 12:06:51 +0000588 >>>
589
590:class:`memoryview` objects allow modifying the underlying object if
591it's a mutable object.
592
593 >>> m2[0] = 75
594 Traceback (most recent call last):
595 File "<stdin>", line 1, in <module>
596 TypeError: cannot modify read-only memory
597 >>> b = bytearray(string.letters) # Creating a mutable object
598 >>> b
599 bytearray(b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
600 >>> mb = memoryview(b)
601 >>> mb[0] = '*' # Assign to view, changing the bytearray.
602 >>> b[0:5] # The bytearray has been changed.
603 bytearray(b'*bcde')
604 >>>
605
606.. seealso::
607
608 :pep:`3137` - Immutable Bytes and Mutable Buffer
609 PEP written by Guido van Rossum.
Antoine Pitrou5cace782010-05-01 12:16:39 +0000610 Implemented by Travis Oliphant, Antoine Pitrou and others.
Andrew M. Kuchling9fbbd3b2010-05-01 12:06:51 +0000611 Backported to 2.7 by Antoine Pitrou; :issue:`2396`.
612
613
614
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000615Other Language Changes
616======================
617
618Some smaller changes made to the core Python language are:
619
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000620* The syntax for set literals has been backported from Python 3.x.
621 Curly brackets are used to surround the contents of the resulting
622 mutable set; set literals are
623 distinguished from dictionaries by not containing colons and values.
624 ``{}`` continues to represent an empty dictionary; use
625 ``set()`` for an empty set.
626
627 >>> {1,2,3,4,5}
628 set([1, 2, 3, 4, 5])
Ezio Melotti021f3342010-04-06 03:26:49 +0000629 >>> set() # empty set
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000630 set([])
Ezio Melotti021f3342010-04-06 03:26:49 +0000631 >>> {} # empty dict
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000632 {}
633
634 Backported by Alexandre Vassalotti; :issue:`2335`.
635
636* Dictionary and set comprehensions are another feature backported from
637 3.x, generalizing list/generator comprehensions to use
638 the literal syntax for sets and dictionaries.
639
Andrew M. Kuchling0efe18a2010-05-08 15:39:46 +0000640 >>> {x: x*x for x in range(6)}
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000641 {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Andrew M. Kuchling0efe18a2010-05-08 15:39:46 +0000642 >>> {('a'*x) for x in range(6)}
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000643 set(['', 'a', 'aa', 'aaa', 'aaaa', 'aaaaa'])
644
645 Backported by Alexandre Vassalotti; :issue:`2333`.
646
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000647* The :keyword:`with` statement can now use multiple context managers
648 in one statement. Context managers are processed from left to right
649 and each one is treated as beginning a new :keyword:`with` statement.
650 This means that::
651
652 with A() as a, B() as b:
653 ... suite of statements ...
654
655 is equivalent to::
656
657 with A() as a:
658 with B() as b:
659 ... suite of statements ...
660
661 The :func:`contextlib.nested` function provides a very similar
662 function, so it's no longer necessary and has been deprecated.
663
664 (Proposed in http://codereview.appspot.com/53094; implemented by
665 Georg Brandl.)
666
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000667* Conversions between floating-point numbers and strings are
668 now correctly rounded on most platforms. These conversions occur
669 in many different places: :func:`str` on
670 floats and complex numbers; the :class:`float` and :class:`complex`
671 constructors;
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000672 numeric formatting; serializing and
673 deserializing floats and complex numbers using the
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000674 :mod:`marshal`, :mod:`pickle`
675 and :mod:`json` modules;
676 parsing of float and imaginary literals in Python code;
Ezio Melotti021f3342010-04-06 03:26:49 +0000677 and :class:`~decimal.Decimal`-to-float conversion.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000678
679 Related to this, the :func:`repr` of a floating-point number *x*
680 now returns a result based on the shortest decimal string that's
681 guaranteed to round back to *x* under correct rounding (with
682 round-half-to-even rounding mode). Previously it gave a string
683 based on rounding x to 17 decimal digits.
684
Ezio Melotti021f3342010-04-06 03:26:49 +0000685 .. maybe add an example?
686
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000687 The rounding library responsible for this improvement works on
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000688 Windows and on Unix platforms using the gcc, icc, or suncc
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000689 compilers. There may be a small number of platforms where correct
690 operation of this code cannot be guaranteed, so the code is not
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +0000691 used on such systems. You can find out which code is being used
692 by checking :data:`sys.float_repr_style`, which will be ``short``
693 if the new code is in use and ``legacy`` if it isn't.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000694
Mark Dickinsonbdd863d2010-01-07 09:28:29 +0000695 Implemented by Eric Smith and Mark Dickinson, using David Gay's
696 :file:`dtoa.c` library; :issue:`7117`.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000697
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000698* Conversions from long integers and regular integers to floating
699 point now round differently, returning the floating-point number
700 closest to the number. This doesn't matter for small integers that
701 can be converted exactly, but for large numbers that will
702 unavoidably lose precision, Python 2.7 now approximates more
703 closely. For example, Python 2.6 computed the following::
704
705 >>> n = 295147905179352891391
706 >>> float(n)
707 2.9514790517935283e+20
708 >>> n - long(float(n))
709 65535L
710
711 Python 2.7's floating-point result is larger, but much closer to the
712 true value::
713
714 >>> n = 295147905179352891391
715 >>> float(n)
716 2.9514790517935289e+20
717 >>> n - long(float(n))
718 -1L
719
720 (Implemented by Mark Dickinson; :issue:`3166`.)
721
722 Integer division is also more accurate in its rounding behaviours. (Also
723 implemented by Mark Dickinson; :issue:`1811`.)
724
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000725* The :meth:`str.format` method now supports automatic numbering of the replacement
Benjamin Petersonaa0a0b92009-04-11 20:27:15 +0000726 fields. This makes using :meth:`str.format` more closely resemble using
727 ``%s`` formatting::
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000728
729 >>> '{}:{}:{}'.format(2009, 04, 'Sunday')
730 '2009:4:Sunday'
731 >>> '{}:{}:{day}'.format(2009, 4, day='Sunday')
732 '2009:4:Sunday'
733
Benjamin Petersonaa0a0b92009-04-11 20:27:15 +0000734 The auto-numbering takes the fields from left to right, so the first ``{...}``
735 specifier will use the first argument to :meth:`str.format`, the next
736 specifier will use the next argument, and so on. You can't mix auto-numbering
737 and explicit numbering -- either number all of your specifier fields or none
738 of them -- but you can mix auto-numbering and named fields, as in the second
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000739 example above. (Contributed by Eric Smith; :issue:`5237`.)
740
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000741 Complex numbers now correctly support usage with :func:`format`,
742 and default to being right-aligned.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000743 Specifying a precision or comma-separation applies to both the real
744 and imaginary parts of the number, but a specified field width and
745 alignment is applied to the whole of the resulting ``1.5+3j``
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000746 output. (Contributed by Eric Smith; :issue:`1588` and :issue:`7988`.)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000747
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000748 The 'F' format code now always formats its output using uppercase characters,
749 so it will now produce 'INF' and 'NAN'.
750 (Contributed by Eric Smith; :issue:`3382`.)
751
Andrew M. Kuchlingc4ae73e2010-04-30 13:47:34 +0000752 A low-level change: the :meth:`object.__format__` method now triggers
753 a :exc:`PendingDeprecationWarning` if it's passed a format string,
754 because the :meth:`__format__` method for :class:`object` converts
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000755 the object to a string representation and formats that. Previously
756 the method silently applied the format string to the string
Andrew M. Kuchlingc4ae73e2010-04-30 13:47:34 +0000757 representation, but that could hide mistakes in Python code. If
758 you're supplying formatting information such as an alignment or
759 precision, presumably you're expecting the formatting to be applied
760 in some object-specific way. (Fixed by Eric Smith; :issue:`7994`.)
761
Mark Dickinson1a707982008-12-17 16:14:37 +0000762* The :func:`int` and :func:`long` types gained a ``bit_length``
Georg Brandl64e1c752009-04-11 18:19:27 +0000763 method that returns the number of bits necessary to represent
Mark Dickinson1a707982008-12-17 16:14:37 +0000764 its argument in binary::
765
766 >>> n = 37
Ezio Melotti021f3342010-04-06 03:26:49 +0000767 >>> bin(n)
Mark Dickinson1a707982008-12-17 16:14:37 +0000768 '0b100101'
769 >>> n.bit_length()
770 6
771 >>> n = 2**123-1
772 >>> n.bit_length()
773 123
774 >>> (n+1).bit_length()
775 124
776
777 (Contributed by Fredrik Johansson and Victor Stinner; :issue:`3439`.)
778
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000779* It's now possible for a subclass of the built-in :class:`unicode` type
780 to override the :meth:`__unicode__` method. (Implemented by
781 Victor Stinner; :issue:`1583863`.)
782
Ezio Melotti021f3342010-04-06 03:26:49 +0000783* The :class:`bytearray` type's :meth:`~bytearray.translate` method now accepts
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000784 ``None`` as its first argument. (Fixed by Georg Brandl;
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000785 :issue:`4759`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000786
Ezio Melotti021f3342010-04-06 03:26:49 +0000787 .. bytearray doesn't seem to be documented
788
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000789* When using ``@classmethod`` and ``@staticmethod`` to wrap
790 methods as class or static methods, the wrapper object now
791 exposes the wrapped function as their :attr:`__func__` attribute.
792 (Contributed by Amaury Forgeot d'Arc, after a suggestion by
793 George Sakkis; :issue:`5982`.)
794
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +0000795* When a restricted set of attributes were set using ``__slots__``,
796 deleting an unset attribute would not raise :exc:`AttributeError`
797 as you would expect. Fixed by Benjamin Peterson; :issue:`7604`.)
798
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000799* A new encoding named "cp720", used primarily for Arabic text, is now
800 supported. (Contributed by Alexander Belchenko and Amaury Forgeot
801 d'Arc; :issue:`1616979`.)
802
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000803* The :class:`file` object will now set the :attr:`filename` attribute
804 on the :exc:`IOError` exception when trying to open a directory
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +0000805 on POSIX platforms (noted by Jan Kaliszewski; :issue:`4764`), and
806 now explicitly checks for and forbids writing to read-only file objects
807 instead of trusting the C library to catch and report the error
808 (fixed by Stefan Krah; :issue:`5677`).
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000809
Benjamin Petersonae9a0a02009-12-31 16:49:37 +0000810* The Python tokenizer now translates line endings itself, so the
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000811 :func:`compile` built-in function now accepts code using any
Benjamin Petersonae9a0a02009-12-31 16:49:37 +0000812 line-ending convention. Additionally, it no longer requires that the
813 code end in a newline.
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +0000814
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000815* Extra parentheses in function definitions are illegal in Python 3.x,
816 meaning that you get a syntax error from ``def f((x)): pass``. In
817 Python3-warning mode, Python 2.7 will now warn about this odd usage.
818 (Noted by James Lingard; :issue:`7362`.)
819
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +0000820* It's now possible to create weak references to old-style class
821 objects. New-style classes were always weak-referenceable. (Fixed
822 by Antoine Pitrou; :issue:`8268`.)
823
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000824* When a module object is garbage-collected, the module's dictionary is
825 now only cleared if no one else is holding a reference to the
826 dictionary (:issue:`7140`).
827
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000828.. ======================================================================
829
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000830.. _new-27-interpreter:
831
832Interpreter Changes
833-------------------------------
834
835A new environment variable, :envvar:`PYTHONWARNINGS`,
836allows controlling warnings. It should be set to a string
837containing warning settings, equivalent to those
838used with the :option:`-W` switch, separated by commas.
839(Contributed by Brian Curtin; :issue:`7301`.)
840
841For example, the following setting will print warnings every time
842they occur, but turn warnings from the :mod:`Cookie` module into an
843error. (The exact syntax for setting an environment variable varies
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000844across operating systems and shells.)
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000845
846::
847
848 export PYTHONWARNINGS=all,error:::Cookie:0
849
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +0000850When running a module using the interpreter's :option:`-m` switch,
851``sys.argv[0]`` will now be set to the string ``'-m'`` while the
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +0000852module is being located, while executing the :file:`__init__.py` files
853for any parent packages of the module to be executed.
854(Suggested by Michael Foord; implemented by Nick Coghlan;
855:issue:`8202`.)
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000856
857.. ======================================================================
858
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000859
860Optimizations
861-------------
862
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000863Several performance enhancements have been added:
864
865.. * A new :program:`configure` option, :option:`--with-computed-gotos`,
866 compiles the main bytecode interpreter loop using a new dispatch
867 mechanism that gives speedups of up to 20%, depending on the system
868 and benchmark. The new mechanism is only supported on certain
869 compilers, such as gcc, SunPro, and icc.
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000870
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000871* A new opcode was added to perform the initial setup for
872 :keyword:`with` statements, looking up the :meth:`__enter__` and
873 :meth:`__exit__` methods. (Contributed by Benjamin Peterson.)
874
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000875* The garbage collector now performs better for one common usage
876 pattern: when many objects are being allocated without deallocating
877 any of them. This would previously take quadratic
878 time for garbage collection, but now the number of full garbage collections
879 is reduced as the number of objects on the heap grows.
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000880 The new logic only performs a full garbage collection pass when
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000881 the middle generation has been collected 10 times and when the
882 number of survivor objects from the middle generation exceeds 10% of
883 the number of objects in the oldest generation. (Suggested by Martin
Ezio Melotti021f3342010-04-06 03:26:49 +0000884 von Löwis and implemented by Antoine Pitrou; :issue:`4074`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000885
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000886* The garbage collector tries to avoid tracking simple containers
887 which can't be part of a cycle. In Python 2.7, this is now true for
888 tuples and dicts containing atomic types (such as ints, strings,
889 etc.). Transitively, a dict containing tuples of atomic types won't
890 be tracked either. This helps reduce the cost of each
891 garbage collection by decreasing the number of objects to be
892 considered and traversed by the collector.
Antoine Pitrouc18f6b02009-03-28 19:10:13 +0000893 (Contributed by Antoine Pitrou; :issue:`4688`.)
894
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000895* Long integers are now stored internally either in base 2**15 or in base
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000896 2**30, the base being determined at build time. Previously, they
897 were always stored in base 2**15. Using base 2**30 gives
898 significant performance improvements on 64-bit machines, but
899 benchmark results on 32-bit machines have been mixed. Therefore,
900 the default is to use base 2**30 on 64-bit machines and base 2**15
901 on 32-bit machines; on Unix, there's a new configure option
902 :option:`--enable-big-digits` that can be used to override this default.
903
904 Apart from the performance improvements this change should be
905 invisible to end users, with one exception: for testing and
Ezio Melotti021f3342010-04-06 03:26:49 +0000906 debugging purposes there's a new structseq :data:`sys.long_info` that
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000907 provides information about the internal format, giving the number of
908 bits per digit and the size in bytes of the C type used to store
909 each digit::
910
911 >>> import sys
912 >>> sys.long_info
913 sys.long_info(bits_per_digit=30, sizeof_digit=4)
914
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000915 (Contributed by Mark Dickinson; :issue:`4258`.)
916
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000917 Another set of changes made long objects a few bytes smaller: 2 bytes
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000918 smaller on 32-bit systems and 6 bytes on 64-bit.
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000919 (Contributed by Mark Dickinson; :issue:`5260`.)
920
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000921* The division algorithm for long integers has been made faster
922 by tightening the inner loop, doing shifts instead of multiplications,
923 and fixing an unnecessary extra iteration.
924 Various benchmarks show speedups of between 50% and 150% for long
925 integer divisions and modulo operations.
926 (Contributed by Mark Dickinson; :issue:`5512`.)
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +0000927 Bitwise operations are also significantly faster (initial patch by
928 Gregory Smith; :issue:`1087418`).
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000929
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000930* The implementation of ``%`` checks for the left-side operand being
931 a Python string and special-cases it; this results in a 1-3%
932 performance increase for applications that frequently use ``%``
933 with strings, such as templating libraries.
934 (Implemented by Collin Winter; :issue:`5176`.)
935
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000936* List comprehensions with an ``if`` condition are compiled into
937 faster bytecode. (Patch by Antoine Pitrou, back-ported to 2.7
938 by Jeffrey Yasskin; :issue:`4715`.)
939
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +0000940* Converting an integer or long integer to a decimal string was made
941 faster by special-casing base 10 instead of using a generalized
942 conversion function that supports arbitrary bases.
943 (Patch by Gawain Bolton; :issue:`6713`.)
944
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +0000945* The :meth:`split`, :meth:`replace`, :meth:`rindex`,
946 :meth:`rpartition`, and :meth:`rsplit` methods of string-like types
947 (strings, Unicode strings, and :class:`bytearray` objects) now use a
948 fast reverse-search algorithm instead of a character-by-character
949 scan. This is sometimes faster by a factor of 10. (Added by
950 Florent Xicluna; :issue:`7462` and :issue:`7622`.)
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +0000951
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000952* The :mod:`pickle` and :mod:`cPickle` modules now automatically
953 intern the strings used for attribute names, reducing memory usage
954 of the objects resulting from unpickling. (Contributed by Jake
955 McGuire; :issue:`5084`.)
956
957* The :mod:`cPickle` module now special-cases dictionaries,
958 nearly halving the time required to pickle them.
959 (Contributed by Collin Winter; :issue:`5670`.)
960
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000961.. ======================================================================
962
Georg Brandl0516f812009-11-18 18:52:35 +0000963New and Improved Modules
964========================
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000965
966As in every release, Python's standard library received a number of
967enhancements and bug fixes. Here's a partial list of the most notable
968changes, sorted alphabetically by module name. Consult the
969:file:`Misc/NEWS` file in the source tree for a more complete list of
970changes, or look through the Subversion logs for all the details.
971
Ezio Melotti021f3342010-04-06 03:26:49 +0000972* The :mod:`bdb` module's base debugging class :class:`~bdb.Bdb`
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000973 gained a feature for skipping modules. The constructor
974 now takes an iterable containing glob-style patterns such as
975 ``django.*``; the debugger will not step into stack frames
976 from a module that matches one of these patterns.
977 (Contributed by Maru Newby after a suggestion by
978 Senthil Kumaran; :issue:`5142`.)
979
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +0000980* The :mod:`binascii` module now supports the buffer API, so it can be
981 used with :class:`memoryview` instances and other similar buffer objects.
982 (Backported from 3.x by Florent Xicluna; :issue:`7703`.)
983
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000984* Updated module: the :mod:`bsddb` module has been updated from 4.7.2devel9
985 to version 4.8.4 of
986 `the pybsddb package <http://www.jcea.es/programacion/pybsddb.htm>`__.
987 The new version features better Python 3.x compatibility, various bug fixes,
988 and adds several new BerkeleyDB flags and methods.
Ezio Melotti021f3342010-04-06 03:26:49 +0000989 (Updated by Jesús Cea Avión; :issue:`8156`. The pybsddb
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000990 changelog can be read at http://hg.jcea.es/pybsddb/file/tip/ChangeLog.)
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000991
Ezio Melotti021f3342010-04-06 03:26:49 +0000992* The :mod:`bz2` module's :class:`~bz2.BZ2File` now supports the context
Andrew M. Kuchling27024912010-05-12 00:38:44 +0000993 management protocol, so you can write ``with bz2.BZ2File(...) as f:``.
Andrew M. Kuchlingbadc7092010-05-08 01:35:55 +0000994 (Contributed by Hagen Fürstenau; :issue:`3860`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000995
Ezio Melotti021f3342010-04-06 03:26:49 +0000996* New class: the :class:`~collections.Counter` class in the :mod:`collections`
997 module is useful for tallying data. :class:`~collections.Counter` instances
998 behave mostly like dictionaries but return zero for missing keys instead of
Georg Brandlf6dab952009-04-28 21:48:35 +0000999 raising a :exc:`KeyError`:
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001000
Georg Brandlf6dab952009-04-28 21:48:35 +00001001 .. doctest::
1002 :options: +NORMALIZE_WHITESPACE
1003
1004 >>> from collections import Counter
1005 >>> c = Counter()
1006 >>> for letter in 'here is a sample of english text':
1007 ... c[letter] += 1
1008 ...
1009 >>> c
1010 Counter({' ': 6, 'e': 5, 's': 3, 'a': 2, 'i': 2, 'h': 2,
1011 'l': 2, 't': 2, 'g': 1, 'f': 1, 'm': 1, 'o': 1, 'n': 1,
1012 'p': 1, 'r': 1, 'x': 1})
1013 >>> c['e']
1014 5
1015 >>> c['z']
1016 0
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001017
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001018 There are three additional :class:`~collections.Counter` methods.
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001019 :meth:`~collections.Counter.most_common` returns the N most common
1020 elements and their counts. :meth:`~collections.Counter.elements`
1021 returns an iterator over the contained elements, repeating each
1022 element as many times as its count.
1023 :meth:`~collections.Counter.subtract` takes an iterable and
1024 subtracts one for each element instead of adding; if the argument is
1025 a dictionary or another :class:`Counter`, the counts are
1026 subtracted. ::
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001027
1028 >>> c.most_common(5)
1029 [(' ', 6), ('e', 5), ('s', 3), ('a', 2), ('i', 2)]
1030 >>> c.elements() ->
1031 'a', 'a', ' ', ' ', ' ', ' ', ' ', ' ',
1032 'e', 'e', 'e', 'e', 'e', 'g', 'f', 'i', 'i',
1033 'h', 'h', 'm', 'l', 'l', 'o', 'n', 'p', 's',
Georg Brandlf6dab952009-04-28 21:48:35 +00001034 's', 's', 'r', 't', 't', 'x'
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001035 >>> c['e']
1036 5
1037 >>> c.subtract('very heavy on the letter e')
1038 >>> c['e'] # Count is now lower
1039 -1
Ezio Melotti021f3342010-04-06 03:26:49 +00001040
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001041 Contributed by Raymond Hettinger; :issue:`1696199`.
1042
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001043 .. revision 79660
1044
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001045 New class: :class:`~collections.OrderedDict` is described in the earlier
Ezio Melotti021f3342010-04-06 03:26:49 +00001046 section :ref:`pep-0372`.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001047
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001048 New method: The :class:`~collections.deque` data type now has a
1049 :meth:`~collections.deque.count` method that returns the number of
1050 contained elements equal to the supplied argument *x*, and a
1051 :meth:`~collections.deque.reverse` method that reverses the elements
1052 of the deque in-place. :class:`deque` also exposes its maximum
1053 length as the read-only :attr:`~collections.deque.maxlen` attribute.
1054 (Both features added by Raymond Hettinger.)
1055
Ezio Melotti021f3342010-04-06 03:26:49 +00001056 The :class:`~collections.namedtuple` class now has an optional *rename* parameter.
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001057 If *rename* is true, field names that are invalid because they've
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001058 been repeated or aren't legal Python identifiers will be
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001059 renamed to legal names that are derived from the field's
1060 position within the list of fields:
1061
Georg Brandlf6dab952009-04-28 21:48:35 +00001062 >>> from collections import namedtuple
1063 >>> T = namedtuple('T', ['field1', '$illegal', 'for', 'field2'], rename=True)
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001064 >>> T._fields
1065 ('field1', '_1', '_2', 'field2')
1066
1067 (Added by Raymond Hettinger; :issue:`1818`.)
1068
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +00001069* Constructors for the parsing classes in the :mod:`ConfigParser` module now
1070 take a *allow_no_value* parameter, defaulting to false; if true,
1071 options without values will be allowed. For example::
1072
1073 >>> import ConfigParser, StringIO
1074 >>> sample_config = """
1075 ... [mysqld]
1076 ... user = mysql
1077 ... pid-file = /var/run/mysqld/mysqld.pid
1078 ... skip-bdb
1079 ... """
1080 >>> config = ConfigParser.RawConfigParser(allow_no_value=True)
1081 >>> config.readfp(StringIO.StringIO(sample_config))
1082 >>> config.get('mysqld', 'user')
1083 'mysql'
1084 >>> print config.get('mysqld', 'skip-bdb')
1085 None
1086 >>> print config.get('mysqld', 'unknown')
1087 Traceback (most recent call last):
1088 ...
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001089 NoOptionError: No option 'unknown' in section: 'mysqld'
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +00001090
1091 (Contributed by Mats Kindahl; :issue:`7005`.)
1092
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001093* Deprecated function: :func:`contextlib.nested`, which allows
1094 handling more than one context manager with a single :keyword:`with`
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001095 statement, has been deprecated, because the :keyword:`with` statement
1096 now supports multiple context managers.
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001097
Ezio Melotti021f3342010-04-06 03:26:49 +00001098* The :mod:`copy` module's :func:`~copy.deepcopy` function will now
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001099 correctly copy bound instance methods. (Implemented by
1100 Robert Collins; :issue:`1515`.)
1101
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001102* The :mod:`ctypes` module now always converts ``None`` to a C NULL
1103 pointer for arguments declared as pointers. (Changed by Thomas
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001104 Heller; :issue:`4606`.) The underlying `libffi library
1105 <http://sourceware.org/libffi/>`__ has been updated to version
1106 3.0.9, containing various fixes for different platforms. (Updated
1107 by Matthias Klose; :issue:`8142`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001108
Ezio Melotti021f3342010-04-06 03:26:49 +00001109* New method: the :mod:`datetime` module's :class:`~datetime.timedelta` class
1110 gained a :meth:`~datetime.timedelta.total_seconds` method that returns the
1111 number of seconds in the duration. (Contributed by Brian Quinlan; :issue:`5788`.)
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001112
Ezio Melotti021f3342010-04-06 03:26:49 +00001113* New method: the :class:`~decimal.Decimal` class gained a
1114 :meth:`~decimal.Decimal.from_float` class method that performs an exact
1115 conversion of a floating-point number to a :class:`~decimal.Decimal`.
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001116 This exact conversion strives for the
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001117 closest decimal approximation to the floating-point representation's value;
1118 the resulting decimal value will therefore still include the inaccuracy,
1119 if any.
1120 For example, ``Decimal.from_float(0.1)`` returns
1121 ``Decimal('0.1000000000000000055511151231257827021181583404541015625')``.
1122 (Implemented by Raymond Hettinger; :issue:`4796`.)
1123
Andrew M. Kuchling04b99cc2010-05-04 01:24:22 +00001124 Comparing instances of :class:`Decimal` with floating-point
1125 numbers now produces sensible results based on the numeric values
1126 of the operands. Previously such comparisons would fall back to
1127 Python's default rules for comparing objects, which produced arbitrary
1128 results based on their type. Note that you still cannot combine
1129 :class:`Decimal` and floating-point in other operations such as addition,
1130 since you should be explicitly choosing how to convert between float and
1131 :class:`Decimal`.
1132 (Fixed by Mark Dickinson; :issue:`2531`.)
1133
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001134 The constructor for :class:`~decimal.Decimal` now accepts
1135 floating-point numbers (added by Raymond Hettinger; :issue:`8257`)
1136 and non-European Unicode characters such as Arabic-Indic digits
1137 (contributed by Mark Dickinson; :issue:`6595`).
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001138
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001139 Most of the methods of the :class:`~decimal.Context` class now accept integers
1140 as well as :class:`~decimal.Decimal` instances; the only exceptions are the
1141 :meth:`~decimal.Context.canonical` and :meth:`~decimal.Context.is_canonical`
1142 methods. (Patch by Juan José Conti; :issue:`7633`.)
1143
Ezio Melotti021f3342010-04-06 03:26:49 +00001144 When using :class:`~decimal.Decimal` instances with a string's
1145 :meth:`~str.format` method, the default alignment was previously
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001146 left-alignment. This has been changed to right-alignment, which is
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001147 more sensible for numeric types. (Changed by Mark Dickinson; :issue:`6857`.)
1148
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001149 Comparisons involving a signaling NaN value (or ``sNAN``) now signal
1150 :const:`InvalidOperation` instead of silently returning a true or
1151 false value depending on the comparison operator. Quiet NaN values
1152 (or ``NaN``) are now hashable. (Fixed by Mark Dickinson;
1153 :issue:`7279`.)
1154
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +00001155* The :mod:`difflib` module now produces output that is more
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00001156 compatible with modern :command:`diff`/:command:`patch` tools
1157 through one small change, using a tab character instead of spaces as
1158 a separator in the header giving the filename. (Fixed by Anatoly
1159 Techtonik; :issue:`7585`.)
1160
1161* The :mod:`doctest` module's :const:`IGNORE_EXCEPTION_DETAIL` flag
1162 will now ignore the name of the module containing the exception
1163 being tested. (Patch by Lennart Regebro; :issue:`7490`.)
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +00001164
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001165* The :class:`~fractions.Fraction` class now accepts a single float or
1166 :class:`~decimal.Decimal` instance, or two rational numbers, as
1167 arguments to its constructor. (Implemented by Mark Dickinson;
1168 rationals added in :issue:`5812`, and float/decimal in
1169 :issue:`8294`.)
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00001170
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001171 Ordering comparisons (``<``, ``<=``, ``>``, ``>=``) between
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +00001172 fractions and complex numbers now raise a :exc:`TypeError`.
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001173 This fixes an oversight, making the :class:`Fraction` match the other
1174 numeric types.
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +00001175
1176 .. revision 79455
1177
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001178* New class: :class:`~ftplib.FTP_TLS` in
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001179 the :mod:`ftplib` module provides secure FTP
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001180 connections using TLS encapsulation of authentication as well as
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001181 subsequent control and data transfers.
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001182 (Contributed by Giampaolo Rodola; :issue:`2054`.)
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001183
Ezio Melotti021f3342010-04-06 03:26:49 +00001184 The :meth:`~ftplib.FTP.storbinary` method for binary uploads can now restart
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001185 uploads thanks to an added *rest* parameter (patch by Pablo Mouzo;
1186 :issue:`6845`.)
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001187
Andrew M. Kuchling6d7dfa22010-04-11 12:49:37 +00001188* New class decorator: :func:`total_ordering` in the :mod:`functools`
1189 module takes a class that defines an :meth:`__eq__` method and one of
1190 :meth:`__lt__`, :meth:`__le__`, :meth:`__gt__`, or :meth:`__ge__`,
1191 and generates the missing comparison methods. Since the
1192 :meth:`__cmp__` method is being deprecated in Python 3.x,
1193 this decorator makes it easier to define ordered classes.
1194 (Added by Raymond Hettinger; :issue:`5479`.)
1195
1196 New function: :func:`cmp_to_key` will take an old-style comparison
1197 function that expects two arguments and return a new callable that
1198 can be used as the *key* parameter to functions such as
1199 :func:`sorted`, :func:`min` and :func:`max`, etc. The primary
1200 intended use is to help with making code compatible with Python 3.x.
1201 (Added by Raymond Hettinger.)
1202
Ezio Melotti021f3342010-04-06 03:26:49 +00001203* New function: the :mod:`gc` module's :func:`~gc.is_tracked` returns
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001204 true if a given instance is tracked by the garbage collector, false
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001205 otherwise. (Contributed by Antoine Pitrou; :issue:`4688`.)
1206
Ezio Melotti021f3342010-04-06 03:26:49 +00001207* The :mod:`gzip` module's :class:`~gzip.GzipFile` now supports the context
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001208 management protocol, so you can write ``with gzip.GzipFile(...) as f:``
Andrew M. Kuchlingbadc7092010-05-08 01:35:55 +00001209 (contributed by Hagen Fürstenau; :issue:`3860`), and it now implements
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +00001210 the :class:`io.BufferedIOBase` ABC, so you can wrap it with
1211 :class:`io.BufferedReader` for faster processing
1212 (contributed by Nir Aides; :issue:`7471`).
1213 It's also now possible to override the modification time
Andrew M. Kuchling77069572009-03-31 01:21:01 +00001214 recorded in a gzipped file by providing an optional timestamp to
1215 the constructor. (Contributed by Jacques Frechet; :issue:`4272`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001216
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001217 Files in gzip format can be padded with trailing zero bytes; the
1218 :mod:`gzip` module will now consume these trailing bytes. (Fixed by
1219 Tadek Pietraszek and Brian Curtin; :issue:`2846`.)
1220
Ezio Melotti021f3342010-04-06 03:26:49 +00001221* New attribute: the :mod:`hashlib` module now has an :attr:`~hashlib.hashlib.algorithms`
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001222 attribute containing a tuple naming the supported algorithms.
1223 In Python 2.7, ``hashlib.algorithms`` contains
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001224 ``('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')``.
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001225 (Contributed by Carl Chenet; :issue:`7418`.)
1226
Ezio Melotti021f3342010-04-06 03:26:49 +00001227* The default :class:`~httplib.HTTPResponse` class used by the :mod:`httplib` module now
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001228 supports buffering, resulting in much faster reading of HTTP responses.
Andrew M. Kuchlingbadc7092010-05-08 01:35:55 +00001229 (Contributed by Kristján Valur Jónsson; :issue:`4879`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001230
Ezio Melotti021f3342010-04-06 03:26:49 +00001231 The :class:`~httplib.HTTPConnection` and :class:`~httplib.HTTPSConnection` classes
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001232 now support a *source_address* parameter, a ``(host, port)`` 2-tuple
1233 giving the source address that will be used for the connection.
1234 (Contributed by Eldon Ziegler; :issue:`3972`.)
1235
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00001236* The :mod:`ihooks` module now supports relative imports. Note that
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001237 :mod:`ihooks` is an older module for customizing imports,
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00001238 superseded by the :mod:`imputil` module added in Python 2.0.
1239 (Relative import support added by Neil Schemenauer.)
1240
1241 .. revision 75423
1242
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001243* The :mod:`imaplib` module now supports IPv6 addresses.
1244 (Contributed by Derek Morr; :issue:`1655`.)
1245
Andrew M. Kuchlingce690522010-04-13 01:32:51 +00001246* New function: the :mod:`inspect` module's :func:`~inspect.getcallargs`
1247 takes a callable and its positional and keyword arguments,
1248 and figures out which of the callable's parameters will receive each argument,
1249 returning a dictionary mapping argument names to their values. For example::
1250
1251 >>> from inspect import getcallargs
1252 >>> def f(a, b=1, *pos, **named):
1253 ... pass
1254 >>> getcallargs(f, 1, 2, 3)
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001255 {'a': 1, 'b': 2, 'pos': (3,), 'named': {}}
Andrew M. Kuchlingce690522010-04-13 01:32:51 +00001256 >>> getcallargs(f, a=2, x=4)
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001257 {'a': 2, 'b': 1, 'pos': (), 'named': {'x': 4}}
Andrew M. Kuchlingce690522010-04-13 01:32:51 +00001258 >>> getcallargs(f)
1259 Traceback (most recent call last):
1260 ...
1261 TypeError: f() takes at least 1 argument (0 given)
1262
1263 Contributed by George Sakkis; :issue:`3135`.
1264
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001265* Updated module: The :mod:`io` library has been upgraded to the version shipped with
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001266 Python 3.1. For 3.1, the I/O library was entirely rewritten in C
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001267 and is 2 to 20 times faster depending on the task being performed. The
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001268 original Python version was renamed to the :mod:`_pyio` module.
1269
1270 One minor resulting change: the :class:`io.TextIOBase` class now
1271 has an :attr:`errors` attribute giving the error setting
1272 used for encoding and decoding errors (one of ``'strict'``, ``'replace'``,
1273 ``'ignore'``).
1274
1275 The :class:`io.FileIO` class now raises an :exc:`OSError` when passed
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001276 an invalid file descriptor. (Implemented by Benjamin Peterson;
Ezio Melotti021f3342010-04-06 03:26:49 +00001277 :issue:`4991`.) The :meth:`~io.IOBase.truncate` method now preserves the
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001278 file position; previously it would change the file position to the
1279 end of the new file. (Fixed by Pascal Chambon; :issue:`6939`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001280
Andrew M. Kuchling5a73ff82009-12-02 14:27:11 +00001281* New function: ``itertools.compress(data, selectors)`` takes two
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001282 iterators. Elements of *data* are returned if the corresponding
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001283 value in *selectors* is true::
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001284
1285 itertools.compress('ABCDEF', [1,0,1,0,1,1]) =>
1286 A, C, E, F
1287
Ezio Melotti021f3342010-04-06 03:26:49 +00001288 .. maybe here is better to use >>> list(itertools.compress(...)) instead
1289
Andrew M. Kuchling5a73ff82009-12-02 14:27:11 +00001290 New function: ``itertools.combinations_with_replacement(iter, r)``
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001291 returns all the possible *r*-length combinations of elements from the
Ezio Melotti021f3342010-04-06 03:26:49 +00001292 iterable *iter*. Unlike :func:`~itertools.combinations`, individual elements
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001293 can be repeated in the generated combinations::
1294
1295 itertools.combinations_with_replacement('abc', 2) =>
1296 ('a', 'a'), ('a', 'b'), ('a', 'c'),
1297 ('b', 'b'), ('b', 'c'), ('c', 'c')
1298
1299 Note that elements are treated as unique depending on their position
1300 in the input, not their actual values.
1301
Ezio Melotti021f3342010-04-06 03:26:49 +00001302 The :func:`itertools.count` function now has a *step* argument that
1303 allows incrementing by values other than 1. :func:`~itertools.count` also
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001304 now allows keyword arguments, and using non-integer values such as
Ezio Melotti021f3342010-04-06 03:26:49 +00001305 floats or :class:`~decimal.Decimal` instances. (Implemented by Raymond
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001306 Hettinger; :issue:`5032`.)
1307
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001308 :func:`itertools.combinations` and :func:`itertools.product`
1309 previously raised :exc:`ValueError` for values of *r* larger than
Andrew M. Kuchling77069572009-03-31 01:21:01 +00001310 the input iterable. This was deemed a specification error, so they
1311 now return an empty iterator. (Fixed by Raymond Hettinger; :issue:`4816`.)
1312
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001313* Updated module: The :mod:`json` module was upgraded to version 2.0.9 of the
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001314 simplejson package, which includes a C extension that makes
1315 encoding and decoding faster.
1316 (Contributed by Bob Ippolito; :issue:`4136`.)
1317
Ezio Melotti021f3342010-04-06 03:26:49 +00001318 To support the new :class:`collections.OrderedDict` type, :func:`json.load`
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001319 now has an optional *object_pairs_hook* parameter that will be called
1320 with any object literal that decodes to a list of pairs.
1321 (Contributed by Raymond Hettinger; :issue:`5381`.)
1322
Andrew M. Kuchling837a5382010-05-06 17:21:59 +00001323* The :mod:`mailbox` module's :class:`Maildir` class now records the
1324 timestamp on the directories it reads, and only re-reads them if the
1325 modification time has subsequently changed. This improves
1326 performance by avoiding unneeded directory scans. (Fixed by
1327 A.M. Kuchling and Antoine Pitrou; :issue:`1607951`, :issue:`6896`.)
1328
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001329* New functions: the :mod:`math` module gained
Ezio Melotti021f3342010-04-06 03:26:49 +00001330 :func:`~math.erf` and :func:`~math.erfc` for the error function and the complementary error function,
1331 :func:`~math.expm1` which computes ``e**x - 1`` with more precision than
1332 using :func:`~math.exp` and subtracting 1,
1333 :func:`~math.gamma` for the Gamma function, and
1334 :func:`~math.lgamma` for the natural log of the Gamma function.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001335 (Contributed by Mark Dickinson and nirinA raseliarison; :issue:`3366`.)
1336
Andrew M. Kuchling24520b42009-04-09 11:22:47 +00001337* The :mod:`multiprocessing` module's :class:`Manager*` classes
1338 can now be passed a callable that will be called whenever
1339 a subprocess is started, along with a set of arguments that will be
1340 passed to the callable.
1341 (Contributed by lekma; :issue:`5585`.)
1342
Ezio Melotti021f3342010-04-06 03:26:49 +00001343 The :class:`~multiprocessing.Pool` class, which controls a pool of worker processes,
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001344 now has an optional *maxtasksperchild* parameter. Worker processes
1345 will perform the specified number of tasks and then exit, causing the
Ezio Melotti021f3342010-04-06 03:26:49 +00001346 :class:`~multiprocessing.Pool` to start a new worker. This is useful if tasks may leak
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001347 memory or other resources, or if some tasks will cause the worker to
1348 become very large.
1349 (Contributed by Charles Cazabon; :issue:`6963`.)
1350
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001351* The :mod:`nntplib` module now supports IPv6 addresses.
1352 (Contributed by Derek Morr; :issue:`1664`.)
1353
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001354* New functions: the :mod:`os` module wraps the following POSIX system
Ezio Melotti021f3342010-04-06 03:26:49 +00001355 calls: :func:`~os.getresgid` and :func:`~os.getresuid`, which return the
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001356 real, effective, and saved GIDs and UIDs;
Ezio Melotti021f3342010-04-06 03:26:49 +00001357 :func:`~os.setresgid` and :func:`~os.setresuid`, which set
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001358 real, effective, and saved GIDs and UIDs to new values;
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001359 :func:`~os.initgroups`, which initialize the group access list
1360 for the current process. (GID/UID functions
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001361 contributed by Travis H.; :issue:`6508`. Support for initgroups added
1362 by Jean-Paul Calderone; :issue:`7333`.)
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001363
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001364 The :func:`os.fork` function now re-initializes the import lock in
Ezio Melotti021f3342010-04-06 03:26:49 +00001365 the child process; this fixes problems on Solaris when :func:`~os.fork`
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001366 is called from a thread. (Fixed by Zsolt Cserna; :issue:`7242`.)
1367
Ezio Melotti021f3342010-04-06 03:26:49 +00001368* In the :mod:`os.path` module, the :func:`~os.path.normpath` and
1369 :func:`~os.path.abspath` functions now preserve Unicode; if their input path
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001370 is a Unicode string, the return value is also a Unicode string.
Ezio Melotti021f3342010-04-06 03:26:49 +00001371 (:meth:`~os.path.normpath` fixed by Matt Giuca in :issue:`5827`;
1372 :meth:`~os.path.abspath` fixed by Ezio Melotti in :issue:`3426`.)
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001373
Andrew M. Kuchling9cb42772009-01-21 02:15:43 +00001374* The :mod:`pydoc` module now has help for the various symbols that Python
1375 uses. You can now do ``help('<<')`` or ``help('@')``, for example.
1376 (Contributed by David Laban; :issue:`4739`.)
1377
Ezio Melotti021f3342010-04-06 03:26:49 +00001378* The :mod:`re` module's :func:`~re.split`, :func:`~re.sub`, and :func:`~re.subn`
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001379 now accept an optional *flags* argument, for consistency with the
1380 other functions in the module. (Added by Gregory P. Smith.)
1381
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001382* New function: :func:`~runpy.run_path` in the :mod:`runpy` module
1383 will execute the code at a provided *path* argument. *path* can be
1384 the path of a Python source file (:file:`example.py`), a compiled
1385 bytecode file (:file:`example.pyc`), a directory
Andrew M. Kuchling304500c2010-05-08 13:29:46 +00001386 (:file:`./package/`), or a zip archive (:file:`example.zip`). If a
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001387 directory or zip path is provided, it will be added to the front of
1388 ``sys.path`` and the module :mod:`__main__` will be imported. It's
1389 expected that the directory or zip contains a :file:`__main__.py`;
1390 if it doesn't, some other :file:`__main__.py` might be imported from
1391 a location later in ``sys.path``. This makes some of the machinery
Andrew M. Kuchling837a5382010-05-06 17:21:59 +00001392 of :mod:`runpy` available to scripts that want to mimic the way
1393 Python's :option:`-m` processes an explicit path name.
1394 (Added by Nick Coghlan; :issue:`6816`.)
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001395
Ezio Melotti021f3342010-04-06 03:26:49 +00001396* New function: in the :mod:`shutil` module, :func:`~shutil.make_archive`
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001397 takes a filename, archive type (zip or tar-format), and a directory
1398 path, and creates an archive containing the directory's contents.
1399 (Added by Tarek Ziadé.)
1400
Ezio Melotti021f3342010-04-06 03:26:49 +00001401 :mod:`shutil`'s :func:`~shutil.copyfile` and :func:`~shutil.copytree`
1402 functions now raise a :exc:`~shutil.SpecialFileError` exception when
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001403 asked to copy a named pipe. Previously the code would treat
1404 named pipes like a regular file by opening them for reading, and
1405 this would block indefinitely. (Fixed by Antoine Pitrou; :issue:`3002`.)
1406
1407* New functions: in the :mod:`site` module, three new functions
1408 return various site- and user-specific paths.
Ezio Melotti021f3342010-04-06 03:26:49 +00001409 :func:`~site.getsitepackages` returns a list containing all
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001410 global site-packages directories,
Ezio Melotti021f3342010-04-06 03:26:49 +00001411 :func:`~site.getusersitepackages` returns the path of the user's
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001412 site-packages directory, and
Ezio Melotti021f3342010-04-06 03:26:49 +00001413 :func:`~site.getuserbase` returns the value of the :envvar:`USER_BASE`
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001414 environment variable, giving the path to a directory that can be used
1415 to store data.
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001416 (Contributed by Tarek Ziadé; :issue:`6693`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001417
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001418 The :mod:`site` module now reports exceptions occurring
1419 when the :mod:`sitecustomize` module is imported, and will no longer
Florent Xiclunaad598332010-03-31 21:40:32 +00001420 catch and swallow the :exc:`KeyboardInterrupt` exception. (Fixed by
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001421 Victor Stinner; :issue:`3137`.)
1422
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001423* The :func:`~socket.create_connection` function
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +00001424 gained a *source_address* parameter, a ``(host, port)`` 2-tuple
1425 giving the source address that will be used for the connection.
1426 (Contributed by Eldon Ziegler; :issue:`3972`.)
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00001427
Ezio Melotti021f3342010-04-06 03:26:49 +00001428 The :meth:`~socket.socket.recv_into` and :meth:`~socket.socket.recvfrom_into`
1429 methods will now write into objects that support the buffer API, most usefully
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001430 the :class:`bytearray` and :class:`memoryview` objects. (Implemented by
1431 Antoine Pitrou; :issue:`8104`.)
1432
Ezio Melotti021f3342010-04-06 03:26:49 +00001433* The :mod:`SocketServer` module's :class:`~SocketServer.TCPServer` class now
Andrew M. Kuchling85fffc32010-05-08 01:15:26 +00001434 supports socket timeouts and disabling the Nagle algorithm.
1435 The :attr:`~SocketServer.TCPServer.disable_nagle_algorithm` class attribute
1436 defaults to False; if overridden to be True,
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001437 new request connections will have the TCP_NODELAY option set to
1438 prevent buffering many small sends into a single TCP packet.
Andrew M. Kuchling85fffc32010-05-08 01:15:26 +00001439 The :attr:`~SocketServer.TCPServer.timeout` class attribute can hold
1440 a timeout in seconds that will be applied to the request socket; if
1441 no request is received within that time, :meth:`handle_timeout`
1442 will be called and :meth:`handle_request` will return.
Andrew M. Kuchlingbadc7092010-05-08 01:35:55 +00001443 (Contributed by Kristján Valur Jónsson; :issue:`6192` and :issue:`6267`.)
Andrew M. Kuchling85fffc32010-05-08 01:15:26 +00001444
1445* The XML-RPC client and server, provided by the :mod:`xmlrpclib` and
1446 :mod:`SimpleXMLRPCServer` modules, have improved performance by
1447 supporting HTTP/1.1 keep-alive and by optionally using gzip encoding
1448 to compress the XML being exchanged. The gzip compression is
1449 controlled by the :attr:`encode_threshold` attribute of
1450 :class:`SimpleXMLRPCRequestHandler`, which contains a size in bytes;
1451 responses larger than this will be compressed.
Andrew M. Kuchlingbadc7092010-05-08 01:35:55 +00001452 (Contributed by Kristján Valur Jónsson; :issue:`6267`.)
Andrew M. Kuchling85fffc32010-05-08 01:15:26 +00001453
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001454
Ezio Melotti021f3342010-04-06 03:26:49 +00001455* Updated module: the :mod:`sqlite3` module has been updated to
Andrew M. Kuchlingfed15762010-03-08 12:00:39 +00001456 version 2.6.0 of the `pysqlite package <http://code.google.com/p/pysqlite/>`__. Version 2.6.0 includes a number of bugfixes, and adds
1457 the ability to load SQLite extensions from shared libraries.
1458 Call the ``enable_load_extension(True)`` method to enable extensions,
Ezio Melotti021f3342010-04-06 03:26:49 +00001459 and then call :meth:`~sqlite3.Connection.load_extension` to load a particular shared library.
Andrew M. Kuchlingfed15762010-03-08 12:00:39 +00001460 (Updated by Gerhard Häring.)
1461
Antoine Pitroud69e6ee2010-05-07 10:15:51 +00001462* The :mod:`ssl` module's :class:`ssl.SSLSocket` objects now support the
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001463 buffer API, which fixed a test suite failure (fix by Antoine Pitrou;
1464 :issue:`7133`) and automatically set
1465 OpenSSL's :cmacro:`SSL_MODE_AUTO_RETRY`, which will prevent an error
1466 code being returned from :meth:`recv` operations that trigger an SSL
1467 renegotiation (fix by Antoine Pitrou; :issue:`8222`).
1468
Antoine Pitroud69e6ee2010-05-07 10:15:51 +00001469 The :func:`ssl.wrap_socket` constructor function now takes a
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001470 *ciphers* argument that's a string listing the encryption algorithms
1471 to be allowed; the format of the string is described
Antoine Pitroud69e6ee2010-05-07 10:15:51 +00001472 `in the OpenSSL documentation
1473 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`__.
1474 (Added by Antoine Pitrou; :issue:`8322`.)
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001475
1476 Another change makes the extension load all of OpenSSL's ciphers and
1477 digest algorithms so that they're all available. Some SSL
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001478 certificates couldn't be verified, reporting an "unknown algorithm"
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001479 error. (Reported by Beda Kosata, and fixed by Antoine Pitrou;
1480 :issue:`8484`.)
1481
1482 The version of OpenSSL being used is now available as the module
Antoine Pitroud69e6ee2010-05-07 10:15:51 +00001483 attributes :data:`ssl.OPENSSL_VERSION` (a string),
1484 :data:`ssl.OPENSSL_VERSION_INFO` (a 5-tuple), and
1485 :data:`ssl.OPENSSL_VERSION_NUMBER` (an integer). (Added by Antoine
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001486 Pitrou; :issue:`8321`.)
1487
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001488* The :mod:`struct` module will no longer silently ignore overflow
1489 errors when a value is too large for a particular integer format
1490 code (one of ``bBhHiIlLqQ``); it now always raises a
1491 :exc:`struct.error` exception. (Changed by Mark Dickinson;
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001492 :issue:`1523`.) The :func:`~struct.pack` function will also
1493 attempt to use :meth:`__index__` to convert and pack non-integers
1494 before trying the :meth:`__int__` method or reporting an error.
1495 (Changed by Mark Dickinson; :issue:`8300`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001496
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001497* New function: the :mod:`subprocess` module's
Ezio Melotti021f3342010-04-06 03:26:49 +00001498 :func:`~subprocess.check_output` runs a command with a specified set of arguments
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001499 and returns the command's output as a string when the command runs without
Ezio Melotti021f3342010-04-06 03:26:49 +00001500 error, or raises a :exc:`~subprocess.CalledProcessError` exception otherwise.
Andrew M. Kuchling10b1ec92009-01-02 21:00:35 +00001501
1502 ::
1503
1504 >>> subprocess.check_output(['df', '-h', '.'])
1505 'Filesystem Size Used Avail Capacity Mounted on\n
1506 /dev/disk0s2 52G 49G 3.0G 94% /\n'
1507
1508 >>> subprocess.check_output(['df', '-h', '/bogus'])
1509 ...
1510 subprocess.CalledProcessError: Command '['df', '-h', '/bogus']' returned non-zero exit status 1
1511
1512 (Contributed by Gregory P. Smith.)
1513
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001514 The :mod:`subprocess` module will now retry its internal system calls
1515 on receiving an :const:`EINTR` signal. (Reported by several people; final
1516 patch by Gregory P. Smith in :issue:`1068268`.)
1517
Ezio Melotti021f3342010-04-06 03:26:49 +00001518* New function: :func:`~symtable.is_declared_global` in the :mod:`symtable` module
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001519 returns true for variables that are explicitly declared to be global,
1520 false for ones that are implicitly global.
1521 (Contributed by Jeremy Hylton.)
1522
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00001523* The :mod:`syslog` module will now use the value of ``sys.argv[0]`` as the
1524 identifier instead of the previous default value of ``'python'``.
1525 (Changed by Sean Reifschneider; :issue:`8451`.)
1526
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001527* The ``sys.version_info`` value is now a named tuple, with attributes
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001528 named :attr:`major`, :attr:`minor`, :attr:`micro`,
1529 :attr:`releaselevel`, and :attr:`serial`. (Contributed by Ross
1530 Light; :issue:`4285`.)
1531
1532 :func:`sys.getwindowsversion` also returns a named tuple,
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +00001533 with attributes named :attr:`major`, :attr:`minor`, :attr:`build`,
Ezio Melotti12477752010-02-08 22:22:41 +00001534 :attr:`platform`, :attr:`service_pack`, :attr:`service_pack_major`,
Eric Smithb3c54882010-02-03 14:17:50 +00001535 :attr:`service_pack_minor`, :attr:`suite_mask`, and
1536 :attr:`product_type`. (Contributed by Brian Curtin; :issue:`7766`.)
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001537
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001538* The :mod:`tarfile` module's default error handling has changed, to
1539 no longer suppress fatal errors. The default error level was previously 0,
1540 which meant that errors would only result in a message being written to the
1541 debug log, but because the debug log is not activated by default,
1542 these errors go unnoticed. The default error level is now 1,
1543 which raises an exception if there's an error.
1544 (Changed by Lars Gustäbel; :issue:`7357`.)
1545
Ezio Melotti021f3342010-04-06 03:26:49 +00001546 :mod:`tarfile` now supports filtering the :class:`~tarfile.TarInfo`
1547 objects being added to a tar file. When you call :meth:`~tarfile.TarFile.add`,
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001548 you may supply an optional *filter* argument
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001549 that's a callable. The *filter* callable will be passed the
Ezio Melotti021f3342010-04-06 03:26:49 +00001550 :class:`~tarfile.TarInfo` for every file being added, and can modify and return it.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001551 If the callable returns ``None``, the file will be excluded from the
1552 resulting archive. This is more powerful than the existing
1553 *exclude* argument, which has therefore been deprecated.
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001554 (Added by Lars Gustäbel; :issue:`6856`.)
Ezio Melotti021f3342010-04-06 03:26:49 +00001555 The :class:`~tarfile.TarFile` class also now supports the context manager protocol.
Andrew M. Kuchlingfed15762010-03-08 12:00:39 +00001556 (Added by Lars Gustäbel; :issue:`7232`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001557
Ezio Melotti021f3342010-04-06 03:26:49 +00001558* The :meth:`~threading.Event.wait` method of the :class:`threading.Event` class
1559 now returns the internal flag on exit. This means the method will usually
1560 return true because :meth:`~threading.Event.wait` is supposed to block until the
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001561 internal flag becomes true. The return value will only be false if
1562 a timeout was provided and the operation timed out.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001563 (Contributed by Tim Lesher; :issue:`1674032`.)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001564
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001565* The Unicode database provided by the :mod:`unicodedata` module is
1566 now used internally to determine which characters are numeric,
1567 whitespace, or represent line breaks. The database also
1568 includes information from the :file:`Unihan.txt` data file (patch
1569 by Anders Chrigström and Amaury Forgeot d'Arc; :issue:`1571184`)
1570 and has been updated to version 5.2.0 (updated by
1571 Florent Xicluna; :issue:`8024`).
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001572
Andrew M. Kuchling04b99cc2010-05-04 01:24:22 +00001573* The :mod:`urlparse` module's :func:`~urlparse.urlsplit` now handles
1574 unknown URL schemes in a fashion compliant with :rfc:`3986`: if the
1575 URL is of the form ``"<something>://..."``, the text before the
1576 ``://`` is treated as the scheme, even if it's a made-up scheme that
1577 the module doesn't know about. This change may break code that
1578 worked around the old behaviour. For example, Python 2.6.4 or 2.5
1579 will return the following:
1580
1581 >>> import urlparse
1582 >>> urlparse.urlsplit('invented://host/filename?query')
1583 ('invented', '', '//host/filename?query', '', '')
1584
1585 Python 2.7 (and Python 2.6.5) will return:
1586
1587 >>> import urlparse
1588 >>> urlparse.urlsplit('invented://host/filename?query')
1589 ('invented', 'host', '/filename?query', '', '')
1590
1591 (Python 2.7 actually produces slightly different output, since it
1592 returns a named tuple instead of a standard tuple.)
1593
1594 The :mod:`urlparse` module also supports IPv6 literal addresses as defined by
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001595 :rfc:`2732` (contributed by Senthil Kumaran; :issue:`2987`). ::
1596
1597 >>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo')
1598 ParseResult(scheme='http', netloc='[1080::8:800:200C:417A]',
1599 path='/foo', params='', query='', fragment='')
1600
Ezio Melotti021f3342010-04-06 03:26:49 +00001601* The :class:`~UserDict.UserDict` class is now a new-style class. (Changed by
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001602 Benjamin Peterson.)
1603
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00001604* New class: the :class:`~weakref.WeakSet` class in the :mod:`weakref`
1605 module is a set that only holds weak references to its elements; elements
1606 will be removed once there are no references pointing to them.
1607 (Originally implemented in Python 3.x by Raymond Hettinger, and backported
1608 to 2.7 by Michael Foord.)
1609
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001610* The ElementTree library, :mod:`xml.etree`, no longer escapes
1611 ampersands and angle brackets when outputting an XML processing
Ezio Melotti021f3342010-04-06 03:26:49 +00001612 instruction (which looks like ``<?xml-stylesheet href="#style1"?>``)
1613 or comment (which looks like ``<!-- comment -->``).
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001614 (Patch by Neil Muller; :issue:`2746`.)
1615
Andrew M. Kuchling85fffc32010-05-08 01:15:26 +00001616* The XML-RPC client and server, provided by the :mod:`xmlrpclib` and
1617 :mod:`SimpleXMLRPCServer` modules, have improved performance by
1618 supporting HTTP/1.1 keep-alive and by optionally using gzip encoding
1619 to compress the XML being exchanged. The gzip compression is
1620 controlled by the :attr:`encode_threshold` attribute of
1621 :class:`SimpleXMLRPCRequestHandler`, which contains a size in bytes;
1622 responses larger than this will be compressed.
Andrew M. Kuchlingbadc7092010-05-08 01:35:55 +00001623 (Contributed by Kristján Valur Jónsson; :issue:`6267`.)
Andrew M. Kuchling85fffc32010-05-08 01:15:26 +00001624
Ezio Melotti021f3342010-04-06 03:26:49 +00001625* The :mod:`zipfile` module's :class:`~zipfile.ZipFile` now supports the context
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001626 management protocol, so you can write ``with zipfile.ZipFile(...) as f:``.
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001627 (Contributed by Brian Curtin; :issue:`5511`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001628
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001629 :mod:`zipfile` now also supports archiving empty directories and
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001630 extracts them correctly. (Fixed by Kuba Wieczorek; :issue:`4710`.)
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001631 Reading files out of an archive is faster, and interleaving
Ezio Melotti021f3342010-04-06 03:26:49 +00001632 :meth:`~zipfile.ZipFile.read` and :meth:`~zipfile.ZipFile.readline` now works correctly.
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001633 (Contributed by Nir Aides; :issue:`7610`.)
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001634
Ezio Melotti021f3342010-04-06 03:26:49 +00001635 The :func:`~zipfile.is_zipfile` function now
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001636 accepts a file object, in addition to the path names accepted in earlier
1637 versions. (Contributed by Gabriel Genellina; :issue:`4756`.)
1638
Ezio Melotti021f3342010-04-06 03:26:49 +00001639 The :meth:`~zipfile.ZipFile.writestr` method now has an optional *compress_type* parameter
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001640 that lets you override the default compression method specified in the
Ezio Melotti021f3342010-04-06 03:26:49 +00001641 :class:`~zipfile.ZipFile` constructor. (Contributed by Ronald Oussoren;
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001642 :issue:`6003`.)
1643
1644
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001645.. ======================================================================
1646.. whole new modules get described in subsections here
1647
1648
1649.. _importlib-section:
1650
1651New module: importlib
1652------------------------------
1653
1654Python 3.1 includes the :mod:`importlib` package, a re-implementation
1655of the logic underlying Python's :keyword:`import` statement.
1656:mod:`importlib` is useful for implementors of Python interpreters and
1657to users who wish to write new importers that can participate in the
1658import process. Python 2.7 doesn't contain the complete
1659:mod:`importlib` package, but instead has a tiny subset that contains
1660a single function, :func:`~importlib.import_module`.
1661
1662``import_module(name, package=None)`` imports a module. *name* is
1663a string containing the module or package's name. It's possible to do
1664relative imports by providing a string that begins with a ``.``
1665character, such as ``..utils.errors``. For relative imports, the
1666*package* argument must be provided and is the name of the package that
1667will be used as the anchor for
1668the relative import. :func:`~importlib.import_module` both inserts the imported
1669module into ``sys.modules`` and returns the module object.
1670
1671Here are some examples::
1672
1673 >>> from importlib import import_module
1674 >>> anydbm = import_module('anydbm') # Standard absolute import
1675 >>> anydbm
1676 <module 'anydbm' from '/p/python/Lib/anydbm.py'>
1677 >>> # Relative import
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001678 >>> file_util = import_module('..file_util', 'distutils.command')
1679 >>> file_util
1680 <module 'distutils.file_util' from '/python/Lib/distutils/file_util.pyc'>
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001681
1682:mod:`importlib` was implemented by Brett Cannon and introduced in
1683Python 3.1.
1684
1685
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00001686New module: sysconfig
1687---------------------------------
1688
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001689The :mod:`sysconfig` module has been pulled out of the Distutils
1690package, becoming a new top-level module in its own right.
1691:mod:`sysconfig` provides functions for getting information about
1692Python's build process: compiler switches, installation paths, the
1693platform name, and whether Python is running from its source
1694directory.
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00001695
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001696Some of the functions in the module are:
1697
1698* :func:`~sysconfig.get_config_var` returns variables from Python's
1699 Makefile and the :file:`pyconfig.h` file.
1700* :func:`~sysconfig.get_config_vars` returns a dictionary containing
1701 all of the configuration variables.
1702* :func:`~sysconfig.getpath` returns the configured path for
1703 a particular type of module: the standard library,
1704 site-specific modules, platform-specific modules, etc.
1705* :func:`~sysconfig.is_python_build` returns true if you're running a
1706 binary from a Python source tree, and false otherwise.
1707
1708Consult the :mod:`sysconfig` documentation for more details and for
1709a complete list of functions.
1710
Andrew M. Kuchling8e343862010-05-08 13:28:03 +00001711The Distutils package and :mod:`sysconfig` are now maintained by Tarek
1712Ziadé, who has also started a Distutils2 package (source repository at
1713http://hg.python.org/distutils2/) for developing a next-generation
1714version of Distutils.
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001715
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00001716
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001717ttk: Themed Widgets for Tk
1718--------------------------
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001719
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001720Tcl/Tk 8.5 includes a set of themed widgets that re-implement basic Tk
1721widgets but have a more customizable appearance and can therefore more
1722closely resemble the native platform's widgets. This widget
1723set was originally called Tile, but was renamed to Ttk (for "themed Tk")
1724on being added to Tcl/Tck release 8.5.
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001725
Andrew M. Kuchling8e343862010-05-08 13:28:03 +00001726To learn more, read the :mod:`ttk` module documentation. You may also
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001727wish to read the Tcl/Tk manual page describing the
Andrew M. Kuchling8e343862010-05-08 13:28:03 +00001728Ttk theme engine, available at
1729http://www.tcl.tk/man/tcl8.5/TkCmd/ttk_intro.htm. Some
1730screenshots of the Python/Ttk code in use are at
1731http://code.google.com/p/python-ttk/wiki/Screenshots.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001732
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001733The :mod:`ttk` module was written by Guilherme Polo and added in
1734:issue:`2983`. An alternate version called ``Tile.py``, written by
1735Martin Franklin and maintained by Kevin Walzer, was proposed for
1736inclusion in :issue:`2618`, but the authors argued that Guilherme
1737Polo's work was more comprehensive.
1738
1739
1740.. _unittest-section:
Tarek Ziadé2b210692010-02-02 23:39:40 +00001741
Andrew M. Kuchlingacab9402010-05-06 17:27:57 +00001742Updated module: unittest
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001743---------------------------------
1744
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001745The :mod:`unittest` module was greatly enhanced; many
1746new features were added. Most of these features were implemented
Andrew M. Kuchlingacab9402010-05-06 17:27:57 +00001747by Michael Foord, unless otherwise noted. The enhanced version of
1748the module is downloadable separately for use with Python versions 2.4 to 2.6,
1749packaged as the :mod:`unittest2` package, from
1750http://pypi.python.org/pypi/unittest2.
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001751
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001752When used from the command line, the module can automatically discover
1753tests. It's not as fancy as `py.test <http://pytest.org>`__ or
1754`nose <http://code.google.com/p/python-nose/>`__, but provides a simple way
1755to run tests kept within a set of package directories. For example,
1756the following command will search the :file:`test/` subdirectory for
1757any importable test files named ``test*.py``::
1758
1759 python -m unittest discover -s test
1760
1761Consult the :mod:`unittest` module documentation for more details.
1762(Developed in :issue:`6001`.)
1763
1764The :func:`main` function supports some other new options:
1765
1766* :option:`-b` or :option:`--buffer` will buffer the standard output
1767 and standard error streams during each test. If the test passes,
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001768 any resulting output will be discarded; on failure, the buffered
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001769 output will be displayed.
1770
1771* :option:`-c` or :option:`--catch` will cause the control-C interrupt
1772 to be handled more gracefully. Instead of interrupting the test
1773 process immediately, the currently running test will be completed
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001774 and then the partial results up to the interruption will be reported.
1775 If you're impatient, a second press of control-C will cause an immediate
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001776 interruption.
1777
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001778 This control-C handler tries to avoid causing problems when the code
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001779 being tested or the tests being run have defined a signal handler of
1780 their own, by noticing that a signal handler was already set and
1781 calling it. If this doesn't work for you, there's a
1782 :func:`removeHandler` decorator that can be used to mark tests that
1783 should have the control-C handling disabled.
1784
1785* :option:`-f` or :option:`--failfast` makes
1786 test execution stop immediately when a test fails instead of
1787 continuing to execute further tests. (Suggested by Cliff Dyer and
1788 implemented by Michael Foord; :issue:`8074`.)
1789
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001790The progress messages now show 'x' for expected failures
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001791and 'u' for unexpected successes when run in verbose mode.
1792(Contributed by Benjamin Peterson.)
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001793
1794Test cases can raise the :exc:`~unittest.SkipTest` exception to skip a
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001795test (:issue:`1034053`).
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001796
Ezio Melotti021f3342010-04-06 03:26:49 +00001797The error messages for :meth:`~unittest.TestCase.assertEqual`,
1798:meth:`~unittest.TestCase.assertTrue`, and :meth:`~unittest.TestCase.assertFalse`
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001799failures now provide more information. If you set the
Ezio Melotti021f3342010-04-06 03:26:49 +00001800:attr:`~unittest.TestCase.longMessage` attribute of your :class:`~unittest.TestCase` classes to
1801True, both the standard error message and any additional message you
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001802provide will be printed for failures. (Added by Michael Foord; :issue:`5663`.)
1803
Ezio Melotti021f3342010-04-06 03:26:49 +00001804The :meth:`~unittest.TestCase.assertRaises` method now
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001805returns a context handler when called without providing a callable
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001806object to run. For example, you can write this::
1807
1808 with self.assertRaises(KeyError):
Ezio Melotti021f3342010-04-06 03:26:49 +00001809 {}['foo']
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001810
1811(Implemented by Antoine Pitrou; :issue:`4444`.)
1812
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001813.. rev 78774
1814
1815Module- and class-level setup and teardown fixtures are now supported.
Ezio Melotti021f3342010-04-06 03:26:49 +00001816Modules can contain :func:`~unittest.setUpModule` and :func:`~unittest.tearDownModule`
1817functions. Classes can have :meth:`~unittest.TestCase.setUpClass` and
1818:meth:`~unittest.TestCase.tearDownClass` methods that must be defined as class methods
1819(using ``@classmethod`` or equivalent). These functions and
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001820methods are invoked when the test runner switches to a test case in a
1821different module or class.
1822
Ezio Melotti021f3342010-04-06 03:26:49 +00001823The methods :meth:`~unittest.TestCase.addCleanup` and
1824:meth:`~unittest.TestCase.doCleanups` were added.
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001825:meth:`~unittest.TestCase.addCleanup` lets you add cleanup functions that
Ezio Melotti021f3342010-04-06 03:26:49 +00001826will be called unconditionally (after :meth:`~unittest.TestCase.setUp` if
1827:meth:`~unittest.TestCase.setUp` fails, otherwise after :meth:`~unittest.TestCase.tearDown`). This allows
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001828for much simpler resource allocation and deallocation during tests
1829(:issue:`5679`).
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001830
1831A number of new methods were added that provide more specialized
1832tests. Many of these methods were written by Google engineers
1833for use in their test suites; Gregory P. Smith, Michael Foord, and
1834GvR worked on merging them into Python's version of :mod:`unittest`.
1835
Ezio Melotti021f3342010-04-06 03:26:49 +00001836* :meth:`~unittest.TestCase.assertIsNone` and :meth:`~unittest.TestCase.assertIsNotNone` take one
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001837 expression and verify that the result is or is not ``None``.
1838
Ezio Melotti021f3342010-04-06 03:26:49 +00001839* :meth:`~unittest.TestCase.assertIs` and :meth:`~unittest.TestCase.assertIsNot`
1840 take two values and check whether the two values evaluate to the same object or not.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001841 (Added by Michael Foord; :issue:`2578`.)
1842
Ezio Melotti021f3342010-04-06 03:26:49 +00001843* :meth:`~unittest.TestCase.assertIsInstance` and
1844 :meth:`~unittest.TestCase.assertNotIsInstance` check whether
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00001845 the resulting object is an instance of a particular class, or of
1846 one of a tuple of classes. (Added by Georg Brandl; :issue:`7031`.)
1847
Ezio Melotti021f3342010-04-06 03:26:49 +00001848* :meth:`~unittest.TestCase.assertGreater`, :meth:`~unittest.TestCase.assertGreaterEqual`,
1849 :meth:`~unittest.TestCase.assertLess`, and :meth:`~unittest.TestCase.assertLessEqual` compare
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001850 two quantities.
1851
Ezio Melotti021f3342010-04-06 03:26:49 +00001852* :meth:`~unittest.TestCase.assertMultiLineEqual` compares two strings, and if they're
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001853 not equal, displays a helpful comparison that highlights the
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001854 differences in the two strings. This comparison is now used by
Ezio Melotti021f3342010-04-06 03:26:49 +00001855 default when Unicode strings are compared with :meth:`~unittest.TestCase.assertEqual`.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001856
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001857* :meth:`~unittest.TestCase.assertRegexpMatches` and
1858 :meth:`~unittest.TestCase.assertNotRegexpMatches` checks whether the
1859 first argument is a string matching or not matching the regular
1860 expression provided as the second argument (:issue:`8038`).
Ezio Melotti021f3342010-04-06 03:26:49 +00001861
1862* :meth:`~unittest.TestCase.assertRaisesRegexp` checks whether a particular exception
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001863 is raised, and then also checks that the string representation of
1864 the exception matches the provided regular expression.
1865
Ezio Melotti021f3342010-04-06 03:26:49 +00001866* :meth:`~unittest.TestCase.assertIn` and :meth:`~unittest.TestCase.assertNotIn`
1867 tests whether *first* is or is not in *second*.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001868
Ezio Melotti021f3342010-04-06 03:26:49 +00001869* :meth:`~unittest.TestCase.assertItemsEqual` tests whether two provided sequences
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001870 contain the same elements.
1871
Ezio Melotti021f3342010-04-06 03:26:49 +00001872* :meth:`~unittest.TestCase.assertSetEqual` compares whether two sets are equal, and
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001873 only reports the differences between the sets in case of error.
1874
Ezio Melotti021f3342010-04-06 03:26:49 +00001875* Similarly, :meth:`~unittest.TestCase.assertListEqual` and :meth:`~unittest.TestCase.assertTupleEqual`
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001876 compare the specified types and explain any differences without necessarily
1877 printing their full values; these methods are now used by default
Ezio Melotti021f3342010-04-06 03:26:49 +00001878 when comparing lists and tuples using :meth:`~unittest.TestCase.assertEqual`.
1879 More generally, :meth:`~unittest.TestCase.assertSequenceEqual` compares two sequences
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001880 and can optionally check whether both sequences are of a
1881 particular type.
1882
Ezio Melotti021f3342010-04-06 03:26:49 +00001883* :meth:`~unittest.TestCase.assertDictEqual` compares two dictionaries and reports the
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001884 differences; it's now used by default when you compare two dictionaries
Ezio Melotti021f3342010-04-06 03:26:49 +00001885 using :meth:`~unittest.TestCase.assertEqual`. :meth:`~unittest.TestCase.assertDictContainsSubset` checks whether
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001886 all of the key/value pairs in *first* are found in *second*.
1887
Ezio Melotti021f3342010-04-06 03:26:49 +00001888* :meth:`~unittest.TestCase.assertAlmostEqual` and :meth:`~unittest.TestCase.assertNotAlmostEqual` test
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001889 whether *first* and *second* are approximately equal. This method
1890 can either round their difference to an optionally-specified number
1891 of *places* (the default is 7) and compare it to zero, or require
1892 the difference to be smaller than a supplied *delta* value.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001893
Ezio Melotti021f3342010-04-06 03:26:49 +00001894* :meth:`~unittest.TestLoader.loadTestsFromName` properly honors the
1895 :attr:`~unittest.TestLoader.suiteClass` attribute of
1896 the :class:`~unittest.TestLoader`. (Fixed by Mark Roddy; :issue:`6866`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001897
Ezio Melotti021f3342010-04-06 03:26:49 +00001898* A new hook lets you extend the :meth:`~unittest.TestCase.assertEqual` method to handle
1899 new data types. The :meth:`~unittest.TestCase.addTypeEqualityFunc` method takes a type
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001900 object and a function. The function will be used when both of the
1901 objects being compared are of the specified type. This function
1902 should compare the two objects and raise an exception if they don't
1903 match; it's a good idea for the function to provide additional
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001904 information about why the two objects aren't matching, much as the new
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001905 sequence comparison methods do.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001906
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001907:func:`unittest.main` now takes an optional ``exit`` argument. If
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001908False, :func:`~unittest.main` doesn't call :func:`sys.exit`, allowing
1909:func:`main` to be used from the interactive interpreter.
1910(Contributed by J. Pablo Fernández; :issue:`3379`.)
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001911
Ezio Melotti021f3342010-04-06 03:26:49 +00001912:class:`~unittest.TestResult` has new :meth:`~unittest.TestResult.startTestRun` and
1913:meth:`~unittest.TestResult.stopTestRun` methods that are called immediately before
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001914and after a test run. (Contributed by Robert Collins; :issue:`5728`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001915
1916With all these changes, the :file:`unittest.py` was becoming awkwardly
1917large, so the module was turned into a package and the code split into
1918several files (by Benjamin Peterson). This doesn't affect how the
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001919module is imported or used.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001920
Andrew M. Kuchling264552a2010-05-10 15:03:35 +00001921.. seealso::
1922
1923 http://www.voidspace.org.uk/python/articles/unittest2.shtml
1924 Describes the new features, how to use them, and the
1925 rationale for various design decisions. (By Michael Foord.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001926
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001927.. _elementtree-section:
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001928
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001929Updated module: ElementTree 1.3
1930---------------------------------
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001931
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001932The version of the ElementTree library included with Python was updated to
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001933version 1.3. Some of the new features are:
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001934
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001935* The various parsing functions now take a *parser* keyword argument
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001936 giving an :class:`XMLParser` instance that will
1937 be used. This makes it possible to override the file's internal encoding::
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001938
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001939 p = ET.XMLParser(encoding='utf-8')
1940 t = ET.XML("""<root/>""", parser=p)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001941
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001942 Errors in parsing XML now raise a :exc:`ParseError` exception, whose
1943 instances have a :attr:`position` attribute
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001944 containing a (*line*, *column*) tuple giving the location of the problem.
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001945
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001946* ElementTree's code for converting trees to a string has been
1947 significantly reworked, making it roughly twice as fast in many
1948 cases. The :class:`ElementTree` :meth:`write` and :class:`Element`
1949 :meth:`write` methods now have a *method* parameter that can be
1950 "xml" (the default), "html", or "text". HTML mode will output empty
1951 elements as ``<empty></empty>`` instead of ``<empty/>``, and text
1952 mode will skip over elements and only output the text chunks. If
1953 you set the :attr:`tag` attribute of an element to ``None`` but
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001954 leave its children in place, the element will be omitted when the
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001955 tree is written out, so you don't need to do more extensive rearrangement
1956 to remove a single element.
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001957
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001958 Namespace handling has also been improved. All ``xmlns:<whatever>``
1959 declarations are now output on the root element, not scattered throughout
1960 the resulting XML. You can set the default namespace for a tree
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001961 by setting the :attr:`default_namespace` attribute and can
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001962 register new prefixes with :meth:`register_namespace`. In XML mode,
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001963 you can use the true/false *xml_declaration* parameter to suppress the
1964 XML declaration.
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001965
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001966* New :class:`Element` method: :meth:`extend` appends the items from a
1967 sequence to the element's children. Elements themselves behave like
1968 sequences, so it's easy to move children from one element to
1969 another::
Andrew M. Kuchlinga17cd4a2009-01-31 02:50:09 +00001970
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001971 from xml.etree import ElementTree as ET
Andrew M. Kuchlinga17cd4a2009-01-31 02:50:09 +00001972
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001973 t = ET.XML("""<list>
1974 <item>1</item> <item>2</item> <item>3</item>
1975 </list>""")
1976 new = ET.XML('<root/>')
1977 new.extend(t)
Andrew M. Kuchlinga17cd4a2009-01-31 02:50:09 +00001978
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001979 # Outputs <root><item>1</item>...</root>
1980 print ET.tostring(new)
Andrew M. Kuchlinga17cd4a2009-01-31 02:50:09 +00001981
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001982* New :class:`Element` method: :meth:`iter` yields the children of the
1983 element as a generator. It's also possible to write ``for child in
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001984 elem:`` to loop over an element's children. The existing method
1985 :meth:`getiterator` is now deprecated, as is :meth:`getchildren`
1986 which constructs and returns a list of children.
Georg Brandl0516f812009-11-18 18:52:35 +00001987
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001988* New :class:`Element` method: :meth:`itertext` yields all chunks of
1989 text that are descendants of the element. For example::
Georg Brandl0516f812009-11-18 18:52:35 +00001990
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001991 t = ET.XML("""<list>
1992 <item>1</item> <item>2</item> <item>3</item>
1993 </list>""")
1994
1995 # Outputs ['\n ', '1', ' ', '2', ' ', '3', '\n']
1996 print list(t.itertext())
1997
Andrew M. Kuchling27024912010-05-12 00:38:44 +00001998* Deprecated: using an element as a Boolean (i.e., ``if elem:``) would
1999 return true if the element had any children, or false if there were
2000 no children. This behaviour is confusing -- ``None`` is false, but
2001 so is a childless element? -- so it will now trigger a
2002 :exc:`FutureWarning`. In your code, you should be explicit: write
2003 ``len(elem) != 0`` if you're interested in the number of children,
2004 or ``elem is not None``.
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00002005
2006Fredrik Lundh develops ElementTree and produced the 1.3 version;
2007you can read his article describing 1.3 at
2008http://effbot.org/zone/elementtree-13-intro.htm.
2009Florent Xicluna updated the version included with
2010Python, after discussions on python-dev and in :issue:`6472`.)
Georg Brandl0516f812009-11-18 18:52:35 +00002011
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002012.. ======================================================================
2013
2014
2015Build and C API Changes
2016=======================
2017
2018Changes to Python's build process and to the C API include:
2019
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00002020* The latest release of the GNU Debugger, GDB 7, can be `scripted
2021 using Python
2022 <http://sourceware.org/gdb/current/onlinedocs/gdb/Python.html>`__.
2023 When you begin debugging an executable program P, GDB will look for
2024 a file named ``P-gdb.py`` and automatically read it. Dave Malcolm
Andrew M. Kuchling27024912010-05-12 00:38:44 +00002025 contributed a :file:`python-gdb.py` that adds a number of
2026 commands useful when debugging Python itself. For example,
2027 ``py-up`` and ``py-down`` go up or down one Python stack frame,
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00002028 which usually corresponds to several C stack frames. ``py-print``
2029 prints the value of a Python variable, and ``py-bt`` prints the
2030 Python stack trace. (Added as a result of :issue:`8032`.)
2031
Andrew M. Kuchling10b1ec92009-01-02 21:00:35 +00002032* If you use the :file:`.gdbinit` file provided with Python,
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002033 the "pyo" macro in the 2.7 version now works correctly when the thread being
2034 debugged doesn't hold the GIL; the macro now acquires it before printing.
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00002035 (Contributed by Victor Stinner; :issue:`3632`.)
2036
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00002037* :cfunc:`Py_AddPendingCall` is now thread-safe, letting any
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00002038 worker thread submit notifications to the main Python thread. This
2039 is particularly useful for asynchronous IO operations.
Andrew M. Kuchlingbadc7092010-05-08 01:35:55 +00002040 (Contributed by Kristján Valur Jónsson; :issue:`4293`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00002041
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002042* New function: :cfunc:`PyCode_NewEmpty` creates an empty code object;
2043 only the filename, function name, and first line number are required.
Andrew M. Kuchling27024912010-05-12 00:38:44 +00002044 This is useful for extension modules that are attempting to
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002045 construct a more useful traceback stack. Previously such
2046 extensions needed to call :cfunc:`PyCode_New`, which had many
2047 more arguments. (Added by Jeffrey Yasskin.)
2048
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00002049* New function: :cfunc:`PyErr_NewExceptionWithDoc` creates a new
2050 exception class, just as the existing :cfunc:`PyErr_NewException` does,
2051 but takes an extra ``char *`` argument containing the docstring for the
Andrew M. Kuchling27024912010-05-12 00:38:44 +00002052 new exception class. (Added by 'lekma' on the Python bug tracker;
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00002053 :issue:`7033`.)
2054
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002055* New function: :cfunc:`PyFrame_GetLineNumber` takes a frame object
2056 and returns the line number that the frame is currently executing.
2057 Previously code would need to get the index of the bytecode
2058 instruction currently executing, and then look up the line number
2059 corresponding to that address. (Added by Jeffrey Yasskin.)
2060
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00002061* New functions: :cfunc:`PyLong_AsLongAndOverflow` and
2062 :cfunc:`PyLong_AsLongLongAndOverflow` approximates a Python long
2063 integer as a C :ctype:`long` or :ctype:`long long`.
2064 If the number is too large to fit into
2065 the output type, an *overflow* flag is set and returned to the caller.
2066 (Contributed by Case Van Horsen; :issue:`7528` and :issue:`7767`.)
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00002067
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00002068* New function: stemming from the rewrite of string-to-float conversion,
2069 a new :cfunc:`PyOS_string_to_double` function was added. The old
2070 :cfunc:`PyOS_ascii_strtod` and :cfunc:`PyOS_ascii_atof` functions
2071 are now deprecated.
2072
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002073* New macros: the Python header files now define the following macros:
2074 :cmacro:`Py_ISALNUM`,
2075 :cmacro:`Py_ISALPHA`,
2076 :cmacro:`Py_ISDIGIT`,
2077 :cmacro:`Py_ISLOWER`,
2078 :cmacro:`Py_ISSPACE`,
2079 :cmacro:`Py_ISUPPER`,
2080 :cmacro:`Py_ISXDIGIT`,
2081 and :cmacro:`Py_TOLOWER`, :cmacro:`Py_TOUPPER`.
2082 All of these functions are analogous to the C
2083 standard macros for classifying characters, but ignore the current
2084 locale setting, because in
2085 several places Python needs to analyze characters in a
2086 locale-independent way. (Added by Eric Smith;
2087 :issue:`5793`.)
2088
2089 .. XXX these macros don't seem to be described in the c-api docs.
2090
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00002091* Removed function: :cmacro:`PyEval_CallObject` is now only available
2092 as a macro. A function version was being kept around to preserve
2093 ABI linking compatibility, but that was in 1997; it can certainly be
Andrew M. Kuchling27024912010-05-12 00:38:44 +00002094 deleted by now. (Removed by Antoine Pitrou; :issue:`8276`.)
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00002095
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00002096* New format codes: the :cfunc:`PyFormat_FromString`,
Andrew M. Kuchling27024912010-05-12 00:38:44 +00002097 :cfunc:`PyFormat_FromStringV`, and :cfunc:`PyErr_Format` functions now
2098 accept ``%lld`` and ``%llu`` format codes for displaying
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00002099 C's :ctype:`long long` types.
2100 (Contributed by Mark Dickinson; :issue:`7228`.)
2101
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002102* The complicated interaction between threads and process forking has
2103 been changed. Previously, the child process created by
2104 :func:`os.fork` might fail because the child is created with only a
2105 single thread running, the thread performing the :func:`os.fork`.
2106 If other threads were holding a lock, such as Python's import lock,
2107 when the fork was performed, the lock would still be marked as
2108 "held" in the new process. But in the child process nothing would
2109 ever release the lock, since the other threads weren't replicated,
2110 and the child process would no longer be able to perform imports.
2111
Andrew M. Kuchling27024912010-05-12 00:38:44 +00002112 Python 2.7 acquires the import lock before performing an
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002113 :func:`os.fork`, and will also clean up any locks created using the
2114 :mod:`threading` module. C extension modules that have internal
2115 locks, or that call :cfunc:`fork()` themselves, will not benefit
2116 from this clean-up.
2117
2118 (Fixed by Thomas Wouters; :issue:`1590864`.)
2119
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00002120* The :cfunc:`Py_Finalize` function now calls the internal
2121 :func:`threading._shutdown` function; this prevents some exceptions from
2122 being raised when an interpreter shuts down.
2123 (Patch by Adam Olsen; :issue:`1722344`.)
2124
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002125* When using the :ctype:`PyMemberDef` structure to define attributes
2126 of a type, Python will no longer let you try to delete or set a
2127 :const:`T_STRING_INPLACE` attribute.
2128
2129 .. rev 79644
2130
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00002131* Global symbols defined by the :mod:`ctypes` module are now prefixed
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002132 with ``Py``, or with ``_ctypes``. (Implemented by Thomas
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00002133 Heller; :issue:`3102`.)
2134
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00002135* New configure option: the :option:`--with-system-expat` switch allows
2136 building the :mod:`pyexpat` module to use the system Expat library.
2137 (Contributed by Arfrever Frehtes Taifersar Arahesis; :issue:`7609`.)
2138
Andrew M. Kuchling27024912010-05-12 00:38:44 +00002139* New configure option: the
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00002140 :option:`--with-valgrind` option will now disable the pymalloc
Andrew M. Kuchlingce690522010-04-13 01:32:51 +00002141 allocator, which is difficult for the Valgrind memory-error detector
2142 to analyze correctly.
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00002143 Valgrind will therefore be better at detecting memory leaks and
2144 overruns. (Contributed by James Henstridge; :issue:`2422`.)
2145
Andrew M. Kuchling27024912010-05-12 00:38:44 +00002146* New configure option: you can now supply an empty string to
2147 :option:`--with-dbmliborder=` in order to disable all of the various
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +00002148 DBM modules. (Added by Arfrever Frehtes Taifersar Arahesis;
2149 :issue:`6491`.)
2150
Andrew M. Kuchling77069572009-03-31 01:21:01 +00002151* The :program:`configure` script now checks for floating-point rounding bugs
2152 on certain 32-bit Intel chips and defines a :cmacro:`X87_DOUBLE_ROUNDING`
2153 preprocessor definition. No code currently uses this definition,
2154 but it's available if anyone wishes to use it.
2155 (Added by Mark Dickinson; :issue:`2937`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002156
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00002157 :program:`configure` also now sets a :envvar:`LDCXXSHARED` Makefile
2158 variable for supporting C++ linking. (Contributed by Arfrever
2159 Frehtes Taifersar Arahesis; :issue:`1222585`.)
2160
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002161* The build process now creates the necessary files for pkg-config
2162 support. (Contributed by Clinton Roy; :issue:`3585`.)
2163
2164* The build process now supports Subversion 1.7. (Contributed by
2165 Arfrever Frehtes Taifersar Arahesis; :issue:`6094`.)
2166
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00002167
Andrew M. Kuchling85fffc32010-05-08 01:15:26 +00002168.. _whatsnew27-capsules:
2169
2170Capsules
2171-------------------
2172
2173Python 3.1 adds a new C datatype, :ctype:`PyCapsule`, for providing a
Andrew M. Kuchling27024912010-05-12 00:38:44 +00002174C API to an extension module. A capsule is essentially the holder of
2175a C ``void *`` pointer, and is made available as a module attribute; for
Andrew M. Kuchling304500c2010-05-08 13:29:46 +00002176example, the :mod:`socket` module's API is exposed as ``socket.CAPI``,
Andrew M. Kuchling27024912010-05-12 00:38:44 +00002177and :mod:`unicodedata` exposes ``ucnhash_CAPI``. Other extensions
Andrew M. Kuchling85fffc32010-05-08 01:15:26 +00002178can import the module, access its dictionary to get the capsule
2179object, and then get the ``void *`` pointer, which will usually point
Andrew M. Kuchling27024912010-05-12 00:38:44 +00002180to an array of pointers to the module's various API functions.
Andrew M. Kuchling85fffc32010-05-08 01:15:26 +00002181
Andrew M. Kuchling27024912010-05-12 00:38:44 +00002182There is an existing data type already used for this,
Andrew M. Kuchling85fffc32010-05-08 01:15:26 +00002183:ctype:`PyCObject`, but it doesn't provide type safety. Evil code
2184written in pure Python could cause a segmentation fault by taking a
2185:ctype:`PyCObject` from module A and somehow substituting it for the
2186:ctype:`PyCObject` in module B. Capsules know their own name,
2187and getting the pointer requires providing the name::
2188
2189 void *vtable;
2190
2191 if (!PyCapsule_IsValid(capsule, "mymodule.CAPI") {
2192 PyErr_SetString(PyExc_ValueError, "argument type invalid");
2193 return NULL;
2194 }
2195
2196 vtable = PyCapsule_GetPointer(capsule, "mymodule.CAPI");
2197
2198You are assured that ``vtable`` points to whatever you're expecting.
2199If a different capsule was passed in, :cfunc:`PyCapsule_IsValid` would
2200detect the mismatched name and return false. Refer to
2201:ref:`using-capsules` for more information on using these objects.
2202
2203Python 2.7 now uses capsules internally to provide various
2204extension-module APIs, but the :cfunc:`PyCObject_AsVoidPtr` was
2205modified to handle capsules, preserving compile-time compatibility
2206with the :ctype:`CObject` interface. Use of
2207:cfunc:`PyCObject_AsVoidPtr` will signal a
2208:exc:`PendingDeprecationWarning`, which is silent by default.
2209
2210Implemented in Python 3.1 and backported to 2.7 by Larry Hastings;
2211discussed in :issue:`5630`.
2212
2213
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002214.. ======================================================================
2215
2216Port-Specific Changes: Windows
2217-----------------------------------
2218
Andrew M. Kuchling10b1ec92009-01-02 21:00:35 +00002219* The :mod:`msvcrt` module now contains some constants from
2220 the :file:`crtassem.h` header file:
2221 :data:`CRT_ASSEMBLY_VERSION`,
2222 :data:`VC_ASSEMBLY_PUBLICKEYTOKEN`,
2223 and :data:`LIBRARIES_ASSEMBLY_NAME_PREFIX`.
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00002224 (Contributed by David Cournapeau; :issue:`4365`.)
2225
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002226* The :mod:`_winreg` module for accessing the registry now implements
2227 the :func:`CreateKeyEx` and :func:`DeleteKeyEx` functions, extended
2228 versions of previously-supported functions that take several extra
2229 arguments. The :func:`DisableReflectionKey`,
2230 :func:`EnableReflectionKey`, and :func:`QueryReflectionKey` were also
2231 tested and documented.
2232 (Implemented by Brian Curtin: :issue:`7347`.)
2233
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00002234* The new :cfunc:`_beginthreadex` API is used to start threads, and
2235 the native thread-local storage functions are now used.
Andrew M. Kuchlingbadc7092010-05-08 01:35:55 +00002236 (Contributed by Kristján Valur Jónsson; :issue:`3582`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002237
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +00002238* The :func:`os.kill` function now works on Windows. The signal value
2239 can be the constants :const:`CTRL_C_EVENT`,
Andrew M. Kuchling27024912010-05-12 00:38:44 +00002240 :const:`CTRL_BREAK_EVENT`, or any integer. The first two constants
2241 will send Control-C and Control-Break keystroke events to
2242 subprocesses; any other value will use the :cfunc:`TerminateProcess`
2243 API. (Contributed by Miki Tebeka; :issue:`1220212`.)
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +00002244
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002245* The :func:`os.listdir` function now correctly fails
2246 for an empty path. (Fixed by Hirokazu Yamamoto; :issue:`5913`.)
2247
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00002248* The :mod:`mimelib` module will now read the MIME database from
2249 the Windows registry when initializing.
2250 (Patch by Gabriel Genellina; :issue:`4969`.)
2251
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002252.. ======================================================================
2253
2254Port-Specific Changes: Mac OS X
2255-----------------------------------
2256
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002257* The path ``/Library/Python/2.7/site-packages`` is now appended to
Andrew M. Kuchling77069572009-03-31 01:21:01 +00002258 ``sys.path``, in order to share added packages between the system
2259 installation and a user-installed copy of the same version.
2260 (Changed by Ronald Oussoren; :issue:`4865`.)
2261
Andrew M. Kuchling04b99cc2010-05-04 01:24:22 +00002262Port-Specific Changes: FreeBSD
2263-----------------------------------
2264
2265* FreeBSD 7.1's :const:`SO_SETFIB` constant, used with
2266 :func:`~socket.getsockopt`/:func:`~socket.setsockopt` to select an
2267 alternate routing table, is now available in the :mod:`socket`
2268 module. (Added by Kyle VanderBeek; :issue:`8235`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002269
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00002270Other Changes and Fixes
2271=======================
2272
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00002273* Two benchmark scripts, :file:`iobench` and :file:`ccbench`, were
2274 added to the :file:`Tools` directory. :file:`iobench` measures the
Andrew M. Kuchling27024912010-05-12 00:38:44 +00002275 speed of the built-in file I/O objects returned by :func:`open`
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00002276 while performing various operations, and :file:`ccbench` is a
2277 concurrency benchmark that tries to measure computing throughput,
2278 thread switching latency, and IO processing bandwidth when
2279 performing several tasks using a varying number of threads.
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00002280
Andrew M. Kuchling77069572009-03-31 01:21:01 +00002281* When importing a module from a :file:`.pyc` or :file:`.pyo` file
2282 with an existing :file:`.py` counterpart, the :attr:`co_filename`
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00002283 attributes of the resulting code objects are overwritten when the
2284 original filename is obsolete. This can happen if the file has been
2285 renamed, moved, or is accessed through different paths. (Patch by
2286 Ziga Seilnacht and Jean-Paul Calderone; :issue:`1180193`.)
Andrew M. Kuchling77069572009-03-31 01:21:01 +00002287
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00002288* The :file:`regrtest.py` script now takes a :option:`--randseed=`
2289 switch that takes an integer that will be used as the random seed
2290 for the :option:`-r` option that executes tests in random order.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002291 The :option:`-r` option also reports the seed that was used
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00002292 (Added by Collin Winter.)
2293
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00002294* Another :file:`regrtest.py` switch is :option:`-j`, which
2295 takes an integer specifying how many tests run in parallel. This
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002296 allows reducing the total runtime on multi-core machines.
Antoine Pitrou4698d992009-05-31 14:20:14 +00002297 This option is compatible with several other options, including the
2298 :option:`-R` switch which is known to produce long runtimes.
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00002299 (Added by Antoine Pitrou, :issue:`6152`.) This can also be used
2300 with a new :option:`-F` switch that runs selected tests in a loop
2301 until they fail. (Added by Antoine Pitrou; :issue:`7312`.)
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00002302
Andrew M. Kuchling85f928a2010-04-15 01:42:27 +00002303* When executed as a script, the :file:`py_compile.py` module now
2304 accepts ``'-'`` as an argument, which will read standard input for
2305 the list of filenames to be compiled. (Contributed by Piotr
2306 Ożarowski; :issue:`8233`.)
2307
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002308.. ======================================================================
2309
2310Porting to Python 2.7
2311=====================
2312
2313This section lists previously described changes and other bugfixes
2314that may require changes to your code:
2315
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00002316* The :func:`range` function processes its arguments more
2317 consistently; it will now call :meth:`__int__` on non-float,
2318 non-integer arguments that are supplied to it. (Fixed by Alexander
2319 Belopolsky; :issue:`1533`.)
2320
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002321* The string :meth:`format` method changed the default precision used
2322 for floating-point and complex numbers from 6 decimal
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002323 places to 12, which matches the precision used by :func:`str`.
2324 (Changed by Eric Smith; :issue:`5920`.)
2325
Amaury Forgeot d'Arc901f2002009-06-09 23:08:13 +00002326* Because of an optimization for the :keyword:`with` statement, the special
2327 methods :meth:`__enter__` and :meth:`__exit__` must belong to the object's
2328 type, and cannot be directly attached to the object's instance. This
Amaury Forgeot d'Arcd81333c2009-06-10 20:30:19 +00002329 affects new-style classes (derived from :class:`object`) and C extension
Amaury Forgeot d'Arc901f2002009-06-09 23:08:13 +00002330 types. (:issue:`6101`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002331
Andrew M. Kuchling837a5382010-05-06 17:21:59 +00002332* Due to a bug in Python 2.6, the *exc_value* parameter to
2333 :meth:`__exit__` methods was often the string representation of the
2334 exception, not an instance. This was fixed in 2.7, so *exc_value*
2335 will be an instance as expected. (Fixed by Florent Xicluna;
2336 :issue:`7853`.)
2337
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00002338* When a restricted set of attributes were set using ``__slots__``,
2339 deleting an unset attribute would not raise :exc:`AttributeError`
2340 as you would expect. Fixed by Benjamin Peterson; :issue:`7604`.)
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002341
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00002342In the standard library:
2343
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002344* When using :class:`Decimal` instances with a string's
2345 :meth:`format` method, the default alignment was previously
2346 left-alignment. This has been changed to right-alignment, which might
2347 change the output of your programs.
2348 (Changed by Mark Dickinson; :issue:`6857`.)
2349
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00002350 Comparisons involving a signaling NaN value (or ``sNAN``) now signal
2351 :const:`InvalidOperation` instead of silently returning a true or
2352 false value depending on the comparison operator. Quiet NaN values
2353 (or ``NaN``) are now hashable. (Fixed by Mark Dickinson;
2354 :issue:`7279`.)
2355
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00002356* The ElementTree library, :mod:`xml.etree`, no longer escapes
2357 ampersands and angle brackets when outputting an XML processing
2358 instruction (which looks like `<?xml-stylesheet href="#style1"?>`)
2359 or comment (which looks like `<!-- comment -->`).
2360 (Patch by Neil Muller; :issue:`2746`.)
2361
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00002362* The :meth:`readline` method of :class:`StringIO` objects now does
2363 nothing when a negative length is requested, as other file-like
2364 objects do. (:issue:`7348`).
2365
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002366* The :mod:`syslog` module will now use the value of ``sys.argv[0]`` as the
2367 identifier instead of the previous default value of ``'python'``.
2368 (Changed by Sean Reifschneider; :issue:`8451`.)
2369
Andrew M. Kuchling27024912010-05-12 00:38:44 +00002370* The :mod:`tarfile` module's default error handling has changed, to
2371 no longer suppress fatal errors. The default error level was previously 0,
2372 which meant that errors would only result in a message being written to the
2373 debug log, but because the debug log is not activated by default,
2374 these errors go unnoticed. The default error level is now 1,
2375 which raises an exception if there's an error.
2376 (Changed by Lars Gustäbel; :issue:`7357`.)
2377
Andrew M. Kuchling04b99cc2010-05-04 01:24:22 +00002378* The :mod:`urlparse` module's :func:`~urlparse.urlsplit` now handles
2379 unknown URL schemes in a fashion compliant with :rfc:`3986`: if the
2380 URL is of the form ``"<something>://..."``, the text before the
2381 ``://`` is treated as the scheme, even if it's a made-up scheme that
2382 the module doesn't know about. This change may break code that
2383 worked around the old behaviour. For example, Python 2.6.4 or 2.5
2384 will return the following:
2385
2386 >>> import urlparse
2387 >>> urlparse.urlsplit('invented://host/filename?query')
2388 ('invented', '', '//host/filename?query', '', '')
2389
2390 Python 2.7 (and Python 2.6.5) will return:
2391
2392 >>> import urlparse
2393 >>> urlparse.urlsplit('invented://host/filename?query')
2394 ('invented', 'host', '/filename?query', '', '')
2395
2396 (Python 2.7 actually produces slightly different output, since it
2397 returns a named tuple instead of a standard tuple.)
2398
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00002399For C extensions:
2400
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +00002401* C extensions that use integer format codes with the ``PyArg_Parse*``
2402 family of functions will now raise a :exc:`TypeError` exception
2403 instead of triggering a :exc:`DeprecationWarning` (:issue:`5080`).
2404
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00002405* Use the new :cfunc:`PyOS_string_to_double` function instead of the old
2406 :cfunc:`PyOS_ascii_strtod` and :cfunc:`PyOS_ascii_atof` functions,
2407 which are now deprecated.
2408
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +00002409
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002410.. ======================================================================
2411
2412
2413.. _acks27:
2414
2415Acknowledgements
2416================
2417
2418The author would like to thank the following people for offering
2419suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchling0efe18a2010-05-08 15:39:46 +00002420article: Nick Coghlan, Philip Jenvey, Ryan Lovett, R. David Murray,
2421Hugh Secker-Walker.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002422