blob: 72aa7e6e3b1bc5f40018e5e58dda0a4684cdd070 [file] [log] [blame]
Benjamin Petersonf10a79a2008-10-11 00:49:57 +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
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00009.. hyperlink all the methods & functions.
Ezio Melotti6c96ffe2010-04-07 04:27:14 +000010
Benjamin Petersond7c3ed52010-06-27 22:32:30 +000011.. T_STRING_INPLACE not described in main docs
12.. "Format String Syntax" in string.rst could use many more examples.
13
Benjamin Petersonf10a79a2008-10-11 00:49:57 +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 Melotti6c96ffe2010-04-07 04:27:14 +000043 * Credit the author of a patch or bugfix. Just the name is
Benjamin Petersonf10a79a2008-10-11 00:49:57 +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
Benjamin Peterson9eea4802009-12-31 03:31:15 +000055This article explains the new features in Python 2.7. The final
Benjamin Petersond7c3ed52010-06-27 22:32:30 +000056release of 2.7 is currently scheduled for July 2010; the detailed
Benjamin Peterson9eea4802009-12-31 03:31:15 +000057schedule is described in :pep:`373`.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000058
Benjamin Petersond7c3ed52010-06-27 22:32:30 +000059Numeric handling has been improved in many ways, for both
60floating-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.
Benjamin Petersond69fe2a2010-02-03 02:59:43 +000066
Benjamin Petersond7c3ed52010-06-27 22:32:30 +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
72This 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.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000080
Benjamin Petersonf6489f92009-11-25 17:46:26 +000081.. _whatsnew27-python31:
82
Benjamin Petersond7c3ed52010-06-27 22:32:30 +000083The Future for Python 2.x
84=========================
85
86Python 2.7 is intended to be the last major release in the 2.x series.
87The Python maintainers are planning to focus their future efforts on
88the Python 3.x series.
89
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
96 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.
99
100* A policy decision was made to silence warnings only of interest to
101 developers. :exc:`DeprecationWarning` and its
102 descendants are now ignored unless otherwise requested, preventing
103 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`.)
106
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
116 that's actually working correctly and burdening application developers
117 with responding to these concerns.
118
119 You can re-enable display of :exc:`DeprecationWarning` messages by
120 running Python with the :option:`-Wdefault` (short form:
121 :option:`-Wd`) switch, or by setting the :envvar:`PYTHONWARNINGS`
122 environment variable to ``"default"`` (or ``"d"``) before running
123 Python. Python code can also re-enable them
124 by calling ``warnings.simplefilter('default')``.
125
126
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000127Python 3.1 Features
128=======================
Benjamin Petersond23f8222009-04-05 19:13:16 +0000129
130Much as Python 2.6 incorporated features from Python 3.0,
Benjamin Petersonf6489f92009-11-25 17:46:26 +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.
Benjamin Petersond23f8222009-04-05 19:13:16 +0000134
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000135A partial list of 3.1 features that were backported to 2.7:
136
Benjamin Petersond7c3ed52010-06-27 22:32:30 +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)}``).
139* Multiple context managers in a single :keyword:`with` statement.
140* A new version of the :mod:`io` library, rewritten in C for performance.
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000141* The ordered-dictionary type described in :ref:`pep-0372`.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000142* The new ``","`` format specifier described in :ref:`pep-0378`.
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000143* The :class:`memoryview` object.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000144* A small subset of the :mod:`importlib` module,
145 `described below <#importlib-section>`__.
Benjamin Peterson9eea4802009-12-31 03:31:15 +0000146* Float-to-string and string-to-float conversions now round their
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000147 results more correctly, and :func:`repr` of a floating-point
Benjamin Peterson9eea4802009-12-31 03:31:15 +0000148 number *x* returns a result that's guaranteed to round back to the
149 same number when converted back to a string.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000150* The :ctype:`PyCapsule` type, used to provide a C API for extension modules.
Benjamin Peterson9eea4802009-12-31 03:31:15 +0000151* The :cfunc:`PyLong_AsLongAndOverflow` C API function.
Benjamin Petersond23f8222009-04-05 19:13:16 +0000152
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000153Other new Python3-mode warnings include:
154
155* :func:`operator.isCallable` and :func:`operator.sequenceIncludes`,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +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
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000162
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000163.. ========================================================================
164.. Large, PEP-level features and changes should be described here.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000165.. ========================================================================
166
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000167.. _pep-0372:
168
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000169PEP 372: Adding an Ordered Dictionary to collections
Benjamin Petersond23f8222009-04-05 19:13:16 +0000170====================================================
171
Benjamin Petersonf6489f92009-11-25 17:46:26 +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
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000175the experiences from those implementations, 2.7 introduces a new
176:class:`~collections.OrderedDict` class in the :mod:`collections` module.
Benjamin Petersond23f8222009-04-05 19:13:16 +0000177
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000178The :class:`~collections.OrderedDict` API provides the same interface as regular
179dictionaries but iterates over keys and values in a guaranteed order
Ezio Melotti6c96ffe2010-04-07 04:27:14 +0000180depending on when a key was first inserted::
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000181
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000182 >>> from collections import OrderedDict
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000183 >>> d = OrderedDict([('first', 1),
184 ... ('second', 2),
Benjamin Petersonf6489f92009-11-25 17:46:26 +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 Melotti6c96ffe2010-04-07 04:27:14 +0000203The :meth:`~collections.OrderedDict.popitem` method has an optional *last*
204argument that defaults to True. If *last* is True, the most recently
Benjamin Petersonf6489f92009-11-25 17:46:26 +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 Melotti6c96ffe2010-04-07 04:27:14 +0000213 >>> od.popitem(last=False)
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000214 (0, 0)
Ezio Melotti6c96ffe2010-04-07 04:27:14 +0000215 >>> od.popitem(last=False)
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000216 (1, 0)
217
218Comparing two ordered dictionaries checks both the keys and values,
219and requires that the insertion order was the same::
220
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000221 >>> od1 = OrderedDict([('first', 1),
222 ... ('second', 2),
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000223 ... ('third', 3)])
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000224 >>> od2 = OrderedDict([('third', 3),
225 ... ('first', 1),
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000226 ... ('second', 2)])
Ezio Melotti6c96ffe2010-04-07 04:27:14 +0000227 >>> od1 == od2
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000228 False
229 >>> # Move 'third' key to the end
Ezio Melotti6c96ffe2010-04-07 04:27:14 +0000230 >>> del od2['third']; od2['third'] = 3
231 >>> od1 == od2
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000232 True
233
Ezio Melotti6c96ffe2010-04-07 04:27:14 +0000234Comparing an :class:`~collections.OrderedDict` with a regular dictionary
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000235ignores the insertion order and just compares the keys and values.
236
Ezio Melotti6c96ffe2010-04-07 04:27:14 +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
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000240deletion doesn't have to traverse the entire linked list and therefore
241remains O(1).
242
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000243The standard library now supports use of ordered dictionaries in several
Ezio Melotti11d22dc2010-04-20 09:55:05 +0000244modules.
245
Benjamin Petersond7c3ed52010-06-27 22:32:30 +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.
Ezio Melotti11d22dc2010-04-20 09:55:05 +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/>`_.
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000259
260.. 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.
265
266.. _pep-0378:
267
268PEP 378: Format Specifier for Thousands Separator
Ezio Melotti6c96ffe2010-04-07 04:27:14 +0000269=================================================
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000270
271To make program output more readable, it can be useful to add
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000272separators to large numbers, rendering them as
Benjamin Petersonf6489f92009-11-25 17:46:26 +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 Melotti6c96ffe2010-04-07 04:27:14 +0000282mini-language used by the :meth:`str.format` method. When
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000283formatting a floating-point number, simply include a comma between the
284width and the precision::
285
Eric Smith2b1a1162010-04-06 14:57:57 +0000286 >>> '{:20,.2f}'.format(18446744073709551616.0)
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000287 '18,446,744,073,709,551,616.00'
288
Eric Smith21e85c72010-04-06 15:21:59 +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
Benjamin Petersonf6489f92009-11-25 17:46:26 +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
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000299.. seealso::
300
301 :pep:`378` - Format Specifier for Thousands Separator
302 PEP written by Raymond Hettinger; implemented by Eric Smith.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000303
Benjamin Peterson9895f912010-03-21 22:05:32 +0000304PEP 389: The argparse Module for Parsing Command Lines
305======================================================
306
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000307The :mod:`argparse` module for parsing command-line arguments was
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000308added as a more powerful replacement for the
Benjamin Peterson08bf91c2010-04-11 16:12:57 +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
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000314library's :cfunc:`getopt` function, so it remains useful if you're writing a
Benjamin Peterson08bf91c2010-04-11 16:12:57 +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
Ezio Melotti11d22dc2010-04-20 09:55:05 +0000322In short, if you're writing a new script and don't need to worry
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000323about compatibility with earlier versions of Python, use
324:mod:`argparse` instead of :mod:`optparse`.
325
Ezio Melotti11d22dc2010-04-20 09:55:05 +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
353 usage: argparse-example.py [-h] [-v] [-o FILE] [-C NUM] [inputs [inputs ...]]
354
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
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000366As with :mod:`optparse`, the command-line switches and arguments
Ezio Melotti11d22dc2010-04-20 09:55:05 +0000367are returned as an object with attributes named by the *dest* parameters::
368
369 -> ./python.exe argparse-example.py -v
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000370 {'output': None,
371 'is_verbose': True,
372 'context': 0,
373 'inputs': []}
Ezio Melotti11d22dc2010-04-20 09:55:05 +0000374
375 -> ./python.exe argparse-example.py -v -o /tmp/output -C 4 file1 file2
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000376 {'output': '/tmp/output',
377 'is_verbose': True,
378 'context': 4,
Ezio Melotti11d22dc2010-04-20 09:55:05 +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
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000385sub-parsers to define subcommands that have different sets of
Ezio Melotti11d22dc2010-04-20 09:55:05 +0000386switches, as in ``svn commit``, ``svn checkout``, etc. You can
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000387specify an argument's type as :class:`~argparse.FileType`, which will
Ezio Melotti11d22dc2010-04-20 09:55:05 +0000388automatically open files for you and understands that ``'-'`` means
389standard input or output.
Benjamin Peterson9895f912010-03-21 22:05:32 +0000390
391.. seealso::
392
Benjamin Peterson08bf91c2010-04-11 16:12:57 +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>`__
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000396 Part of the Python documentation, describing how to convert
397 code that uses :mod:`optparse`.
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000398
Benjamin Peterson9895f912010-03-21 22:05:32 +0000399 :pep:`389` - argparse - New Command Line Parsing Module
400 PEP written and implemented by Steven Bethard.
401
402PEP 391: Dictionary-Based Configuration For Logging
403====================================================
404
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000405.. XXX not documented in library reference yet; add link here once it's added.
Ezio Melotti11d22dc2010-04-20 09:55:05 +0000406
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000407The :mod:`logging` module is very flexible; applications can define
Ezio Melotti11d22dc2010-04-20 09:55:05 +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,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000414but a complex set-up requires verbose but boring code.
Ezio Melotti11d22dc2010-04-20 09:55:05 +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
Benjamin Petersond7c3ed52010-06-27 22:32:30 +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.
Ezio Melotti11d22dc2010-04-20 09:55:05 +0000424
Benjamin Petersond7c3ed52010-06-27 22:32:30 +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.
Benjamin Peterson9895f912010-03-21 22:05:32 +0000430
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000431::
432
433 import logging
434 import logging.config
435
436 configdict = {
437 'version': 1, # Configuration schema in use; must be 1 for now
438 'formatters': {
439 'standard': {
440 'format': ('%(asctime)s %(name)-15s '
441 '%(levelname)-8s %(message)s')}},
442
443 'handlers': {'netlog': {'backupCount': 10,
444 'class': 'logging.handlers.RotatingFileHandler',
445 'filename': '/logs/network.log',
446 'formatter': 'standard',
447 'level': 'INFO',
448 'maxBytes': 1024*1024},
449 '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')
474
475Three smaller enhancements to the :mod:`logging` module, all
476implemented by Vinay Sajip, are:
Ezio Melotti6c96ffe2010-04-07 04:27:14 +0000477
478.. rev79293
479
Benjamin Petersond7c3ed52010-06-27 22:32:30 +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
486* :class:`Logger` instances gained a :meth:`getChild` method that retrieves a
Ezio Melotti6c96ffe2010-04-07 04:27:14 +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
Benjamin Peterson9895f912010-03-21 22:05:32 +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
Ezio Melotti11d22dc2010-04-20 09:55:05 +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
Ezio Melotti11d22dc2010-04-20 09:55:05 +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
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000511:meth:`viewkeys`, :meth:`viewvalues`, and :meth:`viewitems`.
Ezio Melotti11d22dc2010-04-20 09:55:05 +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
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000521Views can be iterated over, but the key and item views also behave
522like sets. The ``&`` operator performs intersection, and ``|``
523performs a union::
524
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
Ezio Melotti11d22dc2010-04-20 09:55:05 +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.
Benjamin Peterson9895f912010-03-21 22:05:32 +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
Benjamin Petersond7c3ed52010-06-27 22:32:30 +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
581The content of the view can be converted to a string of bytes or
582a list of integers:
583
584 >>> m2.tobytes()
585 'abcdefghijklmnopqrstuvwxyz'
586 >>> m2.tolist()
587 [97, 98, 99, 100, 101, 102, 103, ... 121, 122]
588 >>>
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.
610 Implemented by Travis Oliphant, Antoine Pitrou and others.
611 Backported to 2.7 by Antoine Pitrou; :issue:`2396`.
612
613
614
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000615Other Language Changes
616======================
617
618Some smaller changes made to the core Python language are:
619
Benjamin Peterson9895f912010-03-21 22:05:32 +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 Melotti6c96ffe2010-04-07 04:27:14 +0000629 >>> set() # empty set
Benjamin Peterson9895f912010-03-21 22:05:32 +0000630 set([])
Ezio Melotti6c96ffe2010-04-07 04:27:14 +0000631 >>> {} # empty dict
Benjamin Peterson9895f912010-03-21 22:05:32 +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
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000640 >>> {x: x*x for x in range(6)}
Benjamin Peterson9895f912010-03-21 22:05:32 +0000641 {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000642 >>> {('a'*x) for x in range(6)}
Benjamin Peterson9895f912010-03-21 22:05:32 +0000643 set(['', 'a', 'aa', 'aaa', 'aaaa', 'aaaaa'])
644
645 Backported by Alexandre Vassalotti; :issue:`2333`.
646
Benjamin Petersonf6489f92009-11-25 17:46:26 +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
Benjamin Peterson9eea4802009-12-31 03:31:15 +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;
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000672 numeric formatting; serializing and
673 deserializing floats and complex numbers using the
Benjamin Peterson9eea4802009-12-31 03:31:15 +0000674 :mod:`marshal`, :mod:`pickle`
675 and :mod:`json` modules;
676 parsing of float and imaginary literals in Python code;
Ezio Melotti6c96ffe2010-04-07 04:27:14 +0000677 and :class:`~decimal.Decimal`-to-float conversion.
Benjamin Peterson9eea4802009-12-31 03:31:15 +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 Melotti6c96ffe2010-04-07 04:27:14 +0000685 .. maybe add an example?
686
Benjamin Peterson9eea4802009-12-31 03:31:15 +0000687 The rounding library responsible for this improvement works on
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000688 Windows and on Unix platforms using the gcc, icc, or suncc
Benjamin Peterson9eea4802009-12-31 03:31:15 +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
Benjamin Petersona28e7022010-01-09 18:53:06 +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.
Benjamin Peterson9eea4802009-12-31 03:31:15 +0000694
Mark Dickinson0bc8f902010-01-07 09:31:48 +0000695 Implemented by Eric Smith and Mark Dickinson, using David Gay's
696 :file:`dtoa.c` library; :issue:`7117`.
Benjamin Peterson9eea4802009-12-31 03:31:15 +0000697
Benjamin Peterson25c95f12009-05-08 20:42:26 +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
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000702 unavoidably lose precision, Python 2.7 now approximates more
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000703 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
Ezio Melotti6c96ffe2010-04-07 04:27:14 +0000717 >>> n - long(float(n))
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000718 -1L
719
720 (Implemented by Mark Dickinson; :issue:`3166`.)
721
Benjamin Peterson9eea4802009-12-31 03:31:15 +0000722 Integer division is also more accurate in its rounding behaviours. (Also
723 implemented by Mark Dickinson; :issue:`1811`.)
724
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000725* Implicit coercion for complex numbers has been removed; the interpreter
726 will no longer ever attempt to call a :meth:`__coerce__` method on complex
727 objects. (Removed by Meador Inge and Mark Dickinson; :issue:`5211`.)
728
729* The :meth:`str.format` method now supports automatic numbering of the replacement
730 fields. This makes using :meth:`str.format` more closely resemble using
731 ``%s`` formatting::
732
733 >>> '{}:{}:{}'.format(2009, 04, 'Sunday')
734 '2009:4:Sunday'
735 >>> '{}:{}:{day}'.format(2009, 4, day='Sunday')
736 '2009:4:Sunday'
737
738 The auto-numbering takes the fields from left to right, so the first ``{...}``
739 specifier will use the first argument to :meth:`str.format`, the next
740 specifier will use the next argument, and so on. You can't mix auto-numbering
741 and explicit numbering -- either number all of your specifier fields or none
742 of them -- but you can mix auto-numbering and named fields, as in the second
743 example above. (Contributed by Eric Smith; :issue:`5237`.)
744
745 Complex numbers now correctly support usage with :func:`format`,
746 and default to being right-aligned.
747 Specifying a precision or comma-separation applies to both the real
748 and imaginary parts of the number, but a specified field width and
749 alignment is applied to the whole of the resulting ``1.5+3j``
750 output. (Contributed by Eric Smith; :issue:`1588` and :issue:`7988`.)
751
752 The 'F' format code now always formats its output using uppercase characters,
753 so it will now produce 'INF' and 'NAN'.
754 (Contributed by Eric Smith; :issue:`3382`.)
755
756 A low-level change: the :meth:`object.__format__` method now triggers
757 a :exc:`PendingDeprecationWarning` if it's passed a format string,
758 because the :meth:`__format__` method for :class:`object` converts
759 the object to a string representation and formats that. Previously
760 the method silently applied the format string to the string
761 representation, but that could hide mistakes in Python code. If
762 you're supplying formatting information such as an alignment or
763 precision, presumably you're expecting the formatting to be applied
764 in some object-specific way. (Fixed by Eric Smith; :issue:`7994`.)
765
766* The :func:`int` and :func:`long` types gained a ``bit_length``
767 method that returns the number of bits necessary to represent
768 its argument in binary::
769
770 >>> n = 37
771 >>> bin(n)
772 '0b100101'
773 >>> n.bit_length()
774 6
775 >>> n = 2**123-1
776 >>> n.bit_length()
777 123
778 >>> (n+1).bit_length()
779 124
780
781 (Contributed by Fredrik Johansson and Victor Stinner; :issue:`3439`.)
782
783* The :keyword:`import` statement will no longer try a relative import
784 if an absolute import (e.g. ``from .os import sep``) fails. This
785 fixes a bug, but could possibly break certain :keyword:`import`
786 statements that were only working by accident. (Fixed by Meador Inge;
787 :issue:`7902`.)
788
Ezio Melotti6c96ffe2010-04-07 04:27:14 +0000789* It's now possible for a subclass of the built-in :class:`unicode` type
790 to override the :meth:`__unicode__` method. (Implemented by
791 Victor Stinner; :issue:`1583863`.)
792
793* The :class:`bytearray` type's :meth:`~bytearray.translate` method now accepts
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000794 ``None`` as its first argument. (Fixed by Georg Brandl;
Benjamin Petersond23f8222009-04-05 19:13:16 +0000795 :issue:`4759`.)
Mark Dickinsond72c7b62009-03-20 16:00:49 +0000796
Ezio Melotti6c96ffe2010-04-07 04:27:14 +0000797 .. bytearray doesn't seem to be documented
798
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000799* When using ``@classmethod`` and ``@staticmethod`` to wrap
800 methods as class or static methods, the wrapper object now
801 exposes the wrapped function as their :attr:`__func__` attribute.
802 (Contributed by Amaury Forgeot d'Arc, after a suggestion by
803 George Sakkis; :issue:`5982`.)
804
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000805* When a restricted set of attributes were set using ``__slots__``,
806 deleting an unset attribute would not raise :exc:`AttributeError`
807 as you would expect. Fixed by Benjamin Peterson; :issue:`7604`.)
808
809* Two new encodings are now supported: "cp720", used primarily for
810 Arabic text; and "cp858", a variant of CP 850 that adds the euro
811 symbol. (CP720 contributed by Alexander Belchenko and Amaury
812 Forgeot d'Arc in :issue:`1616979`; CP858 contributed by Tim Hatch in
813 :issue:`8016`.)
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000814
Benjamin Peterson9eea4802009-12-31 03:31:15 +0000815* The :class:`file` object will now set the :attr:`filename` attribute
816 on the :exc:`IOError` exception when trying to open a directory
Benjamin Peterson9895f912010-03-21 22:05:32 +0000817 on POSIX platforms (noted by Jan Kaliszewski; :issue:`4764`), and
818 now explicitly checks for and forbids writing to read-only file objects
819 instead of trusting the C library to catch and report the error
820 (fixed by Stefan Krah; :issue:`5677`).
Benjamin Peterson9eea4802009-12-31 03:31:15 +0000821
Benjamin Petersona28e7022010-01-09 18:53:06 +0000822* The Python tokenizer now translates line endings itself, so the
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000823 :func:`compile` built-in function now accepts code using any
Benjamin Petersona28e7022010-01-09 18:53:06 +0000824 line-ending convention. Additionally, it no longer requires that the
825 code end in a newline.
826
Benjamin Peterson9eea4802009-12-31 03:31:15 +0000827* Extra parentheses in function definitions are illegal in Python 3.x,
828 meaning that you get a syntax error from ``def f((x)): pass``. In
829 Python3-warning mode, Python 2.7 will now warn about this odd usage.
830 (Noted by James Lingard; :issue:`7362`.)
831
Ezio Melotti11d22dc2010-04-20 09:55:05 +0000832* It's now possible to create weak references to old-style class
833 objects. New-style classes were always weak-referenceable. (Fixed
834 by Antoine Pitrou; :issue:`8268`.)
835
Benjamin Peterson9895f912010-03-21 22:05:32 +0000836* When a module object is garbage-collected, the module's dictionary is
837 now only cleared if no one else is holding a reference to the
838 dictionary (:issue:`7140`).
839
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000840.. ======================================================================
841
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000842.. _new-27-interpreter:
843
844Interpreter Changes
845-------------------------------
846
847A new environment variable, :envvar:`PYTHONWARNINGS`,
848allows controlling warnings. It should be set to a string
849containing warning settings, equivalent to those
850used with the :option:`-W` switch, separated by commas.
851(Contributed by Brian Curtin; :issue:`7301`.)
852
853For example, the following setting will print warnings every time
854they occur, but turn warnings from the :mod:`Cookie` module into an
855error. (The exact syntax for setting an environment variable varies
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000856across operating systems and shells.)
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000857
858::
859
860 export PYTHONWARNINGS=all,error:::Cookie:0
861
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000862When running a module using the interpreter's :option:`-m` switch,
863``sys.argv[0]`` will now be set to the string ``'-m'`` while the
Nick Coghlan9fc68c42010-07-02 15:57:50 +0000864module is being located. This change is visible to user code while
865executing the :file:`__init__.py` files for any parent packages of
866the module to be executed. (Suggested by Michael Foord; implemented
867by Nick Coghlan; :issue:`8202`.)
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000868
869.. ======================================================================
870
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000871
872Optimizations
873-------------
874
Benjamin Petersond23f8222009-04-05 19:13:16 +0000875Several performance enhancements have been added:
876
877.. * A new :program:`configure` option, :option:`--with-computed-gotos`,
878 compiles the main bytecode interpreter loop using a new dispatch
879 mechanism that gives speedups of up to 20%, depending on the system
880 and benchmark. The new mechanism is only supported on certain
881 compilers, such as gcc, SunPro, and icc.
Benjamin Peterson1010bf32009-01-30 04:00:29 +0000882
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000883* A new opcode was added to perform the initial setup for
884 :keyword:`with` statements, looking up the :meth:`__enter__` and
885 :meth:`__exit__` methods. (Contributed by Benjamin Peterson.)
886
Benjamin Peterson9eea4802009-12-31 03:31:15 +0000887* The garbage collector now performs better for one common usage
888 pattern: when many objects are being allocated without deallocating
889 any of them. This would previously take quadratic
890 time for garbage collection, but now the number of full garbage collections
891 is reduced as the number of objects on the heap grows.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000892 The new logic only performs a full garbage collection pass when
Benjamin Peterson9eea4802009-12-31 03:31:15 +0000893 the middle generation has been collected 10 times and when the
894 number of survivor objects from the middle generation exceeds 10% of
895 the number of objects in the oldest generation. (Suggested by Martin
Ezio Melotti6c96ffe2010-04-07 04:27:14 +0000896 von Löwis and implemented by Antoine Pitrou; :issue:`4074`.)
Benjamin Peterson1010bf32009-01-30 04:00:29 +0000897
Benjamin Petersond23f8222009-04-05 19:13:16 +0000898* The garbage collector tries to avoid tracking simple containers
899 which can't be part of a cycle. In Python 2.7, this is now true for
900 tuples and dicts containing atomic types (such as ints, strings,
901 etc.). Transitively, a dict containing tuples of atomic types won't
902 be tracked either. This helps reduce the cost of each
903 garbage collection by decreasing the number of objects to be
904 considered and traversed by the collector.
Antoine Pitrou9d81def2009-03-28 19:20:09 +0000905 (Contributed by Antoine Pitrou; :issue:`4688`.)
906
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000907* Long integers are now stored internally either in base 2**15 or in base
Benjamin Petersond23f8222009-04-05 19:13:16 +0000908 2**30, the base being determined at build time. Previously, they
909 were always stored in base 2**15. Using base 2**30 gives
910 significant performance improvements on 64-bit machines, but
911 benchmark results on 32-bit machines have been mixed. Therefore,
912 the default is to use base 2**30 on 64-bit machines and base 2**15
913 on 32-bit machines; on Unix, there's a new configure option
914 :option:`--enable-big-digits` that can be used to override this default.
915
916 Apart from the performance improvements this change should be
917 invisible to end users, with one exception: for testing and
Ezio Melotti6c96ffe2010-04-07 04:27:14 +0000918 debugging purposes there's a new structseq :data:`sys.long_info` that
Benjamin Petersond23f8222009-04-05 19:13:16 +0000919 provides information about the internal format, giving the number of
920 bits per digit and the size in bytes of the C type used to store
921 each digit::
922
923 >>> import sys
924 >>> sys.long_info
925 sys.long_info(bits_per_digit=30, sizeof_digit=4)
926
927 (Contributed by Mark Dickinson; :issue:`4258`.)
928
929 Another set of changes made long objects a few bytes smaller: 2 bytes
930 smaller on 32-bit systems and 6 bytes on 64-bit.
931 (Contributed by Mark Dickinson; :issue:`5260`.)
932
933* The division algorithm for long integers has been made faster
934 by tightening the inner loop, doing shifts instead of multiplications,
935 and fixing an unnecessary extra iteration.
936 Various benchmarks show speedups of between 50% and 150% for long
937 integer divisions and modulo operations.
938 (Contributed by Mark Dickinson; :issue:`5512`.)
Benjamin Petersona28e7022010-01-09 18:53:06 +0000939 Bitwise operations are also significantly faster (initial patch by
940 Gregory Smith; :issue:`1087418`).
Benjamin Petersond23f8222009-04-05 19:13:16 +0000941
942* The implementation of ``%`` checks for the left-side operand being
943 a Python string and special-cases it; this results in a 1-3%
944 performance increase for applications that frequently use ``%``
945 with strings, such as templating libraries.
946 (Implemented by Collin Winter; :issue:`5176`.)
947
948* List comprehensions with an ``if`` condition are compiled into
949 faster bytecode. (Patch by Antoine Pitrou, back-ported to 2.7
950 by Jeffrey Yasskin; :issue:`4715`.)
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000951
Benjamin Petersona28e7022010-01-09 18:53:06 +0000952* Converting an integer or long integer to a decimal string was made
953 faster by special-casing base 10 instead of using a generalized
954 conversion function that supports arbitrary bases.
955 (Patch by Gawain Bolton; :issue:`6713`.)
956
Benjamin Petersond69fe2a2010-02-03 02:59:43 +0000957* The :meth:`split`, :meth:`replace`, :meth:`rindex`,
958 :meth:`rpartition`, and :meth:`rsplit` methods of string-like types
959 (strings, Unicode strings, and :class:`bytearray` objects) now use a
960 fast reverse-search algorithm instead of a character-by-character
961 scan. This is sometimes faster by a factor of 10. (Added by
962 Florent Xicluna; :issue:`7462` and :issue:`7622`.)
Benjamin Petersona28e7022010-01-09 18:53:06 +0000963
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000964* The :mod:`pickle` and :mod:`cPickle` modules now automatically
965 intern the strings used for attribute names, reducing memory usage
966 of the objects resulting from unpickling. (Contributed by Jake
967 McGuire; :issue:`5084`.)
968
969* The :mod:`cPickle` module now special-cases dictionaries,
970 nearly halving the time required to pickle them.
971 (Contributed by Collin Winter; :issue:`5670`.)
972
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000973.. ======================================================================
974
Georg Brandl4d131ee2009-11-18 18:53:14 +0000975New and Improved Modules
976========================
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000977
978As in every release, Python's standard library received a number of
979enhancements and bug fixes. Here's a partial list of the most notable
980changes, sorted alphabetically by module name. Consult the
981:file:`Misc/NEWS` file in the source tree for a more complete list of
982changes, or look through the Subversion logs for all the details.
983
Ezio Melotti6c96ffe2010-04-07 04:27:14 +0000984* The :mod:`bdb` module's base debugging class :class:`~bdb.Bdb`
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000985 gained a feature for skipping modules. The constructor
986 now takes an iterable containing glob-style patterns such as
987 ``django.*``; the debugger will not step into stack frames
988 from a module that matches one of these patterns.
989 (Contributed by Maru Newby after a suggestion by
990 Senthil Kumaran; :issue:`5142`.)
991
Benjamin Peterson9895f912010-03-21 22:05:32 +0000992* The :mod:`binascii` module now supports the buffer API, so it can be
993 used with :class:`memoryview` instances and other similar buffer objects.
994 (Backported from 3.x by Florent Xicluna; :issue:`7703`.)
995
Ezio Melotti6c96ffe2010-04-07 04:27:14 +0000996* Updated module: the :mod:`bsddb` module has been updated from 4.7.2devel9
997 to version 4.8.4 of
998 `the pybsddb package <http://www.jcea.es/programacion/pybsddb.htm>`__.
999 The new version features better Python 3.x compatibility, various bug fixes,
1000 and adds several new BerkeleyDB flags and methods.
1001 (Updated by Jesús Cea Avión; :issue:`8156`. The pybsddb
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001002 changelog can be read at http://hg.jcea.es/pybsddb/file/tip/ChangeLog.)
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001003
1004* The :mod:`bz2` module's :class:`~bz2.BZ2File` now supports the context
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001005 management protocol, so you can write ``with bz2.BZ2File(...) as f:``.
1006 (Contributed by Hagen Fürstenau; :issue:`3860`.)
Benjamin Peterson1010bf32009-01-30 04:00:29 +00001007
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001008* New class: the :class:`~collections.Counter` class in the :mod:`collections`
1009 module is useful for tallying data. :class:`~collections.Counter` instances
1010 behave mostly like dictionaries but return zero for missing keys instead of
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001011 raising a :exc:`KeyError`:
Benjamin Peterson1010bf32009-01-30 04:00:29 +00001012
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001013 .. doctest::
1014 :options: +NORMALIZE_WHITESPACE
1015
1016 >>> from collections import Counter
1017 >>> c = Counter()
1018 >>> for letter in 'here is a sample of english text':
1019 ... c[letter] += 1
1020 ...
1021 >>> c
1022 Counter({' ': 6, 'e': 5, 's': 3, 'a': 2, 'i': 2, 'h': 2,
1023 'l': 2, 't': 2, 'g': 1, 'f': 1, 'm': 1, 'o': 1, 'n': 1,
1024 'p': 1, 'r': 1, 'x': 1})
1025 >>> c['e']
1026 5
1027 >>> c['z']
1028 0
Benjamin Peterson1010bf32009-01-30 04:00:29 +00001029
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001030 There are three additional :class:`~collections.Counter` methods.
Ezio Melotti11d22dc2010-04-20 09:55:05 +00001031 :meth:`~collections.Counter.most_common` returns the N most common
1032 elements and their counts. :meth:`~collections.Counter.elements`
1033 returns an iterator over the contained elements, repeating each
1034 element as many times as its count.
1035 :meth:`~collections.Counter.subtract` takes an iterable and
1036 subtracts one for each element instead of adding; if the argument is
1037 a dictionary or another :class:`Counter`, the counts are
1038 subtracted. ::
Benjamin Peterson1010bf32009-01-30 04:00:29 +00001039
1040 >>> c.most_common(5)
1041 [(' ', 6), ('e', 5), ('s', 3), ('a', 2), ('i', 2)]
1042 >>> c.elements() ->
1043 'a', 'a', ' ', ' ', ' ', ' ', ' ', ' ',
1044 'e', 'e', 'e', 'e', 'e', 'g', 'f', 'i', 'i',
1045 'h', 'h', 'm', 'l', 'l', 'o', 'n', 'p', 's',
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001046 's', 's', 'r', 't', 't', 'x'
Ezio Melotti11d22dc2010-04-20 09:55:05 +00001047 >>> c['e']
1048 5
1049 >>> c.subtract('very heavy on the letter e')
1050 >>> c['e'] # Count is now lower
1051 -1
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001052
Benjamin Peterson1010bf32009-01-30 04:00:29 +00001053 Contributed by Raymond Hettinger; :issue:`1696199`.
1054
Ezio Melotti11d22dc2010-04-20 09:55:05 +00001055 .. revision 79660
1056
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001057 New class: :class:`~collections.OrderedDict` is described in the earlier
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001058 section :ref:`pep-0372`.
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001059
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001060 New method: The :class:`~collections.deque` data type now has a
1061 :meth:`~collections.deque.count` method that returns the number of
1062 contained elements equal to the supplied argument *x*, and a
1063 :meth:`~collections.deque.reverse` method that reverses the elements
1064 of the deque in-place. :class:`deque` also exposes its maximum
1065 length as the read-only :attr:`~collections.deque.maxlen` attribute.
1066 (Both features added by Raymond Hettinger.)
1067
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001068 The :class:`~collections.namedtuple` class now has an optional *rename* parameter.
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001069 If *rename* is true, field names that are invalid because they've
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001070 been repeated or aren't legal Python identifiers will be
Benjamin Petersond23f8222009-04-05 19:13:16 +00001071 renamed to legal names that are derived from the field's
1072 position within the list of fields:
1073
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001074 >>> from collections import namedtuple
1075 >>> T = namedtuple('T', ['field1', '$illegal', 'for', 'field2'], rename=True)
Benjamin Petersond23f8222009-04-05 19:13:16 +00001076 >>> T._fields
1077 ('field1', '_1', '_2', 'field2')
1078
1079 (Added by Raymond Hettinger; :issue:`1818`.)
1080
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001081 Finally, the :class:`~collections.Mapping` abstract base class now
1082 raises a :exc:`NotImplemented` exception if a mapping is compared to
1083 another type that isn't a :class:`Mapping`.
1084 (Fixed by Daniel Stutzbach; :issue:`8729`.)
1085
1086* Constructors for the parsing classes in the :mod:`ConfigParser` module now
1087 take a *allow_no_value* parameter, defaulting to false; if true,
1088 options without values will be allowed. For example::
1089
1090 >>> import ConfigParser, StringIO
1091 >>> sample_config = """
1092 ... [mysqld]
1093 ... user = mysql
1094 ... pid-file = /var/run/mysqld/mysqld.pid
1095 ... skip-bdb
1096 ... """
1097 >>> config = ConfigParser.RawConfigParser(allow_no_value=True)
1098 >>> config.readfp(StringIO.StringIO(sample_config))
1099 >>> config.get('mysqld', 'user')
1100 'mysql'
1101 >>> print config.get('mysqld', 'skip-bdb')
1102 None
1103 >>> print config.get('mysqld', 'unknown')
1104 Traceback (most recent call last):
1105 ...
1106 NoOptionError: No option 'unknown' in section: 'mysqld'
1107
1108 (Contributed by Mats Kindahl; :issue:`7005`.)
1109
1110* Deprecated function: :func:`contextlib.nested`, which allows
1111 handling more than one context manager with a single :keyword:`with`
1112 statement, has been deprecated, because the :keyword:`with` statement
1113 now supports multiple context managers.
1114
1115* The :mod:`cookielib` module now ignores cookies that have an invalid
1116 version field, one that doesn't contain an integer value. (Fixed by
1117 John J. Lee; :issue:`3924`.)
Benjamin Peterson9eea4802009-12-31 03:31:15 +00001118
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001119* The :mod:`copy` module's :func:`~copy.deepcopy` function will now
Benjamin Peterson9eea4802009-12-31 03:31:15 +00001120 correctly copy bound instance methods. (Implemented by
1121 Robert Collins; :issue:`1515`.)
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001122
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001123* The :mod:`ctypes` module now always converts ``None`` to a C NULL
1124 pointer for arguments declared as pointers. (Changed by Thomas
Benjamin Peterson9895f912010-03-21 22:05:32 +00001125 Heller; :issue:`4606`.) The underlying `libffi library
1126 <http://sourceware.org/libffi/>`__ has been updated to version
1127 3.0.9, containing various fixes for different platforms. (Updated
1128 by Matthias Klose; :issue:`8142`.)
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001129
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001130* New method: the :mod:`datetime` module's :class:`~datetime.timedelta` class
1131 gained a :meth:`~datetime.timedelta.total_seconds` method that returns the
1132 number of seconds in the duration. (Contributed by Brian Quinlan; :issue:`5788`.)
Benjamin Peterson9eea4802009-12-31 03:31:15 +00001133
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001134* New method: the :class:`~decimal.Decimal` class gained a
1135 :meth:`~decimal.Decimal.from_float` class method that performs an exact
1136 conversion of a floating-point number to a :class:`~decimal.Decimal`.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001137 This exact conversion strives for the
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001138 closest decimal approximation to the floating-point representation's value;
1139 the resulting decimal value will therefore still include the inaccuracy,
1140 if any.
1141 For example, ``Decimal.from_float(0.1)`` returns
1142 ``Decimal('0.1000000000000000055511151231257827021181583404541015625')``.
1143 (Implemented by Raymond Hettinger; :issue:`4796`.)
1144
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001145 Comparing instances of :class:`Decimal` with floating-point
1146 numbers now produces sensible results based on the numeric values
1147 of the operands. Previously such comparisons would fall back to
1148 Python's default rules for comparing objects, which produced arbitrary
1149 results based on their type. Note that you still cannot combine
1150 :class:`Decimal` and floating-point in other operations such as addition,
1151 since you should be explicitly choosing how to convert between float and
1152 :class:`Decimal`.
1153 (Fixed by Mark Dickinson; :issue:`2531`.)
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001154
Ezio Melotti11d22dc2010-04-20 09:55:05 +00001155 The constructor for :class:`~decimal.Decimal` now accepts
1156 floating-point numbers (added by Raymond Hettinger; :issue:`8257`)
1157 and non-European Unicode characters such as Arabic-Indic digits
1158 (contributed by Mark Dickinson; :issue:`6595`).
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001159
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001160 Most of the methods of the :class:`~decimal.Context` class now accept integers
1161 as well as :class:`~decimal.Decimal` instances; the only exceptions are the
1162 :meth:`~decimal.Context.canonical` and :meth:`~decimal.Context.is_canonical`
1163 methods. (Patch by Juan José Conti; :issue:`7633`.)
1164
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001165 When using :class:`~decimal.Decimal` instances with a string's
1166 :meth:`~str.format` method, the default alignment was previously
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001167 left-alignment. This has been changed to right-alignment, which is
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001168 more sensible for numeric types. (Changed by Mark Dickinson; :issue:`6857`.)
1169
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001170 Comparisons involving a signaling NaN value (or ``sNAN``) now signal
1171 :const:`InvalidOperation` instead of silently returning a true or
1172 false value depending on the comparison operator. Quiet NaN values
1173 (or ``NaN``) are now hashable. (Fixed by Mark Dickinson;
1174 :issue:`7279`.)
1175
Ezio Melotti11d22dc2010-04-20 09:55:05 +00001176* The :mod:`difflib` module now produces output that is more
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001177 compatible with modern :command:`diff`/:command:`patch` tools
1178 through one small change, using a tab character instead of spaces as
1179 a separator in the header giving the filename. (Fixed by Anatoly
1180 Techtonik; :issue:`7585`.)
1181
1182* The Distutils ``sdist`` command now always regenerates the
1183 :file:`MANIFEST` file, since even if the :file:`MANIFEST.in` or
1184 :file:`setup.py` files haven't been modified, the user might have
1185 created some new files that should be included.
1186 (Fixed by Tarek Ziadé; :issue:`8688`.)
1187
1188* The :mod:`doctest` module's :const:`IGNORE_EXCEPTION_DETAIL` flag
1189 will now ignore the name of the module containing the exception
1190 being tested. (Patch by Lennart Regebro; :issue:`7490`.)
1191
1192* The :mod:`email` module's :class:`~email.message.Message` class will
1193 now accept a Unicode-valued payload, automatically converting the
1194 payload to the encoding specified by :attr:`output_charset`.
1195 (Added by R. David Murray; :issue:`1368247`.)
Ezio Melotti11d22dc2010-04-20 09:55:05 +00001196
1197* The :class:`~fractions.Fraction` class now accepts a single float or
1198 :class:`~decimal.Decimal` instance, or two rational numbers, as
1199 arguments to its constructor. (Implemented by Mark Dickinson;
1200 rationals added in :issue:`5812`, and float/decimal in
1201 :issue:`8294`.)
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001202
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001203 Ordering comparisons (``<``, ``<=``, ``>``, ``>=``) between
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00001204 fractions and complex numbers now raise a :exc:`TypeError`.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001205 This fixes an oversight, making the :class:`Fraction` match the other
1206 numeric types.
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00001207
1208 .. revision 79455
1209
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001210* New class: :class:`~ftplib.FTP_TLS` in
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001211 the :mod:`ftplib` module provides secure FTP
Benjamin Peterson9eea4802009-12-31 03:31:15 +00001212 connections using TLS encapsulation of authentication as well as
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001213 subsequent control and data transfers.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001214 (Contributed by Giampaolo Rodola; :issue:`2054`.)
Benjamin Peterson9eea4802009-12-31 03:31:15 +00001215
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001216 The :meth:`~ftplib.FTP.storbinary` method for binary uploads can now restart
1217 uploads thanks to an added *rest* parameter (patch by Pablo Mouzo;
1218 :issue:`6845`.)
1219
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00001220* New class decorator: :func:`total_ordering` in the :mod:`functools`
1221 module takes a class that defines an :meth:`__eq__` method and one of
1222 :meth:`__lt__`, :meth:`__le__`, :meth:`__gt__`, or :meth:`__ge__`,
1223 and generates the missing comparison methods. Since the
1224 :meth:`__cmp__` method is being deprecated in Python 3.x,
1225 this decorator makes it easier to define ordered classes.
1226 (Added by Raymond Hettinger; :issue:`5479`.)
1227
1228 New function: :func:`cmp_to_key` will take an old-style comparison
1229 function that expects two arguments and return a new callable that
1230 can be used as the *key* parameter to functions such as
1231 :func:`sorted`, :func:`min` and :func:`max`, etc. The primary
1232 intended use is to help with making code compatible with Python 3.x.
1233 (Added by Raymond Hettinger.)
1234
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001235* New function: the :mod:`gc` module's :func:`~gc.is_tracked` returns
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001236 true if a given instance is tracked by the garbage collector, false
Benjamin Petersond23f8222009-04-05 19:13:16 +00001237 otherwise. (Contributed by Antoine Pitrou; :issue:`4688`.)
1238
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001239* The :mod:`gzip` module's :class:`~gzip.GzipFile` now supports the context
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001240 management protocol, so you can write ``with gzip.GzipFile(...) as f:``
1241 (contributed by Hagen Fürstenau; :issue:`3860`), and it now implements
Benjamin Peterson9895f912010-03-21 22:05:32 +00001242 the :class:`io.BufferedIOBase` ABC, so you can wrap it with
1243 :class:`io.BufferedReader` for faster processing
1244 (contributed by Nir Aides; :issue:`7471`).
1245 It's also now possible to override the modification time
Benjamin Petersond23f8222009-04-05 19:13:16 +00001246 recorded in a gzipped file by providing an optional timestamp to
1247 the constructor. (Contributed by Jacques Frechet; :issue:`4272`.)
Benjamin Peterson1010bf32009-01-30 04:00:29 +00001248
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00001249 Files in gzip format can be padded with trailing zero bytes; the
1250 :mod:`gzip` module will now consume these trailing bytes. (Fixed by
1251 Tadek Pietraszek and Brian Curtin; :issue:`2846`.)
1252
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001253* New attribute: the :mod:`hashlib` module now has an :attr:`~hashlib.hashlib.algorithms`
1254 attribute containing a tuple naming the supported algorithms.
1255 In Python 2.7, ``hashlib.algorithms`` contains
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001256 ``('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')``.
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001257 (Contributed by Carl Chenet; :issue:`7418`.)
1258
1259* The default :class:`~httplib.HTTPResponse` class used by the :mod:`httplib` module now
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001260 supports buffering, resulting in much faster reading of HTTP responses.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001261 (Contributed by Kristján Valur Jónsson; :issue:`4879`.)
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001262
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001263 The :class:`~httplib.HTTPConnection` and :class:`~httplib.HTTPSConnection` classes
Benjamin Peterson9895f912010-03-21 22:05:32 +00001264 now support a *source_address* parameter, a ``(host, port)`` 2-tuple
1265 giving the source address that will be used for the connection.
1266 (Contributed by Eldon Ziegler; :issue:`3972`.)
1267
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001268* The :mod:`ihooks` module now supports relative imports. Note that
1269 :mod:`ihooks` is an older module for customizing imports,
1270 superseded by the :mod:`imputil` module added in Python 2.0.
1271 (Relative import support added by Neil Schemenauer.)
1272
1273 .. revision 75423
1274
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001275* The :mod:`imaplib` module now supports IPv6 addresses.
1276 (Contributed by Derek Morr; :issue:`1655`.)
1277
Ezio Melotti11d22dc2010-04-20 09:55:05 +00001278* New function: the :mod:`inspect` module's :func:`~inspect.getcallargs`
1279 takes a callable and its positional and keyword arguments,
1280 and figures out which of the callable's parameters will receive each argument,
1281 returning a dictionary mapping argument names to their values. For example::
1282
1283 >>> from inspect import getcallargs
1284 >>> def f(a, b=1, *pos, **named):
1285 ... pass
1286 >>> getcallargs(f, 1, 2, 3)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001287 {'a': 1, 'b': 2, 'pos': (3,), 'named': {}}
Ezio Melotti11d22dc2010-04-20 09:55:05 +00001288 >>> getcallargs(f, a=2, x=4)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001289 {'a': 2, 'b': 1, 'pos': (), 'named': {'x': 4}}
Ezio Melotti11d22dc2010-04-20 09:55:05 +00001290 >>> getcallargs(f)
1291 Traceback (most recent call last):
1292 ...
1293 TypeError: f() takes at least 1 argument (0 given)
1294
1295 Contributed by George Sakkis; :issue:`3135`.
1296
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001297* Updated module: The :mod:`io` library has been upgraded to the version shipped with
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001298 Python 3.1. For 3.1, the I/O library was entirely rewritten in C
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001299 and is 2 to 20 times faster depending on the task being performed. The
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001300 original Python version was renamed to the :mod:`_pyio` module.
1301
1302 One minor resulting change: the :class:`io.TextIOBase` class now
1303 has an :attr:`errors` attribute giving the error setting
1304 used for encoding and decoding errors (one of ``'strict'``, ``'replace'``,
1305 ``'ignore'``).
1306
1307 The :class:`io.FileIO` class now raises an :exc:`OSError` when passed
Benjamin Peterson1010bf32009-01-30 04:00:29 +00001308 an invalid file descriptor. (Implemented by Benjamin Peterson;
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001309 :issue:`4991`.) The :meth:`~io.IOBase.truncate` method now preserves the
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00001310 file position; previously it would change the file position to the
1311 end of the new file. (Fixed by Pascal Chambon; :issue:`6939`.)
Benjamin Peterson1010bf32009-01-30 04:00:29 +00001312
Benjamin Peterson97dd9872009-12-13 01:23:39 +00001313* New function: ``itertools.compress(data, selectors)`` takes two
Benjamin Petersond23f8222009-04-05 19:13:16 +00001314 iterators. Elements of *data* are returned if the corresponding
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001315 value in *selectors* is true::
Benjamin Petersond23f8222009-04-05 19:13:16 +00001316
1317 itertools.compress('ABCDEF', [1,0,1,0,1,1]) =>
1318 A, C, E, F
1319
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001320 .. maybe here is better to use >>> list(itertools.compress(...)) instead
1321
Benjamin Peterson97dd9872009-12-13 01:23:39 +00001322 New function: ``itertools.combinations_with_replacement(iter, r)``
Benjamin Petersond23f8222009-04-05 19:13:16 +00001323 returns all the possible *r*-length combinations of elements from the
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001324 iterable *iter*. Unlike :func:`~itertools.combinations`, individual elements
Benjamin Petersond23f8222009-04-05 19:13:16 +00001325 can be repeated in the generated combinations::
1326
1327 itertools.combinations_with_replacement('abc', 2) =>
1328 ('a', 'a'), ('a', 'b'), ('a', 'c'),
1329 ('b', 'b'), ('b', 'c'), ('c', 'c')
1330
1331 Note that elements are treated as unique depending on their position
1332 in the input, not their actual values.
1333
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001334 The :func:`itertools.count` function now has a *step* argument that
1335 allows incrementing by values other than 1. :func:`~itertools.count` also
Benjamin Petersond23f8222009-04-05 19:13:16 +00001336 now allows keyword arguments, and using non-integer values such as
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001337 floats or :class:`~decimal.Decimal` instances. (Implemented by Raymond
Benjamin Petersond23f8222009-04-05 19:13:16 +00001338 Hettinger; :issue:`5032`.)
1339
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001340 :func:`itertools.combinations` and :func:`itertools.product`
1341 previously raised :exc:`ValueError` for values of *r* larger than
Benjamin Petersond23f8222009-04-05 19:13:16 +00001342 the input iterable. This was deemed a specification error, so they
1343 now return an empty iterator. (Fixed by Raymond Hettinger; :issue:`4816`.)
1344
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001345* Updated module: The :mod:`json` module was upgraded to version 2.0.9 of the
Benjamin Petersond23f8222009-04-05 19:13:16 +00001346 simplejson package, which includes a C extension that makes
1347 encoding and decoding faster.
1348 (Contributed by Bob Ippolito; :issue:`4136`.)
1349
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001350 To support the new :class:`collections.OrderedDict` type, :func:`json.load`
Benjamin Petersond23f8222009-04-05 19:13:16 +00001351 now has an optional *object_pairs_hook* parameter that will be called
1352 with any object literal that decodes to a list of pairs.
1353 (Contributed by Raymond Hettinger; :issue:`5381`.)
1354
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001355* The :mod:`mailbox` module's :class:`Maildir` class now records the
1356 timestamp on the directories it reads, and only re-reads them if the
1357 modification time has subsequently changed. This improves
1358 performance by avoiding unneeded directory scans. (Fixed by
1359 A.M. Kuchling and Antoine Pitrou; :issue:`1607951`, :issue:`6896`.)
1360
Benjamin Peterson9eea4802009-12-31 03:31:15 +00001361* New functions: the :mod:`math` module gained
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001362 :func:`~math.erf` and :func:`~math.erfc` for the error function and the complementary error function,
1363 :func:`~math.expm1` which computes ``e**x - 1`` with more precision than
1364 using :func:`~math.exp` and subtracting 1,
1365 :func:`~math.gamma` for the Gamma function, and
1366 :func:`~math.lgamma` for the natural log of the Gamma function.
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001367 (Contributed by Mark Dickinson and nirinA raseliarison; :issue:`3366`.)
1368
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001369* The :mod:`multiprocessing` module's :class:`Manager*` classes
1370 can now be passed a callable that will be called whenever
1371 a subprocess is started, along with a set of arguments that will be
1372 passed to the callable.
1373 (Contributed by lekma; :issue:`5585`.)
1374
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001375 The :class:`~multiprocessing.Pool` class, which controls a pool of worker processes,
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00001376 now has an optional *maxtasksperchild* parameter. Worker processes
1377 will perform the specified number of tasks and then exit, causing the
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001378 :class:`~multiprocessing.Pool` to start a new worker. This is useful if tasks may leak
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00001379 memory or other resources, or if some tasks will cause the worker to
1380 become very large.
1381 (Contributed by Charles Cazabon; :issue:`6963`.)
1382
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001383* The :mod:`nntplib` module now supports IPv6 addresses.
1384 (Contributed by Derek Morr; :issue:`1664`.)
1385
Benjamin Peterson9eea4802009-12-31 03:31:15 +00001386* New functions: the :mod:`os` module wraps the following POSIX system
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001387 calls: :func:`~os.getresgid` and :func:`~os.getresuid`, which return the
Benjamin Peterson9eea4802009-12-31 03:31:15 +00001388 real, effective, and saved GIDs and UIDs;
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001389 :func:`~os.setresgid` and :func:`~os.setresuid`, which set
Benjamin Peterson9eea4802009-12-31 03:31:15 +00001390 real, effective, and saved GIDs and UIDs to new values;
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001391 :func:`~os.initgroups`, which initialize the group access list
1392 for the current process. (GID/UID functions
Benjamin Peterson9eea4802009-12-31 03:31:15 +00001393 contributed by Travis H.; :issue:`6508`. Support for initgroups added
1394 by Jean-Paul Calderone; :issue:`7333`.)
1395
Benjamin Peterson9895f912010-03-21 22:05:32 +00001396 The :func:`os.fork` function now re-initializes the import lock in
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001397 the child process; this fixes problems on Solaris when :func:`~os.fork`
Benjamin Peterson9895f912010-03-21 22:05:32 +00001398 is called from a thread. (Fixed by Zsolt Cserna; :issue:`7242`.)
1399
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001400* In the :mod:`os.path` module, the :func:`~os.path.normpath` and
1401 :func:`~os.path.abspath` functions now preserve Unicode; if their input path
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00001402 is a Unicode string, the return value is also a Unicode string.
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001403 (:meth:`~os.path.normpath` fixed by Matt Giuca in :issue:`5827`;
1404 :meth:`~os.path.abspath` fixed by Ezio Melotti in :issue:`3426`.)
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00001405
Benjamin Peterson1010bf32009-01-30 04:00:29 +00001406* The :mod:`pydoc` module now has help for the various symbols that Python
1407 uses. You can now do ``help('<<')`` or ``help('@')``, for example.
1408 (Contributed by David Laban; :issue:`4739`.)
1409
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001410* The :mod:`re` module's :func:`~re.split`, :func:`~re.sub`, and :func:`~re.subn`
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001411 now accept an optional *flags* argument, for consistency with the
1412 other functions in the module. (Added by Gregory P. Smith.)
1413
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001414* New function: :func:`~runpy.run_path` in the :mod:`runpy` module
1415 will execute the code at a provided *path* argument. *path* can be
1416 the path of a Python source file (:file:`example.py`), a compiled
1417 bytecode file (:file:`example.pyc`), a directory
1418 (:file:`./package/`), or a zip archive (:file:`example.zip`). If a
1419 directory or zip path is provided, it will be added to the front of
1420 ``sys.path`` and the module :mod:`__main__` will be imported. It's
1421 expected that the directory or zip contains a :file:`__main__.py`;
1422 if it doesn't, some other :file:`__main__.py` might be imported from
Nick Coghlan9fc68c42010-07-02 15:57:50 +00001423 a location later in ``sys.path``. This makes more of the machinery
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001424 of :mod:`runpy` available to scripts that want to mimic the way
Nick Coghlan9fc68c42010-07-02 15:57:50 +00001425 Python's command line processes an explicit path name.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001426 (Added by Nick Coghlan; :issue:`6816`.)
1427
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001428* New function: in the :mod:`shutil` module, :func:`~shutil.make_archive`
1429 takes a filename, archive type (zip or tar-format), and a directory
1430 path, and creates an archive containing the directory's contents.
1431 (Added by Tarek Ziadé.)
1432
1433 :mod:`shutil`'s :func:`~shutil.copyfile` and :func:`~shutil.copytree`
1434 functions now raise a :exc:`~shutil.SpecialFileError` exception when
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001435 asked to copy a named pipe. Previously the code would treat
1436 named pipes like a regular file by opening them for reading, and
1437 this would block indefinitely. (Fixed by Antoine Pitrou; :issue:`3002`.)
1438
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001439* The :mod:`signal` module no longer re-installs the signal handler
1440 unless this is truly necessary, which fixes a bug that could make it
1441 impossible to catch the EINTR signal robustly. (Fixed by
1442 Charles-Francois Natali; :issue:`8354`.)
1443
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001444* New functions: in the :mod:`site` module, three new functions
1445 return various site- and user-specific paths.
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001446 :func:`~site.getsitepackages` returns a list containing all
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001447 global site-packages directories,
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001448 :func:`~site.getusersitepackages` returns the path of the user's
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001449 site-packages directory, and
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001450 :func:`~site.getuserbase` returns the value of the :envvar:`USER_BASE`
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001451 environment variable, giving the path to a directory that can be used
1452 to store data.
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00001453 (Contributed by Tarek Ziadé; :issue:`6693`.)
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001454
Benjamin Peterson9895f912010-03-21 22:05:32 +00001455 The :mod:`site` module now reports exceptions occurring
1456 when the :mod:`sitecustomize` module is imported, and will no longer
Florent Xicluna41fe6152010-04-02 18:52:12 +00001457 catch and swallow the :exc:`KeyboardInterrupt` exception. (Fixed by
Benjamin Peterson9895f912010-03-21 22:05:32 +00001458 Victor Stinner; :issue:`3137`.)
1459
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001460* The :func:`~socket.create_connection` function
Benjamin Peterson9895f912010-03-21 22:05:32 +00001461 gained a *source_address* parameter, a ``(host, port)`` 2-tuple
1462 giving the source address that will be used for the connection.
1463 (Contributed by Eldon Ziegler; :issue:`3972`.)
1464
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001465 The :meth:`~socket.socket.recv_into` and :meth:`~socket.socket.recvfrom_into`
1466 methods will now write into objects that support the buffer API, most usefully
Benjamin Peterson9895f912010-03-21 22:05:32 +00001467 the :class:`bytearray` and :class:`memoryview` objects. (Implemented by
1468 Antoine Pitrou; :issue:`8104`.)
Benjamin Petersona28e7022010-01-09 18:53:06 +00001469
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001470* The :mod:`SocketServer` module's :class:`~SocketServer.TCPServer` class now
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001471 supports socket timeouts and disabling the Nagle algorithm.
1472 The :attr:`~SocketServer.TCPServer.disable_nagle_algorithm` class attribute
1473 defaults to False; if overridden to be True,
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001474 new request connections will have the TCP_NODELAY option set to
1475 prevent buffering many small sends into a single TCP packet.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001476 The :attr:`~SocketServer.TCPServer.timeout` class attribute can hold
1477 a timeout in seconds that will be applied to the request socket; if
1478 no request is received within that time, :meth:`handle_timeout`
1479 will be called and :meth:`handle_request` will return.
1480 (Contributed by Kristján Valur Jónsson; :issue:`6192` and :issue:`6267`.)
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001481
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001482* Updated module: the :mod:`sqlite3` module has been updated to
Benjamin Peterson9895f912010-03-21 22:05:32 +00001483 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
1484 the ability to load SQLite extensions from shared libraries.
1485 Call the ``enable_load_extension(True)`` method to enable extensions,
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001486 and then call :meth:`~sqlite3.Connection.load_extension` to load a particular shared library.
Benjamin Peterson9895f912010-03-21 22:05:32 +00001487 (Updated by Gerhard Häring.)
1488
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001489* The :mod:`ssl` module's :class:`ssl.SSLSocket` objects now support the
1490 buffer API, which fixed a test suite failure (fix by Antoine Pitrou;
1491 :issue:`7133`) and automatically set
1492 OpenSSL's :cmacro:`SSL_MODE_AUTO_RETRY`, which will prevent an error
1493 code being returned from :meth:`recv` operations that trigger an SSL
1494 renegotiation (fix by Antoine Pitrou; :issue:`8222`).
1495
1496 The :func:`ssl.wrap_socket` constructor function now takes a
1497 *ciphers* argument that's a string listing the encryption algorithms
1498 to be allowed; the format of the string is described
1499 `in the OpenSSL documentation
1500 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`__.
1501 (Added by Antoine Pitrou; :issue:`8322`.)
1502
1503 Another change makes the extension load all of OpenSSL's ciphers and
1504 digest algorithms so that they're all available. Some SSL
1505 certificates couldn't be verified, reporting an "unknown algorithm"
1506 error. (Reported by Beda Kosata, and fixed by Antoine Pitrou;
1507 :issue:`8484`.)
1508
1509 The version of OpenSSL being used is now available as the module
1510 attributes :data:`ssl.OPENSSL_VERSION` (a string),
1511 :data:`ssl.OPENSSL_VERSION_INFO` (a 5-tuple), and
1512 :data:`ssl.OPENSSL_VERSION_NUMBER` (an integer). (Added by Antoine
1513 Pitrou; :issue:`8321`.)
1514
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001515* The :mod:`struct` module will no longer silently ignore overflow
1516 errors when a value is too large for a particular integer format
1517 code (one of ``bBhHiIlLqQ``); it now always raises a
1518 :exc:`struct.error` exception. (Changed by Mark Dickinson;
Ezio Melotti11d22dc2010-04-20 09:55:05 +00001519 :issue:`1523`.) The :func:`~struct.pack` function will also
1520 attempt to use :meth:`__index__` to convert and pack non-integers
1521 before trying the :meth:`__int__` method or reporting an error.
1522 (Changed by Mark Dickinson; :issue:`8300`.)
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001523
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001524* New function: the :mod:`subprocess` module's
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001525 :func:`~subprocess.check_output` runs a command with a specified set of arguments
Benjamin Petersond23f8222009-04-05 19:13:16 +00001526 and returns the command's output as a string when the command runs without
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001527 error, or raises a :exc:`~subprocess.CalledProcessError` exception otherwise.
Georg Brandl1f01deb2009-01-03 22:47:39 +00001528
1529 ::
1530
1531 >>> subprocess.check_output(['df', '-h', '.'])
1532 'Filesystem Size Used Avail Capacity Mounted on\n
1533 /dev/disk0s2 52G 49G 3.0G 94% /\n'
1534
1535 >>> subprocess.check_output(['df', '-h', '/bogus'])
1536 ...
1537 subprocess.CalledProcessError: Command '['df', '-h', '/bogus']' returned non-zero exit status 1
1538
1539 (Contributed by Gregory P. Smith.)
1540
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001541 The :mod:`subprocess` module will now retry its internal system calls
1542 on receiving an :const:`EINTR` signal. (Reported by several people; final
1543 patch by Gregory P. Smith in :issue:`1068268`.)
1544
1545* New function: :func:`~symtable.is_declared_global` in the :mod:`symtable` module
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001546 returns true for variables that are explicitly declared to be global,
1547 false for ones that are implicitly global.
1548 (Contributed by Jeremy Hylton.)
1549
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001550* The :mod:`syslog` module will now use the value of ``sys.argv[0]`` as the
1551 identifier instead of the previous default value of ``'python'``.
1552 (Changed by Sean Reifschneider; :issue:`8451`.)
1553
Benjamin Petersond23f8222009-04-05 19:13:16 +00001554* The ``sys.version_info`` value is now a named tuple, with attributes
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00001555 named :attr:`major`, :attr:`minor`, :attr:`micro`,
1556 :attr:`releaselevel`, and :attr:`serial`. (Contributed by Ross
1557 Light; :issue:`4285`.)
Benjamin Petersond23f8222009-04-05 19:13:16 +00001558
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00001559 :func:`sys.getwindowsversion` also returns a named tuple,
Ezio Melotti0d85e412010-03-13 00:39:49 +00001560 with attributes named :attr:`major`, :attr:`minor`, :attr:`build`,
1561 :attr:`platform`, :attr:`service_pack`, :attr:`service_pack_major`,
Eric Smithb0869402010-02-03 14:25:10 +00001562 :attr:`service_pack_minor`, :attr:`suite_mask`, and
1563 :attr:`product_type`. (Contributed by Brian Curtin; :issue:`7766`.)
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00001564
1565* The :mod:`tarfile` module's default error handling has changed, to
1566 no longer suppress fatal errors. The default error level was previously 0,
1567 which meant that errors would only result in a message being written to the
1568 debug log, but because the debug log is not activated by default,
1569 these errors go unnoticed. The default error level is now 1,
1570 which raises an exception if there's an error.
1571 (Changed by Lars Gustäbel; :issue:`7357`.)
1572
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001573 :mod:`tarfile` now supports filtering the :class:`~tarfile.TarInfo`
1574 objects being added to a tar file. When you call :meth:`~tarfile.TarFile.add`,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001575 you may supply an optional *filter* argument
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001576 that's a callable. The *filter* callable will be passed the
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001577 :class:`~tarfile.TarInfo` for every file being added, and can modify and return it.
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001578 If the callable returns ``None``, the file will be excluded from the
1579 resulting archive. This is more powerful than the existing
1580 *exclude* argument, which has therefore been deprecated.
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00001581 (Added by Lars Gustäbel; :issue:`6856`.)
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001582 The :class:`~tarfile.TarFile` class also now supports the context manager protocol.
Benjamin Peterson9895f912010-03-21 22:05:32 +00001583 (Added by Lars Gustäbel; :issue:`7232`.)
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001584
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001585* The :meth:`~threading.Event.wait` method of the :class:`threading.Event` class
1586 now returns the internal flag on exit. This means the method will usually
1587 return true because :meth:`~threading.Event.wait` is supposed to block until the
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001588 internal flag becomes true. The return value will only be false if
1589 a timeout was provided and the operation timed out.
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001590 (Contributed by Tim Lesher; :issue:`1674032`.)
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001591
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001592* The Unicode database provided by the :mod:`unicodedata` module is
1593 now used internally to determine which characters are numeric,
1594 whitespace, or represent line breaks. The database also
1595 includes information from the :file:`Unihan.txt` data file (patch
1596 by Anders Chrigström and Amaury Forgeot d'Arc; :issue:`1571184`)
1597 and has been updated to version 5.2.0 (updated by
1598 Florent Xicluna; :issue:`8024`).
Ezio Melotti4c5475d2010-03-22 23:16:42 +00001599
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001600* The :mod:`urlparse` module's :func:`~urlparse.urlsplit` now handles
1601 unknown URL schemes in a fashion compliant with :rfc:`3986`: if the
1602 URL is of the form ``"<something>://..."``, the text before the
1603 ``://`` is treated as the scheme, even if it's a made-up scheme that
1604 the module doesn't know about. This change may break code that
1605 worked around the old behaviour. For example, Python 2.6.4 or 2.5
1606 will return the following:
1607
1608 >>> import urlparse
1609 >>> urlparse.urlsplit('invented://host/filename?query')
1610 ('invented', '', '//host/filename?query', '', '')
1611
1612 Python 2.7 (and Python 2.6.5) will return:
1613
1614 >>> import urlparse
1615 >>> urlparse.urlsplit('invented://host/filename?query')
1616 ('invented', 'host', '/filename?query', '', '')
1617
1618 (Python 2.7 actually produces slightly different output, since it
1619 returns a named tuple instead of a standard tuple.)
1620
1621 The :mod:`urlparse` module also supports IPv6 literal addresses as defined by
1622 :rfc:`2732` (contributed by Senthil Kumaran; :issue:`2987`). ::
1623
1624 >>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo')
1625 ParseResult(scheme='http', netloc='[1080::8:800:200C:417A]',
1626 path='/foo', params='', query='', fragment='')
1627
1628* New class: the :class:`~weakref.WeakSet` class in the :mod:`weakref`
1629 module is a set that only holds weak references to its elements; elements
1630 will be removed once there are no references pointing to them.
1631 (Originally implemented in Python 3.x by Raymond Hettinger, and backported
1632 to 2.7 by Michael Foord.)
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00001633
Benjamin Peterson9895f912010-03-21 22:05:32 +00001634* The ElementTree library, :mod:`xml.etree`, no longer escapes
1635 ampersands and angle brackets when outputting an XML processing
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001636 instruction (which looks like ``<?xml-stylesheet href="#style1"?>``)
1637 or comment (which looks like ``<!-- comment -->``).
Benjamin Peterson9895f912010-03-21 22:05:32 +00001638 (Patch by Neil Muller; :issue:`2746`.)
1639
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001640* The XML-RPC client and server, provided by the :mod:`xmlrpclib` and
1641 :mod:`SimpleXMLRPCServer` modules, have improved performance by
1642 supporting HTTP/1.1 keep-alive and by optionally using gzip encoding
1643 to compress the XML being exchanged. The gzip compression is
1644 controlled by the :attr:`encode_threshold` attribute of
1645 :class:`SimpleXMLRPCRequestHandler`, which contains a size in bytes;
1646 responses larger than this will be compressed.
1647 (Contributed by Kristján Valur Jónsson; :issue:`6267`.)
1648
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001649* The :mod:`zipfile` module's :class:`~zipfile.ZipFile` now supports the context
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001650 management protocol, so you can write ``with zipfile.ZipFile(...) as f:``.
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00001651 (Contributed by Brian Curtin; :issue:`5511`.)
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001652
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001653 :mod:`zipfile` now also supports archiving empty directories and
Benjamin Petersond23f8222009-04-05 19:13:16 +00001654 extracts them correctly. (Fixed by Kuba Wieczorek; :issue:`4710`.)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001655 Reading files out of an archive is faster, and interleaving
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001656 :meth:`~zipfile.ZipFile.read` and :meth:`~zipfile.ZipFile.readline` now works correctly.
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00001657 (Contributed by Nir Aides; :issue:`7610`.)
1658
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001659 The :func:`~zipfile.is_zipfile` function now
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00001660 accepts a file object, in addition to the path names accepted in earlier
1661 versions. (Contributed by Gabriel Genellina; :issue:`4756`.)
Benjamin Petersond23f8222009-04-05 19:13:16 +00001662
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001663 The :meth:`~zipfile.ZipFile.writestr` method now has an optional *compress_type* parameter
Benjamin Peterson9895f912010-03-21 22:05:32 +00001664 that lets you override the default compression method specified in the
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001665 :class:`~zipfile.ZipFile` constructor. (Contributed by Ronald Oussoren;
Benjamin Peterson9895f912010-03-21 22:05:32 +00001666 :issue:`6003`.)
1667
Benjamin Peterson9895f912010-03-21 22:05:32 +00001668
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001669.. ======================================================================
1670.. whole new modules get described in subsections here
1671
Tarek Ziadéba0eacf2010-02-02 23:43:21 +00001672
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001673.. _importlib-section:
1674
1675New module: importlib
1676------------------------------
1677
1678Python 3.1 includes the :mod:`importlib` package, a re-implementation
1679of the logic underlying Python's :keyword:`import` statement.
1680:mod:`importlib` is useful for implementors of Python interpreters and
1681to users who wish to write new importers that can participate in the
1682import process. Python 2.7 doesn't contain the complete
1683:mod:`importlib` package, but instead has a tiny subset that contains
1684a single function, :func:`~importlib.import_module`.
1685
1686``import_module(name, package=None)`` imports a module. *name* is
1687a string containing the module or package's name. It's possible to do
1688relative imports by providing a string that begins with a ``.``
1689character, such as ``..utils.errors``. For relative imports, the
1690*package* argument must be provided and is the name of the package that
1691will be used as the anchor for
1692the relative import. :func:`~importlib.import_module` both inserts the imported
1693module into ``sys.modules`` and returns the module object.
1694
1695Here are some examples::
1696
1697 >>> from importlib import import_module
1698 >>> anydbm = import_module('anydbm') # Standard absolute import
1699 >>> anydbm
1700 <module 'anydbm' from '/p/python/Lib/anydbm.py'>
1701 >>> # Relative import
1702 >>> file_util = import_module('..file_util', 'distutils.command')
1703 >>> file_util
1704 <module 'distutils.file_util' from '/python/Lib/distutils/file_util.pyc'>
1705
1706:mod:`importlib` was implemented by Brett Cannon and introduced in
1707Python 3.1.
1708
1709
1710New module: sysconfig
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001711---------------------------------
1712
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001713The :mod:`sysconfig` module has been pulled out of the Distutils
1714package, becoming a new top-level module in its own right.
1715:mod:`sysconfig` provides functions for getting information about
1716Python's build process: compiler switches, installation paths, the
1717platform name, and whether Python is running from its source
1718directory.
1719
1720Some of the functions in the module are:
1721
1722* :func:`~sysconfig.get_config_var` returns variables from Python's
1723 Makefile and the :file:`pyconfig.h` file.
1724* :func:`~sysconfig.get_config_vars` returns a dictionary containing
1725 all of the configuration variables.
1726* :func:`~sysconfig.getpath` returns the configured path for
1727 a particular type of module: the standard library,
1728 site-specific modules, platform-specific modules, etc.
1729* :func:`~sysconfig.is_python_build` returns true if you're running a
1730 binary from a Python source tree, and false otherwise.
1731
1732Consult the :mod:`sysconfig` documentation for more details and for
1733a complete list of functions.
1734
1735The Distutils package and :mod:`sysconfig` are now maintained by Tarek
1736Ziadé, who has also started a Distutils2 package (source repository at
1737http://hg.python.org/distutils2/) for developing a next-generation
1738version of Distutils.
1739
1740
1741ttk: Themed Widgets for Tk
1742--------------------------
1743
1744Tcl/Tk 8.5 includes a set of themed widgets that re-implement basic Tk
1745widgets but have a more customizable appearance and can therefore more
1746closely resemble the native platform's widgets. This widget
1747set was originally called Tile, but was renamed to Ttk (for "themed Tk")
1748on being added to Tcl/Tck release 8.5.
1749
1750To learn more, read the :mod:`ttk` module documentation. You may also
1751wish to read the Tcl/Tk manual page describing the
1752Ttk theme engine, available at
1753http://www.tcl.tk/man/tcl8.5/TkCmd/ttk_intro.htm. Some
1754screenshots of the Python/Ttk code in use are at
1755http://code.google.com/p/python-ttk/wiki/Screenshots.
1756
1757The :mod:`ttk` module was written by Guilherme Polo and added in
1758:issue:`2983`. An alternate version called ``Tile.py``, written by
1759Martin Franklin and maintained by Kevin Walzer, was proposed for
1760inclusion in :issue:`2618`, but the authors argued that Guilherme
1761Polo's work was more comprehensive.
1762
1763
1764.. _unittest-section:
1765
1766Updated module: unittest
1767---------------------------------
1768
1769The :mod:`unittest` module was greatly enhanced; many
1770new features were added. Most of these features were implemented
1771by Michael Foord, unless otherwise noted. The enhanced version of
1772the module is downloadable separately for use with Python versions 2.4 to 2.6,
1773packaged as the :mod:`unittest2` package, from
1774http://pypi.python.org/pypi/unittest2.
1775
1776When used from the command line, the module can automatically discover
1777tests. It's not as fancy as `py.test <http://pytest.org>`__ or
1778`nose <http://code.google.com/p/python-nose/>`__, but provides a simple way
1779to run tests kept within a set of package directories. For example,
1780the following command will search the :file:`test/` subdirectory for
1781any importable test files named ``test*.py``::
1782
1783 python -m unittest discover -s test
1784
1785Consult the :mod:`unittest` module documentation for more details.
1786(Developed in :issue:`6001`.)
1787
1788The :func:`main` function supports some other new options:
1789
1790* :option:`-b` or :option:`--buffer` will buffer the standard output
1791 and standard error streams during each test. If the test passes,
1792 any resulting output will be discarded; on failure, the buffered
1793 output will be displayed.
1794
1795* :option:`-c` or :option:`--catch` will cause the control-C interrupt
1796 to be handled more gracefully. Instead of interrupting the test
1797 process immediately, the currently running test will be completed
1798 and then the partial results up to the interruption will be reported.
1799 If you're impatient, a second press of control-C will cause an immediate
1800 interruption.
1801
1802 This control-C handler tries to avoid causing problems when the code
1803 being tested or the tests being run have defined a signal handler of
1804 their own, by noticing that a signal handler was already set and
1805 calling it. If this doesn't work for you, there's a
1806 :func:`removeHandler` decorator that can be used to mark tests that
1807 should have the control-C handling disabled.
1808
1809* :option:`-f` or :option:`--failfast` makes
1810 test execution stop immediately when a test fails instead of
1811 continuing to execute further tests. (Suggested by Cliff Dyer and
1812 implemented by Michael Foord; :issue:`8074`.)
1813
1814The progress messages now show 'x' for expected failures
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001815and 'u' for unexpected successes when run in verbose mode.
1816(Contributed by Benjamin Peterson.)
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001817
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001818Test cases can raise the :exc:`~unittest.SkipTest` exception to skip a
1819test (:issue:`1034053`).
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001820
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001821The error messages for :meth:`~unittest.TestCase.assertEqual`,
1822:meth:`~unittest.TestCase.assertTrue`, and :meth:`~unittest.TestCase.assertFalse`
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001823failures now provide more information. If you set the
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001824:attr:`~unittest.TestCase.longMessage` attribute of your :class:`~unittest.TestCase` classes to
1825True, both the standard error message and any additional message you
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001826provide will be printed for failures. (Added by Michael Foord; :issue:`5663`.)
1827
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001828The :meth:`~unittest.TestCase.assertRaises` method now
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001829returns a context handler when called without providing a callable
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001830object to run. For example, you can write this::
1831
1832 with self.assertRaises(KeyError):
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001833 {}['foo']
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001834
1835(Implemented by Antoine Pitrou; :issue:`4444`.)
1836
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001837.. rev 78774
1838
1839Module- and class-level setup and teardown fixtures are now supported.
1840Modules can contain :func:`~unittest.setUpModule` and :func:`~unittest.tearDownModule`
1841functions. Classes can have :meth:`~unittest.TestCase.setUpClass` and
1842:meth:`~unittest.TestCase.tearDownClass` methods that must be defined as class methods
1843(using ``@classmethod`` or equivalent). These functions and
1844methods are invoked when the test runner switches to a test case in a
1845different module or class.
1846
1847The methods :meth:`~unittest.TestCase.addCleanup` and
1848:meth:`~unittest.TestCase.doCleanups` were added.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001849:meth:`~unittest.TestCase.addCleanup` lets you add cleanup functions that
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001850will be called unconditionally (after :meth:`~unittest.TestCase.setUp` if
1851:meth:`~unittest.TestCase.setUp` fails, otherwise after :meth:`~unittest.TestCase.tearDown`). This allows
1852for much simpler resource allocation and deallocation during tests
1853(:issue:`5679`).
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001854
1855A number of new methods were added that provide more specialized
1856tests. Many of these methods were written by Google engineers
1857for use in their test suites; Gregory P. Smith, Michael Foord, and
1858GvR worked on merging them into Python's version of :mod:`unittest`.
1859
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001860* :meth:`~unittest.TestCase.assertIsNone` and :meth:`~unittest.TestCase.assertIsNotNone` take one
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001861 expression and verify that the result is or is not ``None``.
1862
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001863* :meth:`~unittest.TestCase.assertIs` and :meth:`~unittest.TestCase.assertIsNot`
1864 take two values and check whether the two values evaluate to the same object or not.
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001865 (Added by Michael Foord; :issue:`2578`.)
1866
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001867* :meth:`~unittest.TestCase.assertIsInstance` and
1868 :meth:`~unittest.TestCase.assertNotIsInstance` check whether
Benjamin Petersona28e7022010-01-09 18:53:06 +00001869 the resulting object is an instance of a particular class, or of
1870 one of a tuple of classes. (Added by Georg Brandl; :issue:`7031`.)
1871
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001872* :meth:`~unittest.TestCase.assertGreater`, :meth:`~unittest.TestCase.assertGreaterEqual`,
1873 :meth:`~unittest.TestCase.assertLess`, and :meth:`~unittest.TestCase.assertLessEqual` compare
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001874 two quantities.
1875
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001876* :meth:`~unittest.TestCase.assertMultiLineEqual` compares two strings, and if they're
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001877 not equal, displays a helpful comparison that highlights the
Benjamin Peterson9895f912010-03-21 22:05:32 +00001878 differences in the two strings. This comparison is now used by
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001879 default when Unicode strings are compared with :meth:`~unittest.TestCase.assertEqual`.
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001880
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001881* :meth:`~unittest.TestCase.assertRegexpMatches` and
1882 :meth:`~unittest.TestCase.assertNotRegexpMatches` checks whether the
1883 first argument is a string matching or not matching the regular
1884 expression provided as the second argument (:issue:`8038`).
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001885
1886* :meth:`~unittest.TestCase.assertRaisesRegexp` checks whether a particular exception
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001887 is raised, and then also checks that the string representation of
1888 the exception matches the provided regular expression.
1889
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001890* :meth:`~unittest.TestCase.assertIn` and :meth:`~unittest.TestCase.assertNotIn`
1891 tests whether *first* is or is not in *second*.
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001892
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001893* :meth:`~unittest.TestCase.assertItemsEqual` tests whether two provided sequences
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001894 contain the same elements.
1895
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001896* :meth:`~unittest.TestCase.assertSetEqual` compares whether two sets are equal, and
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001897 only reports the differences between the sets in case of error.
1898
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001899* Similarly, :meth:`~unittest.TestCase.assertListEqual` and :meth:`~unittest.TestCase.assertTupleEqual`
Benjamin Peterson9895f912010-03-21 22:05:32 +00001900 compare the specified types and explain any differences without necessarily
1901 printing their full values; these methods are now used by default
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001902 when comparing lists and tuples using :meth:`~unittest.TestCase.assertEqual`.
1903 More generally, :meth:`~unittest.TestCase.assertSequenceEqual` compares two sequences
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001904 and can optionally check whether both sequences are of a
1905 particular type.
1906
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001907* :meth:`~unittest.TestCase.assertDictEqual` compares two dictionaries and reports the
Benjamin Peterson9895f912010-03-21 22:05:32 +00001908 differences; it's now used by default when you compare two dictionaries
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001909 using :meth:`~unittest.TestCase.assertEqual`. :meth:`~unittest.TestCase.assertDictContainsSubset` checks whether
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001910 all of the key/value pairs in *first* are found in *second*.
1911
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001912* :meth:`~unittest.TestCase.assertAlmostEqual` and :meth:`~unittest.TestCase.assertNotAlmostEqual` test
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001913 whether *first* and *second* are approximately equal. This method
1914 can either round their difference to an optionally-specified number
1915 of *places* (the default is 7) and compare it to zero, or require
1916 the difference to be smaller than a supplied *delta* value.
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001917
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001918* :meth:`~unittest.TestLoader.loadTestsFromName` properly honors the
1919 :attr:`~unittest.TestLoader.suiteClass` attribute of
1920 the :class:`~unittest.TestLoader`. (Fixed by Mark Roddy; :issue:`6866`.)
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001921
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001922* A new hook lets you extend the :meth:`~unittest.TestCase.assertEqual` method to handle
1923 new data types. The :meth:`~unittest.TestCase.addTypeEqualityFunc` method takes a type
1924 object and a function. The function will be used when both of the
1925 objects being compared are of the specified type. This function
1926 should compare the two objects and raise an exception if they don't
1927 match; it's a good idea for the function to provide additional
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001928 information about why the two objects aren't matching, much as the new
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001929 sequence comparison methods do.
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001930
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001931:func:`unittest.main` now takes an optional ``exit`` argument. If
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001932False, :func:`~unittest.main` doesn't call :func:`sys.exit`, allowing
1933:func:`main` to be used from the interactive interpreter.
1934(Contributed by J. Pablo Fernández; :issue:`3379`.)
Ezio Melotti6c96ffe2010-04-07 04:27:14 +00001935
1936:class:`~unittest.TestResult` has new :meth:`~unittest.TestResult.startTestRun` and
1937:meth:`~unittest.TestResult.stopTestRun` methods that are called immediately before
1938and after a test run. (Contributed by Robert Collins; :issue:`5728`.)
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001939
1940With all these changes, the :file:`unittest.py` was becoming awkwardly
1941large, so the module was turned into a package and the code split into
1942several files (by Benjamin Peterson). This doesn't affect how the
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001943module is imported or used.
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001944
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001945.. seealso::
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001946
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001947 http://www.voidspace.org.uk/python/articles/unittest2.shtml
1948 Describes the new features, how to use them, and the
1949 rationale for various design decisions. (By Michael Foord.)
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001950
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001951.. _elementtree-section:
Benjamin Petersond23f8222009-04-05 19:13:16 +00001952
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001953Updated module: ElementTree 1.3
1954---------------------------------
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001955
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001956The version of the ElementTree library included with Python was updated to
1957version 1.3. Some of the new features are:
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001958
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001959* The various parsing functions now take a *parser* keyword argument
1960 giving an :class:`XMLParser` instance that will
1961 be used. This makes it possible to override the file's internal encoding::
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001962
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001963 p = ET.XMLParser(encoding='utf-8')
1964 t = ET.XML("""<root/>""", parser=p)
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001965
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001966 Errors in parsing XML now raise a :exc:`ParseError` exception, whose
1967 instances have a :attr:`position` attribute
1968 containing a (*line*, *column*) tuple giving the location of the problem.
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001969
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001970* ElementTree's code for converting trees to a string has been
1971 significantly reworked, making it roughly twice as fast in many
1972 cases. The :class:`ElementTree` :meth:`write` and :class:`Element`
1973 :meth:`write` methods now have a *method* parameter that can be
1974 "xml" (the default), "html", or "text". HTML mode will output empty
1975 elements as ``<empty></empty>`` instead of ``<empty/>``, and text
1976 mode will skip over elements and only output the text chunks. If
1977 you set the :attr:`tag` attribute of an element to ``None`` but
1978 leave its children in place, the element will be omitted when the
1979 tree is written out, so you don't need to do more extensive rearrangement
1980 to remove a single element.
Benjamin Petersond23f8222009-04-05 19:13:16 +00001981
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001982 Namespace handling has also been improved. All ``xmlns:<whatever>``
1983 declarations are now output on the root element, not scattered throughout
1984 the resulting XML. You can set the default namespace for a tree
1985 by setting the :attr:`default_namespace` attribute and can
1986 register new prefixes with :meth:`register_namespace`. In XML mode,
1987 you can use the true/false *xml_declaration* parameter to suppress the
1988 XML declaration.
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001989
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001990* New :class:`Element` method: :meth:`extend` appends the items from a
1991 sequence to the element's children. Elements themselves behave like
1992 sequences, so it's easy to move children from one element to
1993 another::
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001994
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001995 from xml.etree import ElementTree as ET
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001996
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001997 t = ET.XML("""<list>
1998 <item>1</item> <item>2</item> <item>3</item>
1999 </list>""")
2000 new = ET.XML('<root/>')
2001 new.extend(t)
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00002002
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002003 # Outputs <root><item>1</item>...</root>
2004 print ET.tostring(new)
Georg Brandl4d131ee2009-11-18 18:53:14 +00002005
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002006* New :class:`Element` method: :meth:`iter` yields the children of the
2007 element as a generator. It's also possible to write ``for child in
2008 elem:`` to loop over an element's children. The existing method
2009 :meth:`getiterator` is now deprecated, as is :meth:`getchildren`
2010 which constructs and returns a list of children.
Georg Brandl4d131ee2009-11-18 18:53:14 +00002011
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002012* New :class:`Element` method: :meth:`itertext` yields all chunks of
2013 text that are descendants of the element. For example::
2014
2015 t = ET.XML("""<list>
2016 <item>1</item> <item>2</item> <item>3</item>
2017 </list>""")
2018
2019 # Outputs ['\n ', '1', ' ', '2', ' ', '3', '\n']
2020 print list(t.itertext())
2021
2022* Deprecated: using an element as a Boolean (i.e., ``if elem:``) would
2023 return true if the element had any children, or false if there were
2024 no children. This behaviour is confusing -- ``None`` is false, but
2025 so is a childless element? -- so it will now trigger a
2026 :exc:`FutureWarning`. In your code, you should be explicit: write
2027 ``len(elem) != 0`` if you're interested in the number of children,
2028 or ``elem is not None``.
2029
2030Fredrik Lundh develops ElementTree and produced the 1.3 version;
2031you can read his article describing 1.3 at
2032http://effbot.org/zone/elementtree-13-intro.htm.
2033Florent Xicluna updated the version included with
2034Python, after discussions on python-dev and in :issue:`6472`.)
Georg Brandl4d131ee2009-11-18 18:53:14 +00002035
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002036.. ======================================================================
2037
2038
2039Build and C API Changes
2040=======================
2041
2042Changes to Python's build process and to the C API include:
2043
Ezio Melotti11d22dc2010-04-20 09:55:05 +00002044* The latest release of the GNU Debugger, GDB 7, can be `scripted
2045 using Python
2046 <http://sourceware.org/gdb/current/onlinedocs/gdb/Python.html>`__.
2047 When you begin debugging an executable program P, GDB will look for
2048 a file named ``P-gdb.py`` and automatically read it. Dave Malcolm
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002049 contributed a :file:`python-gdb.py` that adds a number of
2050 commands useful when debugging Python itself. For example,
2051 ``py-up`` and ``py-down`` go up or down one Python stack frame,
Ezio Melotti11d22dc2010-04-20 09:55:05 +00002052 which usually corresponds to several C stack frames. ``py-print``
2053 prints the value of a Python variable, and ``py-bt`` prints the
2054 Python stack trace. (Added as a result of :issue:`8032`.)
2055
Georg Brandl1f01deb2009-01-03 22:47:39 +00002056* If you use the :file:`.gdbinit` file provided with Python,
Benjamin Petersonf6489f92009-11-25 17:46:26 +00002057 the "pyo" macro in the 2.7 version now works correctly when the thread being
2058 debugged doesn't hold the GIL; the macro now acquires it before printing.
Benjamin Peterson1010bf32009-01-30 04:00:29 +00002059 (Contributed by Victor Stinner; :issue:`3632`.)
2060
Benjamin Petersond23f8222009-04-05 19:13:16 +00002061* :cfunc:`Py_AddPendingCall` is now thread-safe, letting any
Benjamin Peterson1010bf32009-01-30 04:00:29 +00002062 worker thread submit notifications to the main Python thread. This
2063 is particularly useful for asynchronous IO operations.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002064 (Contributed by Kristján Valur Jónsson; :issue:`4293`.)
Benjamin Peterson1010bf32009-01-30 04:00:29 +00002065
Benjamin Petersonf6489f92009-11-25 17:46:26 +00002066* New function: :cfunc:`PyCode_NewEmpty` creates an empty code object;
2067 only the filename, function name, and first line number are required.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002068 This is useful for extension modules that are attempting to
Benjamin Petersonf6489f92009-11-25 17:46:26 +00002069 construct a more useful traceback stack. Previously such
2070 extensions needed to call :cfunc:`PyCode_New`, which had many
2071 more arguments. (Added by Jeffrey Yasskin.)
2072
Benjamin Peterson9eea4802009-12-31 03:31:15 +00002073* New function: :cfunc:`PyErr_NewExceptionWithDoc` creates a new
2074 exception class, just as the existing :cfunc:`PyErr_NewException` does,
2075 but takes an extra ``char *`` argument containing the docstring for the
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002076 new exception class. (Added by 'lekma' on the Python bug tracker;
Benjamin Peterson9eea4802009-12-31 03:31:15 +00002077 :issue:`7033`.)
2078
Benjamin Petersonf6489f92009-11-25 17:46:26 +00002079* New function: :cfunc:`PyFrame_GetLineNumber` takes a frame object
2080 and returns the line number that the frame is currently executing.
2081 Previously code would need to get the index of the bytecode
2082 instruction currently executing, and then look up the line number
2083 corresponding to that address. (Added by Jeffrey Yasskin.)
2084
Benjamin Petersond69fe2a2010-02-03 02:59:43 +00002085* New functions: :cfunc:`PyLong_AsLongAndOverflow` and
2086 :cfunc:`PyLong_AsLongLongAndOverflow` approximates a Python long
2087 integer as a C :ctype:`long` or :ctype:`long long`.
2088 If the number is too large to fit into
2089 the output type, an *overflow* flag is set and returned to the caller.
2090 (Contributed by Case Van Horsen; :issue:`7528` and :issue:`7767`.)
Benjamin Peterson9eea4802009-12-31 03:31:15 +00002091
Benjamin Petersona28e7022010-01-09 18:53:06 +00002092* New function: stemming from the rewrite of string-to-float conversion,
2093 a new :cfunc:`PyOS_string_to_double` function was added. The old
2094 :cfunc:`PyOS_ascii_strtod` and :cfunc:`PyOS_ascii_atof` functions
2095 are now deprecated.
2096
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002097* New function: :cfunc:`PySys_SetArgvEx` sets the value of
2098 ``sys.argv`` and can optionally update ``sys.path`` to include the
2099 directory containing the script named by ``sys.argv[0]`` depending
2100 on the value of an *updatepath* parameter.
2101
2102 This function was added to close a security hole for applications
2103 that embed Python. The old function, :cfunc:`PySys_SetArgv`, would
2104 always update ``sys.path``, and sometimes it would add the current
2105 directory. This meant that, if you ran an application embedding
2106 Python in a directory controlled by someone else, attackers could
2107 put a Trojan-horse module in the directory (say, a file named
2108 :file:`os.py`) that your application would then import and run.
2109
2110 If you maintain a C/C++ application that embeds Python, check
2111 whether you're calling :cfunc:`PySys_SetArgv` and carefully consider
2112 whether the application should be using :cfunc:`PySys_SetArgvEx`
2113 with *updatepath* set to false.
2114
2115 Security issue reported as `CVE-2008-5983
2116 <http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983>`_;
2117 discussed in :issue:`5753`, and fixed by Antoine Pitrou.
2118
Benjamin Petersonf6489f92009-11-25 17:46:26 +00002119* New macros: the Python header files now define the following macros:
2120 :cmacro:`Py_ISALNUM`,
2121 :cmacro:`Py_ISALPHA`,
2122 :cmacro:`Py_ISDIGIT`,
2123 :cmacro:`Py_ISLOWER`,
2124 :cmacro:`Py_ISSPACE`,
2125 :cmacro:`Py_ISUPPER`,
2126 :cmacro:`Py_ISXDIGIT`,
2127 and :cmacro:`Py_TOLOWER`, :cmacro:`Py_TOUPPER`.
2128 All of these functions are analogous to the C
2129 standard macros for classifying characters, but ignore the current
2130 locale setting, because in
2131 several places Python needs to analyze characters in a
2132 locale-independent way. (Added by Eric Smith;
2133 :issue:`5793`.)
2134
2135 .. XXX these macros don't seem to be described in the c-api docs.
2136
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002137* Removed function: :cmacro:`PyEval_CallObject` is now only available
2138 as a macro. A function version was being kept around to preserve
2139 ABI linking compatibility, but that was in 1997; it can certainly be
2140 deleted by now. (Removed by Antoine Pitrou; :issue:`8276`.)
2141
Benjamin Peterson9eea4802009-12-31 03:31:15 +00002142* New format codes: the :cfunc:`PyFormat_FromString`,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002143 :cfunc:`PyFormat_FromStringV`, and :cfunc:`PyErr_Format` functions now
2144 accept ``%lld`` and ``%llu`` format codes for displaying
Benjamin Peterson9eea4802009-12-31 03:31:15 +00002145 C's :ctype:`long long` types.
2146 (Contributed by Mark Dickinson; :issue:`7228`.)
2147
Benjamin Petersonf6489f92009-11-25 17:46:26 +00002148* The complicated interaction between threads and process forking has
2149 been changed. Previously, the child process created by
2150 :func:`os.fork` might fail because the child is created with only a
2151 single thread running, the thread performing the :func:`os.fork`.
2152 If other threads were holding a lock, such as Python's import lock,
2153 when the fork was performed, the lock would still be marked as
2154 "held" in the new process. But in the child process nothing would
2155 ever release the lock, since the other threads weren't replicated,
2156 and the child process would no longer be able to perform imports.
2157
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002158 Python 2.7 acquires the import lock before performing an
Benjamin Petersonf6489f92009-11-25 17:46:26 +00002159 :func:`os.fork`, and will also clean up any locks created using the
2160 :mod:`threading` module. C extension modules that have internal
2161 locks, or that call :cfunc:`fork()` themselves, will not benefit
2162 from this clean-up.
2163
2164 (Fixed by Thomas Wouters; :issue:`1590864`.)
2165
Benjamin Petersona28e7022010-01-09 18:53:06 +00002166* The :cfunc:`Py_Finalize` function now calls the internal
2167 :func:`threading._shutdown` function; this prevents some exceptions from
2168 being raised when an interpreter shuts down.
2169 (Patch by Adam Olsen; :issue:`1722344`.)
2170
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002171* When using the :ctype:`PyMemberDef` structure to define attributes
2172 of a type, Python will no longer let you try to delete or set a
2173 :const:`T_STRING_INPLACE` attribute.
2174
2175 .. rev 79644
2176
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002177* Global symbols defined by the :mod:`ctypes` module are now prefixed
Benjamin Petersonf6489f92009-11-25 17:46:26 +00002178 with ``Py``, or with ``_ctypes``. (Implemented by Thomas
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002179 Heller; :issue:`3102`.)
2180
Benjamin Petersona28e7022010-01-09 18:53:06 +00002181* New configure option: the :option:`--with-system-expat` switch allows
2182 building the :mod:`pyexpat` module to use the system Expat library.
2183 (Contributed by Arfrever Frehtes Taifersar Arahesis; :issue:`7609`.)
2184
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002185* New configure option: the
Benjamin Petersona28e7022010-01-09 18:53:06 +00002186 :option:`--with-valgrind` option will now disable the pymalloc
Ezio Melotti11d22dc2010-04-20 09:55:05 +00002187 allocator, which is difficult for the Valgrind memory-error detector
2188 to analyze correctly.
Benjamin Petersona28e7022010-01-09 18:53:06 +00002189 Valgrind will therefore be better at detecting memory leaks and
2190 overruns. (Contributed by James Henstridge; :issue:`2422`.)
2191
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002192* New configure option: you can now supply an empty string to
2193 :option:`--with-dbmliborder=` in order to disable all of the various
Benjamin Petersona28e7022010-01-09 18:53:06 +00002194 DBM modules. (Added by Arfrever Frehtes Taifersar Arahesis;
2195 :issue:`6491`.)
2196
Benjamin Petersond23f8222009-04-05 19:13:16 +00002197* The :program:`configure` script now checks for floating-point rounding bugs
2198 on certain 32-bit Intel chips and defines a :cmacro:`X87_DOUBLE_ROUNDING`
2199 preprocessor definition. No code currently uses this definition,
2200 but it's available if anyone wishes to use it.
2201 (Added by Mark Dickinson; :issue:`2937`.)
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002202
Ezio Melotti11d22dc2010-04-20 09:55:05 +00002203 :program:`configure` also now sets a :envvar:`LDCXXSHARED` Makefile
2204 variable for supporting C++ linking. (Contributed by Arfrever
2205 Frehtes Taifersar Arahesis; :issue:`1222585`.)
2206
Benjamin Petersonf6489f92009-11-25 17:46:26 +00002207* The build process now creates the necessary files for pkg-config
2208 support. (Contributed by Clinton Roy; :issue:`3585`.)
2209
2210* The build process now supports Subversion 1.7. (Contributed by
2211 Arfrever Frehtes Taifersar Arahesis; :issue:`6094`.)
2212
Benjamin Peterson9eea4802009-12-31 03:31:15 +00002213
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002214.. _whatsnew27-capsules:
2215
2216Capsules
2217-------------------
2218
2219Python 3.1 adds a new C datatype, :ctype:`PyCapsule`, for providing a
2220C API to an extension module. A capsule is essentially the holder of
2221a C ``void *`` pointer, and is made available as a module attribute; for
2222example, the :mod:`socket` module's API is exposed as ``socket.CAPI``,
2223and :mod:`unicodedata` exposes ``ucnhash_CAPI``. Other extensions
2224can import the module, access its dictionary to get the capsule
2225object, and then get the ``void *`` pointer, which will usually point
2226to an array of pointers to the module's various API functions.
2227
2228There is an existing data type already used for this,
2229:ctype:`PyCObject`, but it doesn't provide type safety. Evil code
2230written in pure Python could cause a segmentation fault by taking a
2231:ctype:`PyCObject` from module A and somehow substituting it for the
2232:ctype:`PyCObject` in module B. Capsules know their own name,
2233and getting the pointer requires providing the name::
2234
2235 void *vtable;
2236
2237 if (!PyCapsule_IsValid(capsule, "mymodule.CAPI") {
2238 PyErr_SetString(PyExc_ValueError, "argument type invalid");
2239 return NULL;
2240 }
2241
2242 vtable = PyCapsule_GetPointer(capsule, "mymodule.CAPI");
2243
2244You are assured that ``vtable`` points to whatever you're expecting.
2245If a different capsule was passed in, :cfunc:`PyCapsule_IsValid` would
2246detect the mismatched name and return false. Refer to
2247:ref:`using-capsules` for more information on using these objects.
2248
2249Python 2.7 now uses capsules internally to provide various
2250extension-module APIs, but the :cfunc:`PyCObject_AsVoidPtr` was
2251modified to handle capsules, preserving compile-time compatibility
2252with the :ctype:`CObject` interface. Use of
2253:cfunc:`PyCObject_AsVoidPtr` will signal a
2254:exc:`PendingDeprecationWarning`, which is silent by default.
2255
2256Implemented in Python 3.1 and backported to 2.7 by Larry Hastings;
2257discussed in :issue:`5630`.
2258
2259
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002260.. ======================================================================
2261
2262Port-Specific Changes: Windows
2263-----------------------------------
2264
Georg Brandl1f01deb2009-01-03 22:47:39 +00002265* The :mod:`msvcrt` module now contains some constants from
2266 the :file:`crtassem.h` header file:
2267 :data:`CRT_ASSEMBLY_VERSION`,
2268 :data:`VC_ASSEMBLY_PUBLICKEYTOKEN`,
2269 and :data:`LIBRARIES_ASSEMBLY_NAME_PREFIX`.
Benjamin Peterson1010bf32009-01-30 04:00:29 +00002270 (Contributed by David Cournapeau; :issue:`4365`.)
2271
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002272* The :mod:`_winreg` module for accessing the registry now implements
2273 the :func:`CreateKeyEx` and :func:`DeleteKeyEx` functions, extended
2274 versions of previously-supported functions that take several extra
2275 arguments. The :func:`DisableReflectionKey`,
2276 :func:`EnableReflectionKey`, and :func:`QueryReflectionKey` were also
2277 tested and documented.
2278 (Implemented by Brian Curtin: :issue:`7347`.)
2279
Benjamin Peterson1010bf32009-01-30 04:00:29 +00002280* The new :cfunc:`_beginthreadex` API is used to start threads, and
2281 the native thread-local storage functions are now used.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002282 (Contributed by Kristján Valur Jónsson; :issue:`3582`.)
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002283
Ezio Melotti11d22dc2010-04-20 09:55:05 +00002284* The :func:`os.kill` function now works on Windows. The signal value
2285 can be the constants :const:`CTRL_C_EVENT`,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002286 :const:`CTRL_BREAK_EVENT`, or any integer. The first two constants
2287 will send Control-C and Control-Break keystroke events to
2288 subprocesses; any other value will use the :cfunc:`TerminateProcess`
2289 API. (Contributed by Miki Tebeka; :issue:`1220212`.)
Ezio Melotti11d22dc2010-04-20 09:55:05 +00002290
Benjamin Petersonf6489f92009-11-25 17:46:26 +00002291* The :func:`os.listdir` function now correctly fails
2292 for an empty path. (Fixed by Hirokazu Yamamoto; :issue:`5913`.)
2293
Benjamin Peterson9eea4802009-12-31 03:31:15 +00002294* The :mod:`mimelib` module will now read the MIME database from
2295 the Windows registry when initializing.
2296 (Patch by Gabriel Genellina; :issue:`4969`.)
2297
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002298.. ======================================================================
2299
2300Port-Specific Changes: Mac OS X
2301-----------------------------------
2302
Benjamin Petersonf6489f92009-11-25 17:46:26 +00002303* The path ``/Library/Python/2.7/site-packages`` is now appended to
Benjamin Petersond23f8222009-04-05 19:13:16 +00002304 ``sys.path``, in order to share added packages between the system
2305 installation and a user-installed copy of the same version.
2306 (Changed by Ronald Oussoren; :issue:`4865`.)
2307
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002308Port-Specific Changes: FreeBSD
2309-----------------------------------
2310
2311* FreeBSD 7.1's :const:`SO_SETFIB` constant, used with
2312 :func:`~socket.getsockopt`/:func:`~socket.setsockopt` to select an
2313 alternate routing table, is now available in the :mod:`socket`
2314 module. (Added by Kyle VanderBeek; :issue:`8235`.)
Benjamin Petersond23f8222009-04-05 19:13:16 +00002315
2316Other Changes and Fixes
2317=======================
2318
Benjamin Peterson9895f912010-03-21 22:05:32 +00002319* Two benchmark scripts, :file:`iobench` and :file:`ccbench`, were
2320 added to the :file:`Tools` directory. :file:`iobench` measures the
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002321 speed of the built-in file I/O objects returned by :func:`open`
Benjamin Peterson9895f912010-03-21 22:05:32 +00002322 while performing various operations, and :file:`ccbench` is a
2323 concurrency benchmark that tries to measure computing throughput,
2324 thread switching latency, and IO processing bandwidth when
2325 performing several tasks using a varying number of threads.
2326
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002327* The :file:`Tools/i18n/msgfmt.py` script now understands plural
2328 forms in :file:`.po` files. (Fixed by Martin von Löwis;
2329 :issue:`5464`.)
2330
Benjamin Petersond23f8222009-04-05 19:13:16 +00002331* When importing a module from a :file:`.pyc` or :file:`.pyo` file
2332 with an existing :file:`.py` counterpart, the :attr:`co_filename`
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002333 attributes of the resulting code objects are overwritten when the
2334 original filename is obsolete. This can happen if the file has been
2335 renamed, moved, or is accessed through different paths. (Patch by
2336 Ziga Seilnacht and Jean-Paul Calderone; :issue:`1180193`.)
Benjamin Petersond23f8222009-04-05 19:13:16 +00002337
2338* The :file:`regrtest.py` script now takes a :option:`--randseed=`
2339 switch that takes an integer that will be used as the random seed
2340 for the :option:`-r` option that executes tests in random order.
Benjamin Petersonf6489f92009-11-25 17:46:26 +00002341 The :option:`-r` option also reports the seed that was used
Benjamin Petersond23f8222009-04-05 19:13:16 +00002342 (Added by Collin Winter.)
2343
Benjamin Petersona28e7022010-01-09 18:53:06 +00002344* Another :file:`regrtest.py` switch is :option:`-j`, which
2345 takes an integer specifying how many tests run in parallel. This
Benjamin Petersonf6489f92009-11-25 17:46:26 +00002346 allows reducing the total runtime on multi-core machines.
Antoine Pitrou88909542009-06-29 13:54:42 +00002347 This option is compatible with several other options, including the
2348 :option:`-R` switch which is known to produce long runtimes.
Benjamin Petersona28e7022010-01-09 18:53:06 +00002349 (Added by Antoine Pitrou, :issue:`6152`.) This can also be used
2350 with a new :option:`-F` switch that runs selected tests in a loop
2351 until they fail. (Added by Antoine Pitrou; :issue:`7312`.)
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002352
Ezio Melotti11d22dc2010-04-20 09:55:05 +00002353* When executed as a script, the :file:`py_compile.py` module now
2354 accepts ``'-'`` as an argument, which will read standard input for
2355 the list of filenames to be compiled. (Contributed by Piotr
2356 Ożarowski; :issue:`8233`.)
2357
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002358.. ======================================================================
2359
2360Porting to Python 2.7
2361=====================
2362
2363This section lists previously described changes and other bugfixes
2364that may require changes to your code:
2365
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002366* The :func:`range` function processes its arguments more
2367 consistently; it will now call :meth:`__int__` on non-float,
2368 non-integer arguments that are supplied to it. (Fixed by Alexander
2369 Belopolsky; :issue:`1533`.)
Benjamin Petersonf6489f92009-11-25 17:46:26 +00002370
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002371* The string :meth:`format` method changed the default precision used
2372 for floating-point and complex numbers from 6 decimal
Benjamin Petersonf6489f92009-11-25 17:46:26 +00002373 places to 12, which matches the precision used by :func:`str`.
2374 (Changed by Eric Smith; :issue:`5920`.)
2375
Benjamin Peterson87c8d872009-06-11 22:54:11 +00002376* Because of an optimization for the :keyword:`with` statement, the special
2377 methods :meth:`__enter__` and :meth:`__exit__` must belong to the object's
2378 type, and cannot be directly attached to the object's instance. This
2379 affects new-style classes (derived from :class:`object`) and C extension
2380 types. (:issue:`6101`.)
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002381
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002382* Due to a bug in Python 2.6, the *exc_value* parameter to
2383 :meth:`__exit__` methods was often the string representation of the
2384 exception, not an instance. This was fixed in 2.7, so *exc_value*
2385 will be an instance as expected. (Fixed by Florent Xicluna;
2386 :issue:`7853`.)
2387
2388* When a restricted set of attributes were set using ``__slots__``,
2389 deleting an unset attribute would not raise :exc:`AttributeError`
2390 as you would expect. Fixed by Benjamin Peterson; :issue:`7604`.)
Benjamin Peterson9eea4802009-12-31 03:31:15 +00002391
Benjamin Peterson9895f912010-03-21 22:05:32 +00002392In the standard library:
2393
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002394* Operations with :class:`datetime` instances that resulted in a year
2395 falling outside the supported range didn't always raise
2396 :exc:`OverflowError`. Such errors are now checked more carefully
2397 and will now raise the exception. (Reported by Mark Leander, patch
2398 by Anand B. Pillai and Alexander Belopolsky; :issue:`7150`.)
2399
2400* When using :class:`Decimal` instances with a string's
2401 :meth:`format` method, the default alignment was previously
2402 left-alignment. This has been changed to right-alignment, which might
2403 change the output of your programs.
2404 (Changed by Mark Dickinson; :issue:`6857`.)
2405
2406 Comparisons involving a signaling NaN value (or ``sNAN``) now signal
2407 :const:`InvalidOperation` instead of silently returning a true or
2408 false value depending on the comparison operator. Quiet NaN values
2409 (or ``NaN``) are now hashable. (Fixed by Mark Dickinson;
2410 :issue:`7279`.)
2411
Benjamin Peterson9895f912010-03-21 22:05:32 +00002412* The ElementTree library, :mod:`xml.etree`, no longer escapes
2413 ampersands and angle brackets when outputting an XML processing
2414 instruction (which looks like `<?xml-stylesheet href="#style1"?>`)
2415 or comment (which looks like `<!-- comment -->`).
2416 (Patch by Neil Muller; :issue:`2746`.)
2417
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002418* The :meth:`readline` method of :class:`StringIO` objects now does
2419 nothing when a negative length is requested, as other file-like
2420 objects do. (:issue:`7348`).
2421
2422* The :mod:`syslog` module will now use the value of ``sys.argv[0]`` as the
2423 identifier instead of the previous default value of ``'python'``.
2424 (Changed by Sean Reifschneider; :issue:`8451`.)
2425
2426* The :mod:`tarfile` module's default error handling has changed, to
2427 no longer suppress fatal errors. The default error level was previously 0,
2428 which meant that errors would only result in a message being written to the
2429 debug log, but because the debug log is not activated by default,
2430 these errors go unnoticed. The default error level is now 1,
2431 which raises an exception if there's an error.
2432 (Changed by Lars Gustäbel; :issue:`7357`.)
2433
2434* The :mod:`urlparse` module's :func:`~urlparse.urlsplit` now handles
2435 unknown URL schemes in a fashion compliant with :rfc:`3986`: if the
2436 URL is of the form ``"<something>://..."``, the text before the
2437 ``://`` is treated as the scheme, even if it's a made-up scheme that
2438 the module doesn't know about. This change may break code that
2439 worked around the old behaviour. For example, Python 2.6.4 or 2.5
2440 will return the following:
2441
2442 >>> import urlparse
2443 >>> urlparse.urlsplit('invented://host/filename?query')
2444 ('invented', '', '//host/filename?query', '', '')
2445
2446 Python 2.7 (and Python 2.6.5) will return:
2447
2448 >>> import urlparse
2449 >>> urlparse.urlsplit('invented://host/filename?query')
2450 ('invented', 'host', '/filename?query', '', '')
2451
2452 (Python 2.7 actually produces slightly different output, since it
2453 returns a named tuple instead of a standard tuple.)
2454
Benjamin Petersona28e7022010-01-09 18:53:06 +00002455For C extensions:
2456
2457* C extensions that use integer format codes with the ``PyArg_Parse*``
2458 family of functions will now raise a :exc:`TypeError` exception
2459 instead of triggering a :exc:`DeprecationWarning` (:issue:`5080`).
2460
2461* Use the new :cfunc:`PyOS_string_to_double` function instead of the old
2462 :cfunc:`PyOS_ascii_strtod` and :cfunc:`PyOS_ascii_atof` functions,
2463 which are now deprecated.
2464
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002465For applications that embed Python:
2466
2467* The :cfunc:`PySys_SetArgvEx` function was added, letting
2468 applications close a security hole when the existing
2469 :cfunc:`PySys_SetArgv` function was used. Check whether you're
2470 calling :cfunc:`PySys_SetArgv` and carefully consider whether the
2471 application should be using :cfunc:`PySys_SetArgvEx` with
2472 *updatepath* set to false.
Benjamin Petersona28e7022010-01-09 18:53:06 +00002473
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002474.. ======================================================================
2475
2476
2477.. _acks27:
2478
2479Acknowledgements
2480================
2481
2482The author would like to thank the following people for offering
2483suggestions, corrections and assistance with various drafts of this
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002484article: Nick Coghlan, Philip Jenvey, Ryan Lovett, R. David Murray,
2485Hugh Secker-Walker.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002486