blob: 300ef908174f0d82ee985bd24162627788d764e2 [file] [log] [blame]
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001****************************
2 What's New in Python 2.7
3****************************
4
5:Author: A.M. Kuchling (amk at amk.ca)
6:Release: |release|
7:Date: |today|
8
Andrew M. Kuchling6d7dfa22010-04-11 12:49:37 +00009.. hyperlink all the methods & functions.
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +000010
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +000011.. T_STRING_INPLACE not described in main docs
Andrew M. Kuchling0efe18a2010-05-08 15:39:46 +000012.. "Format String Syntax" in string.rst could use many more examples.
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +000013
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000014.. $Id$
15 Rules for maintenance:
16
17 * Anyone can add text to this document. Do not spend very much time
18 on the wording of your changes, because your text will probably
19 get rewritten to some degree.
20
21 * The maintainer will go through Misc/NEWS periodically and add
22 changes; it's therefore more important to add your changes to
23 Misc/NEWS than to this file.
24
25 * This is not a complete list of every single change; completeness
26 is the purpose of Misc/NEWS. Some changes I consider too small
27 or esoteric to include. If such a change is added to the text,
28 I'll just remove it. (This is another reason you shouldn't spend
29 too much time on writing your addition.)
30
31 * If you want to draw your new text to the attention of the
32 maintainer, add 'XXX' to the beginning of the paragraph or
33 section.
34
35 * It's OK to just add a fragmentary note about a change. For
36 example: "XXX Describe the transmogrify() function added to the
37 socket module." The maintainer will research the change and
38 write the necessary text.
39
40 * You can comment out your additions if you like, but it's not
41 necessary (especially when a final release is some months away).
42
Ezio Melotti021f3342010-04-06 03:26:49 +000043 * Credit the author of a patch or bugfix. Just the name is
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000044 sufficient; the e-mail address isn't necessary.
45
46 * It's helpful to add the bug/patch number in a parenthetical comment.
47
48 XXX Describe the transmogrify() function added to the socket
49 module.
50 (Contributed by P.Y. Developer; :issue:`12345`.)
51
52 This saves the maintainer some effort going through the SVN logs
53 when researching a change.
54
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +000055This article explains the new features in Python 2.7. The final
Andrew M. Kuchling837a5382010-05-06 17:21:59 +000056release of 2.7 is currently scheduled for July 2010; the detailed
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +000057schedule is described in :pep:`373`.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000058
Andrew M. Kuchling0efe18a2010-05-08 15:39:46 +000059Python 2.7 is planned to be the last of the 2.x releases, so we worked
60on making it a good release for the long term. To help with porting
61to Python 3, several new features from the Python 3.x series have been
62included in 2.7.
63
64Numeric handling has been improved in many ways, both for
65floating-point numbers and for the :class:`Decimal` class. There are
66some useful additions to the standard library, such as a greatly
67enhanced :mod:`unittest` module, the :mod:`argparse` module for
68parsing command-line options, convenient ordered-dictionary and
69:class:`Counter` classes in the :mod:`collections` module, and many
70other improvements.
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.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000080
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +000081.. _whatsnew27-python31:
82
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +000083The Future for Python 2.x
84=========================
85
86Python 2.7 is intended to be the last major release in the 2.x series.
Andrew M. Kuchlingd1e696b2010-05-07 11:30:47 +000087The Python maintainers are planning to focus their future efforts on
88the Python 3.x series.
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +000089
90This means that 2.7 will remain in place for a long time, running
91production systems that have not been ported to Python 3.x.
92Two consequences of the long-term significance of 2.7 are:
93
94* It's very likely the 2.7 release will have a longer period of
95 maintenance compared to earlier 2.x versions. Python 2.7 will
Andrew M. Kuchling0efe18a2010-05-08 15:39:46 +000096 continue to be maintained while the transition to 3.x continues, and
97 the developers are planning to support Python 2.7 with bug-fix
98 releases beyond the typical two years.
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +000099
Andrew M. Kuchlingd1e696b2010-05-07 11:30:47 +0000100* A policy decision was made to silence warnings only of interest to
101 developers by default. :exc:`DeprecationWarning` and its
102 descendants are now ignored unless otherwise requested, preventing
Andrew M. Kuchling0efe18a2010-05-08 15:39:46 +0000103 users from seeing warnings triggered by an application. This change
104 was also made in the branch that will become Python 3.2. (Discussed
105 on stdlib-sig and carried out in :issue:`7319`.)
Andrew M. Kuchlingd1e696b2010-05-07 11:30:47 +0000106
107 In previous releases, :exc:`DeprecationWarning` messages were
108 enabled by default, providing Python developers with a clear
109 indication of where their code may break in a future major version
110 of Python.
111
112 However, there are increasingly many users of Python-based
113 applications who are not directly involved in the development of
114 those applications. :exc:`DeprecationWarning` messages are
115 irrelevant to such users, making them worry about an application
116 that's actually working correctly and burdening the developers of
117 these applications with responding to these concerns.
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +0000118
119 You can re-enable display of :exc:`DeprecationWarning` messages by
120 running Python with the :option:`-Wdefault` (short form:
Andrew M. Kuchling0efe18a2010-05-08 15:39:46 +0000121 :option:`-Wd`) switch, or by setting the :envvar:`PYTHONWARNINGS`
122 environment variable to ``"default"`` or ``"d"``) before running
123 Python. Python code can also re-enable them
124 by calling ``warnings.simplefilter('default')``.
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +0000125
126
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000127Python 3.1 Features
128=======================
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000129
130Much as Python 2.6 incorporated features from Python 3.0,
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000131version 2.7 incorporates some of the new features
132in Python 3.1. The 2.x series continues to provide tools
133for migrating to the 3.x series.
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000134
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000135A partial list of 3.1 features that were backported to 2.7:
136
Andrew M. Kuchling0efe18a2010-05-08 15:39:46 +0000137* The syntax for set literals (``{1,2,3}`` is a mutable set).
138* Dictionary and set comprehensions (``{ i: i*2 for i in range(3)}``).
Andrew M. Kuchling93c40d42010-05-10 14:18:27 +0000139* Multiple context managers in a single :keyword:`with` statement.
Andrew M. Kuchling837a5382010-05-06 17:21:59 +0000140* A new version of the :mod:`io` library, rewritten in C for performance.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000141* The ordered-dictionary type described in :ref:`pep-0372`.
Andrew M. Kuchling8f254e72009-12-08 02:37:05 +0000142* The new format specifier described in :ref:`pep-0378`.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000143* The :class:`memoryview` object.
144* A small subset of the :mod:`importlib` module `described below <#importlib-section>`__.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000145* Float-to-string and string-to-float conversions now round their
146 results more correctly. And :func:`repr` of a floating-point
147 number *x* returns a result that's guaranteed to round back to the
148 same number when converted back to a string.
Andrew M. Kuchling93c40d42010-05-10 14:18:27 +0000149* The :ctype:`PyCapsule` type, used to provide a C API for extension modules.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000150* The :cfunc:`PyLong_AsLongAndOverflow` C API function.
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000151
152One porting change: the :option:`-3` switch now automatically
153enables the :option:`-Qwarn` switch that causes warnings
154about using classic division with integers and long integers.
155
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000156Other new Python3-mode warnings include:
157
158* :func:`operator.isCallable` and :func:`operator.sequenceIncludes`,
159 which are not supported in 3.x.
160
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000161.. ========================================================================
162.. Large, PEP-level features and changes should be described here.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000163.. ========================================================================
164
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000165.. _pep-0372:
166
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000167PEP 372: Adding an ordered dictionary to collections
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000168====================================================
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000169
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000170Regular Python dictionaries iterate over key/value pairs in arbitrary order.
171Over the years, a number of authors have written alternative implementations
172that remember the order that the keys were originally inserted. Based on
173the experiences from those implementations, a new
Ezio Melotti021f3342010-04-06 03:26:49 +0000174:class:`~collections.OrderedDict` class has been introduced in the
175:mod:`collections` module.
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000176
Ezio Melotti021f3342010-04-06 03:26:49 +0000177The :class:`~collections.OrderedDict` API is substantially the same as regular
178dictionaries but will iterate over keys and values in a guaranteed order
179depending on when a key was first inserted::
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000180
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000181 >>> from collections import OrderedDict
182 >>> d = OrderedDict([('first', 1), ('second', 2),
183 ... ('third', 3)])
184 >>> d.items()
185 [('first', 1), ('second', 2), ('third', 3)]
186
187If a new entry overwrites an existing entry, the original insertion
188position is left unchanged::
189
190 >>> d['second'] = 4
191 >>> d.items()
192 [('first', 1), ('second', 4), ('third', 3)]
193
194Deleting an entry and reinserting it will move it to the end::
195
196 >>> del d['second']
197 >>> d['second'] = 5
198 >>> d.items()
199 [('first', 1), ('third', 3), ('second', 5)]
200
Ezio Melotti021f3342010-04-06 03:26:49 +0000201The :meth:`~collections.OrderedDict.popitem` method has an optional *last*
202argument that defaults to True. If *last* is True, the most recently
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000203added key is returned and removed; if it's False, the
204oldest key is selected::
205
206 >>> od = OrderedDict([(x,0) for x in range(20)])
207 >>> od.popitem()
208 (19, 0)
209 >>> od.popitem()
210 (18, 0)
Ezio Melotti021f3342010-04-06 03:26:49 +0000211 >>> od.popitem(last=False)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000212 (0, 0)
Ezio Melotti021f3342010-04-06 03:26:49 +0000213 >>> od.popitem(last=False)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000214 (1, 0)
215
216Comparing two ordered dictionaries checks both the keys and values,
217and requires that the insertion order was the same::
218
219 >>> od1 = OrderedDict([('first', 1), ('second', 2),
220 ... ('third', 3)])
221 >>> od2 = OrderedDict([('third', 3), ('first', 1),
222 ... ('second', 2)])
Ezio Melotti021f3342010-04-06 03:26:49 +0000223 >>> od1 == od2
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000224 False
225 >>> # Move 'third' key to the end
Ezio Melotti021f3342010-04-06 03:26:49 +0000226 >>> del od2['third']; od2['third'] = 3
227 >>> od1 == od2
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000228 True
229
Ezio Melotti021f3342010-04-06 03:26:49 +0000230Comparing an :class:`~collections.OrderedDict` with a regular dictionary
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000231ignores the insertion order and just compares the keys and values.
232
Ezio Melotti021f3342010-04-06 03:26:49 +0000233How does the :class:`~collections.OrderedDict` work? It maintains a
234doubly-linked list of keys, appending new keys to the list as they're inserted.
235A secondary dictionary maps keys to their corresponding list node, so
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000236deletion doesn't have to traverse the entire linked list and therefore
237remains O(1).
238
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000239The standard library now supports use of ordered dictionaries in several
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +0000240modules.
241
242* The :mod:`ConfigParser` module uses them by default, letting
243 configuration files be read, modified, and then written back in their original
244 order.
245
246* The :meth:`~collections.somenamedtuple._asdict()` method for
247 :func:`collections.namedtuple` now returns an ordered dictionary with the
248 values appearing in the same order as the underlying tuple indices.
249
250* The :mod:`json` module's :class:`~json.JSONDecoder` class
251 constructor was extended with an *object_pairs_hook* parameter to
252 allow :class:`OrderedDict` instances to be built by the decoder.
253 Support was also added for third-party tools like
254 `PyYAML <http://pyyaml.org/>`_.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000255
Andrew M. Kuchling7fe65a02009-10-13 15:49:33 +0000256.. seealso::
257
258 :pep:`372` - Adding an ordered dictionary to collections
259 PEP written by Armin Ronacher and Raymond Hettinger;
260 implemented by Raymond Hettinger.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000261
262.. _pep-0378:
263
264PEP 378: Format Specifier for Thousands Separator
Ezio Melotti021f3342010-04-06 03:26:49 +0000265=================================================
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000266
267To make program output more readable, it can be useful to add
268separators to large numbers and render them as
26918,446,744,073,709,551,616 instead of 18446744073709551616.
270
271The fully general solution for doing this is the :mod:`locale` module,
272which can use different separators ("," in North America, "." in
273Europe) and different grouping sizes, but :mod:`locale` is complicated
274to use and unsuitable for multi-threaded applications where different
275threads are producing output for different locales.
276
277Therefore, a simple comma-grouping mechanism has been added to the
Ezio Melotti021f3342010-04-06 03:26:49 +0000278mini-language used by the :meth:`str.format` method. When
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000279formatting a floating-point number, simply include a comma between the
280width and the precision::
281
Eric Smithc4663852010-04-06 14:30:15 +0000282 >>> '{:20,.2f}'.format(18446744073709551616.0)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000283 '18,446,744,073,709,551,616.00'
284
Eric Smith6a928602010-04-06 15:17:33 +0000285When formatting an integer, include the comma after the width:
286
287 >>> '{:20,d}'.format(18446744073709551616)
288 '18,446,744,073,709,551,616'
289
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000290This mechanism is not adaptable at all; commas are always used as the
291separator and the grouping is always into three-digit groups. The
292comma-formatting mechanism isn't as general as the :mod:`locale`
293module, but it's easier to use.
294
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000295.. seealso::
296
297 :pep:`378` - Format Specifier for Thousands Separator
298 PEP written by Raymond Hettinger; implemented by Eric Smith.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000299
Andrew M. Kuchlingab21f752010-03-02 13:55:33 +0000300PEP 389: The argparse Module for Parsing Command Lines
301======================================================
302
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000303The :mod:`argparse` module for parsing command-line arguments was
304added, intended as a more powerful replacement for the
305:mod:`optparse` module.
306
307This means Python now supports three different modules for parsing
308command-line arguments: :mod:`getopt`, :mod:`optparse`, and
309:mod:`argparse`. The :mod:`getopt` module closely resembles the C
310:cfunc:`getopt` function, so it remains useful if you're writing a
311Python prototype that will eventually be rewritten in C.
312:mod:`optparse` becomes redundant, but there are no plans to remove it
313because there are many scripts still using it, and there's no
314automated way to update these scripts. (Making the :mod:`argparse`
315API consistent with :mod:`optparse`'s interface was discussed but
316rejected as too messy and difficult.)
317
Andrew M. Kuchlingf03641a2010-04-14 01:14:59 +0000318In short, if you're writing a new script and don't need to worry
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000319about compatibility with earlier versions of Python, use
320:mod:`argparse` instead of :mod:`optparse`.
321
Andrew M. Kuchlingf03641a2010-04-14 01:14:59 +0000322Here's an example::
323
324 import argparse
325
326 parser = argparse.ArgumentParser(description='Command-line example.')
327
328 # Add optional switches
329 parser.add_argument('-v', action='store_true', dest='is_verbose',
330 help='produce verbose output')
331 parser.add_argument('-o', action='store', dest='output',
332 metavar='FILE',
333 help='direct output to FILE instead of stdout')
334 parser.add_argument('-C', action='store', type=int, dest='context',
335 metavar='NUM', default=0,
336 help='display NUM lines of added context')
337
338 # Allow any number of additional arguments.
339 parser.add_argument(nargs='*', action='store', dest='inputs',
340 help='input filenames (default is stdin)')
341
342 args = parser.parse_args()
343 print args.__dict__
344
345Unless you override it, :option:`-h` and :option:`--help` switches
346are automatically added, and produce neatly formatted output::
347
348 -> ./python.exe argparse-example.py --help
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +0000349 usage: argparse-example.py [-h] [-v] [-o FILE] [-C NUM] [inputs [inputs ...]]
Andrew M. Kuchlingf03641a2010-04-14 01:14:59 +0000350
351 Command-line example.
352
353 positional arguments:
354 inputs input filenames (default is stdin)
355
356 optional arguments:
357 -h, --help show this help message and exit
358 -v produce verbose output
359 -o FILE direct output to FILE instead of stdout
360 -C NUM display NUM lines of added context
361
362Similarly to :mod:`optparse`, the command-line switches and arguments
363are returned as an object with attributes named by the *dest* parameters::
364
365 -> ./python.exe argparse-example.py -v
366 {'output': None, 'is_verbose': True, 'context': 0, 'inputs': []}
367
368 -> ./python.exe argparse-example.py -v -o /tmp/output -C 4 file1 file2
369 {'output': '/tmp/output', 'is_verbose': True, 'context': 4,
370 'inputs': ['file1', 'file2']}
371
372:mod:`argparse` has much fancier validation than :mod:`optparse`; you
373can specify an exact number of arguments as an integer, 0 or more
374arguments by passing ``'*'``, 1 or more by passing ``'+'``, or an
375optional argument with ``'?'``. A top-level parser can contain
376sub-parsers, so you can define subcommands that have different sets of
377switches, as in ``svn commit``, ``svn checkout``, etc. You can
378specify an argument type as :class:`~argparse.FileType`, which will
379automatically open files for you and understands that ``'-'`` means
380standard input or output.
Andrew M. Kuchlingab21f752010-03-02 13:55:33 +0000381
382.. seealso::
383
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000384 `argparse module documentation <http://docs.python.org/dev/library/argparse.html>`__
385
386 `Upgrading optparse code to use argparse <http://docs.python.org/dev/library/argparse.html#upgrading-optparse-code>`__
387
Andrew M. Kuchlingab21f752010-03-02 13:55:33 +0000388 :pep:`389` - argparse - New Command Line Parsing Module
389 PEP written and implemented by Steven Bethard.
390
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000391PEP 391: Dictionary-Based Configuration For Logging
392====================================================
393
Andrew M. Kuchlingb6c1aeb2010-04-14 14:28:31 +0000394.. not documented in library reference yet.
395
396The :mod:`logging` module is very flexible; an application can define
397a tree of logging subsystems, and each logger in this tree can filter
398out certain messages, format them differently, and direct messages to
399a varying number of handlers.
400
401All this flexibility can require a lot of configuration. You can
402write Python statements to create objects and set their properties,
403but a complex set-up would require verbose but boring code.
404:mod:`logging` also supports a :func:`~logging.config.fileConfig`
405function that parses a file, but the file format doesn't support
406configuring filters, and it's messier to generate programmatically.
407
408Python 2.7 adds a :func:`~logging.config.dictConfig` function that
409uses a dictionary, and there are many ways to produce a dictionary
410from different sources. You can construct one with code, of course.
411Python's standard library now includes a JSON parser, so you could
412parse a file containing JSON, or you could use a YAML parsing library
413if one is installed.
414
Andrew M. Kuchling8e343862010-05-08 13:28:03 +0000415The following example configures two loggers, the root logger and a
416logger named "network". Messages sent to the root logger will be
417sent to the system log using the syslog protocol, and messages
418to the "network" logger will be written to a :file:`network.log` file
419that will be rotated once the log reaches 1Mb.
420
421::
422
423 import logging
424 import logging.config
425
426 configdict = {
427 'version': 1, # Must be 1 at present
428 'formatters': {
429 'standard': {
430 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(message)s'}},
431
432 'handlers': {'netlog': {'backupCount': 10,
433 'class': 'logging.handlers.RotatingFileHandler',
434 'filename': '/logs/network.log',
435 'formatter': 'standard',
436 'level': 'INFO',
437 'maxBytes': 1024*1024},
438 'syslog': {'class': 'logging.handlers.SysLogHandler',
439 'formatter': 'standard',
440 'level': 'ERROR'}},
441
442 # Specify all the subordinate loggers
443 'loggers': {
444 'network': {
445 'handlers': ['netlog']
446 }
447 },
448 # Specify properties of the root logger
449 'root': {
450 'handlers': ['syslog']
451 },
452 }
453
454 # Set up configuration
455 logging.config.dictConfig(configdict)
456
457 # As an example, log two error messages
458 logger = logging.getLogger('/')
459 logger.error('Database not found')
460
461 netlogger = logging.getLogger('network')
462 netlogger.error('Connection failed')
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000463
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +0000464Three smaller enhancements to the :mod:`logging` module, all
465implemented by Vinay Sajip, are:
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000466
467.. rev79293
468
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +0000469* The :class:`~logging.handlers.SysLogHandler` class now supports
470 syslogging over TCP. The constructor has a *socktype* parameter
471 giving the type of socket to use, either :const:`socket.SOCK_DGRAM`
472 for UDP or :const:`socket.SOCK_STREAM` for TCP. The default
473 protocol remains UDP.
474
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +0000475* :class:`Logger` instances gained a :meth:`getChild` method that retrieves a
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000476 descendant logger using a relative path. For example,
477 once you retrieve a logger by doing ``log = getLogger('app')``,
478 calling ``log.getChild('network.listen')`` is equivalent to
479 ``getLogger('app.network.listen')``.
480
481* The :class:`LoggerAdapter` class gained a :meth:`isEnabledFor` method
482 that takes a *level* and returns whether the underlying logger would
483 process a message of that level of importance.
484
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000485.. seealso::
486
487 :pep:`391` - Dictionary-Based Configuration For Logging
488 PEP written and implemented by Vinay Sajip.
489
490PEP 3106: Dictionary Views
491====================================================
492
Andrew M. Kuchling85f928a2010-04-15 01:42:27 +0000493The dictionary methods :meth:`keys`, :meth:`values`, and :meth:`items`
494are different in Python 3.x. They return an object called a :dfn:`view`
495instead of a fully materialized list.
496
Andrew M. Kuchling85f928a2010-04-15 01:42:27 +0000497It's not possible to change the return values of :meth:`keys`,
498:meth:`values`, and :meth:`items` in Python 2.7 because too much code
499would break. Instead the 3.x versions were added under the new names
500of :meth:`viewkeys`, :meth:`viewvalues`, and :meth:`viewitems`.
501
502::
503
504 >>> d = dict((i*10, chr(65+i)) for i in range(26))
505 >>> d
506 {0: 'A', 130: 'N', 10: 'B', 140: 'O', 20: ..., 250: 'Z'}
507 >>> d.viewkeys()
508 dict_keys([0, 130, 10, 140, 20, 150, 30, ..., 250])
509
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +0000510Views can be iterated over, but they also behave like sets. The ``&``
511operator performs intersection, and ``|`` performs a union::
512
513 >>> d1 = dict((i*10, chr(65+i)) for i in range(26))
514 >>> d2 = dict((i**.5, i) for i in range(1000))
515 >>> d1.viewkeys() & d2.viewkeys()
516 set([0.0, 10.0, 20.0, 30.0])
517 >>> d1.viewkeys() | range(0, 30)
518 set([0, 1, 130, 3, 4, 5, 6, ..., 120, 250])
519
Andrew M. Kuchling85f928a2010-04-15 01:42:27 +0000520The view keeps track of the dictionary and its contents change as the
521dictionary is modified::
522
523 >>> vk = d.viewkeys()
524 >>> vk
525 dict_keys([0, 130, 10, ..., 250])
526 >>> d[260] = '&'
527 >>> vk
528 dict_keys([0, 130, 260, 10, ..., 250])
529
530However, note that you can't add or remove keys while you're iterating
531over the view::
532
533 >>> for k in vk:
534 ... d[k*2] = k
535 ...
536 Traceback (most recent call last):
537 File "<stdin>", line 1, in <module>
538 RuntimeError: dictionary changed size during iteration
539
540You can use the view methods in Python 2.x code, and the 2to3
541converter will change them to the standard :meth:`keys`,
542:meth:`values`, and :meth:`items` methods.
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000543
544.. seealso::
545
546 :pep:`3106` - Revamping dict.keys(), .values() and .items()
547 PEP written by Guido van Rossum.
548 Backported to 2.7 by Alexandre Vassalotti; :issue:`1967`.
549
550
Andrew M. Kuchling9fbbd3b2010-05-01 12:06:51 +0000551PEP 3137: The memoryview Object
552====================================================
553
554The :class:`memoryview` object provides a view of another object's
555memory content that matches the :class:`bytes` type's interface.
556
557 >>> import string
558 >>> m = memoryview(string.letters)
559 >>> m
560 <memory at 0x37f850>
561 >>> len(m) # Returns length of underlying object
562 52
563 >>> m[0], m[25], m[26] # Indexing returns one byte
564 ('a', 'z', 'A')
565 >>> m2 = m[0:26] # Slicing returns another memoryview
566 >>> m2
567 <memory at 0x37f080>
568
569The content of the view can be converted to a string of bytes or to
570a list of integers:
571
572 >>> m2.tobytes()
573 'abcdefghijklmnopqrstuvwxyz'
574 >>> m2.tolist()
575 [97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122]
576 >>>
577
578:class:`memoryview` objects allow modifying the underlying object if
579it's a mutable object.
580
581 >>> m2[0] = 75
582 Traceback (most recent call last):
583 File "<stdin>", line 1, in <module>
584 TypeError: cannot modify read-only memory
585 >>> b = bytearray(string.letters) # Creating a mutable object
586 >>> b
587 bytearray(b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
588 >>> mb = memoryview(b)
589 >>> mb[0] = '*' # Assign to view, changing the bytearray.
590 >>> b[0:5] # The bytearray has been changed.
591 bytearray(b'*bcde')
592 >>>
593
594.. seealso::
595
596 :pep:`3137` - Immutable Bytes and Mutable Buffer
597 PEP written by Guido van Rossum.
Antoine Pitrou5cace782010-05-01 12:16:39 +0000598 Implemented by Travis Oliphant, Antoine Pitrou and others.
Andrew M. Kuchling9fbbd3b2010-05-01 12:06:51 +0000599 Backported to 2.7 by Antoine Pitrou; :issue:`2396`.
600
601
602
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000603Other Language Changes
604======================
605
606Some smaller changes made to the core Python language are:
607
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000608* The syntax for set literals has been backported from Python 3.x.
609 Curly brackets are used to surround the contents of the resulting
610 mutable set; set literals are
611 distinguished from dictionaries by not containing colons and values.
612 ``{}`` continues to represent an empty dictionary; use
613 ``set()`` for an empty set.
614
615 >>> {1,2,3,4,5}
616 set([1, 2, 3, 4, 5])
Ezio Melotti021f3342010-04-06 03:26:49 +0000617 >>> set() # empty set
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000618 set([])
Ezio Melotti021f3342010-04-06 03:26:49 +0000619 >>> {} # empty dict
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000620 {}
621
622 Backported by Alexandre Vassalotti; :issue:`2335`.
623
624* Dictionary and set comprehensions are another feature backported from
625 3.x, generalizing list/generator comprehensions to use
626 the literal syntax for sets and dictionaries.
627
Andrew M. Kuchling0efe18a2010-05-08 15:39:46 +0000628 >>> {x: x*x for x in range(6)}
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000629 {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Andrew M. Kuchling0efe18a2010-05-08 15:39:46 +0000630 >>> {('a'*x) for x in range(6)}
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000631 set(['', 'a', 'aa', 'aaa', 'aaaa', 'aaaaa'])
632
633 Backported by Alexandre Vassalotti; :issue:`2333`.
634
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000635* The :keyword:`with` statement can now use multiple context managers
636 in one statement. Context managers are processed from left to right
637 and each one is treated as beginning a new :keyword:`with` statement.
638 This means that::
639
640 with A() as a, B() as b:
641 ... suite of statements ...
642
643 is equivalent to::
644
645 with A() as a:
646 with B() as b:
647 ... suite of statements ...
648
649 The :func:`contextlib.nested` function provides a very similar
650 function, so it's no longer necessary and has been deprecated.
651
652 (Proposed in http://codereview.appspot.com/53094; implemented by
653 Georg Brandl.)
654
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000655* Conversions between floating-point numbers and strings are
656 now correctly rounded on most platforms. These conversions occur
657 in many different places: :func:`str` on
658 floats and complex numbers; the :class:`float` and :class:`complex`
659 constructors;
660 numeric formatting; serialization and
661 deserialization of floats and complex numbers using the
662 :mod:`marshal`, :mod:`pickle`
663 and :mod:`json` modules;
664 parsing of float and imaginary literals in Python code;
Ezio Melotti021f3342010-04-06 03:26:49 +0000665 and :class:`~decimal.Decimal`-to-float conversion.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000666
667 Related to this, the :func:`repr` of a floating-point number *x*
668 now returns a result based on the shortest decimal string that's
669 guaranteed to round back to *x* under correct rounding (with
670 round-half-to-even rounding mode). Previously it gave a string
671 based on rounding x to 17 decimal digits.
672
Ezio Melotti021f3342010-04-06 03:26:49 +0000673 .. maybe add an example?
674
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000675 The rounding library responsible for this improvement works on
676 Windows, and on Unix platforms using the gcc, icc, or suncc
677 compilers. There may be a small number of platforms where correct
678 operation of this code cannot be guaranteed, so the code is not
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +0000679 used on such systems. You can find out which code is being used
680 by checking :data:`sys.float_repr_style`, which will be ``short``
681 if the new code is in use and ``legacy`` if it isn't.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000682
Mark Dickinsonbdd863d2010-01-07 09:28:29 +0000683 Implemented by Eric Smith and Mark Dickinson, using David Gay's
684 :file:`dtoa.c` library; :issue:`7117`.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000685
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000686* The :meth:`str.format` method now supports automatic numbering of the replacement
Benjamin Petersonaa0a0b92009-04-11 20:27:15 +0000687 fields. This makes using :meth:`str.format` more closely resemble using
688 ``%s`` formatting::
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000689
690 >>> '{}:{}:{}'.format(2009, 04, 'Sunday')
691 '2009:4:Sunday'
692 >>> '{}:{}:{day}'.format(2009, 4, day='Sunday')
693 '2009:4:Sunday'
694
Benjamin Petersonaa0a0b92009-04-11 20:27:15 +0000695 The auto-numbering takes the fields from left to right, so the first ``{...}``
696 specifier will use the first argument to :meth:`str.format`, the next
697 specifier will use the next argument, and so on. You can't mix auto-numbering
698 and explicit numbering -- either number all of your specifier fields or none
699 of them -- but you can mix auto-numbering and named fields, as in the second
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000700 example above. (Contributed by Eric Smith; :issue:`5237`.)
701
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000702 Complex numbers now correctly support usage with :func:`format`,
703 and default to being right-aligned.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000704 Specifying a precision or comma-separation applies to both the real
705 and imaginary parts of the number, but a specified field width and
706 alignment is applied to the whole of the resulting ``1.5+3j``
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000707 output. (Contributed by Eric Smith; :issue:`1588` and :issue:`7988`.)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000708
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000709 The 'F' format code now always formats its output using uppercase characters,
710 so it will now produce 'INF' and 'NAN'.
711 (Contributed by Eric Smith; :issue:`3382`.)
712
Andrew M. Kuchlingc4ae73e2010-04-30 13:47:34 +0000713 A low-level change: the :meth:`object.__format__` method now triggers
714 a :exc:`PendingDeprecationWarning` if it's passed a format string,
715 because the :meth:`__format__` method for :class:`object` converts
716 the object to a string representation and formats that. The method
717 used to silently apply the format string to the string
718 representation, but that could hide mistakes in Python code. If
719 you're supplying formatting information such as an alignment or
720 precision, presumably you're expecting the formatting to be applied
721 in some object-specific way. (Fixed by Eric Smith; :issue:`7994`.)
722
Mark Dickinson1a707982008-12-17 16:14:37 +0000723* The :func:`int` and :func:`long` types gained a ``bit_length``
Georg Brandl64e1c752009-04-11 18:19:27 +0000724 method that returns the number of bits necessary to represent
Mark Dickinson1a707982008-12-17 16:14:37 +0000725 its argument in binary::
726
727 >>> n = 37
Ezio Melotti021f3342010-04-06 03:26:49 +0000728 >>> bin(n)
Mark Dickinson1a707982008-12-17 16:14:37 +0000729 '0b100101'
730 >>> n.bit_length()
731 6
732 >>> n = 2**123-1
733 >>> n.bit_length()
734 123
735 >>> (n+1).bit_length()
736 124
737
738 (Contributed by Fredrik Johansson and Victor Stinner; :issue:`3439`.)
739
Andrew M. Kuchling92b97002009-05-02 17:12:15 +0000740* Conversions from long integers and regular integers to floating
741 point now round differently, returning the floating-point number
742 closest to the number. This doesn't matter for small integers that
743 can be converted exactly, but for large numbers that will
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000744 unavoidably lose precision, Python 2.7 now approximates more
Andrew M. Kuchling92b97002009-05-02 17:12:15 +0000745 closely. For example, Python 2.6 computed the following::
746
747 >>> n = 295147905179352891391
748 >>> float(n)
749 2.9514790517935283e+20
750 >>> n - long(float(n))
751 65535L
752
753 Python 2.7's floating-point result is larger, but much closer to the
754 true value::
755
756 >>> n = 295147905179352891391
757 >>> float(n)
758 2.9514790517935289e+20
Ezio Melotti021f3342010-04-06 03:26:49 +0000759 >>> n - long(float(n))
Andrew M. Kuchling92b97002009-05-02 17:12:15 +0000760 -1L
761
762 (Implemented by Mark Dickinson; :issue:`3166`.)
763
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000764 Integer division is also more accurate in its rounding behaviours. (Also
765 implemented by Mark Dickinson; :issue:`1811`.)
766
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000767* It's now possible for a subclass of the built-in :class:`unicode` type
768 to override the :meth:`__unicode__` method. (Implemented by
769 Victor Stinner; :issue:`1583863`.)
770
Ezio Melotti021f3342010-04-06 03:26:49 +0000771* The :class:`bytearray` type's :meth:`~bytearray.translate` method now accepts
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000772 ``None`` as its first argument. (Fixed by Georg Brandl;
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000773 :issue:`4759`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000774
Ezio Melotti021f3342010-04-06 03:26:49 +0000775 .. bytearray doesn't seem to be documented
776
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000777* When using ``@classmethod`` and ``@staticmethod`` to wrap
778 methods as class or static methods, the wrapper object now
779 exposes the wrapped function as their :attr:`__func__` attribute.
780 (Contributed by Amaury Forgeot d'Arc, after a suggestion by
781 George Sakkis; :issue:`5982`.)
782
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +0000783* When a restricted set of attributes were set using ``__slots__``,
784 deleting an unset attribute would not raise :exc:`AttributeError`
785 as you would expect. Fixed by Benjamin Peterson; :issue:`7604`.)
786
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000787* A new encoding named "cp720", used primarily for Arabic text, is now
788 supported. (Contributed by Alexander Belchenko and Amaury Forgeot
789 d'Arc; :issue:`1616979`.)
790
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000791* The :class:`file` object will now set the :attr:`filename` attribute
792 on the :exc:`IOError` exception when trying to open a directory
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +0000793 on POSIX platforms (noted by Jan Kaliszewski; :issue:`4764`), and
794 now explicitly checks for and forbids writing to read-only file objects
795 instead of trusting the C library to catch and report the error
796 (fixed by Stefan Krah; :issue:`5677`).
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000797
Benjamin Petersonae9a0a02009-12-31 16:49:37 +0000798* The Python tokenizer now translates line endings itself, so the
799 :func:`compile` built-in function can now accept code using any
800 line-ending convention. Additionally, it no longer requires that the
801 code end in a newline.
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +0000802
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000803* Extra parentheses in function definitions are illegal in Python 3.x,
804 meaning that you get a syntax error from ``def f((x)): pass``. In
805 Python3-warning mode, Python 2.7 will now warn about this odd usage.
806 (Noted by James Lingard; :issue:`7362`.)
807
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +0000808* It's now possible to create weak references to old-style class
809 objects. New-style classes were always weak-referenceable. (Fixed
810 by Antoine Pitrou; :issue:`8268`.)
811
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000812* When a module object is garbage-collected, the module's dictionary is
813 now only cleared if no one else is holding a reference to the
814 dictionary (:issue:`7140`).
815
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000816.. ======================================================================
817
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000818.. _new-27-interpreter:
819
820Interpreter Changes
821-------------------------------
822
823A new environment variable, :envvar:`PYTHONWARNINGS`,
824allows controlling warnings. It should be set to a string
825containing warning settings, equivalent to those
826used with the :option:`-W` switch, separated by commas.
827(Contributed by Brian Curtin; :issue:`7301`.)
828
829For example, the following setting will print warnings every time
830they occur, but turn warnings from the :mod:`Cookie` module into an
831error. (The exact syntax for setting an environment variable varies
832across operating systems and shells, so it may be different for you.)
833
834::
835
836 export PYTHONWARNINGS=all,error:::Cookie:0
837
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +0000838When running a module using the interpreter's :option:`-m` switch,
839``sys.argv[0]`` will now be set to the string ``'-m'`` while the
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +0000840module is being located, while executing the :file:`__init__.py` files
841for any parent packages of the module to be executed.
842(Suggested by Michael Foord; implemented by Nick Coghlan;
843:issue:`8202`.)
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000844
845.. ======================================================================
846
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000847
848Optimizations
849-------------
850
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000851Several performance enhancements have been added:
852
853.. * A new :program:`configure` option, :option:`--with-computed-gotos`,
854 compiles the main bytecode interpreter loop using a new dispatch
855 mechanism that gives speedups of up to 20%, depending on the system
856 and benchmark. The new mechanism is only supported on certain
857 compilers, such as gcc, SunPro, and icc.
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000858
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000859* A new opcode was added to perform the initial setup for
860 :keyword:`with` statements, looking up the :meth:`__enter__` and
861 :meth:`__exit__` methods. (Contributed by Benjamin Peterson.)
862
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000863* The garbage collector now performs better for one common usage
864 pattern: when many objects are being allocated without deallocating
865 any of them. This would previously take quadratic
866 time for garbage collection, but now the number of full garbage collections
867 is reduced as the number of objects on the heap grows.
868 The new logic is to only perform a full garbage collection pass when
869 the middle generation has been collected 10 times and when the
870 number of survivor objects from the middle generation exceeds 10% of
871 the number of objects in the oldest generation. (Suggested by Martin
Ezio Melotti021f3342010-04-06 03:26:49 +0000872 von Löwis and implemented by Antoine Pitrou; :issue:`4074`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000873
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000874* The garbage collector tries to avoid tracking simple containers
875 which can't be part of a cycle. In Python 2.7, this is now true for
876 tuples and dicts containing atomic types (such as ints, strings,
877 etc.). Transitively, a dict containing tuples of atomic types won't
878 be tracked either. This helps reduce the cost of each
879 garbage collection by decreasing the number of objects to be
880 considered and traversed by the collector.
Antoine Pitrouc18f6b02009-03-28 19:10:13 +0000881 (Contributed by Antoine Pitrou; :issue:`4688`.)
882
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000883* Long integers are now stored internally either in base 2**15 or in base
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000884 2**30, the base being determined at build time. Previously, they
885 were always stored in base 2**15. Using base 2**30 gives
886 significant performance improvements on 64-bit machines, but
887 benchmark results on 32-bit machines have been mixed. Therefore,
888 the default is to use base 2**30 on 64-bit machines and base 2**15
889 on 32-bit machines; on Unix, there's a new configure option
890 :option:`--enable-big-digits` that can be used to override this default.
891
892 Apart from the performance improvements this change should be
893 invisible to end users, with one exception: for testing and
Ezio Melotti021f3342010-04-06 03:26:49 +0000894 debugging purposes there's a new structseq :data:`sys.long_info` that
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000895 provides information about the internal format, giving the number of
896 bits per digit and the size in bytes of the C type used to store
897 each digit::
898
899 >>> import sys
900 >>> sys.long_info
901 sys.long_info(bits_per_digit=30, sizeof_digit=4)
902
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000903 (Contributed by Mark Dickinson; :issue:`4258`.)
904
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000905 Another set of changes made long objects a few bytes smaller: 2 bytes
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000906 smaller on 32-bit systems and 6 bytes on 64-bit.
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000907 (Contributed by Mark Dickinson; :issue:`5260`.)
908
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000909* The division algorithm for long integers has been made faster
910 by tightening the inner loop, doing shifts instead of multiplications,
911 and fixing an unnecessary extra iteration.
912 Various benchmarks show speedups of between 50% and 150% for long
913 integer divisions and modulo operations.
914 (Contributed by Mark Dickinson; :issue:`5512`.)
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +0000915 Bitwise operations are also significantly faster (initial patch by
916 Gregory Smith; :issue:`1087418`).
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000917
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000918* The implementation of ``%`` checks for the left-side operand being
919 a Python string and special-cases it; this results in a 1-3%
920 performance increase for applications that frequently use ``%``
921 with strings, such as templating libraries.
922 (Implemented by Collin Winter; :issue:`5176`.)
923
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000924* List comprehensions with an ``if`` condition are compiled into
925 faster bytecode. (Patch by Antoine Pitrou, back-ported to 2.7
926 by Jeffrey Yasskin; :issue:`4715`.)
927
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +0000928* Converting an integer or long integer to a decimal string was made
929 faster by special-casing base 10 instead of using a generalized
930 conversion function that supports arbitrary bases.
931 (Patch by Gawain Bolton; :issue:`6713`.)
932
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +0000933* The :meth:`split`, :meth:`replace`, :meth:`rindex`,
934 :meth:`rpartition`, and :meth:`rsplit` methods of string-like types
935 (strings, Unicode strings, and :class:`bytearray` objects) now use a
936 fast reverse-search algorithm instead of a character-by-character
937 scan. This is sometimes faster by a factor of 10. (Added by
938 Florent Xicluna; :issue:`7462` and :issue:`7622`.)
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +0000939
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000940* The :mod:`pickle` and :mod:`cPickle` modules now automatically
941 intern the strings used for attribute names, reducing memory usage
942 of the objects resulting from unpickling. (Contributed by Jake
943 McGuire; :issue:`5084`.)
944
945* The :mod:`cPickle` module now special-cases dictionaries,
946 nearly halving the time required to pickle them.
947 (Contributed by Collin Winter; :issue:`5670`.)
948
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000949.. ======================================================================
950
Georg Brandl0516f812009-11-18 18:52:35 +0000951New and Improved Modules
952========================
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000953
954As in every release, Python's standard library received a number of
955enhancements and bug fixes. Here's a partial list of the most notable
956changes, sorted alphabetically by module name. Consult the
957:file:`Misc/NEWS` file in the source tree for a more complete list of
958changes, or look through the Subversion logs for all the details.
959
Ezio Melotti021f3342010-04-06 03:26:49 +0000960* The :mod:`bdb` module's base debugging class :class:`~bdb.Bdb`
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000961 gained a feature for skipping modules. The constructor
962 now takes an iterable containing glob-style patterns such as
963 ``django.*``; the debugger will not step into stack frames
964 from a module that matches one of these patterns.
965 (Contributed by Maru Newby after a suggestion by
966 Senthil Kumaran; :issue:`5142`.)
967
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +0000968* The :mod:`binascii` module now supports the buffer API, so it can be
969 used with :class:`memoryview` instances and other similar buffer objects.
970 (Backported from 3.x by Florent Xicluna; :issue:`7703`.)
971
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000972* Updated module: the :mod:`bsddb` module has been updated from 4.7.2devel9
973 to version 4.8.4 of
974 `the pybsddb package <http://www.jcea.es/programacion/pybsddb.htm>`__.
975 The new version features better Python 3.x compatibility, various bug fixes,
976 and adds several new BerkeleyDB flags and methods.
Ezio Melotti021f3342010-04-06 03:26:49 +0000977 (Updated by Jesús Cea Avión; :issue:`8156`. The pybsddb
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000978 changelog can be browsed at http://hg.jcea.es/pybsddb/file/tip/ChangeLog.)
979
Ezio Melotti021f3342010-04-06 03:26:49 +0000980* The :mod:`bz2` module's :class:`~bz2.BZ2File` now supports the context
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000981 management protocol, so you can write ``with bz2.BZ2File(...) as f: ...``.
Andrew M. Kuchlingbadc7092010-05-08 01:35:55 +0000982 (Contributed by Hagen Fürstenau; :issue:`3860`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000983
Ezio Melotti021f3342010-04-06 03:26:49 +0000984* New class: the :class:`~collections.Counter` class in the :mod:`collections`
985 module is useful for tallying data. :class:`~collections.Counter` instances
986 behave mostly like dictionaries but return zero for missing keys instead of
Georg Brandlf6dab952009-04-28 21:48:35 +0000987 raising a :exc:`KeyError`:
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000988
Georg Brandlf6dab952009-04-28 21:48:35 +0000989 .. doctest::
990 :options: +NORMALIZE_WHITESPACE
991
992 >>> from collections import Counter
993 >>> c = Counter()
994 >>> for letter in 'here is a sample of english text':
995 ... c[letter] += 1
996 ...
997 >>> c
998 Counter({' ': 6, 'e': 5, 's': 3, 'a': 2, 'i': 2, 'h': 2,
999 'l': 2, 't': 2, 'g': 1, 'f': 1, 'm': 1, 'o': 1, 'n': 1,
1000 'p': 1, 'r': 1, 'x': 1})
1001 >>> c['e']
1002 5
1003 >>> c['z']
1004 0
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001005
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001006 There are three additional :class:`~collections.Counter` methods:
1007 :meth:`~collections.Counter.most_common` returns the N most common
1008 elements and their counts. :meth:`~collections.Counter.elements`
1009 returns an iterator over the contained elements, repeating each
1010 element as many times as its count.
1011 :meth:`~collections.Counter.subtract` takes an iterable and
1012 subtracts one for each element instead of adding; if the argument is
1013 a dictionary or another :class:`Counter`, the counts are
1014 subtracted. ::
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001015
1016 >>> c.most_common(5)
1017 [(' ', 6), ('e', 5), ('s', 3), ('a', 2), ('i', 2)]
1018 >>> c.elements() ->
1019 'a', 'a', ' ', ' ', ' ', ' ', ' ', ' ',
1020 'e', 'e', 'e', 'e', 'e', 'g', 'f', 'i', 'i',
1021 'h', 'h', 'm', 'l', 'l', 'o', 'n', 'p', 's',
Georg Brandlf6dab952009-04-28 21:48:35 +00001022 's', 's', 'r', 't', 't', 'x'
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001023 >>> c['e']
1024 5
1025 >>> c.subtract('very heavy on the letter e')
1026 >>> c['e'] # Count is now lower
1027 -1
Ezio Melotti021f3342010-04-06 03:26:49 +00001028
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001029 Contributed by Raymond Hettinger; :issue:`1696199`.
1030
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001031 .. revision 79660
1032
Ezio Melotti021f3342010-04-06 03:26:49 +00001033 The new :class:`~collections.OrderedDict` class is described in the earlier
1034 section :ref:`pep-0372`.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001035
Ezio Melotti021f3342010-04-06 03:26:49 +00001036 The :class:`~collections.namedtuple` class now has an optional *rename* parameter.
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001037 If *rename* is true, field names that are invalid because they've
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001038 been repeated or that aren't legal Python identifiers will be
1039 renamed to legal names that are derived from the field's
1040 position within the list of fields:
1041
Georg Brandlf6dab952009-04-28 21:48:35 +00001042 >>> from collections import namedtuple
1043 >>> T = namedtuple('T', ['field1', '$illegal', 'for', 'field2'], rename=True)
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001044 >>> T._fields
1045 ('field1', '_1', '_2', 'field2')
1046
1047 (Added by Raymond Hettinger; :issue:`1818`.)
1048
Andrew M. Kuchling6d7dfa22010-04-11 12:49:37 +00001049 The :class:`~collections.deque` data type now has a
1050 :meth:`~collections.deque.count` method that returns the number of
1051 contained elements equal to the supplied argument *x*, and a
1052 :meth:`~collections.deque.reverse` method that reverses the elements
1053 of the deque in-place. :class:`deque` also exposes its maximum
1054 length as the read-only :attr:`~collections.deque.maxlen` attribute.
1055 (Both features added by Raymond Hettinger.)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001056
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +00001057* Constructors for the parsing classes in the :mod:`ConfigParser` module now
1058 take a *allow_no_value* parameter, defaulting to false; if true,
1059 options without values will be allowed. For example::
1060
1061 >>> import ConfigParser, StringIO
1062 >>> sample_config = """
1063 ... [mysqld]
1064 ... user = mysql
1065 ... pid-file = /var/run/mysqld/mysqld.pid
1066 ... skip-bdb
1067 ... """
1068 >>> config = ConfigParser.RawConfigParser(allow_no_value=True)
1069 >>> config.readfp(StringIO.StringIO(sample_config))
1070 >>> config.get('mysqld', 'user')
1071 'mysql'
1072 >>> print config.get('mysqld', 'skip-bdb')
1073 None
1074 >>> print config.get('mysqld', 'unknown')
1075 Traceback (most recent call last):
1076 ...
1077 ConfigParser.NoOptionError: No option 'unknown' in section: 'mysqld'
1078
1079 (Contributed by Mats Kindahl; :issue:`7005`.)
1080
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001081* Deprecated function: :func:`contextlib.nested`, which allows
1082 handling more than one context manager with a single :keyword:`with`
1083 statement, has been deprecated, because :keyword:`with` supports
1084 multiple context managers syntactically now.
1085
Ezio Melotti021f3342010-04-06 03:26:49 +00001086* The :mod:`copy` module's :func:`~copy.deepcopy` function will now
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001087 correctly copy bound instance methods. (Implemented by
1088 Robert Collins; :issue:`1515`.)
1089
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001090* The :mod:`ctypes` module now always converts ``None`` to a C NULL
1091 pointer for arguments declared as pointers. (Changed by Thomas
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001092 Heller; :issue:`4606`.) The underlying `libffi library
1093 <http://sourceware.org/libffi/>`__ has been updated to version
1094 3.0.9, containing various fixes for different platforms. (Updated
1095 by Matthias Klose; :issue:`8142`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001096
Ezio Melotti021f3342010-04-06 03:26:49 +00001097* New method: the :mod:`datetime` module's :class:`~datetime.timedelta` class
1098 gained a :meth:`~datetime.timedelta.total_seconds` method that returns the
1099 number of seconds in the duration. (Contributed by Brian Quinlan; :issue:`5788`.)
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001100
Ezio Melotti021f3342010-04-06 03:26:49 +00001101* New method: the :class:`~decimal.Decimal` class gained a
1102 :meth:`~decimal.Decimal.from_float` class method that performs an exact
1103 conversion of a floating-point number to a :class:`~decimal.Decimal`.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001104 Note that this is an **exact** conversion that strives for the
1105 closest decimal approximation to the floating-point representation's value;
1106 the resulting decimal value will therefore still include the inaccuracy,
1107 if any.
1108 For example, ``Decimal.from_float(0.1)`` returns
1109 ``Decimal('0.1000000000000000055511151231257827021181583404541015625')``.
1110 (Implemented by Raymond Hettinger; :issue:`4796`.)
1111
Andrew M. Kuchling04b99cc2010-05-04 01:24:22 +00001112 Comparing instances of :class:`Decimal` with floating-point
1113 numbers now produces sensible results based on the numeric values
1114 of the operands. Previously such comparisons would fall back to
1115 Python's default rules for comparing objects, which produced arbitrary
1116 results based on their type. Note that you still cannot combine
1117 :class:`Decimal` and floating-point in other operations such as addition,
1118 since you should be explicitly choosing how to convert between float and
1119 :class:`Decimal`.
1120 (Fixed by Mark Dickinson; :issue:`2531`.)
1121
Ezio Melotti021f3342010-04-06 03:26:49 +00001122 Most of the methods of the :class:`~decimal.Context` class now accept integers
1123 as well as :class:`~decimal.Decimal` instances; the only exceptions are the
1124 :meth:`~decimal.Context.canonical` and :meth:`~decimal.Context.is_canonical`
1125 methods. (Patch by Juan José Conti; :issue:`7633`.)
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001126
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001127 The constructor for :class:`~decimal.Decimal` now accepts
1128 floating-point numbers (added by Raymond Hettinger; :issue:`8257`)
1129 and non-European Unicode characters such as Arabic-Indic digits
1130 (contributed by Mark Dickinson; :issue:`6595`).
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001131
Ezio Melotti021f3342010-04-06 03:26:49 +00001132 When using :class:`~decimal.Decimal` instances with a string's
1133 :meth:`~str.format` method, the default alignment was previously
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001134 left-alignment. This has been changed to right-alignment, which seems
1135 more sensible for numeric types. (Changed by Mark Dickinson; :issue:`6857`.)
1136
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001137 Comparisons involving a signaling NaN value (or ``sNAN``) now signal
1138 :const:`InvalidOperation` instead of silently returning a true or
1139 false value depending on the comparison operator. Quiet NaN values
1140 (or ``NaN``) are now hashable. (Fixed by Mark Dickinson;
1141 :issue:`7279`.)
1142
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +00001143* The :mod:`difflib` module now produces output that is more
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00001144 compatible with modern :command:`diff`/:command:`patch` tools
1145 through one small change, using a tab character instead of spaces as
1146 a separator in the header giving the filename. (Fixed by Anatoly
1147 Techtonik; :issue:`7585`.)
1148
1149* The :mod:`doctest` module's :const:`IGNORE_EXCEPTION_DETAIL` flag
1150 will now ignore the name of the module containing the exception
1151 being tested. (Patch by Lennart Regebro; :issue:`7490`.)
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +00001152
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001153* The :class:`~fractions.Fraction` class now accepts a single float or
1154 :class:`~decimal.Decimal` instance, or two rational numbers, as
1155 arguments to its constructor. (Implemented by Mark Dickinson;
1156 rationals added in :issue:`5812`, and float/decimal in
1157 :issue:`8294`.)
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00001158
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +00001159 An oversight was fixed, making the :class:`Fraction` match the other
1160 numeric types; ordering comparisons (``<``, ``<=``, ``>``, ``>=``) between
1161 fractions and complex numbers now raise a :exc:`TypeError`.
1162
1163 .. revision 79455
1164
Ezio Melotti021f3342010-04-06 03:26:49 +00001165* New class: a new :class:`~ftplib.FTP_TLS` class in
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001166 the :mod:`ftplib` module provides secure FTP
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001167 connections using TLS encapsulation of authentication as well as
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001168 subsequent control and data transfers.
1169 (Contributed by Giampaolo Rodola', :issue:`2054`.)
1170
Ezio Melotti021f3342010-04-06 03:26:49 +00001171 The :meth:`~ftplib.FTP.storbinary` method for binary uploads can now restart
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001172 uploads thanks to an added *rest* parameter (patch by Pablo Mouzo;
1173 :issue:`6845`.)
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001174
Andrew M. Kuchling6d7dfa22010-04-11 12:49:37 +00001175* New class decorator: :func:`total_ordering` in the :mod:`functools`
1176 module takes a class that defines an :meth:`__eq__` method and one of
1177 :meth:`__lt__`, :meth:`__le__`, :meth:`__gt__`, or :meth:`__ge__`,
1178 and generates the missing comparison methods. Since the
1179 :meth:`__cmp__` method is being deprecated in Python 3.x,
1180 this decorator makes it easier to define ordered classes.
1181 (Added by Raymond Hettinger; :issue:`5479`.)
1182
1183 New function: :func:`cmp_to_key` will take an old-style comparison
1184 function that expects two arguments and return a new callable that
1185 can be used as the *key* parameter to functions such as
1186 :func:`sorted`, :func:`min` and :func:`max`, etc. The primary
1187 intended use is to help with making code compatible with Python 3.x.
1188 (Added by Raymond Hettinger.)
1189
Ezio Melotti021f3342010-04-06 03:26:49 +00001190* New function: the :mod:`gc` module's :func:`~gc.is_tracked` returns
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001191 true if a given instance is tracked by the garbage collector, false
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001192 otherwise. (Contributed by Antoine Pitrou; :issue:`4688`.)
1193
Ezio Melotti021f3342010-04-06 03:26:49 +00001194* The :mod:`gzip` module's :class:`~gzip.GzipFile` now supports the context
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +00001195 management protocol, so you can write ``with gzip.GzipFile(...) as f: ...``
Andrew M. Kuchlingbadc7092010-05-08 01:35:55 +00001196 (contributed by Hagen Fürstenau; :issue:`3860`), and it now implements
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +00001197 the :class:`io.BufferedIOBase` ABC, so you can wrap it with
1198 :class:`io.BufferedReader` for faster processing
1199 (contributed by Nir Aides; :issue:`7471`).
1200 It's also now possible to override the modification time
Andrew M. Kuchling77069572009-03-31 01:21:01 +00001201 recorded in a gzipped file by providing an optional timestamp to
1202 the constructor. (Contributed by Jacques Frechet; :issue:`4272`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001203
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001204 Files in gzip format can be padded with trailing zero bytes; the
1205 :mod:`gzip` module will now consume these trailing bytes. (Fixed by
1206 Tadek Pietraszek and Brian Curtin; :issue:`2846`.)
1207
Ezio Melotti021f3342010-04-06 03:26:49 +00001208* New attribute: the :mod:`hashlib` module now has an :attr:`~hashlib.hashlib.algorithms`
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001209 attribute containing a tuple naming the supported algorithms.
1210 In Python 2.7, ``hashlib.algorithms`` contains
1211 ``('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')``
1212 (Contributed by Carl Chenet; :issue:`7418`.)
1213
Ezio Melotti021f3342010-04-06 03:26:49 +00001214* The default :class:`~httplib.HTTPResponse` class used by the :mod:`httplib` module now
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001215 supports buffering, resulting in much faster reading of HTTP responses.
Andrew M. Kuchlingbadc7092010-05-08 01:35:55 +00001216 (Contributed by Kristján Valur Jónsson; :issue:`4879`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001217
Ezio Melotti021f3342010-04-06 03:26:49 +00001218 The :class:`~httplib.HTTPConnection` and :class:`~httplib.HTTPSConnection` classes
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001219 now support a *source_address* parameter, a ``(host, port)`` 2-tuple
1220 giving the source address that will be used for the connection.
1221 (Contributed by Eldon Ziegler; :issue:`3972`.)
1222
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00001223* The :mod:`ihooks` module now supports relative imports. Note that
1224 :mod:`ihooks` is an older module used to support customizing imports,
1225 superseded by the :mod:`imputil` module added in Python 2.0.
1226 (Relative import support added by Neil Schemenauer.)
1227
1228 .. revision 75423
1229
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001230* The :mod:`imaplib` module now supports IPv6 addresses.
1231 (Contributed by Derek Morr; :issue:`1655`.)
1232
Andrew M. Kuchlingce690522010-04-13 01:32:51 +00001233* New function: the :mod:`inspect` module's :func:`~inspect.getcallargs`
1234 takes a callable and its positional and keyword arguments,
1235 and figures out which of the callable's parameters will receive each argument,
1236 returning a dictionary mapping argument names to their values. For example::
1237
1238 >>> from inspect import getcallargs
1239 >>> def f(a, b=1, *pos, **named):
1240 ... pass
1241 >>> getcallargs(f, 1, 2, 3)
1242 {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
1243 >>> getcallargs(f, a=2, x=4)
1244 {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
1245 >>> getcallargs(f)
1246 Traceback (most recent call last):
1247 ...
1248 TypeError: f() takes at least 1 argument (0 given)
1249
1250 Contributed by George Sakkis; :issue:`3135`.
1251
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001252* Updated module: The :mod:`io` library has been upgraded to the version shipped with
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001253 Python 3.1. For 3.1, the I/O library was entirely rewritten in C
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001254 and is 2 to 20 times faster depending on the task being performed. The
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001255 original Python version was renamed to the :mod:`_pyio` module.
1256
1257 One minor resulting change: the :class:`io.TextIOBase` class now
1258 has an :attr:`errors` attribute giving the error setting
1259 used for encoding and decoding errors (one of ``'strict'``, ``'replace'``,
1260 ``'ignore'``).
1261
1262 The :class:`io.FileIO` class now raises an :exc:`OSError` when passed
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001263 an invalid file descriptor. (Implemented by Benjamin Peterson;
Ezio Melotti021f3342010-04-06 03:26:49 +00001264 :issue:`4991`.) The :meth:`~io.IOBase.truncate` method now preserves the
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001265 file position; previously it would change the file position to the
1266 end of the new file. (Fixed by Pascal Chambon; :issue:`6939`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001267
Andrew M. Kuchling5a73ff82009-12-02 14:27:11 +00001268* New function: ``itertools.compress(data, selectors)`` takes two
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001269 iterators. Elements of *data* are returned if the corresponding
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001270 value in *selectors* is true::
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001271
1272 itertools.compress('ABCDEF', [1,0,1,0,1,1]) =>
1273 A, C, E, F
1274
Ezio Melotti021f3342010-04-06 03:26:49 +00001275 .. maybe here is better to use >>> list(itertools.compress(...)) instead
1276
Andrew M. Kuchling5a73ff82009-12-02 14:27:11 +00001277 New function: ``itertools.combinations_with_replacement(iter, r)``
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001278 returns all the possible *r*-length combinations of elements from the
Ezio Melotti021f3342010-04-06 03:26:49 +00001279 iterable *iter*. Unlike :func:`~itertools.combinations`, individual elements
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001280 can be repeated in the generated combinations::
1281
1282 itertools.combinations_with_replacement('abc', 2) =>
1283 ('a', 'a'), ('a', 'b'), ('a', 'c'),
1284 ('b', 'b'), ('b', 'c'), ('c', 'c')
1285
1286 Note that elements are treated as unique depending on their position
1287 in the input, not their actual values.
1288
Ezio Melotti021f3342010-04-06 03:26:49 +00001289 The :func:`itertools.count` function now has a *step* argument that
1290 allows incrementing by values other than 1. :func:`~itertools.count` also
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001291 now allows keyword arguments, and using non-integer values such as
Ezio Melotti021f3342010-04-06 03:26:49 +00001292 floats or :class:`~decimal.Decimal` instances. (Implemented by Raymond
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001293 Hettinger; :issue:`5032`.)
1294
Andrew M. Kuchling77069572009-03-31 01:21:01 +00001295 :func:`itertools.combinations` and :func:`itertools.product` were
1296 previously raising :exc:`ValueError` for values of *r* larger than
1297 the input iterable. This was deemed a specification error, so they
1298 now return an empty iterator. (Fixed by Raymond Hettinger; :issue:`4816`.)
1299
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001300* Updated module: The :mod:`json` module was upgraded to version 2.0.9 of the
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001301 simplejson package, which includes a C extension that makes
1302 encoding and decoding faster.
1303 (Contributed by Bob Ippolito; :issue:`4136`.)
1304
Ezio Melotti021f3342010-04-06 03:26:49 +00001305 To support the new :class:`collections.OrderedDict` type, :func:`json.load`
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001306 now has an optional *object_pairs_hook* parameter that will be called
1307 with any object literal that decodes to a list of pairs.
1308 (Contributed by Raymond Hettinger; :issue:`5381`.)
1309
Andrew M. Kuchling837a5382010-05-06 17:21:59 +00001310* The :mod:`mailbox` module's :class:`Maildir` class now records the
1311 timestamp on the directories it reads, and only re-reads them if the
1312 modification time has subsequently changed. This improves
1313 performance by avoiding unneeded directory scans. (Fixed by
1314 A.M. Kuchling and Antoine Pitrou; :issue:`1607951`, :issue:`6896`.)
1315
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001316* New functions: the :mod:`math` module gained
Ezio Melotti021f3342010-04-06 03:26:49 +00001317 :func:`~math.erf` and :func:`~math.erfc` for the error function and the complementary error function,
1318 :func:`~math.expm1` which computes ``e**x - 1`` with more precision than
1319 using :func:`~math.exp` and subtracting 1,
1320 :func:`~math.gamma` for the Gamma function, and
1321 :func:`~math.lgamma` for the natural log of the Gamma function.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001322 (Contributed by Mark Dickinson and nirinA raseliarison; :issue:`3366`.)
1323
Andrew M. Kuchling24520b42009-04-09 11:22:47 +00001324* The :mod:`multiprocessing` module's :class:`Manager*` classes
1325 can now be passed a callable that will be called whenever
1326 a subprocess is started, along with a set of arguments that will be
1327 passed to the callable.
1328 (Contributed by lekma; :issue:`5585`.)
1329
Ezio Melotti021f3342010-04-06 03:26:49 +00001330 The :class:`~multiprocessing.Pool` class, which controls a pool of worker processes,
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001331 now has an optional *maxtasksperchild* parameter. Worker processes
1332 will perform the specified number of tasks and then exit, causing the
Ezio Melotti021f3342010-04-06 03:26:49 +00001333 :class:`~multiprocessing.Pool` to start a new worker. This is useful if tasks may leak
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001334 memory or other resources, or if some tasks will cause the worker to
1335 become very large.
1336 (Contributed by Charles Cazabon; :issue:`6963`.)
1337
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001338* The :mod:`nntplib` module now supports IPv6 addresses.
1339 (Contributed by Derek Morr; :issue:`1664`.)
1340
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001341* New functions: the :mod:`os` module wraps the following POSIX system
Ezio Melotti021f3342010-04-06 03:26:49 +00001342 calls: :func:`~os.getresgid` and :func:`~os.getresuid`, which return the
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001343 real, effective, and saved GIDs and UIDs;
Ezio Melotti021f3342010-04-06 03:26:49 +00001344 :func:`~os.setresgid` and :func:`~os.setresuid`, which set
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001345 real, effective, and saved GIDs and UIDs to new values;
Ezio Melotti021f3342010-04-06 03:26:49 +00001346 :func:`~os.initgroups`. (GID/UID functions
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001347 contributed by Travis H.; :issue:`6508`. Support for initgroups added
1348 by Jean-Paul Calderone; :issue:`7333`.)
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001349
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001350 The :func:`os.fork` function now re-initializes the import lock in
Ezio Melotti021f3342010-04-06 03:26:49 +00001351 the child process; this fixes problems on Solaris when :func:`~os.fork`
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001352 is called from a thread. (Fixed by Zsolt Cserna; :issue:`7242`.)
1353
Ezio Melotti021f3342010-04-06 03:26:49 +00001354* In the :mod:`os.path` module, the :func:`~os.path.normpath` and
1355 :func:`~os.path.abspath` functions now preserve Unicode; if their input path
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001356 is a Unicode string, the return value is also a Unicode string.
Ezio Melotti021f3342010-04-06 03:26:49 +00001357 (:meth:`~os.path.normpath` fixed by Matt Giuca in :issue:`5827`;
1358 :meth:`~os.path.abspath` fixed by Ezio Melotti in :issue:`3426`.)
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001359
Andrew M. Kuchling9cb42772009-01-21 02:15:43 +00001360* The :mod:`pydoc` module now has help for the various symbols that Python
1361 uses. You can now do ``help('<<')`` or ``help('@')``, for example.
1362 (Contributed by David Laban; :issue:`4739`.)
1363
Ezio Melotti021f3342010-04-06 03:26:49 +00001364* The :mod:`re` module's :func:`~re.split`, :func:`~re.sub`, and :func:`~re.subn`
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001365 now accept an optional *flags* argument, for consistency with the
1366 other functions in the module. (Added by Gregory P. Smith.)
1367
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001368* New function: :func:`~runpy.run_path` in the :mod:`runpy` module
1369 will execute the code at a provided *path* argument. *path* can be
1370 the path of a Python source file (:file:`example.py`), a compiled
1371 bytecode file (:file:`example.pyc`), a directory
Andrew M. Kuchling304500c2010-05-08 13:29:46 +00001372 (:file:`./package/`), or a zip archive (:file:`example.zip`). If a
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001373 directory or zip path is provided, it will be added to the front of
1374 ``sys.path`` and the module :mod:`__main__` will be imported. It's
1375 expected that the directory or zip contains a :file:`__main__.py`;
1376 if it doesn't, some other :file:`__main__.py` might be imported from
1377 a location later in ``sys.path``. This makes some of the machinery
Andrew M. Kuchling837a5382010-05-06 17:21:59 +00001378 of :mod:`runpy` available to scripts that want to mimic the way
1379 Python's :option:`-m` processes an explicit path name.
1380 (Added by Nick Coghlan; :issue:`6816`.)
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001381
Ezio Melotti021f3342010-04-06 03:26:49 +00001382* New function: in the :mod:`shutil` module, :func:`~shutil.make_archive`
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001383 takes a filename, archive type (zip or tar-format), and a directory
1384 path, and creates an archive containing the directory's contents.
1385 (Added by Tarek Ziadé.)
1386
Ezio Melotti021f3342010-04-06 03:26:49 +00001387 :mod:`shutil`'s :func:`~shutil.copyfile` and :func:`~shutil.copytree`
1388 functions now raise a :exc:`~shutil.SpecialFileError` exception when
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001389 asked to copy a named pipe. Previously the code would treat
1390 named pipes like a regular file by opening them for reading, and
1391 this would block indefinitely. (Fixed by Antoine Pitrou; :issue:`3002`.)
1392
1393* New functions: in the :mod:`site` module, three new functions
1394 return various site- and user-specific paths.
Ezio Melotti021f3342010-04-06 03:26:49 +00001395 :func:`~site.getsitepackages` returns a list containing all
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001396 global site-packages directories, and
Ezio Melotti021f3342010-04-06 03:26:49 +00001397 :func:`~site.getusersitepackages` returns the path of the user's
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001398 site-packages directory.
Ezio Melotti021f3342010-04-06 03:26:49 +00001399 :func:`~site.getuserbase` returns the value of the :envvar:`USER_BASE`
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001400 environment variable, giving the path to a directory that can be used
1401 to store data.
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001402 (Contributed by Tarek Ziadé; :issue:`6693`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001403
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001404 The :mod:`site` module now reports exceptions occurring
1405 when the :mod:`sitecustomize` module is imported, and will no longer
Florent Xiclunaad598332010-03-31 21:40:32 +00001406 catch and swallow the :exc:`KeyboardInterrupt` exception. (Fixed by
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001407 Victor Stinner; :issue:`3137`.)
1408
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001409* The :func:`~socket.create_connection` function
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +00001410 gained a *source_address* parameter, a ``(host, port)`` 2-tuple
1411 giving the source address that will be used for the connection.
1412 (Contributed by Eldon Ziegler; :issue:`3972`.)
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00001413
Ezio Melotti021f3342010-04-06 03:26:49 +00001414 The :meth:`~socket.socket.recv_into` and :meth:`~socket.socket.recvfrom_into`
1415 methods will now write into objects that support the buffer API, most usefully
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001416 the :class:`bytearray` and :class:`memoryview` objects. (Implemented by
1417 Antoine Pitrou; :issue:`8104`.)
1418
Ezio Melotti021f3342010-04-06 03:26:49 +00001419* The :mod:`SocketServer` module's :class:`~SocketServer.TCPServer` class now
Andrew M. Kuchling85fffc32010-05-08 01:15:26 +00001420 supports socket timeouts and disabling the Nagle algorithm.
1421 The :attr:`~SocketServer.TCPServer.disable_nagle_algorithm` class attribute
1422 defaults to False; if overridden to be True,
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001423 new request connections will have the TCP_NODELAY option set to
1424 prevent buffering many small sends into a single TCP packet.
Andrew M. Kuchling85fffc32010-05-08 01:15:26 +00001425 The :attr:`~SocketServer.TCPServer.timeout` class attribute can hold
1426 a timeout in seconds that will be applied to the request socket; if
1427 no request is received within that time, :meth:`handle_timeout`
1428 will be called and :meth:`handle_request` will return.
Andrew M. Kuchlingbadc7092010-05-08 01:35:55 +00001429 (Contributed by Kristján Valur Jónsson; :issue:`6192` and :issue:`6267`.)
Andrew M. Kuchling85fffc32010-05-08 01:15:26 +00001430
1431* The XML-RPC client and server, provided by the :mod:`xmlrpclib` and
1432 :mod:`SimpleXMLRPCServer` modules, have improved performance by
1433 supporting HTTP/1.1 keep-alive and by optionally using gzip encoding
1434 to compress the XML being exchanged. The gzip compression is
1435 controlled by the :attr:`encode_threshold` attribute of
1436 :class:`SimpleXMLRPCRequestHandler`, which contains a size in bytes;
1437 responses larger than this will be compressed.
Andrew M. Kuchlingbadc7092010-05-08 01:35:55 +00001438 (Contributed by Kristján Valur Jónsson; :issue:`6267`.)
Andrew M. Kuchling85fffc32010-05-08 01:15:26 +00001439
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001440
Ezio Melotti021f3342010-04-06 03:26:49 +00001441* Updated module: the :mod:`sqlite3` module has been updated to
Andrew M. Kuchlingfed15762010-03-08 12:00:39 +00001442 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
1443 the ability to load SQLite extensions from shared libraries.
1444 Call the ``enable_load_extension(True)`` method to enable extensions,
Ezio Melotti021f3342010-04-06 03:26:49 +00001445 and then call :meth:`~sqlite3.Connection.load_extension` to load a particular shared library.
Andrew M. Kuchlingfed15762010-03-08 12:00:39 +00001446 (Updated by Gerhard Häring.)
1447
Antoine Pitroud69e6ee2010-05-07 10:15:51 +00001448* The :mod:`ssl` module's :class:`ssl.SSLSocket` objects now support the
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001449 buffer API, which fixed a test suite failure (fix by Antoine Pitrou;
1450 :issue:`7133`) and automatically set
1451 OpenSSL's :cmacro:`SSL_MODE_AUTO_RETRY`, which will prevent an error
1452 code being returned from :meth:`recv` operations that trigger an SSL
1453 renegotiation (fix by Antoine Pitrou; :issue:`8222`).
1454
Antoine Pitroud69e6ee2010-05-07 10:15:51 +00001455 The :func:`ssl.wrap_socket` constructor function now takes a
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001456 *ciphers* argument that's a string listing the encryption algorithms
1457 to be allowed; the format of the string is described
Antoine Pitroud69e6ee2010-05-07 10:15:51 +00001458 `in the OpenSSL documentation
1459 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`__.
1460 (Added by Antoine Pitrou; :issue:`8322`.)
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001461
1462 Another change makes the extension load all of OpenSSL's ciphers and
1463 digest algorithms so that they're all available. Some SSL
1464 certificates couldn't be verified, reporting an 'unknown algorithm'
1465 error. (Reported by Beda Kosata, and fixed by Antoine Pitrou;
1466 :issue:`8484`.)
1467
1468 The version of OpenSSL being used is now available as the module
Antoine Pitroud69e6ee2010-05-07 10:15:51 +00001469 attributes :data:`ssl.OPENSSL_VERSION` (a string),
1470 :data:`ssl.OPENSSL_VERSION_INFO` (a 5-tuple), and
1471 :data:`ssl.OPENSSL_VERSION_NUMBER` (an integer). (Added by Antoine
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001472 Pitrou; :issue:`8321`.)
1473
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001474* The :mod:`struct` module will no longer silently ignore overflow
1475 errors when a value is too large for a particular integer format
1476 code (one of ``bBhHiIlLqQ``); it now always raises a
1477 :exc:`struct.error` exception. (Changed by Mark Dickinson;
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001478 :issue:`1523`.) The :func:`~struct.pack` function will also
1479 attempt to use :meth:`__index__` to convert and pack non-integers
1480 before trying the :meth:`__int__` method or reporting an error.
1481 (Changed by Mark Dickinson; :issue:`8300`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001482
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001483* New function: the :mod:`subprocess` module's
Ezio Melotti021f3342010-04-06 03:26:49 +00001484 :func:`~subprocess.check_output` runs a command with a specified set of arguments
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001485 and returns the command's output as a string when the command runs without
Ezio Melotti021f3342010-04-06 03:26:49 +00001486 error, or raises a :exc:`~subprocess.CalledProcessError` exception otherwise.
Andrew M. Kuchling10b1ec92009-01-02 21:00:35 +00001487
1488 ::
1489
1490 >>> subprocess.check_output(['df', '-h', '.'])
1491 'Filesystem Size Used Avail Capacity Mounted on\n
1492 /dev/disk0s2 52G 49G 3.0G 94% /\n'
1493
1494 >>> subprocess.check_output(['df', '-h', '/bogus'])
1495 ...
1496 subprocess.CalledProcessError: Command '['df', '-h', '/bogus']' returned non-zero exit status 1
1497
1498 (Contributed by Gregory P. Smith.)
1499
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001500 The :mod:`subprocess` module will now retry its internal system calls
1501 on receiving an :const:`EINTR` signal. (Reported by several people; final
1502 patch by Gregory P. Smith in :issue:`1068268`.)
1503
Ezio Melotti021f3342010-04-06 03:26:49 +00001504* New function: :func:`~symtable.is_declared_global` in the :mod:`symtable` module
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001505 returns true for variables that are explicitly declared to be global,
1506 false for ones that are implicitly global.
1507 (Contributed by Jeremy Hylton.)
1508
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00001509* The :mod:`syslog` module will now use the value of ``sys.argv[0]`` as the
1510 identifier instead of the previous default value of ``'python'``.
1511 (Changed by Sean Reifschneider; :issue:`8451`.)
1512
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001513* The ``sys.version_info`` value is now a named tuple, with attributes
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001514 named :attr:`major`, :attr:`minor`, :attr:`micro`,
1515 :attr:`releaselevel`, and :attr:`serial`. (Contributed by Ross
1516 Light; :issue:`4285`.)
1517
1518 :func:`sys.getwindowsversion` also returns a named tuple,
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +00001519 with attributes named :attr:`major`, :attr:`minor`, :attr:`build`,
Ezio Melotti12477752010-02-08 22:22:41 +00001520 :attr:`platform`, :attr:`service_pack`, :attr:`service_pack_major`,
Eric Smithb3c54882010-02-03 14:17:50 +00001521 :attr:`service_pack_minor`, :attr:`suite_mask`, and
1522 :attr:`product_type`. (Contributed by Brian Curtin; :issue:`7766`.)
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001523
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001524* The :mod:`tarfile` module's default error handling has changed, to
1525 no longer suppress fatal errors. The default error level was previously 0,
1526 which meant that errors would only result in a message being written to the
1527 debug log, but because the debug log is not activated by default,
1528 these errors go unnoticed. The default error level is now 1,
1529 which raises an exception if there's an error.
1530 (Changed by Lars Gustäbel; :issue:`7357`.)
1531
Ezio Melotti021f3342010-04-06 03:26:49 +00001532 :mod:`tarfile` now supports filtering the :class:`~tarfile.TarInfo`
1533 objects being added to a tar file. When you call :meth:`~tarfile.TarFile.add`,
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001534 instance, you may supply an optional *filter* argument
1535 that's a callable. The *filter* callable will be passed the
Ezio Melotti021f3342010-04-06 03:26:49 +00001536 :class:`~tarfile.TarInfo` for every file being added, and can modify and return it.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001537 If the callable returns ``None``, the file will be excluded from the
1538 resulting archive. This is more powerful than the existing
1539 *exclude* argument, which has therefore been deprecated.
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001540 (Added by Lars Gustäbel; :issue:`6856`.)
Ezio Melotti021f3342010-04-06 03:26:49 +00001541 The :class:`~tarfile.TarFile` class also now supports the context manager protocol.
Andrew M. Kuchlingfed15762010-03-08 12:00:39 +00001542 (Added by Lars Gustäbel; :issue:`7232`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001543
Ezio Melotti021f3342010-04-06 03:26:49 +00001544* The :meth:`~threading.Event.wait` method of the :class:`threading.Event` class
1545 now returns the internal flag on exit. This means the method will usually
1546 return true because :meth:`~threading.Event.wait` is supposed to block until the
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001547 internal flag becomes true. The return value will only be false if
1548 a timeout was provided and the operation timed out.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001549 (Contributed by Tim Lesher; :issue:`1674032`.)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001550
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001551* The Unicode database provided by the :mod:`unicodedata` module is
1552 now used internally to determine which characters are numeric,
1553 whitespace, or represent line breaks. The database also
1554 includes information from the :file:`Unihan.txt` data file (patch
1555 by Anders Chrigström and Amaury Forgeot d'Arc; :issue:`1571184`)
1556 and has been updated to version 5.2.0 (updated by
1557 Florent Xicluna; :issue:`8024`).
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001558
Andrew M. Kuchling04b99cc2010-05-04 01:24:22 +00001559* The :mod:`urlparse` module's :func:`~urlparse.urlsplit` now handles
1560 unknown URL schemes in a fashion compliant with :rfc:`3986`: if the
1561 URL is of the form ``"<something>://..."``, the text before the
1562 ``://`` is treated as the scheme, even if it's a made-up scheme that
1563 the module doesn't know about. This change may break code that
1564 worked around the old behaviour. For example, Python 2.6.4 or 2.5
1565 will return the following:
1566
1567 >>> import urlparse
1568 >>> urlparse.urlsplit('invented://host/filename?query')
1569 ('invented', '', '//host/filename?query', '', '')
1570
1571 Python 2.7 (and Python 2.6.5) will return:
1572
1573 >>> import urlparse
1574 >>> urlparse.urlsplit('invented://host/filename?query')
1575 ('invented', 'host', '/filename?query', '', '')
1576
1577 (Python 2.7 actually produces slightly different output, since it
1578 returns a named tuple instead of a standard tuple.)
1579
1580 The :mod:`urlparse` module also supports IPv6 literal addresses as defined by
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001581 :rfc:`2732` (contributed by Senthil Kumaran; :issue:`2987`). ::
1582
1583 >>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo')
1584 ParseResult(scheme='http', netloc='[1080::8:800:200C:417A]',
1585 path='/foo', params='', query='', fragment='')
1586
Ezio Melotti021f3342010-04-06 03:26:49 +00001587* The :class:`~UserDict.UserDict` class is now a new-style class. (Changed by
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001588 Benjamin Peterson.)
1589
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00001590* New class: the :class:`~weakref.WeakSet` class in the :mod:`weakref`
1591 module is a set that only holds weak references to its elements; elements
1592 will be removed once there are no references pointing to them.
1593 (Originally implemented in Python 3.x by Raymond Hettinger, and backported
1594 to 2.7 by Michael Foord.)
1595
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001596* The ElementTree library, :mod:`xml.etree`, no longer escapes
1597 ampersands and angle brackets when outputting an XML processing
Ezio Melotti021f3342010-04-06 03:26:49 +00001598 instruction (which looks like ``<?xml-stylesheet href="#style1"?>``)
1599 or comment (which looks like ``<!-- comment -->``).
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001600 (Patch by Neil Muller; :issue:`2746`.)
1601
Andrew M. Kuchling85fffc32010-05-08 01:15:26 +00001602* The XML-RPC client and server, provided by the :mod:`xmlrpclib` and
1603 :mod:`SimpleXMLRPCServer` modules, have improved performance by
1604 supporting HTTP/1.1 keep-alive and by optionally using gzip encoding
1605 to compress the XML being exchanged. The gzip compression is
1606 controlled by the :attr:`encode_threshold` attribute of
1607 :class:`SimpleXMLRPCRequestHandler`, which contains a size in bytes;
1608 responses larger than this will be compressed.
Andrew M. Kuchlingbadc7092010-05-08 01:35:55 +00001609 (Contributed by Kristján Valur Jónsson; :issue:`6267`.)
Andrew M. Kuchling85fffc32010-05-08 01:15:26 +00001610
Ezio Melotti021f3342010-04-06 03:26:49 +00001611* The :mod:`zipfile` module's :class:`~zipfile.ZipFile` now supports the context
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001612 management protocol, so you can write ``with zipfile.ZipFile(...) as f: ...``.
1613 (Contributed by Brian Curtin; :issue:`5511`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001614
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001615 :mod:`zipfile` now also supports archiving empty directories and
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001616 extracts them correctly. (Fixed by Kuba Wieczorek; :issue:`4710`.)
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001617 Reading files out of an archive is faster, and interleaving
Ezio Melotti021f3342010-04-06 03:26:49 +00001618 :meth:`~zipfile.ZipFile.read` and :meth:`~zipfile.ZipFile.readline` now works correctly.
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001619 (Contributed by Nir Aides; :issue:`7610`.)
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001620
Ezio Melotti021f3342010-04-06 03:26:49 +00001621 The :func:`~zipfile.is_zipfile` function now
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001622 accepts a file object, in addition to the path names accepted in earlier
1623 versions. (Contributed by Gabriel Genellina; :issue:`4756`.)
1624
Ezio Melotti021f3342010-04-06 03:26:49 +00001625 The :meth:`~zipfile.ZipFile.writestr` method now has an optional *compress_type* parameter
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001626 that lets you override the default compression method specified in the
Ezio Melotti021f3342010-04-06 03:26:49 +00001627 :class:`~zipfile.ZipFile` constructor. (Contributed by Ronald Oussoren;
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001628 :issue:`6003`.)
1629
1630
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001631.. ======================================================================
1632.. whole new modules get described in subsections here
1633
1634
1635.. _importlib-section:
1636
1637New module: importlib
1638------------------------------
1639
1640Python 3.1 includes the :mod:`importlib` package, a re-implementation
1641of the logic underlying Python's :keyword:`import` statement.
1642:mod:`importlib` is useful for implementors of Python interpreters and
1643to users who wish to write new importers that can participate in the
1644import process. Python 2.7 doesn't contain the complete
1645:mod:`importlib` package, but instead has a tiny subset that contains
1646a single function, :func:`~importlib.import_module`.
1647
1648``import_module(name, package=None)`` imports a module. *name* is
1649a string containing the module or package's name. It's possible to do
1650relative imports by providing a string that begins with a ``.``
1651character, such as ``..utils.errors``. For relative imports, the
1652*package* argument must be provided and is the name of the package that
1653will be used as the anchor for
1654the relative import. :func:`~importlib.import_module` both inserts the imported
1655module into ``sys.modules`` and returns the module object.
1656
1657Here are some examples::
1658
1659 >>> from importlib import import_module
1660 >>> anydbm = import_module('anydbm') # Standard absolute import
1661 >>> anydbm
1662 <module 'anydbm' from '/p/python/Lib/anydbm.py'>
1663 >>> # Relative import
1664 >>> sysconfig = import_module('..sysconfig', 'distutils.command')
1665 >>> sysconfig
1666 <module 'distutils.sysconfig' from '/p/python/Lib/distutils/sysconfig.pyc'>
1667
1668:mod:`importlib` was implemented by Brett Cannon and introduced in
1669Python 3.1.
1670
1671
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00001672New module: sysconfig
1673---------------------------------
1674
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001675The :mod:`sysconfig` module has been pulled out of the Distutils
1676package, becoming a new top-level module in its own right.
1677:mod:`sysconfig` provides functions for getting information about
1678Python's build process: compiler switches, installation paths, the
1679platform name, and whether Python is running from its source
1680directory.
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00001681
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001682Some of the functions in the module are:
1683
1684* :func:`~sysconfig.get_config_var` returns variables from Python's
1685 Makefile and the :file:`pyconfig.h` file.
1686* :func:`~sysconfig.get_config_vars` returns a dictionary containing
1687 all of the configuration variables.
1688* :func:`~sysconfig.getpath` returns the configured path for
1689 a particular type of module: the standard library,
1690 site-specific modules, platform-specific modules, etc.
1691* :func:`~sysconfig.is_python_build` returns true if you're running a
1692 binary from a Python source tree, and false otherwise.
1693
1694Consult the :mod:`sysconfig` documentation for more details and for
1695a complete list of functions.
1696
Andrew M. Kuchling8e343862010-05-08 13:28:03 +00001697The Distutils package and :mod:`sysconfig` are now maintained by Tarek
1698Ziadé, who has also started a Distutils2 package (source repository at
1699http://hg.python.org/distutils2/) for developing a next-generation
1700version of Distutils.
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001701
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00001702
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001703ttk: Themed Widgets for Tk
1704--------------------------
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001705
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001706Tcl/Tk 8.5 includes a set of themed widgets that re-implement basic Tk
1707widgets but have a more customizable appearance and can therefore more
1708closely resemble the native platform's widgets. This widget
1709set was originally called Tile, but was renamed to Ttk (for "themed Tk")
1710on being added to Tcl/Tck release 8.5.
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001711
Andrew M. Kuchling8e343862010-05-08 13:28:03 +00001712To learn more, read the :mod:`ttk` module documentation. You may also
1713wish to read Tcl/Tk manual page describing the
1714Ttk theme engine, available at
1715http://www.tcl.tk/man/tcl8.5/TkCmd/ttk_intro.htm. Some
1716screenshots of the Python/Ttk code in use are at
1717http://code.google.com/p/python-ttk/wiki/Screenshots.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001718
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001719The :mod:`ttk` module was written by Guilherme Polo and added in
1720:issue:`2983`. An alternate version called ``Tile.py``, written by
1721Martin Franklin and maintained by Kevin Walzer, was proposed for
1722inclusion in :issue:`2618`, but the authors argued that Guilherme
1723Polo's work was more comprehensive.
1724
1725
1726.. _unittest-section:
Tarek Ziadé2b210692010-02-02 23:39:40 +00001727
Andrew M. Kuchlingacab9402010-05-06 17:27:57 +00001728Updated module: unittest
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001729---------------------------------
1730
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001731The :mod:`unittest` module was greatly enhanced; many
1732new features were added. Most of these features were implemented
Andrew M. Kuchlingacab9402010-05-06 17:27:57 +00001733by Michael Foord, unless otherwise noted. The enhanced version of
1734the module is downloadable separately for use with Python versions 2.4 to 2.6,
1735packaged as the :mod:`unittest2` package, from
1736http://pypi.python.org/pypi/unittest2.
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001737
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001738When used from the command line, the module can automatically discover
1739tests. It's not as fancy as `py.test <http://pytest.org>`__ or
1740`nose <http://code.google.com/p/python-nose/>`__, but provides a simple way
1741to run tests kept within a set of package directories. For example,
1742the following command will search the :file:`test/` subdirectory for
1743any importable test files named ``test*.py``::
1744
1745 python -m unittest discover -s test
1746
1747Consult the :mod:`unittest` module documentation for more details.
1748(Developed in :issue:`6001`.)
1749
1750The :func:`main` function supports some other new options:
1751
1752* :option:`-b` or :option:`--buffer` will buffer the standard output
1753 and standard error streams during each test. If the test passes,
1754 any resulting output will be discard; on failure, the buffered
1755 output will be displayed.
1756
1757* :option:`-c` or :option:`--catch` will cause the control-C interrupt
1758 to be handled more gracefully. Instead of interrupting the test
1759 process immediately, the currently running test will be completed
1760 and then the resulting partial results will be reported. If you're
1761 impatient, a second press of control-C will cause an immediate
1762 interruption.
1763
1764 This control-C handler tries to avoid interfering when the code
1765 being tested or the tests being run have defined a signal handler of
1766 their own, by noticing that a signal handler was already set and
1767 calling it. If this doesn't work for you, there's a
1768 :func:`removeHandler` decorator that can be used to mark tests that
1769 should have the control-C handling disabled.
1770
1771* :option:`-f` or :option:`--failfast` makes
1772 test execution stop immediately when a test fails instead of
1773 continuing to execute further tests. (Suggested by Cliff Dyer and
1774 implemented by Michael Foord; :issue:`8074`.)
1775
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001776The progress messages now shows 'x' for expected failures
1777and 'u' for unexpected successes when run in verbose mode.
1778(Contributed by Benjamin Peterson.)
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001779
1780Test cases can raise the :exc:`~unittest.SkipTest` exception to skip a
1781test. (:issue:`1034053`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001782
Ezio Melotti021f3342010-04-06 03:26:49 +00001783The error messages for :meth:`~unittest.TestCase.assertEqual`,
1784:meth:`~unittest.TestCase.assertTrue`, and :meth:`~unittest.TestCase.assertFalse`
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001785failures now provide more information. If you set the
Ezio Melotti021f3342010-04-06 03:26:49 +00001786:attr:`~unittest.TestCase.longMessage` attribute of your :class:`~unittest.TestCase` classes to
1787True, both the standard error message and any additional message you
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001788provide will be printed for failures. (Added by Michael Foord; :issue:`5663`.)
1789
Ezio Melotti021f3342010-04-06 03:26:49 +00001790The :meth:`~unittest.TestCase.assertRaises` method now
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001791return a context handler when called without providing a callable
1792object to run. For example, you can write this::
1793
1794 with self.assertRaises(KeyError):
Ezio Melotti021f3342010-04-06 03:26:49 +00001795 {}['foo']
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001796
1797(Implemented by Antoine Pitrou; :issue:`4444`.)
1798
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001799.. rev 78774
1800
1801Module- and class-level setup and teardown fixtures are now supported.
Ezio Melotti021f3342010-04-06 03:26:49 +00001802Modules can contain :func:`~unittest.setUpModule` and :func:`~unittest.tearDownModule`
1803functions. Classes can have :meth:`~unittest.TestCase.setUpClass` and
1804:meth:`~unittest.TestCase.tearDownClass` methods that must be defined as class methods
1805(using ``@classmethod`` or equivalent). These functions and
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001806methods are invoked when the test runner switches to a test case in a
1807different module or class.
1808
Ezio Melotti021f3342010-04-06 03:26:49 +00001809The methods :meth:`~unittest.TestCase.addCleanup` and
1810:meth:`~unittest.TestCase.doCleanups` were added.
1811:meth:`~unittest.TestCase.addCleanup` allows you to add cleanup functions that
1812will be called unconditionally (after :meth:`~unittest.TestCase.setUp` if
1813:meth:`~unittest.TestCase.setUp` fails, otherwise after :meth:`~unittest.TestCase.tearDown`). This allows
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001814for much simpler resource allocation and deallocation during tests
1815(:issue:`5679`).
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001816
1817A number of new methods were added that provide more specialized
1818tests. Many of these methods were written by Google engineers
1819for use in their test suites; Gregory P. Smith, Michael Foord, and
1820GvR worked on merging them into Python's version of :mod:`unittest`.
1821
Ezio Melotti021f3342010-04-06 03:26:49 +00001822* :meth:`~unittest.TestCase.assertIsNone` and :meth:`~unittest.TestCase.assertIsNotNone` take one
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001823 expression and verify that the result is or is not ``None``.
1824
Ezio Melotti021f3342010-04-06 03:26:49 +00001825* :meth:`~unittest.TestCase.assertIs` and :meth:`~unittest.TestCase.assertIsNot`
1826 take two values and check whether the two values evaluate to the same object or not.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001827 (Added by Michael Foord; :issue:`2578`.)
1828
Ezio Melotti021f3342010-04-06 03:26:49 +00001829* :meth:`~unittest.TestCase.assertIsInstance` and
1830 :meth:`~unittest.TestCase.assertNotIsInstance` check whether
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00001831 the resulting object is an instance of a particular class, or of
1832 one of a tuple of classes. (Added by Georg Brandl; :issue:`7031`.)
1833
Ezio Melotti021f3342010-04-06 03:26:49 +00001834* :meth:`~unittest.TestCase.assertGreater`, :meth:`~unittest.TestCase.assertGreaterEqual`,
1835 :meth:`~unittest.TestCase.assertLess`, and :meth:`~unittest.TestCase.assertLessEqual` compare
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001836 two quantities.
1837
Ezio Melotti021f3342010-04-06 03:26:49 +00001838* :meth:`~unittest.TestCase.assertMultiLineEqual` compares two strings, and if they're
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001839 not equal, displays a helpful comparison that highlights the
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001840 differences in the two strings. This comparison is now used by
Ezio Melotti021f3342010-04-06 03:26:49 +00001841 default when Unicode strings are compared with :meth:`~unittest.TestCase.assertEqual`.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001842
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001843* :meth:`~unittest.TestCase.assertRegexpMatches` and
1844 :meth:`~unittest.TestCase.assertNotRegexpMatches` checks whether the
1845 first argument is a string matching or not matching the regular
1846 expression provided as the second argument (:issue:`8038`).
Ezio Melotti021f3342010-04-06 03:26:49 +00001847
1848* :meth:`~unittest.TestCase.assertRaisesRegexp` checks whether a particular exception
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001849 is raised, and then also checks that the string representation of
1850 the exception matches the provided regular expression.
1851
Ezio Melotti021f3342010-04-06 03:26:49 +00001852* :meth:`~unittest.TestCase.assertIn` and :meth:`~unittest.TestCase.assertNotIn`
1853 tests whether *first* is or is not in *second*.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001854
Ezio Melotti021f3342010-04-06 03:26:49 +00001855* :meth:`~unittest.TestCase.assertItemsEqual` tests whether two provided sequences
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001856 contain the same elements.
1857
Ezio Melotti021f3342010-04-06 03:26:49 +00001858* :meth:`~unittest.TestCase.assertSetEqual` compares whether two sets are equal, and
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001859 only reports the differences between the sets in case of error.
1860
Ezio Melotti021f3342010-04-06 03:26:49 +00001861* Similarly, :meth:`~unittest.TestCase.assertListEqual` and :meth:`~unittest.TestCase.assertTupleEqual`
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001862 compare the specified types and explain any differences without necessarily
1863 printing their full values; these methods are now used by default
Ezio Melotti021f3342010-04-06 03:26:49 +00001864 when comparing lists and tuples using :meth:`~unittest.TestCase.assertEqual`.
1865 More generally, :meth:`~unittest.TestCase.assertSequenceEqual` compares two sequences
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001866 and can optionally check whether both sequences are of a
1867 particular type.
1868
Ezio Melotti021f3342010-04-06 03:26:49 +00001869* :meth:`~unittest.TestCase.assertDictEqual` compares two dictionaries and reports the
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001870 differences; it's now used by default when you compare two dictionaries
Ezio Melotti021f3342010-04-06 03:26:49 +00001871 using :meth:`~unittest.TestCase.assertEqual`. :meth:`~unittest.TestCase.assertDictContainsSubset` checks whether
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001872 all of the key/value pairs in *first* are found in *second*.
1873
Ezio Melotti021f3342010-04-06 03:26:49 +00001874* :meth:`~unittest.TestCase.assertAlmostEqual` and :meth:`~unittest.TestCase.assertNotAlmostEqual` test
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001875 whether *first* and *second* are approximately equal. This method
1876 can either round their difference to an optionally-specified number
1877 of *places* (the default is 7) and compare it to zero, or require
1878 the difference to be smaller than a supplied *delta* value.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001879
Ezio Melotti021f3342010-04-06 03:26:49 +00001880* :meth:`~unittest.TestLoader.loadTestsFromName` properly honors the
1881 :attr:`~unittest.TestLoader.suiteClass` attribute of
1882 the :class:`~unittest.TestLoader`. (Fixed by Mark Roddy; :issue:`6866`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001883
Ezio Melotti021f3342010-04-06 03:26:49 +00001884* A new hook lets you extend the :meth:`~unittest.TestCase.assertEqual` method to handle
1885 new data types. The :meth:`~unittest.TestCase.addTypeEqualityFunc` method takes a type
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001886 object and a function. The function will be used when both of the
1887 objects being compared are of the specified type. This function
1888 should compare the two objects and raise an exception if they don't
1889 match; it's a good idea for the function to provide additional
1890 information about why the two objects are matching, much as the new
1891 sequence comparison methods do.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001892
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001893:func:`unittest.main` now takes an optional ``exit`` argument. If
Ezio Melotti021f3342010-04-06 03:26:49 +00001894False, :func:`~unittest.main` doesn't call :func:`sys.exit`, allowing it to be
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001895used from the interactive interpreter. (Contributed by J. Pablo
1896Fernández; :issue:`3379`.)
1897
Ezio Melotti021f3342010-04-06 03:26:49 +00001898:class:`~unittest.TestResult` has new :meth:`~unittest.TestResult.startTestRun` and
1899:meth:`~unittest.TestResult.stopTestRun` methods that are called immediately before
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001900and after a test run. (Contributed by Robert Collins; :issue:`5728`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001901
1902With all these changes, the :file:`unittest.py` was becoming awkwardly
1903large, so the module was turned into a package and the code split into
1904several files (by Benjamin Peterson). This doesn't affect how the
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001905module is imported or used.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001906
1907
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001908.. _elementtree-section:
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001909
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001910Updated module: ElementTree 1.3
1911---------------------------------
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001912
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001913The version of the ElementTree library included with Python was updated to
1914version 1.3. Some of the new features in ElementTree 1.3 are:
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001915
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001916* The various parsing functions now take a *parser* keyword argument
1917 that can be used to provide an :class:`XMLParser` instance that will
1918 be used. This makes it possible to override the file's internal encoding:
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001919
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001920 p = ET.XMLParser(encoding='utf-8')
1921 t = ET.XML("""<root/>""", parser=p)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001922
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001923 Errors in parsing XML now raise a :exc:`ParseError` exception.
1924 Instances of :exc:`ParseError` have a :attr:`position` attribute
1925 containing a (*line*, *column*) tuple giving the location of the problem.
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001926
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001927* ElementTree's code for converting trees to a string has been
1928 significantly reworked, making it roughly twice as fast in many
1929 cases. The :class:`ElementTree` :meth:`write` and :class:`Element`
1930 :meth:`write` methods now have a *method* parameter that can be
1931 "xml" (the default), "html", or "text". HTML mode will output empty
1932 elements as ``<empty></empty>`` instead of ``<empty/>``, and text
1933 mode will skip over elements and only output the text chunks. If
1934 you set the :attr:`tag` attribute of an element to ``None`` but
1935 leaves its children in place, the element will be omitted when the
1936 tree is written out, so you don't need to do more extensive rearrangement
1937 to remove a single element.
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001938
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001939 Namespace aspects have also been improved. All the ``xmlns:<whatever>``
1940 declarations are now put on the root element and not scattered throughout
1941 the resulting output. You can set the default namespace for a tree
1942 by setting the :attr:`default_namespace` attribute and can
1943 register new prefixes with :meth:`regsiter_namespace`. In XML mode,
1944 you can use the true/false *xml_declaration* parameter to suppress the
1945 XML declaration.
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001946
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001947* New :class:`Element` method: :meth:`extend` appends the items from a
1948 sequence to the element's children. Elements themselves behave like
1949 sequences, so it's easy to move children from one element to
1950 another::
Andrew M. Kuchlinga17cd4a2009-01-31 02:50:09 +00001951
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001952 from xml.etree import ElementTree as ET
Andrew M. Kuchlinga17cd4a2009-01-31 02:50:09 +00001953
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001954 t = ET.XML("""<list>
1955 <item>1</item> <item>2</item> <item>3</item>
1956 </list>""")
1957 new = ET.XML('<root/>')
1958 new.extend(t)
Andrew M. Kuchlinga17cd4a2009-01-31 02:50:09 +00001959
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001960 # Outputs <root><item>1</item>...</root>
1961 print ET.tostring(new)
Andrew M. Kuchlinga17cd4a2009-01-31 02:50:09 +00001962
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001963* New :class:`Element` method: :meth:`iter` yields the children of the
1964 element as a generator. It's also possible to write ``for child in
1965 elem: ...`` to loop over an element's children. The existing method
1966 :meth:`getiterator` is now deprecated. :meth:`getchildren` is
1967 another similar method that constructs and returns a list of
1968 children; it's also deprecated.
Georg Brandl0516f812009-11-18 18:52:35 +00001969
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001970* New :class:`Element` method: :meth:`itertext` yields all chunks of
1971 text that are descendants of the element. For example::
Georg Brandl0516f812009-11-18 18:52:35 +00001972
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001973 t = ET.XML("""<list>
1974 <item>1</item> <item>2</item> <item>3</item>
1975 </list>""")
1976
1977 # Outputs ['\n ', '1', ' ', '2', ' ', '3', '\n']
1978 print list(t.itertext())
1979
1980* Deprecated: using an element as a Boolean (i.e., ``if elem: ...``)
1981 would return true if the element had any children, or false if
1982 there were no children. This behaviour will eventually change or be removed
1983 because it's confusing (``None`` is false, but so is a childless element?),
1984 so it will now trigger a :exc:`FutureWarning`. In your code,
1985 you should be explicit: write ``len(elem) != 0`` if you're interested in
1986 the number of children, or ``elem is not None`` Instead,
1987
1988Fredrik Lundh develops ElementTree and produced the 1.3 version;
1989you can read his article describing 1.3 at
1990http://effbot.org/zone/elementtree-13-intro.htm.
1991Florent Xicluna updated the version included with
1992Python, after discussions on python-dev and in :issue:`6472`.)
Georg Brandl0516f812009-11-18 18:52:35 +00001993
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001994.. ======================================================================
1995
1996
1997Build and C API Changes
1998=======================
1999
2000Changes to Python's build process and to the C API include:
2001
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00002002* The latest release of the GNU Debugger, GDB 7, can be `scripted
2003 using Python
2004 <http://sourceware.org/gdb/current/onlinedocs/gdb/Python.html>`__.
2005 When you begin debugging an executable program P, GDB will look for
2006 a file named ``P-gdb.py`` and automatically read it. Dave Malcolm
2007 contributed a :file:`python-gdb.py` that adds a number of useful
2008 commands when debugging Python itself. For example, there are
2009 ``py-up`` and ``py-down`` that go up or down one Python stack frame,
2010 which usually corresponds to several C stack frames. ``py-print``
2011 prints the value of a Python variable, and ``py-bt`` prints the
2012 Python stack trace. (Added as a result of :issue:`8032`.)
2013
Andrew M. Kuchling10b1ec92009-01-02 21:00:35 +00002014* If you use the :file:`.gdbinit` file provided with Python,
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002015 the "pyo" macro in the 2.7 version now works correctly when the thread being
2016 debugged doesn't hold the GIL; the macro now acquires it before printing.
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00002017 (Contributed by Victor Stinner; :issue:`3632`.)
2018
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00002019* :cfunc:`Py_AddPendingCall` is now thread-safe, letting any
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00002020 worker thread submit notifications to the main Python thread. This
2021 is particularly useful for asynchronous IO operations.
Andrew M. Kuchlingbadc7092010-05-08 01:35:55 +00002022 (Contributed by Kristján Valur Jónsson; :issue:`4293`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00002023
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002024* New function: :cfunc:`PyCode_NewEmpty` creates an empty code object;
2025 only the filename, function name, and first line number are required.
2026 This is useful to extension modules that are attempting to
2027 construct a more useful traceback stack. Previously such
2028 extensions needed to call :cfunc:`PyCode_New`, which had many
2029 more arguments. (Added by Jeffrey Yasskin.)
2030
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00002031* New function: :cfunc:`PyErr_NewExceptionWithDoc` creates a new
2032 exception class, just as the existing :cfunc:`PyErr_NewException` does,
2033 but takes an extra ``char *`` argument containing the docstring for the
2034 new exception class. (Added by the 'lekma' user on the Python bug tracker;
2035 :issue:`7033`.)
2036
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002037* New function: :cfunc:`PyFrame_GetLineNumber` takes a frame object
2038 and returns the line number that the frame is currently executing.
2039 Previously code would need to get the index of the bytecode
2040 instruction currently executing, and then look up the line number
2041 corresponding to that address. (Added by Jeffrey Yasskin.)
2042
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00002043* New functions: :cfunc:`PyLong_AsLongAndOverflow` and
2044 :cfunc:`PyLong_AsLongLongAndOverflow` approximates a Python long
2045 integer as a C :ctype:`long` or :ctype:`long long`.
2046 If the number is too large to fit into
2047 the output type, an *overflow* flag is set and returned to the caller.
2048 (Contributed by Case Van Horsen; :issue:`7528` and :issue:`7767`.)
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00002049
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00002050* New function: stemming from the rewrite of string-to-float conversion,
2051 a new :cfunc:`PyOS_string_to_double` function was added. The old
2052 :cfunc:`PyOS_ascii_strtod` and :cfunc:`PyOS_ascii_atof` functions
2053 are now deprecated.
2054
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002055* New macros: the Python header files now define the following macros:
2056 :cmacro:`Py_ISALNUM`,
2057 :cmacro:`Py_ISALPHA`,
2058 :cmacro:`Py_ISDIGIT`,
2059 :cmacro:`Py_ISLOWER`,
2060 :cmacro:`Py_ISSPACE`,
2061 :cmacro:`Py_ISUPPER`,
2062 :cmacro:`Py_ISXDIGIT`,
2063 and :cmacro:`Py_TOLOWER`, :cmacro:`Py_TOUPPER`.
2064 All of these functions are analogous to the C
2065 standard macros for classifying characters, but ignore the current
2066 locale setting, because in
2067 several places Python needs to analyze characters in a
2068 locale-independent way. (Added by Eric Smith;
2069 :issue:`5793`.)
2070
2071 .. XXX these macros don't seem to be described in the c-api docs.
2072
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00002073* Removed function: :cmacro:`PyEval_CallObject` is now only available
2074 as a macro. A function version was being kept around to preserve
2075 ABI linking compatibility, but that was in 1997; it can certainly be
2076 deleted. (Removed by Antoine Pitrou; :issue:`8276`.)
2077
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00002078* New format codes: the :cfunc:`PyFormat_FromString`,
2079 :cfunc:`PyFormat_FromStringV`, and :cfunc:`PyErr_Format` now
2080 accepts ``%lld`` and ``%llu`` format codes for displaying values of
2081 C's :ctype:`long long` types.
2082 (Contributed by Mark Dickinson; :issue:`7228`.)
2083
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002084* The complicated interaction between threads and process forking has
2085 been changed. Previously, the child process created by
2086 :func:`os.fork` might fail because the child is created with only a
2087 single thread running, the thread performing the :func:`os.fork`.
2088 If other threads were holding a lock, such as Python's import lock,
2089 when the fork was performed, the lock would still be marked as
2090 "held" in the new process. But in the child process nothing would
2091 ever release the lock, since the other threads weren't replicated,
2092 and the child process would no longer be able to perform imports.
2093
2094 Python 2.7 now acquires the import lock before performing an
2095 :func:`os.fork`, and will also clean up any locks created using the
2096 :mod:`threading` module. C extension modules that have internal
2097 locks, or that call :cfunc:`fork()` themselves, will not benefit
2098 from this clean-up.
2099
2100 (Fixed by Thomas Wouters; :issue:`1590864`.)
2101
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00002102* The :cfunc:`Py_Finalize` function now calls the internal
2103 :func:`threading._shutdown` function; this prevents some exceptions from
2104 being raised when an interpreter shuts down.
2105 (Patch by Adam Olsen; :issue:`1722344`.)
2106
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002107* When using the :ctype:`PyMemberDef` structure to define attributes
2108 of a type, Python will no longer let you try to delete or set a
2109 :const:`T_STRING_INPLACE` attribute.
2110
2111 .. rev 79644
2112
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00002113* Global symbols defined by the :mod:`ctypes` module are now prefixed
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002114 with ``Py``, or with ``_ctypes``. (Implemented by Thomas
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00002115 Heller; :issue:`3102`.)
2116
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00002117* New configure option: the :option:`--with-system-expat` switch allows
2118 building the :mod:`pyexpat` module to use the system Expat library.
2119 (Contributed by Arfrever Frehtes Taifersar Arahesis; :issue:`7609`.)
2120
Andrew M. Kuchlingce690522010-04-13 01:32:51 +00002121* New configure option: compiling Python with the
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00002122 :option:`--with-valgrind` option will now disable the pymalloc
Andrew M. Kuchlingce690522010-04-13 01:32:51 +00002123 allocator, which is difficult for the Valgrind memory-error detector
2124 to analyze correctly.
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00002125 Valgrind will therefore be better at detecting memory leaks and
2126 overruns. (Contributed by James Henstridge; :issue:`2422`.)
2127
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +00002128* New configure option: you can now supply no arguments to
2129 :option:`--with-dbmliborder=` in order to build none of the various
2130 DBM modules. (Added by Arfrever Frehtes Taifersar Arahesis;
2131 :issue:`6491`.)
2132
Andrew M. Kuchling77069572009-03-31 01:21:01 +00002133* The :program:`configure` script now checks for floating-point rounding bugs
2134 on certain 32-bit Intel chips and defines a :cmacro:`X87_DOUBLE_ROUNDING`
2135 preprocessor definition. No code currently uses this definition,
2136 but it's available if anyone wishes to use it.
2137 (Added by Mark Dickinson; :issue:`2937`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002138
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00002139 :program:`configure` also now sets a :envvar:`LDCXXSHARED` Makefile
2140 variable for supporting C++ linking. (Contributed by Arfrever
2141 Frehtes Taifersar Arahesis; :issue:`1222585`.)
2142
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002143* The build process now creates the necessary files for pkg-config
2144 support. (Contributed by Clinton Roy; :issue:`3585`.)
2145
2146* The build process now supports Subversion 1.7. (Contributed by
2147 Arfrever Frehtes Taifersar Arahesis; :issue:`6094`.)
2148
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00002149
Andrew M. Kuchling85fffc32010-05-08 01:15:26 +00002150.. _whatsnew27-capsules:
2151
2152Capsules
2153-------------------
2154
2155Python 3.1 adds a new C datatype, :ctype:`PyCapsule`, for providing a
2156C API to an extension module. A capsule is essentially the holder for
2157a C ``void *`` pointer, and is bound to a module attribute; for
Andrew M. Kuchling304500c2010-05-08 13:29:46 +00002158example, the :mod:`socket` module's API is exposed as ``socket.CAPI``,
Andrew M. Kuchling85fffc32010-05-08 01:15:26 +00002159and :mod:`unicodedata` calls it ``ucnhash_CAPI``. Other extensions
2160can import the module, access its dictionary to get the capsule
2161object, and then get the ``void *`` pointer, which will usually point
2162to an array of pointers to the various API functions.
2163
2164There is an existing data type that already does this,
2165:ctype:`PyCObject`, but it doesn't provide type safety. Evil code
2166written in pure Python could cause a segmentation fault by taking a
2167:ctype:`PyCObject` from module A and somehow substituting it for the
2168:ctype:`PyCObject` in module B. Capsules know their own name,
2169and getting the pointer requires providing the name::
2170
2171 void *vtable;
2172
2173 if (!PyCapsule_IsValid(capsule, "mymodule.CAPI") {
2174 PyErr_SetString(PyExc_ValueError, "argument type invalid");
2175 return NULL;
2176 }
2177
2178 vtable = PyCapsule_GetPointer(capsule, "mymodule.CAPI");
2179
2180You are assured that ``vtable`` points to whatever you're expecting.
2181If a different capsule was passed in, :cfunc:`PyCapsule_IsValid` would
2182detect the mismatched name and return false. Refer to
2183:ref:`using-capsules` for more information on using these objects.
2184
2185Python 2.7 now uses capsules internally to provide various
2186extension-module APIs, but the :cfunc:`PyCObject_AsVoidPtr` was
2187modified to handle capsules, preserving compile-time compatibility
2188with the :ctype:`CObject` interface. Use of
2189:cfunc:`PyCObject_AsVoidPtr` will signal a
2190:exc:`PendingDeprecationWarning`, which is silent by default.
2191
2192Implemented in Python 3.1 and backported to 2.7 by Larry Hastings;
2193discussed in :issue:`5630`.
2194
2195
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002196.. ======================================================================
2197
2198Port-Specific Changes: Windows
2199-----------------------------------
2200
Andrew M. Kuchling10b1ec92009-01-02 21:00:35 +00002201* The :mod:`msvcrt` module now contains some constants from
2202 the :file:`crtassem.h` header file:
2203 :data:`CRT_ASSEMBLY_VERSION`,
2204 :data:`VC_ASSEMBLY_PUBLICKEYTOKEN`,
2205 and :data:`LIBRARIES_ASSEMBLY_NAME_PREFIX`.
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00002206 (Contributed by David Cournapeau; :issue:`4365`.)
2207
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002208* The :mod:`_winreg` module for accessing the registry now implements
2209 the :func:`CreateKeyEx` and :func:`DeleteKeyEx` functions, extended
2210 versions of previously-supported functions that take several extra
2211 arguments. The :func:`DisableReflectionKey`,
2212 :func:`EnableReflectionKey`, and :func:`QueryReflectionKey` were also
2213 tested and documented.
2214 (Implemented by Brian Curtin: :issue:`7347`.)
2215
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00002216* The new :cfunc:`_beginthreadex` API is used to start threads, and
2217 the native thread-local storage functions are now used.
Andrew M. Kuchlingbadc7092010-05-08 01:35:55 +00002218 (Contributed by Kristján Valur Jónsson; :issue:`3582`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002219
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +00002220* The :func:`os.kill` function now works on Windows. The signal value
2221 can be the constants :const:`CTRL_C_EVENT`,
2222 :const:`CTRL_BREAK_EVENT`, or any integer. The Control-C and
2223 Control-Break keystroke events can be sent to subprocesses; any
2224 other value will use the :cfunc:`TerminateProcess` API.
2225 (Contributed by Miki Tebeka; :issue:`1220212`.)
2226
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002227* The :func:`os.listdir` function now correctly fails
2228 for an empty path. (Fixed by Hirokazu Yamamoto; :issue:`5913`.)
2229
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00002230* The :mod:`mimelib` module will now read the MIME database from
2231 the Windows registry when initializing.
2232 (Patch by Gabriel Genellina; :issue:`4969`.)
2233
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002234.. ======================================================================
2235
2236Port-Specific Changes: Mac OS X
2237-----------------------------------
2238
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002239* The path ``/Library/Python/2.7/site-packages`` is now appended to
Andrew M. Kuchling77069572009-03-31 01:21:01 +00002240 ``sys.path``, in order to share added packages between the system
2241 installation and a user-installed copy of the same version.
2242 (Changed by Ronald Oussoren; :issue:`4865`.)
2243
Andrew M. Kuchling04b99cc2010-05-04 01:24:22 +00002244Port-Specific Changes: FreeBSD
2245-----------------------------------
2246
2247* FreeBSD 7.1's :const:`SO_SETFIB` constant, used with
2248 :func:`~socket.getsockopt`/:func:`~socket.setsockopt` to select an
2249 alternate routing table, is now available in the :mod:`socket`
2250 module. (Added by Kyle VanderBeek; :issue:`8235`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002251
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00002252Other Changes and Fixes
2253=======================
2254
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00002255* Two benchmark scripts, :file:`iobench` and :file:`ccbench`, were
2256 added to the :file:`Tools` directory. :file:`iobench` measures the
Antoine Pitroudde96e62010-02-08 20:25:47 +00002257 speed of built-in file I/O objects (as returned by :func:`open`)
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00002258 while performing various operations, and :file:`ccbench` is a
2259 concurrency benchmark that tries to measure computing throughput,
2260 thread switching latency, and IO processing bandwidth when
2261 performing several tasks using a varying number of threads.
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00002262
Andrew M. Kuchling77069572009-03-31 01:21:01 +00002263* When importing a module from a :file:`.pyc` or :file:`.pyo` file
2264 with an existing :file:`.py` counterpart, the :attr:`co_filename`
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00002265 attributes of the resulting code objects are overwritten when the
2266 original filename is obsolete. This can happen if the file has been
2267 renamed, moved, or is accessed through different paths. (Patch by
2268 Ziga Seilnacht and Jean-Paul Calderone; :issue:`1180193`.)
Andrew M. Kuchling77069572009-03-31 01:21:01 +00002269
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00002270* The :file:`regrtest.py` script now takes a :option:`--randseed=`
2271 switch that takes an integer that will be used as the random seed
2272 for the :option:`-r` option that executes tests in random order.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002273 The :option:`-r` option also reports the seed that was used
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00002274 (Added by Collin Winter.)
2275
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00002276* Another :file:`regrtest.py` switch is :option:`-j`, which
2277 takes an integer specifying how many tests run in parallel. This
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002278 allows reducing the total runtime on multi-core machines.
Antoine Pitrou4698d992009-05-31 14:20:14 +00002279 This option is compatible with several other options, including the
2280 :option:`-R` switch which is known to produce long runtimes.
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00002281 (Added by Antoine Pitrou, :issue:`6152`.) This can also be used
2282 with a new :option:`-F` switch that runs selected tests in a loop
2283 until they fail. (Added by Antoine Pitrou; :issue:`7312`.)
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00002284
Andrew M. Kuchling85f928a2010-04-15 01:42:27 +00002285* When executed as a script, the :file:`py_compile.py` module now
2286 accepts ``'-'`` as an argument, which will read standard input for
2287 the list of filenames to be compiled. (Contributed by Piotr
2288 Ożarowski; :issue:`8233`.)
2289
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002290.. ======================================================================
2291
2292Porting to Python 2.7
2293=====================
2294
2295This section lists previously described changes and other bugfixes
2296that may require changes to your code:
2297
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00002298* The :func:`range` function processes its arguments more
2299 consistently; it will now call :meth:`__int__` on non-float,
2300 non-integer arguments that are supplied to it. (Fixed by Alexander
2301 Belopolsky; :issue:`1533`.)
2302
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002303* The string :meth:`format` method changed the default precision used
2304 for floating-point and complex numbers from 6 decimal
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002305 places to 12, which matches the precision used by :func:`str`.
2306 (Changed by Eric Smith; :issue:`5920`.)
2307
Amaury Forgeot d'Arc901f2002009-06-09 23:08:13 +00002308* Because of an optimization for the :keyword:`with` statement, the special
2309 methods :meth:`__enter__` and :meth:`__exit__` must belong to the object's
2310 type, and cannot be directly attached to the object's instance. This
Amaury Forgeot d'Arcd81333c2009-06-10 20:30:19 +00002311 affects new-style classes (derived from :class:`object`) and C extension
Amaury Forgeot d'Arc901f2002009-06-09 23:08:13 +00002312 types. (:issue:`6101`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002313
Andrew M. Kuchling837a5382010-05-06 17:21:59 +00002314* Due to a bug in Python 2.6, the *exc_value* parameter to
2315 :meth:`__exit__` methods was often the string representation of the
2316 exception, not an instance. This was fixed in 2.7, so *exc_value*
2317 will be an instance as expected. (Fixed by Florent Xicluna;
2318 :issue:`7853`.)
2319
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00002320* When a restricted set of attributes were set using ``__slots__``,
2321 deleting an unset attribute would not raise :exc:`AttributeError`
2322 as you would expect. Fixed by Benjamin Peterson; :issue:`7604`.)
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002323
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00002324In the standard library:
2325
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002326* When using :class:`Decimal` instances with a string's
2327 :meth:`format` method, the default alignment was previously
2328 left-alignment. This has been changed to right-alignment, which might
2329 change the output of your programs.
2330 (Changed by Mark Dickinson; :issue:`6857`.)
2331
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00002332 Comparisons involving a signaling NaN value (or ``sNAN``) now signal
2333 :const:`InvalidOperation` instead of silently returning a true or
2334 false value depending on the comparison operator. Quiet NaN values
2335 (or ``NaN``) are now hashable. (Fixed by Mark Dickinson;
2336 :issue:`7279`.)
2337
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00002338* The ElementTree library, :mod:`xml.etree`, no longer escapes
2339 ampersands and angle brackets when outputting an XML processing
2340 instruction (which looks like `<?xml-stylesheet href="#style1"?>`)
2341 or comment (which looks like `<!-- comment -->`).
2342 (Patch by Neil Muller; :issue:`2746`.)
2343
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00002344* The :meth:`readline` method of :class:`StringIO` objects now does
2345 nothing when a negative length is requested, as other file-like
2346 objects do. (:issue:`7348`).
2347
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002348* The :mod:`syslog` module will now use the value of ``sys.argv[0]`` as the
2349 identifier instead of the previous default value of ``'python'``.
2350 (Changed by Sean Reifschneider; :issue:`8451`.)
2351
Andrew M. Kuchling04b99cc2010-05-04 01:24:22 +00002352* The :mod:`urlparse` module's :func:`~urlparse.urlsplit` now handles
2353 unknown URL schemes in a fashion compliant with :rfc:`3986`: if the
2354 URL is of the form ``"<something>://..."``, the text before the
2355 ``://`` is treated as the scheme, even if it's a made-up scheme that
2356 the module doesn't know about. This change may break code that
2357 worked around the old behaviour. For example, Python 2.6.4 or 2.5
2358 will return the following:
2359
2360 >>> import urlparse
2361 >>> urlparse.urlsplit('invented://host/filename?query')
2362 ('invented', '', '//host/filename?query', '', '')
2363
2364 Python 2.7 (and Python 2.6.5) will return:
2365
2366 >>> import urlparse
2367 >>> urlparse.urlsplit('invented://host/filename?query')
2368 ('invented', 'host', '/filename?query', '', '')
2369
2370 (Python 2.7 actually produces slightly different output, since it
2371 returns a named tuple instead of a standard tuple.)
2372
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00002373For C extensions:
2374
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +00002375* C extensions that use integer format codes with the ``PyArg_Parse*``
2376 family of functions will now raise a :exc:`TypeError` exception
2377 instead of triggering a :exc:`DeprecationWarning` (:issue:`5080`).
2378
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00002379* Use the new :cfunc:`PyOS_string_to_double` function instead of the old
2380 :cfunc:`PyOS_ascii_strtod` and :cfunc:`PyOS_ascii_atof` functions,
2381 which are now deprecated.
2382
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +00002383
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002384.. ======================================================================
2385
2386
2387.. _acks27:
2388
2389Acknowledgements
2390================
2391
2392The author would like to thank the following people for offering
2393suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchling0efe18a2010-05-08 15:39:46 +00002394article: Nick Coghlan, Philip Jenvey, Ryan Lovett, R. David Murray,
2395Hugh Secker-Walker.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002396