blob: 67c02185a888dcce0d2b81f45ca4fcb8ef583c7f [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. Kuchling85fffc32010-05-08 01:15:26 +00009.. Big jobs: pep 391 example
Andrew M. Kuchling837a5382010-05-06 17:21:59 +000010
Andrew M. Kuchling6d7dfa22010-04-11 12:49:37 +000011.. hyperlink all the methods & functions.
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +000012
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +000013.. T_STRING_INPLACE not described in main docs
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +000014.. XXX "Format String Syntax" in string.rst could use many more examples.
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +000015
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000016.. $Id$
17 Rules for maintenance:
18
19 * Anyone can add text to this document. Do not spend very much time
20 on the wording of your changes, because your text will probably
21 get rewritten to some degree.
22
23 * The maintainer will go through Misc/NEWS periodically and add
24 changes; it's therefore more important to add your changes to
25 Misc/NEWS than to this file.
26
27 * This is not a complete list of every single change; completeness
28 is the purpose of Misc/NEWS. Some changes I consider too small
29 or esoteric to include. If such a change is added to the text,
30 I'll just remove it. (This is another reason you shouldn't spend
31 too much time on writing your addition.)
32
33 * If you want to draw your new text to the attention of the
34 maintainer, add 'XXX' to the beginning of the paragraph or
35 section.
36
37 * It's OK to just add a fragmentary note about a change. For
38 example: "XXX Describe the transmogrify() function added to the
39 socket module." The maintainer will research the change and
40 write the necessary text.
41
42 * You can comment out your additions if you like, but it's not
43 necessary (especially when a final release is some months away).
44
Ezio Melotti021f3342010-04-06 03:26:49 +000045 * Credit the author of a patch or bugfix. Just the name is
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000046 sufficient; the e-mail address isn't necessary.
47
48 * It's helpful to add the bug/patch number in a parenthetical comment.
49
50 XXX Describe the transmogrify() function added to the socket
51 module.
52 (Contributed by P.Y. Developer; :issue:`12345`.)
53
54 This saves the maintainer some effort going through the SVN logs
55 when researching a change.
56
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +000057This article explains the new features in Python 2.7. The final
Andrew M. Kuchling837a5382010-05-06 17:21:59 +000058release of 2.7 is currently scheduled for July 2010; the detailed
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +000059schedule is described in :pep:`373`.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000060
61.. Compare with previous release in 2 - 3 sentences here.
62 add hyperlink when the documentation becomes available online.
63
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +000064.. _whatsnew27-python31:
65
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +000066The Future for Python 2.x
67=========================
68
69Python 2.7 is intended to be the last major release in the 2.x series.
Andrew M. Kuchlingd1e696b2010-05-07 11:30:47 +000070The Python maintainers are planning to focus their future efforts on
71the Python 3.x series.
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +000072
73This means that 2.7 will remain in place for a long time, running
74production systems that have not been ported to Python 3.x.
75Two consequences of the long-term significance of 2.7 are:
76
77* It's very likely the 2.7 release will have a longer period of
78 maintenance compared to earlier 2.x versions. Python 2.7 will
Andrew M. Kuchlingd1e696b2010-05-07 11:30:47 +000079 continue to be maintained while the transition to 3.x continues.
80 Maintenance releases for Python 2.7 will probably be made for 5
81 years.
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +000082
Andrew M. Kuchlingd1e696b2010-05-07 11:30:47 +000083* A policy decision was made to silence warnings only of interest to
84 developers by default. :exc:`DeprecationWarning` and its
85 descendants are now ignored unless otherwise requested, preventing
86 users from seeing warnings triggered by an application. (Carried
87 out in :issue:`7319`.)
88
89 In previous releases, :exc:`DeprecationWarning` messages were
90 enabled by default, providing Python developers with a clear
91 indication of where their code may break in a future major version
92 of Python.
93
94 However, there are increasingly many users of Python-based
95 applications who are not directly involved in the development of
96 those applications. :exc:`DeprecationWarning` messages are
97 irrelevant to such users, making them worry about an application
98 that's actually working correctly and burdening the developers of
99 these applications with responding to these concerns.
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +0000100
101 You can re-enable display of :exc:`DeprecationWarning` messages by
102 running Python with the :option:`-Wdefault` (short form:
103 :option:`-Wd`) switch, or you can add
104 ``warnings.simplefilter('default')`` to your code.
105
106
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000107Python 3.1 Features
108=======================
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000109
110Much as Python 2.6 incorporated features from Python 3.0,
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000111version 2.7 incorporates some of the new features
112in Python 3.1. The 2.x series continues to provide tools
113for migrating to the 3.x series.
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000114
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000115A partial list of 3.1 features that were backported to 2.7:
116
Andrew M. Kuchling837a5382010-05-06 17:21:59 +0000117* A new version of the :mod:`io` library, rewritten in C for performance.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000118* The ordered-dictionary type described in :ref:`pep-0372`.
Andrew M. Kuchling8f254e72009-12-08 02:37:05 +0000119* The new format specifier described in :ref:`pep-0378`.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000120* The :class:`memoryview` object.
121* A small subset of the :mod:`importlib` module `described below <#importlib-section>`__.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000122* Float-to-string and string-to-float conversions now round their
123 results more correctly. And :func:`repr` of a floating-point
124 number *x* returns a result that's guaranteed to round back to the
125 same number when converted back to a string.
Andrew M. Kuchling85fffc32010-05-08 01:15:26 +0000126* The :ctype:`PyCapsule` type, used to provide a C API for an extension module.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000127* The :cfunc:`PyLong_AsLongAndOverflow` C API function.
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000128
129One porting change: the :option:`-3` switch now automatically
130enables the :option:`-Qwarn` switch that causes warnings
131about using classic division with integers and long integers.
132
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000133Other new Python3-mode warnings include:
134
135* :func:`operator.isCallable` and :func:`operator.sequenceIncludes`,
136 which are not supported in 3.x.
137
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000138.. ========================================================================
139.. Large, PEP-level features and changes should be described here.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000140.. ========================================================================
141
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000142.. _pep-0372:
143
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000144PEP 372: Adding an ordered dictionary to collections
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000145====================================================
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000146
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000147Regular Python dictionaries iterate over key/value pairs in arbitrary order.
148Over the years, a number of authors have written alternative implementations
149that remember the order that the keys were originally inserted. Based on
150the experiences from those implementations, a new
Ezio Melotti021f3342010-04-06 03:26:49 +0000151:class:`~collections.OrderedDict` class has been introduced in the
152:mod:`collections` module.
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000153
Ezio Melotti021f3342010-04-06 03:26:49 +0000154The :class:`~collections.OrderedDict` API is substantially the same as regular
155dictionaries but will iterate over keys and values in a guaranteed order
156depending on when a key was first inserted::
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000157
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000158 >>> from collections import OrderedDict
159 >>> d = OrderedDict([('first', 1), ('second', 2),
160 ... ('third', 3)])
161 >>> d.items()
162 [('first', 1), ('second', 2), ('third', 3)]
163
164If a new entry overwrites an existing entry, the original insertion
165position is left unchanged::
166
167 >>> d['second'] = 4
168 >>> d.items()
169 [('first', 1), ('second', 4), ('third', 3)]
170
171Deleting an entry and reinserting it will move it to the end::
172
173 >>> del d['second']
174 >>> d['second'] = 5
175 >>> d.items()
176 [('first', 1), ('third', 3), ('second', 5)]
177
Ezio Melotti021f3342010-04-06 03:26:49 +0000178The :meth:`~collections.OrderedDict.popitem` method has an optional *last*
179argument that defaults to True. If *last* is True, the most recently
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000180added key is returned and removed; if it's False, the
181oldest key is selected::
182
183 >>> od = OrderedDict([(x,0) for x in range(20)])
184 >>> od.popitem()
185 (19, 0)
186 >>> od.popitem()
187 (18, 0)
Ezio Melotti021f3342010-04-06 03:26:49 +0000188 >>> od.popitem(last=False)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000189 (0, 0)
Ezio Melotti021f3342010-04-06 03:26:49 +0000190 >>> od.popitem(last=False)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000191 (1, 0)
192
193Comparing two ordered dictionaries checks both the keys and values,
194and requires that the insertion order was the same::
195
196 >>> od1 = OrderedDict([('first', 1), ('second', 2),
197 ... ('third', 3)])
198 >>> od2 = OrderedDict([('third', 3), ('first', 1),
199 ... ('second', 2)])
Ezio Melotti021f3342010-04-06 03:26:49 +0000200 >>> od1 == od2
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000201 False
202 >>> # Move 'third' key to the end
Ezio Melotti021f3342010-04-06 03:26:49 +0000203 >>> del od2['third']; od2['third'] = 3
204 >>> od1 == od2
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000205 True
206
Ezio Melotti021f3342010-04-06 03:26:49 +0000207Comparing an :class:`~collections.OrderedDict` with a regular dictionary
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000208ignores the insertion order and just compares the keys and values.
209
Ezio Melotti021f3342010-04-06 03:26:49 +0000210How does the :class:`~collections.OrderedDict` work? It maintains a
211doubly-linked list of keys, appending new keys to the list as they're inserted.
212A secondary dictionary maps keys to their corresponding list node, so
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000213deletion doesn't have to traverse the entire linked list and therefore
214remains O(1).
215
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000216The standard library now supports use of ordered dictionaries in several
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +0000217modules.
218
219* The :mod:`ConfigParser` module uses them by default, letting
220 configuration files be read, modified, and then written back in their original
221 order.
222
223* The :meth:`~collections.somenamedtuple._asdict()` method for
224 :func:`collections.namedtuple` now returns an ordered dictionary with the
225 values appearing in the same order as the underlying tuple indices.
226
227* The :mod:`json` module's :class:`~json.JSONDecoder` class
228 constructor was extended with an *object_pairs_hook* parameter to
229 allow :class:`OrderedDict` instances to be built by the decoder.
230 Support was also added for third-party tools like
231 `PyYAML <http://pyyaml.org/>`_.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000232
Andrew M. Kuchling7fe65a02009-10-13 15:49:33 +0000233.. seealso::
234
235 :pep:`372` - Adding an ordered dictionary to collections
236 PEP written by Armin Ronacher and Raymond Hettinger;
237 implemented by Raymond Hettinger.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000238
239.. _pep-0378:
240
241PEP 378: Format Specifier for Thousands Separator
Ezio Melotti021f3342010-04-06 03:26:49 +0000242=================================================
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000243
244To make program output more readable, it can be useful to add
245separators to large numbers and render them as
24618,446,744,073,709,551,616 instead of 18446744073709551616.
247
248The fully general solution for doing this is the :mod:`locale` module,
249which can use different separators ("," in North America, "." in
250Europe) and different grouping sizes, but :mod:`locale` is complicated
251to use and unsuitable for multi-threaded applications where different
252threads are producing output for different locales.
253
254Therefore, a simple comma-grouping mechanism has been added to the
Ezio Melotti021f3342010-04-06 03:26:49 +0000255mini-language used by the :meth:`str.format` method. When
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000256formatting a floating-point number, simply include a comma between the
257width and the precision::
258
Eric Smithc4663852010-04-06 14:30:15 +0000259 >>> '{:20,.2f}'.format(18446744073709551616.0)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000260 '18,446,744,073,709,551,616.00'
261
Eric Smith6a928602010-04-06 15:17:33 +0000262When formatting an integer, include the comma after the width:
263
264 >>> '{:20,d}'.format(18446744073709551616)
265 '18,446,744,073,709,551,616'
266
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000267This mechanism is not adaptable at all; commas are always used as the
268separator and the grouping is always into three-digit groups. The
269comma-formatting mechanism isn't as general as the :mod:`locale`
270module, but it's easier to use.
271
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000272.. seealso::
273
274 :pep:`378` - Format Specifier for Thousands Separator
275 PEP written by Raymond Hettinger; implemented by Eric Smith.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000276
Andrew M. Kuchlingab21f752010-03-02 13:55:33 +0000277PEP 389: The argparse Module for Parsing Command Lines
278======================================================
279
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000280The :mod:`argparse` module for parsing command-line arguments was
281added, intended as a more powerful replacement for the
282:mod:`optparse` module.
283
284This means Python now supports three different modules for parsing
285command-line arguments: :mod:`getopt`, :mod:`optparse`, and
286:mod:`argparse`. The :mod:`getopt` module closely resembles the C
287:cfunc:`getopt` function, so it remains useful if you're writing a
288Python prototype that will eventually be rewritten in C.
289:mod:`optparse` becomes redundant, but there are no plans to remove it
290because there are many scripts still using it, and there's no
291automated way to update these scripts. (Making the :mod:`argparse`
292API consistent with :mod:`optparse`'s interface was discussed but
293rejected as too messy and difficult.)
294
Andrew M. Kuchlingf03641a2010-04-14 01:14:59 +0000295In short, if you're writing a new script and don't need to worry
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000296about compatibility with earlier versions of Python, use
297:mod:`argparse` instead of :mod:`optparse`.
298
Andrew M. Kuchlingf03641a2010-04-14 01:14:59 +0000299Here's an example::
300
301 import argparse
302
303 parser = argparse.ArgumentParser(description='Command-line example.')
304
305 # Add optional switches
306 parser.add_argument('-v', action='store_true', dest='is_verbose',
307 help='produce verbose output')
308 parser.add_argument('-o', action='store', dest='output',
309 metavar='FILE',
310 help='direct output to FILE instead of stdout')
311 parser.add_argument('-C', action='store', type=int, dest='context',
312 metavar='NUM', default=0,
313 help='display NUM lines of added context')
314
315 # Allow any number of additional arguments.
316 parser.add_argument(nargs='*', action='store', dest='inputs',
317 help='input filenames (default is stdin)')
318
319 args = parser.parse_args()
320 print args.__dict__
321
322Unless you override it, :option:`-h` and :option:`--help` switches
323are automatically added, and produce neatly formatted output::
324
325 -> ./python.exe argparse-example.py --help
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +0000326 usage: argparse-example.py [-h] [-v] [-o FILE] [-C NUM] [inputs [inputs ...]]
Andrew M. Kuchlingf03641a2010-04-14 01:14:59 +0000327
328 Command-line example.
329
330 positional arguments:
331 inputs input filenames (default is stdin)
332
333 optional arguments:
334 -h, --help show this help message and exit
335 -v produce verbose output
336 -o FILE direct output to FILE instead of stdout
337 -C NUM display NUM lines of added context
338
339Similarly to :mod:`optparse`, the command-line switches and arguments
340are returned as an object with attributes named by the *dest* parameters::
341
342 -> ./python.exe argparse-example.py -v
343 {'output': None, 'is_verbose': True, 'context': 0, 'inputs': []}
344
345 -> ./python.exe argparse-example.py -v -o /tmp/output -C 4 file1 file2
346 {'output': '/tmp/output', 'is_verbose': True, 'context': 4,
347 'inputs': ['file1', 'file2']}
348
349:mod:`argparse` has much fancier validation than :mod:`optparse`; you
350can specify an exact number of arguments as an integer, 0 or more
351arguments by passing ``'*'``, 1 or more by passing ``'+'``, or an
352optional argument with ``'?'``. A top-level parser can contain
353sub-parsers, so you can define subcommands that have different sets of
354switches, as in ``svn commit``, ``svn checkout``, etc. You can
355specify an argument type as :class:`~argparse.FileType`, which will
356automatically open files for you and understands that ``'-'`` means
357standard input or output.
Andrew M. Kuchlingab21f752010-03-02 13:55:33 +0000358
359.. seealso::
360
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000361 `argparse module documentation <http://docs.python.org/dev/library/argparse.html>`__
362
363 `Upgrading optparse code to use argparse <http://docs.python.org/dev/library/argparse.html#upgrading-optparse-code>`__
364
Andrew M. Kuchlingab21f752010-03-02 13:55:33 +0000365 :pep:`389` - argparse - New Command Line Parsing Module
366 PEP written and implemented by Steven Bethard.
367
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000368PEP 391: Dictionary-Based Configuration For Logging
369====================================================
370
Andrew M. Kuchlingb6c1aeb2010-04-14 14:28:31 +0000371.. not documented in library reference yet.
372
373The :mod:`logging` module is very flexible; an application can define
374a tree of logging subsystems, and each logger in this tree can filter
375out certain messages, format them differently, and direct messages to
376a varying number of handlers.
377
378All this flexibility can require a lot of configuration. You can
379write Python statements to create objects and set their properties,
380but a complex set-up would require verbose but boring code.
381:mod:`logging` also supports a :func:`~logging.config.fileConfig`
382function that parses a file, but the file format doesn't support
383configuring filters, and it's messier to generate programmatically.
384
385Python 2.7 adds a :func:`~logging.config.dictConfig` function that
386uses a dictionary, and there are many ways to produce a dictionary
387from different sources. You can construct one with code, of course.
388Python's standard library now includes a JSON parser, so you could
389parse a file containing JSON, or you could use a YAML parsing library
390if one is installed.
391
Andrew M. Kuchling8e343862010-05-08 13:28:03 +0000392The following example configures two loggers, the root logger and a
393logger named "network". Messages sent to the root logger will be
394sent to the system log using the syslog protocol, and messages
395to the "network" logger will be written to a :file:`network.log` file
396that will be rotated once the log reaches 1Mb.
397
398::
399
400 import logging
401 import logging.config
402
403 configdict = {
404 'version': 1, # Must be 1 at present
405 'formatters': {
406 'standard': {
407 'format': '%(asctime)s %(name)-15s %(levelname)-8s %(message)s'}},
408
409 'handlers': {'netlog': {'backupCount': 10,
410 'class': 'logging.handlers.RotatingFileHandler',
411 'filename': '/logs/network.log',
412 'formatter': 'standard',
413 'level': 'INFO',
414 'maxBytes': 1024*1024},
415 'syslog': {'class': 'logging.handlers.SysLogHandler',
416 'formatter': 'standard',
417 'level': 'ERROR'}},
418
419 # Specify all the subordinate loggers
420 'loggers': {
421 'network': {
422 'handlers': ['netlog']
423 }
424 },
425 # Specify properties of the root logger
426 'root': {
427 'handlers': ['syslog']
428 },
429 }
430
431 # Set up configuration
432 logging.config.dictConfig(configdict)
433
434 # As an example, log two error messages
435 logger = logging.getLogger('/')
436 logger.error('Database not found')
437
438 netlogger = logging.getLogger('network')
439 netlogger.error('Connection failed')
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000440
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +0000441Three smaller enhancements to the :mod:`logging` module, all
442implemented by Vinay Sajip, are:
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000443
444.. rev79293
445
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +0000446* The :class:`~logging.handlers.SysLogHandler` class now supports
447 syslogging over TCP. The constructor has a *socktype* parameter
448 giving the type of socket to use, either :const:`socket.SOCK_DGRAM`
449 for UDP or :const:`socket.SOCK_STREAM` for TCP. The default
450 protocol remains UDP.
451
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +0000452* :class:`Logger` instances gained a :meth:`getChild` method that retrieves a
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000453 descendant logger using a relative path. For example,
454 once you retrieve a logger by doing ``log = getLogger('app')``,
455 calling ``log.getChild('network.listen')`` is equivalent to
456 ``getLogger('app.network.listen')``.
457
458* The :class:`LoggerAdapter` class gained a :meth:`isEnabledFor` method
459 that takes a *level* and returns whether the underlying logger would
460 process a message of that level of importance.
461
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000462.. seealso::
463
464 :pep:`391` - Dictionary-Based Configuration For Logging
465 PEP written and implemented by Vinay Sajip.
466
467PEP 3106: Dictionary Views
468====================================================
469
Andrew M. Kuchling85f928a2010-04-15 01:42:27 +0000470The dictionary methods :meth:`keys`, :meth:`values`, and :meth:`items`
471are different in Python 3.x. They return an object called a :dfn:`view`
472instead of a fully materialized list.
473
Andrew M. Kuchling85f928a2010-04-15 01:42:27 +0000474It's not possible to change the return values of :meth:`keys`,
475:meth:`values`, and :meth:`items` in Python 2.7 because too much code
476would break. Instead the 3.x versions were added under the new names
477of :meth:`viewkeys`, :meth:`viewvalues`, and :meth:`viewitems`.
478
479::
480
481 >>> d = dict((i*10, chr(65+i)) for i in range(26))
482 >>> d
483 {0: 'A', 130: 'N', 10: 'B', 140: 'O', 20: ..., 250: 'Z'}
484 >>> d.viewkeys()
485 dict_keys([0, 130, 10, 140, 20, 150, 30, ..., 250])
486
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +0000487Views can be iterated over, but they also behave like sets. The ``&``
488operator performs intersection, and ``|`` performs a union::
489
490 >>> d1 = dict((i*10, chr(65+i)) for i in range(26))
491 >>> d2 = dict((i**.5, i) for i in range(1000))
492 >>> d1.viewkeys() & d2.viewkeys()
493 set([0.0, 10.0, 20.0, 30.0])
494 >>> d1.viewkeys() | range(0, 30)
495 set([0, 1, 130, 3, 4, 5, 6, ..., 120, 250])
496
Andrew M. Kuchling85f928a2010-04-15 01:42:27 +0000497The view keeps track of the dictionary and its contents change as the
498dictionary is modified::
499
500 >>> vk = d.viewkeys()
501 >>> vk
502 dict_keys([0, 130, 10, ..., 250])
503 >>> d[260] = '&'
504 >>> vk
505 dict_keys([0, 130, 260, 10, ..., 250])
506
507However, note that you can't add or remove keys while you're iterating
508over the view::
509
510 >>> for k in vk:
511 ... d[k*2] = k
512 ...
513 Traceback (most recent call last):
514 File "<stdin>", line 1, in <module>
515 RuntimeError: dictionary changed size during iteration
516
517You can use the view methods in Python 2.x code, and the 2to3
518converter will change them to the standard :meth:`keys`,
519:meth:`values`, and :meth:`items` methods.
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000520
521.. seealso::
522
523 :pep:`3106` - Revamping dict.keys(), .values() and .items()
524 PEP written by Guido van Rossum.
525 Backported to 2.7 by Alexandre Vassalotti; :issue:`1967`.
526
527
Andrew M. Kuchling9fbbd3b2010-05-01 12:06:51 +0000528PEP 3137: The memoryview Object
529====================================================
530
531The :class:`memoryview` object provides a view of another object's
532memory content that matches the :class:`bytes` type's interface.
533
534 >>> import string
535 >>> m = memoryview(string.letters)
536 >>> m
537 <memory at 0x37f850>
538 >>> len(m) # Returns length of underlying object
539 52
540 >>> m[0], m[25], m[26] # Indexing returns one byte
541 ('a', 'z', 'A')
542 >>> m2 = m[0:26] # Slicing returns another memoryview
543 >>> m2
544 <memory at 0x37f080>
545
546The content of the view can be converted to a string of bytes or to
547a list of integers:
548
549 >>> m2.tobytes()
550 'abcdefghijklmnopqrstuvwxyz'
551 >>> m2.tolist()
552 [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]
553 >>>
554
555:class:`memoryview` objects allow modifying the underlying object if
556it's a mutable object.
557
558 >>> m2[0] = 75
559 Traceback (most recent call last):
560 File "<stdin>", line 1, in <module>
561 TypeError: cannot modify read-only memory
562 >>> b = bytearray(string.letters) # Creating a mutable object
563 >>> b
564 bytearray(b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
565 >>> mb = memoryview(b)
566 >>> mb[0] = '*' # Assign to view, changing the bytearray.
567 >>> b[0:5] # The bytearray has been changed.
568 bytearray(b'*bcde')
569 >>>
570
571.. seealso::
572
573 :pep:`3137` - Immutable Bytes and Mutable Buffer
574 PEP written by Guido van Rossum.
Antoine Pitrou5cace782010-05-01 12:16:39 +0000575 Implemented by Travis Oliphant, Antoine Pitrou and others.
Andrew M. Kuchling9fbbd3b2010-05-01 12:06:51 +0000576 Backported to 2.7 by Antoine Pitrou; :issue:`2396`.
577
578
579
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000580Other Language Changes
581======================
582
583Some smaller changes made to the core Python language are:
584
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000585* The syntax for set literals has been backported from Python 3.x.
586 Curly brackets are used to surround the contents of the resulting
587 mutable set; set literals are
588 distinguished from dictionaries by not containing colons and values.
589 ``{}`` continues to represent an empty dictionary; use
590 ``set()`` for an empty set.
591
592 >>> {1,2,3,4,5}
593 set([1, 2, 3, 4, 5])
Ezio Melotti021f3342010-04-06 03:26:49 +0000594 >>> set() # empty set
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000595 set([])
Ezio Melotti021f3342010-04-06 03:26:49 +0000596 >>> {} # empty dict
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000597 {}
598
599 Backported by Alexandre Vassalotti; :issue:`2335`.
600
601* Dictionary and set comprehensions are another feature backported from
602 3.x, generalizing list/generator comprehensions to use
603 the literal syntax for sets and dictionaries.
604
605 >>> {x:x*x for x in range(6)}
606 {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
607 >>> {'a'*x for x in range(6)}
608 set(['', 'a', 'aa', 'aaa', 'aaaa', 'aaaaa'])
609
610 Backported by Alexandre Vassalotti; :issue:`2333`.
611
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000612* The :keyword:`with` statement can now use multiple context managers
613 in one statement. Context managers are processed from left to right
614 and each one is treated as beginning a new :keyword:`with` statement.
615 This means that::
616
617 with A() as a, B() as b:
618 ... suite of statements ...
619
620 is equivalent to::
621
622 with A() as a:
623 with B() as b:
624 ... suite of statements ...
625
626 The :func:`contextlib.nested` function provides a very similar
627 function, so it's no longer necessary and has been deprecated.
628
629 (Proposed in http://codereview.appspot.com/53094; implemented by
630 Georg Brandl.)
631
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000632* Conversions between floating-point numbers and strings are
633 now correctly rounded on most platforms. These conversions occur
634 in many different places: :func:`str` on
635 floats and complex numbers; the :class:`float` and :class:`complex`
636 constructors;
637 numeric formatting; serialization and
638 deserialization of floats and complex numbers using the
639 :mod:`marshal`, :mod:`pickle`
640 and :mod:`json` modules;
641 parsing of float and imaginary literals in Python code;
Ezio Melotti021f3342010-04-06 03:26:49 +0000642 and :class:`~decimal.Decimal`-to-float conversion.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000643
644 Related to this, the :func:`repr` of a floating-point number *x*
645 now returns a result based on the shortest decimal string that's
646 guaranteed to round back to *x* under correct rounding (with
647 round-half-to-even rounding mode). Previously it gave a string
648 based on rounding x to 17 decimal digits.
649
Ezio Melotti021f3342010-04-06 03:26:49 +0000650 .. maybe add an example?
651
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000652 The rounding library responsible for this improvement works on
653 Windows, and on Unix platforms using the gcc, icc, or suncc
654 compilers. There may be a small number of platforms where correct
655 operation of this code cannot be guaranteed, so the code is not
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +0000656 used on such systems. You can find out which code is being used
657 by checking :data:`sys.float_repr_style`, which will be ``short``
658 if the new code is in use and ``legacy`` if it isn't.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000659
Mark Dickinsonbdd863d2010-01-07 09:28:29 +0000660 Implemented by Eric Smith and Mark Dickinson, using David Gay's
661 :file:`dtoa.c` library; :issue:`7117`.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000662
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000663* The :meth:`str.format` method now supports automatic numbering of the replacement
Benjamin Petersonaa0a0b92009-04-11 20:27:15 +0000664 fields. This makes using :meth:`str.format` more closely resemble using
665 ``%s`` formatting::
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000666
667 >>> '{}:{}:{}'.format(2009, 04, 'Sunday')
668 '2009:4:Sunday'
669 >>> '{}:{}:{day}'.format(2009, 4, day='Sunday')
670 '2009:4:Sunday'
671
Benjamin Petersonaa0a0b92009-04-11 20:27:15 +0000672 The auto-numbering takes the fields from left to right, so the first ``{...}``
673 specifier will use the first argument to :meth:`str.format`, the next
674 specifier will use the next argument, and so on. You can't mix auto-numbering
675 and explicit numbering -- either number all of your specifier fields or none
676 of them -- but you can mix auto-numbering and named fields, as in the second
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000677 example above. (Contributed by Eric Smith; :issue:`5237`.)
678
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000679 Complex numbers now correctly support usage with :func:`format`,
680 and default to being right-aligned.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000681 Specifying a precision or comma-separation applies to both the real
682 and imaginary parts of the number, but a specified field width and
683 alignment is applied to the whole of the resulting ``1.5+3j``
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000684 output. (Contributed by Eric Smith; :issue:`1588` and :issue:`7988`.)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000685
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000686 The 'F' format code now always formats its output using uppercase characters,
687 so it will now produce 'INF' and 'NAN'.
688 (Contributed by Eric Smith; :issue:`3382`.)
689
Andrew M. Kuchlingc4ae73e2010-04-30 13:47:34 +0000690 A low-level change: the :meth:`object.__format__` method now triggers
691 a :exc:`PendingDeprecationWarning` if it's passed a format string,
692 because the :meth:`__format__` method for :class:`object` converts
693 the object to a string representation and formats that. The method
694 used to silently apply the format string to the string
695 representation, but that could hide mistakes in Python code. If
696 you're supplying formatting information such as an alignment or
697 precision, presumably you're expecting the formatting to be applied
698 in some object-specific way. (Fixed by Eric Smith; :issue:`7994`.)
699
Mark Dickinson1a707982008-12-17 16:14:37 +0000700* The :func:`int` and :func:`long` types gained a ``bit_length``
Georg Brandl64e1c752009-04-11 18:19:27 +0000701 method that returns the number of bits necessary to represent
Mark Dickinson1a707982008-12-17 16:14:37 +0000702 its argument in binary::
703
704 >>> n = 37
Ezio Melotti021f3342010-04-06 03:26:49 +0000705 >>> bin(n)
Mark Dickinson1a707982008-12-17 16:14:37 +0000706 '0b100101'
707 >>> n.bit_length()
708 6
709 >>> n = 2**123-1
710 >>> n.bit_length()
711 123
712 >>> (n+1).bit_length()
713 124
714
715 (Contributed by Fredrik Johansson and Victor Stinner; :issue:`3439`.)
716
Andrew M. Kuchling92b97002009-05-02 17:12:15 +0000717* Conversions from long integers and regular integers to floating
718 point now round differently, returning the floating-point number
719 closest to the number. This doesn't matter for small integers that
720 can be converted exactly, but for large numbers that will
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000721 unavoidably lose precision, Python 2.7 now approximates more
Andrew M. Kuchling92b97002009-05-02 17:12:15 +0000722 closely. For example, Python 2.6 computed the following::
723
724 >>> n = 295147905179352891391
725 >>> float(n)
726 2.9514790517935283e+20
727 >>> n - long(float(n))
728 65535L
729
730 Python 2.7's floating-point result is larger, but much closer to the
731 true value::
732
733 >>> n = 295147905179352891391
734 >>> float(n)
735 2.9514790517935289e+20
Ezio Melotti021f3342010-04-06 03:26:49 +0000736 >>> n - long(float(n))
Andrew M. Kuchling92b97002009-05-02 17:12:15 +0000737 -1L
738
739 (Implemented by Mark Dickinson; :issue:`3166`.)
740
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000741 Integer division is also more accurate in its rounding behaviours. (Also
742 implemented by Mark Dickinson; :issue:`1811`.)
743
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000744* It's now possible for a subclass of the built-in :class:`unicode` type
745 to override the :meth:`__unicode__` method. (Implemented by
746 Victor Stinner; :issue:`1583863`.)
747
Ezio Melotti021f3342010-04-06 03:26:49 +0000748* The :class:`bytearray` type's :meth:`~bytearray.translate` method now accepts
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000749 ``None`` as its first argument. (Fixed by Georg Brandl;
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000750 :issue:`4759`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000751
Ezio Melotti021f3342010-04-06 03:26:49 +0000752 .. bytearray doesn't seem to be documented
753
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000754* When using ``@classmethod`` and ``@staticmethod`` to wrap
755 methods as class or static methods, the wrapper object now
756 exposes the wrapped function as their :attr:`__func__` attribute.
757 (Contributed by Amaury Forgeot d'Arc, after a suggestion by
758 George Sakkis; :issue:`5982`.)
759
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +0000760* When a restricted set of attributes were set using ``__slots__``,
761 deleting an unset attribute would not raise :exc:`AttributeError`
762 as you would expect. Fixed by Benjamin Peterson; :issue:`7604`.)
763
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000764* A new encoding named "cp720", used primarily for Arabic text, is now
765 supported. (Contributed by Alexander Belchenko and Amaury Forgeot
766 d'Arc; :issue:`1616979`.)
767
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000768* The :class:`file` object will now set the :attr:`filename` attribute
769 on the :exc:`IOError` exception when trying to open a directory
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +0000770 on POSIX platforms (noted by Jan Kaliszewski; :issue:`4764`), and
771 now explicitly checks for and forbids writing to read-only file objects
772 instead of trusting the C library to catch and report the error
773 (fixed by Stefan Krah; :issue:`5677`).
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000774
Benjamin Petersonae9a0a02009-12-31 16:49:37 +0000775* The Python tokenizer now translates line endings itself, so the
776 :func:`compile` built-in function can now accept code using any
777 line-ending convention. Additionally, it no longer requires that the
778 code end in a newline.
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +0000779
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000780* Extra parentheses in function definitions are illegal in Python 3.x,
781 meaning that you get a syntax error from ``def f((x)): pass``. In
782 Python3-warning mode, Python 2.7 will now warn about this odd usage.
783 (Noted by James Lingard; :issue:`7362`.)
784
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +0000785* It's now possible to create weak references to old-style class
786 objects. New-style classes were always weak-referenceable. (Fixed
787 by Antoine Pitrou; :issue:`8268`.)
788
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000789* When a module object is garbage-collected, the module's dictionary is
790 now only cleared if no one else is holding a reference to the
791 dictionary (:issue:`7140`).
792
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000793.. ======================================================================
794
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000795.. _new-27-interpreter:
796
797Interpreter Changes
798-------------------------------
799
800A new environment variable, :envvar:`PYTHONWARNINGS`,
801allows controlling warnings. It should be set to a string
802containing warning settings, equivalent to those
803used with the :option:`-W` switch, separated by commas.
804(Contributed by Brian Curtin; :issue:`7301`.)
805
806For example, the following setting will print warnings every time
807they occur, but turn warnings from the :mod:`Cookie` module into an
808error. (The exact syntax for setting an environment variable varies
809across operating systems and shells, so it may be different for you.)
810
811::
812
813 export PYTHONWARNINGS=all,error:::Cookie:0
814
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +0000815When running a module using the interpreter's :option:`-m` switch,
816``sys.argv[0]`` will now be set to the string ``'-m'`` while the
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +0000817module is being located, while executing the :file:`__init__.py` files
818for any parent packages of the module to be executed.
819(Suggested by Michael Foord; implemented by Nick Coghlan;
820:issue:`8202`.)
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000821
822.. ======================================================================
823
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000824
825Optimizations
826-------------
827
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000828Several performance enhancements have been added:
829
830.. * A new :program:`configure` option, :option:`--with-computed-gotos`,
831 compiles the main bytecode interpreter loop using a new dispatch
832 mechanism that gives speedups of up to 20%, depending on the system
833 and benchmark. The new mechanism is only supported on certain
834 compilers, such as gcc, SunPro, and icc.
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000835
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000836* A new opcode was added to perform the initial setup for
837 :keyword:`with` statements, looking up the :meth:`__enter__` and
838 :meth:`__exit__` methods. (Contributed by Benjamin Peterson.)
839
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000840* The garbage collector now performs better for one common usage
841 pattern: when many objects are being allocated without deallocating
842 any of them. This would previously take quadratic
843 time for garbage collection, but now the number of full garbage collections
844 is reduced as the number of objects on the heap grows.
845 The new logic is to only perform a full garbage collection pass when
846 the middle generation has been collected 10 times and when the
847 number of survivor objects from the middle generation exceeds 10% of
848 the number of objects in the oldest generation. (Suggested by Martin
Ezio Melotti021f3342010-04-06 03:26:49 +0000849 von Löwis and implemented by Antoine Pitrou; :issue:`4074`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000850
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000851* The garbage collector tries to avoid tracking simple containers
852 which can't be part of a cycle. In Python 2.7, this is now true for
853 tuples and dicts containing atomic types (such as ints, strings,
854 etc.). Transitively, a dict containing tuples of atomic types won't
855 be tracked either. This helps reduce the cost of each
856 garbage collection by decreasing the number of objects to be
857 considered and traversed by the collector.
Antoine Pitrouc18f6b02009-03-28 19:10:13 +0000858 (Contributed by Antoine Pitrou; :issue:`4688`.)
859
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000860* Long integers are now stored internally either in base 2**15 or in base
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000861 2**30, the base being determined at build time. Previously, they
862 were always stored in base 2**15. Using base 2**30 gives
863 significant performance improvements on 64-bit machines, but
864 benchmark results on 32-bit machines have been mixed. Therefore,
865 the default is to use base 2**30 on 64-bit machines and base 2**15
866 on 32-bit machines; on Unix, there's a new configure option
867 :option:`--enable-big-digits` that can be used to override this default.
868
869 Apart from the performance improvements this change should be
870 invisible to end users, with one exception: for testing and
Ezio Melotti021f3342010-04-06 03:26:49 +0000871 debugging purposes there's a new structseq :data:`sys.long_info` that
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000872 provides information about the internal format, giving the number of
873 bits per digit and the size in bytes of the C type used to store
874 each digit::
875
876 >>> import sys
877 >>> sys.long_info
878 sys.long_info(bits_per_digit=30, sizeof_digit=4)
879
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000880 (Contributed by Mark Dickinson; :issue:`4258`.)
881
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000882 Another set of changes made long objects a few bytes smaller: 2 bytes
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000883 smaller on 32-bit systems and 6 bytes on 64-bit.
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000884 (Contributed by Mark Dickinson; :issue:`5260`.)
885
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000886* The division algorithm for long integers has been made faster
887 by tightening the inner loop, doing shifts instead of multiplications,
888 and fixing an unnecessary extra iteration.
889 Various benchmarks show speedups of between 50% and 150% for long
890 integer divisions and modulo operations.
891 (Contributed by Mark Dickinson; :issue:`5512`.)
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +0000892 Bitwise operations are also significantly faster (initial patch by
893 Gregory Smith; :issue:`1087418`).
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000894
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000895* The implementation of ``%`` checks for the left-side operand being
896 a Python string and special-cases it; this results in a 1-3%
897 performance increase for applications that frequently use ``%``
898 with strings, such as templating libraries.
899 (Implemented by Collin Winter; :issue:`5176`.)
900
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000901* List comprehensions with an ``if`` condition are compiled into
902 faster bytecode. (Patch by Antoine Pitrou, back-ported to 2.7
903 by Jeffrey Yasskin; :issue:`4715`.)
904
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +0000905* Converting an integer or long integer to a decimal string was made
906 faster by special-casing base 10 instead of using a generalized
907 conversion function that supports arbitrary bases.
908 (Patch by Gawain Bolton; :issue:`6713`.)
909
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +0000910* The :meth:`split`, :meth:`replace`, :meth:`rindex`,
911 :meth:`rpartition`, and :meth:`rsplit` methods of string-like types
912 (strings, Unicode strings, and :class:`bytearray` objects) now use a
913 fast reverse-search algorithm instead of a character-by-character
914 scan. This is sometimes faster by a factor of 10. (Added by
915 Florent Xicluna; :issue:`7462` and :issue:`7622`.)
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +0000916
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000917* The :mod:`pickle` and :mod:`cPickle` modules now automatically
918 intern the strings used for attribute names, reducing memory usage
919 of the objects resulting from unpickling. (Contributed by Jake
920 McGuire; :issue:`5084`.)
921
922* The :mod:`cPickle` module now special-cases dictionaries,
923 nearly halving the time required to pickle them.
924 (Contributed by Collin Winter; :issue:`5670`.)
925
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000926.. ======================================================================
927
Georg Brandl0516f812009-11-18 18:52:35 +0000928New and Improved Modules
929========================
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000930
931As in every release, Python's standard library received a number of
932enhancements and bug fixes. Here's a partial list of the most notable
933changes, sorted alphabetically by module name. Consult the
934:file:`Misc/NEWS` file in the source tree for a more complete list of
935changes, or look through the Subversion logs for all the details.
936
Ezio Melotti021f3342010-04-06 03:26:49 +0000937* The :mod:`bdb` module's base debugging class :class:`~bdb.Bdb`
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000938 gained a feature for skipping modules. The constructor
939 now takes an iterable containing glob-style patterns such as
940 ``django.*``; the debugger will not step into stack frames
941 from a module that matches one of these patterns.
942 (Contributed by Maru Newby after a suggestion by
943 Senthil Kumaran; :issue:`5142`.)
944
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +0000945* The :mod:`binascii` module now supports the buffer API, so it can be
946 used with :class:`memoryview` instances and other similar buffer objects.
947 (Backported from 3.x by Florent Xicluna; :issue:`7703`.)
948
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000949* Updated module: the :mod:`bsddb` module has been updated from 4.7.2devel9
950 to version 4.8.4 of
951 `the pybsddb package <http://www.jcea.es/programacion/pybsddb.htm>`__.
952 The new version features better Python 3.x compatibility, various bug fixes,
953 and adds several new BerkeleyDB flags and methods.
Ezio Melotti021f3342010-04-06 03:26:49 +0000954 (Updated by Jesús Cea Avión; :issue:`8156`. The pybsddb
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000955 changelog can be browsed at http://hg.jcea.es/pybsddb/file/tip/ChangeLog.)
956
Ezio Melotti021f3342010-04-06 03:26:49 +0000957* The :mod:`bz2` module's :class:`~bz2.BZ2File` now supports the context
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000958 management protocol, so you can write ``with bz2.BZ2File(...) as f: ...``.
Andrew M. Kuchlingbadc7092010-05-08 01:35:55 +0000959 (Contributed by Hagen Fürstenau; :issue:`3860`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000960
Ezio Melotti021f3342010-04-06 03:26:49 +0000961* New class: the :class:`~collections.Counter` class in the :mod:`collections`
962 module is useful for tallying data. :class:`~collections.Counter` instances
963 behave mostly like dictionaries but return zero for missing keys instead of
Georg Brandlf6dab952009-04-28 21:48:35 +0000964 raising a :exc:`KeyError`:
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000965
Georg Brandlf6dab952009-04-28 21:48:35 +0000966 .. doctest::
967 :options: +NORMALIZE_WHITESPACE
968
969 >>> from collections import Counter
970 >>> c = Counter()
971 >>> for letter in 'here is a sample of english text':
972 ... c[letter] += 1
973 ...
974 >>> c
975 Counter({' ': 6, 'e': 5, 's': 3, 'a': 2, 'i': 2, 'h': 2,
976 'l': 2, 't': 2, 'g': 1, 'f': 1, 'm': 1, 'o': 1, 'n': 1,
977 'p': 1, 'r': 1, 'x': 1})
978 >>> c['e']
979 5
980 >>> c['z']
981 0
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000982
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +0000983 There are three additional :class:`~collections.Counter` methods:
984 :meth:`~collections.Counter.most_common` returns the N most common
985 elements and their counts. :meth:`~collections.Counter.elements`
986 returns an iterator over the contained elements, repeating each
987 element as many times as its count.
988 :meth:`~collections.Counter.subtract` takes an iterable and
989 subtracts one for each element instead of adding; if the argument is
990 a dictionary or another :class:`Counter`, the counts are
991 subtracted. ::
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000992
993 >>> c.most_common(5)
994 [(' ', 6), ('e', 5), ('s', 3), ('a', 2), ('i', 2)]
995 >>> c.elements() ->
996 'a', 'a', ' ', ' ', ' ', ' ', ' ', ' ',
997 'e', 'e', 'e', 'e', 'e', 'g', 'f', 'i', 'i',
998 'h', 'h', 'm', 'l', 'l', 'o', 'n', 'p', 's',
Georg Brandlf6dab952009-04-28 21:48:35 +0000999 's', 's', 'r', 't', 't', 'x'
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001000 >>> c['e']
1001 5
1002 >>> c.subtract('very heavy on the letter e')
1003 >>> c['e'] # Count is now lower
1004 -1
Ezio Melotti021f3342010-04-06 03:26:49 +00001005
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001006 Contributed by Raymond Hettinger; :issue:`1696199`.
1007
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001008 .. revision 79660
1009
Ezio Melotti021f3342010-04-06 03:26:49 +00001010 The new :class:`~collections.OrderedDict` class is described in the earlier
1011 section :ref:`pep-0372`.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001012
Ezio Melotti021f3342010-04-06 03:26:49 +00001013 The :class:`~collections.namedtuple` class now has an optional *rename* parameter.
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001014 If *rename* is true, field names that are invalid because they've
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001015 been repeated or that aren't legal Python identifiers will be
1016 renamed to legal names that are derived from the field's
1017 position within the list of fields:
1018
Georg Brandlf6dab952009-04-28 21:48:35 +00001019 >>> from collections import namedtuple
1020 >>> T = namedtuple('T', ['field1', '$illegal', 'for', 'field2'], rename=True)
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001021 >>> T._fields
1022 ('field1', '_1', '_2', 'field2')
1023
1024 (Added by Raymond Hettinger; :issue:`1818`.)
1025
Andrew M. Kuchling6d7dfa22010-04-11 12:49:37 +00001026 The :class:`~collections.deque` data type now has a
1027 :meth:`~collections.deque.count` method that returns the number of
1028 contained elements equal to the supplied argument *x*, and a
1029 :meth:`~collections.deque.reverse` method that reverses the elements
1030 of the deque in-place. :class:`deque` also exposes its maximum
1031 length as the read-only :attr:`~collections.deque.maxlen` attribute.
1032 (Both features added by Raymond Hettinger.)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001033
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +00001034* Constructors for the parsing classes in the :mod:`ConfigParser` module now
1035 take a *allow_no_value* parameter, defaulting to false; if true,
1036 options without values will be allowed. For example::
1037
1038 >>> import ConfigParser, StringIO
1039 >>> sample_config = """
1040 ... [mysqld]
1041 ... user = mysql
1042 ... pid-file = /var/run/mysqld/mysqld.pid
1043 ... skip-bdb
1044 ... """
1045 >>> config = ConfigParser.RawConfigParser(allow_no_value=True)
1046 >>> config.readfp(StringIO.StringIO(sample_config))
1047 >>> config.get('mysqld', 'user')
1048 'mysql'
1049 >>> print config.get('mysqld', 'skip-bdb')
1050 None
1051 >>> print config.get('mysqld', 'unknown')
1052 Traceback (most recent call last):
1053 ...
1054 ConfigParser.NoOptionError: No option 'unknown' in section: 'mysqld'
1055
1056 (Contributed by Mats Kindahl; :issue:`7005`.)
1057
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001058* Deprecated function: :func:`contextlib.nested`, which allows
1059 handling more than one context manager with a single :keyword:`with`
1060 statement, has been deprecated, because :keyword:`with` supports
1061 multiple context managers syntactically now.
1062
Ezio Melotti021f3342010-04-06 03:26:49 +00001063* The :mod:`copy` module's :func:`~copy.deepcopy` function will now
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001064 correctly copy bound instance methods. (Implemented by
1065 Robert Collins; :issue:`1515`.)
1066
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001067* The :mod:`ctypes` module now always converts ``None`` to a C NULL
1068 pointer for arguments declared as pointers. (Changed by Thomas
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001069 Heller; :issue:`4606`.) The underlying `libffi library
1070 <http://sourceware.org/libffi/>`__ has been updated to version
1071 3.0.9, containing various fixes for different platforms. (Updated
1072 by Matthias Klose; :issue:`8142`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001073
Ezio Melotti021f3342010-04-06 03:26:49 +00001074* New method: the :mod:`datetime` module's :class:`~datetime.timedelta` class
1075 gained a :meth:`~datetime.timedelta.total_seconds` method that returns the
1076 number of seconds in the duration. (Contributed by Brian Quinlan; :issue:`5788`.)
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001077
Ezio Melotti021f3342010-04-06 03:26:49 +00001078* New method: the :class:`~decimal.Decimal` class gained a
1079 :meth:`~decimal.Decimal.from_float` class method that performs an exact
1080 conversion of a floating-point number to a :class:`~decimal.Decimal`.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001081 Note that this is an **exact** conversion that strives for the
1082 closest decimal approximation to the floating-point representation's value;
1083 the resulting decimal value will therefore still include the inaccuracy,
1084 if any.
1085 For example, ``Decimal.from_float(0.1)`` returns
1086 ``Decimal('0.1000000000000000055511151231257827021181583404541015625')``.
1087 (Implemented by Raymond Hettinger; :issue:`4796`.)
1088
Andrew M. Kuchling04b99cc2010-05-04 01:24:22 +00001089 Comparing instances of :class:`Decimal` with floating-point
1090 numbers now produces sensible results based on the numeric values
1091 of the operands. Previously such comparisons would fall back to
1092 Python's default rules for comparing objects, which produced arbitrary
1093 results based on their type. Note that you still cannot combine
1094 :class:`Decimal` and floating-point in other operations such as addition,
1095 since you should be explicitly choosing how to convert between float and
1096 :class:`Decimal`.
1097 (Fixed by Mark Dickinson; :issue:`2531`.)
1098
Ezio Melotti021f3342010-04-06 03:26:49 +00001099 Most of the methods of the :class:`~decimal.Context` class now accept integers
1100 as well as :class:`~decimal.Decimal` instances; the only exceptions are the
1101 :meth:`~decimal.Context.canonical` and :meth:`~decimal.Context.is_canonical`
1102 methods. (Patch by Juan José Conti; :issue:`7633`.)
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001103
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001104 The constructor for :class:`~decimal.Decimal` now accepts
1105 floating-point numbers (added by Raymond Hettinger; :issue:`8257`)
1106 and non-European Unicode characters such as Arabic-Indic digits
1107 (contributed by Mark Dickinson; :issue:`6595`).
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001108
Ezio Melotti021f3342010-04-06 03:26:49 +00001109 When using :class:`~decimal.Decimal` instances with a string's
1110 :meth:`~str.format` method, the default alignment was previously
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001111 left-alignment. This has been changed to right-alignment, which seems
1112 more sensible for numeric types. (Changed by Mark Dickinson; :issue:`6857`.)
1113
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001114 Comparisons involving a signaling NaN value (or ``sNAN``) now signal
1115 :const:`InvalidOperation` instead of silently returning a true or
1116 false value depending on the comparison operator. Quiet NaN values
1117 (or ``NaN``) are now hashable. (Fixed by Mark Dickinson;
1118 :issue:`7279`.)
1119
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +00001120* The :mod:`difflib` module now produces output that is more
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00001121 compatible with modern :command:`diff`/:command:`patch` tools
1122 through one small change, using a tab character instead of spaces as
1123 a separator in the header giving the filename. (Fixed by Anatoly
1124 Techtonik; :issue:`7585`.)
1125
1126* The :mod:`doctest` module's :const:`IGNORE_EXCEPTION_DETAIL` flag
1127 will now ignore the name of the module containing the exception
1128 being tested. (Patch by Lennart Regebro; :issue:`7490`.)
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +00001129
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001130* The :class:`~fractions.Fraction` class now accepts a single float or
1131 :class:`~decimal.Decimal` instance, or two rational numbers, as
1132 arguments to its constructor. (Implemented by Mark Dickinson;
1133 rationals added in :issue:`5812`, and float/decimal in
1134 :issue:`8294`.)
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00001135
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +00001136 An oversight was fixed, making the :class:`Fraction` match the other
1137 numeric types; ordering comparisons (``<``, ``<=``, ``>``, ``>=``) between
1138 fractions and complex numbers now raise a :exc:`TypeError`.
1139
1140 .. revision 79455
1141
Ezio Melotti021f3342010-04-06 03:26:49 +00001142* New class: a new :class:`~ftplib.FTP_TLS` class in
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001143 the :mod:`ftplib` module provides secure FTP
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001144 connections using TLS encapsulation of authentication as well as
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001145 subsequent control and data transfers.
1146 (Contributed by Giampaolo Rodola', :issue:`2054`.)
1147
Ezio Melotti021f3342010-04-06 03:26:49 +00001148 The :meth:`~ftplib.FTP.storbinary` method for binary uploads can now restart
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001149 uploads thanks to an added *rest* parameter (patch by Pablo Mouzo;
1150 :issue:`6845`.)
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001151
Andrew M. Kuchling6d7dfa22010-04-11 12:49:37 +00001152* New class decorator: :func:`total_ordering` in the :mod:`functools`
1153 module takes a class that defines an :meth:`__eq__` method and one of
1154 :meth:`__lt__`, :meth:`__le__`, :meth:`__gt__`, or :meth:`__ge__`,
1155 and generates the missing comparison methods. Since the
1156 :meth:`__cmp__` method is being deprecated in Python 3.x,
1157 this decorator makes it easier to define ordered classes.
1158 (Added by Raymond Hettinger; :issue:`5479`.)
1159
1160 New function: :func:`cmp_to_key` will take an old-style comparison
1161 function that expects two arguments and return a new callable that
1162 can be used as the *key* parameter to functions such as
1163 :func:`sorted`, :func:`min` and :func:`max`, etc. The primary
1164 intended use is to help with making code compatible with Python 3.x.
1165 (Added by Raymond Hettinger.)
1166
Ezio Melotti021f3342010-04-06 03:26:49 +00001167* New function: the :mod:`gc` module's :func:`~gc.is_tracked` returns
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001168 true if a given instance is tracked by the garbage collector, false
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001169 otherwise. (Contributed by Antoine Pitrou; :issue:`4688`.)
1170
Ezio Melotti021f3342010-04-06 03:26:49 +00001171* The :mod:`gzip` module's :class:`~gzip.GzipFile` now supports the context
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +00001172 management protocol, so you can write ``with gzip.GzipFile(...) as f: ...``
Andrew M. Kuchlingbadc7092010-05-08 01:35:55 +00001173 (contributed by Hagen Fürstenau; :issue:`3860`), and it now implements
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +00001174 the :class:`io.BufferedIOBase` ABC, so you can wrap it with
1175 :class:`io.BufferedReader` for faster processing
1176 (contributed by Nir Aides; :issue:`7471`).
1177 It's also now possible to override the modification time
Andrew M. Kuchling77069572009-03-31 01:21:01 +00001178 recorded in a gzipped file by providing an optional timestamp to
1179 the constructor. (Contributed by Jacques Frechet; :issue:`4272`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001180
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001181 Files in gzip format can be padded with trailing zero bytes; the
1182 :mod:`gzip` module will now consume these trailing bytes. (Fixed by
1183 Tadek Pietraszek and Brian Curtin; :issue:`2846`.)
1184
Ezio Melotti021f3342010-04-06 03:26:49 +00001185* New attribute: the :mod:`hashlib` module now has an :attr:`~hashlib.hashlib.algorithms`
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001186 attribute containing a tuple naming the supported algorithms.
1187 In Python 2.7, ``hashlib.algorithms`` contains
1188 ``('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')``
1189 (Contributed by Carl Chenet; :issue:`7418`.)
1190
Ezio Melotti021f3342010-04-06 03:26:49 +00001191* The default :class:`~httplib.HTTPResponse` class used by the :mod:`httplib` module now
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001192 supports buffering, resulting in much faster reading of HTTP responses.
Andrew M. Kuchlingbadc7092010-05-08 01:35:55 +00001193 (Contributed by Kristján Valur Jónsson; :issue:`4879`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001194
Ezio Melotti021f3342010-04-06 03:26:49 +00001195 The :class:`~httplib.HTTPConnection` and :class:`~httplib.HTTPSConnection` classes
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001196 now support a *source_address* parameter, a ``(host, port)`` 2-tuple
1197 giving the source address that will be used for the connection.
1198 (Contributed by Eldon Ziegler; :issue:`3972`.)
1199
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00001200* The :mod:`ihooks` module now supports relative imports. Note that
1201 :mod:`ihooks` is an older module used to support customizing imports,
1202 superseded by the :mod:`imputil` module added in Python 2.0.
1203 (Relative import support added by Neil Schemenauer.)
1204
1205 .. revision 75423
1206
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001207* The :mod:`imaplib` module now supports IPv6 addresses.
1208 (Contributed by Derek Morr; :issue:`1655`.)
1209
Andrew M. Kuchlingce690522010-04-13 01:32:51 +00001210* New function: the :mod:`inspect` module's :func:`~inspect.getcallargs`
1211 takes a callable and its positional and keyword arguments,
1212 and figures out which of the callable's parameters will receive each argument,
1213 returning a dictionary mapping argument names to their values. For example::
1214
1215 >>> from inspect import getcallargs
1216 >>> def f(a, b=1, *pos, **named):
1217 ... pass
1218 >>> getcallargs(f, 1, 2, 3)
1219 {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
1220 >>> getcallargs(f, a=2, x=4)
1221 {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
1222 >>> getcallargs(f)
1223 Traceback (most recent call last):
1224 ...
1225 TypeError: f() takes at least 1 argument (0 given)
1226
1227 Contributed by George Sakkis; :issue:`3135`.
1228
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001229* Updated module: The :mod:`io` library has been upgraded to the version shipped with
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001230 Python 3.1. For 3.1, the I/O library was entirely rewritten in C
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001231 and is 2 to 20 times faster depending on the task being performed. The
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001232 original Python version was renamed to the :mod:`_pyio` module.
1233
1234 One minor resulting change: the :class:`io.TextIOBase` class now
1235 has an :attr:`errors` attribute giving the error setting
1236 used for encoding and decoding errors (one of ``'strict'``, ``'replace'``,
1237 ``'ignore'``).
1238
1239 The :class:`io.FileIO` class now raises an :exc:`OSError` when passed
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001240 an invalid file descriptor. (Implemented by Benjamin Peterson;
Ezio Melotti021f3342010-04-06 03:26:49 +00001241 :issue:`4991`.) The :meth:`~io.IOBase.truncate` method now preserves the
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001242 file position; previously it would change the file position to the
1243 end of the new file. (Fixed by Pascal Chambon; :issue:`6939`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001244
Andrew M. Kuchling5a73ff82009-12-02 14:27:11 +00001245* New function: ``itertools.compress(data, selectors)`` takes two
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001246 iterators. Elements of *data* are returned if the corresponding
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001247 value in *selectors* is true::
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001248
1249 itertools.compress('ABCDEF', [1,0,1,0,1,1]) =>
1250 A, C, E, F
1251
Ezio Melotti021f3342010-04-06 03:26:49 +00001252 .. maybe here is better to use >>> list(itertools.compress(...)) instead
1253
Andrew M. Kuchling5a73ff82009-12-02 14:27:11 +00001254 New function: ``itertools.combinations_with_replacement(iter, r)``
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001255 returns all the possible *r*-length combinations of elements from the
Ezio Melotti021f3342010-04-06 03:26:49 +00001256 iterable *iter*. Unlike :func:`~itertools.combinations`, individual elements
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001257 can be repeated in the generated combinations::
1258
1259 itertools.combinations_with_replacement('abc', 2) =>
1260 ('a', 'a'), ('a', 'b'), ('a', 'c'),
1261 ('b', 'b'), ('b', 'c'), ('c', 'c')
1262
1263 Note that elements are treated as unique depending on their position
1264 in the input, not their actual values.
1265
Ezio Melotti021f3342010-04-06 03:26:49 +00001266 The :func:`itertools.count` function now has a *step* argument that
1267 allows incrementing by values other than 1. :func:`~itertools.count` also
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001268 now allows keyword arguments, and using non-integer values such as
Ezio Melotti021f3342010-04-06 03:26:49 +00001269 floats or :class:`~decimal.Decimal` instances. (Implemented by Raymond
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001270 Hettinger; :issue:`5032`.)
1271
Andrew M. Kuchling77069572009-03-31 01:21:01 +00001272 :func:`itertools.combinations` and :func:`itertools.product` were
1273 previously raising :exc:`ValueError` for values of *r* larger than
1274 the input iterable. This was deemed a specification error, so they
1275 now return an empty iterator. (Fixed by Raymond Hettinger; :issue:`4816`.)
1276
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001277* Updated module: The :mod:`json` module was upgraded to version 2.0.9 of the
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001278 simplejson package, which includes a C extension that makes
1279 encoding and decoding faster.
1280 (Contributed by Bob Ippolito; :issue:`4136`.)
1281
Ezio Melotti021f3342010-04-06 03:26:49 +00001282 To support the new :class:`collections.OrderedDict` type, :func:`json.load`
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001283 now has an optional *object_pairs_hook* parameter that will be called
1284 with any object literal that decodes to a list of pairs.
1285 (Contributed by Raymond Hettinger; :issue:`5381`.)
1286
Andrew M. Kuchling837a5382010-05-06 17:21:59 +00001287* The :mod:`mailbox` module's :class:`Maildir` class now records the
1288 timestamp on the directories it reads, and only re-reads them if the
1289 modification time has subsequently changed. This improves
1290 performance by avoiding unneeded directory scans. (Fixed by
1291 A.M. Kuchling and Antoine Pitrou; :issue:`1607951`, :issue:`6896`.)
1292
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001293* New functions: the :mod:`math` module gained
Ezio Melotti021f3342010-04-06 03:26:49 +00001294 :func:`~math.erf` and :func:`~math.erfc` for the error function and the complementary error function,
1295 :func:`~math.expm1` which computes ``e**x - 1`` with more precision than
1296 using :func:`~math.exp` and subtracting 1,
1297 :func:`~math.gamma` for the Gamma function, and
1298 :func:`~math.lgamma` for the natural log of the Gamma function.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001299 (Contributed by Mark Dickinson and nirinA raseliarison; :issue:`3366`.)
1300
Andrew M. Kuchling24520b42009-04-09 11:22:47 +00001301* The :mod:`multiprocessing` module's :class:`Manager*` classes
1302 can now be passed a callable that will be called whenever
1303 a subprocess is started, along with a set of arguments that will be
1304 passed to the callable.
1305 (Contributed by lekma; :issue:`5585`.)
1306
Ezio Melotti021f3342010-04-06 03:26:49 +00001307 The :class:`~multiprocessing.Pool` class, which controls a pool of worker processes,
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001308 now has an optional *maxtasksperchild* parameter. Worker processes
1309 will perform the specified number of tasks and then exit, causing the
Ezio Melotti021f3342010-04-06 03:26:49 +00001310 :class:`~multiprocessing.Pool` to start a new worker. This is useful if tasks may leak
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001311 memory or other resources, or if some tasks will cause the worker to
1312 become very large.
1313 (Contributed by Charles Cazabon; :issue:`6963`.)
1314
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001315* The :mod:`nntplib` module now supports IPv6 addresses.
1316 (Contributed by Derek Morr; :issue:`1664`.)
1317
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001318* New functions: the :mod:`os` module wraps the following POSIX system
Ezio Melotti021f3342010-04-06 03:26:49 +00001319 calls: :func:`~os.getresgid` and :func:`~os.getresuid`, which return the
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001320 real, effective, and saved GIDs and UIDs;
Ezio Melotti021f3342010-04-06 03:26:49 +00001321 :func:`~os.setresgid` and :func:`~os.setresuid`, which set
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001322 real, effective, and saved GIDs and UIDs to new values;
Ezio Melotti021f3342010-04-06 03:26:49 +00001323 :func:`~os.initgroups`. (GID/UID functions
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001324 contributed by Travis H.; :issue:`6508`. Support for initgroups added
1325 by Jean-Paul Calderone; :issue:`7333`.)
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001326
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001327 The :func:`os.fork` function now re-initializes the import lock in
Ezio Melotti021f3342010-04-06 03:26:49 +00001328 the child process; this fixes problems on Solaris when :func:`~os.fork`
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001329 is called from a thread. (Fixed by Zsolt Cserna; :issue:`7242`.)
1330
Ezio Melotti021f3342010-04-06 03:26:49 +00001331* In the :mod:`os.path` module, the :func:`~os.path.normpath` and
1332 :func:`~os.path.abspath` functions now preserve Unicode; if their input path
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001333 is a Unicode string, the return value is also a Unicode string.
Ezio Melotti021f3342010-04-06 03:26:49 +00001334 (:meth:`~os.path.normpath` fixed by Matt Giuca in :issue:`5827`;
1335 :meth:`~os.path.abspath` fixed by Ezio Melotti in :issue:`3426`.)
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001336
Andrew M. Kuchling9cb42772009-01-21 02:15:43 +00001337* The :mod:`pydoc` module now has help for the various symbols that Python
1338 uses. You can now do ``help('<<')`` or ``help('@')``, for example.
1339 (Contributed by David Laban; :issue:`4739`.)
1340
Ezio Melotti021f3342010-04-06 03:26:49 +00001341* The :mod:`re` module's :func:`~re.split`, :func:`~re.sub`, and :func:`~re.subn`
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001342 now accept an optional *flags* argument, for consistency with the
1343 other functions in the module. (Added by Gregory P. Smith.)
1344
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001345* New function: :func:`~runpy.run_path` in the :mod:`runpy` module
1346 will execute the code at a provided *path* argument. *path* can be
1347 the path of a Python source file (:file:`example.py`), a compiled
1348 bytecode file (:file:`example.pyc`), a directory
Andrew M. Kuchling304500c2010-05-08 13:29:46 +00001349 (:file:`./package/`), or a zip archive (:file:`example.zip`). If a
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001350 directory or zip path is provided, it will be added to the front of
1351 ``sys.path`` and the module :mod:`__main__` will be imported. It's
1352 expected that the directory or zip contains a :file:`__main__.py`;
1353 if it doesn't, some other :file:`__main__.py` might be imported from
1354 a location later in ``sys.path``. This makes some of the machinery
Andrew M. Kuchling837a5382010-05-06 17:21:59 +00001355 of :mod:`runpy` available to scripts that want to mimic the way
1356 Python's :option:`-m` processes an explicit path name.
1357 (Added by Nick Coghlan; :issue:`6816`.)
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001358
Ezio Melotti021f3342010-04-06 03:26:49 +00001359* New function: in the :mod:`shutil` module, :func:`~shutil.make_archive`
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001360 takes a filename, archive type (zip or tar-format), and a directory
1361 path, and creates an archive containing the directory's contents.
1362 (Added by Tarek Ziadé.)
1363
Ezio Melotti021f3342010-04-06 03:26:49 +00001364 :mod:`shutil`'s :func:`~shutil.copyfile` and :func:`~shutil.copytree`
1365 functions now raise a :exc:`~shutil.SpecialFileError` exception when
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001366 asked to copy a named pipe. Previously the code would treat
1367 named pipes like a regular file by opening them for reading, and
1368 this would block indefinitely. (Fixed by Antoine Pitrou; :issue:`3002`.)
1369
1370* New functions: in the :mod:`site` module, three new functions
1371 return various site- and user-specific paths.
Ezio Melotti021f3342010-04-06 03:26:49 +00001372 :func:`~site.getsitepackages` returns a list containing all
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001373 global site-packages directories, and
Ezio Melotti021f3342010-04-06 03:26:49 +00001374 :func:`~site.getusersitepackages` returns the path of the user's
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001375 site-packages directory.
Ezio Melotti021f3342010-04-06 03:26:49 +00001376 :func:`~site.getuserbase` returns the value of the :envvar:`USER_BASE`
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001377 environment variable, giving the path to a directory that can be used
1378 to store data.
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001379 (Contributed by Tarek Ziadé; :issue:`6693`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001380
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001381 The :mod:`site` module now reports exceptions occurring
1382 when the :mod:`sitecustomize` module is imported, and will no longer
Florent Xiclunaad598332010-03-31 21:40:32 +00001383 catch and swallow the :exc:`KeyboardInterrupt` exception. (Fixed by
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001384 Victor Stinner; :issue:`3137`.)
1385
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001386* The :func:`~socket.create_connection` function
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +00001387 gained a *source_address* parameter, a ``(host, port)`` 2-tuple
1388 giving the source address that will be used for the connection.
1389 (Contributed by Eldon Ziegler; :issue:`3972`.)
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00001390
Ezio Melotti021f3342010-04-06 03:26:49 +00001391 The :meth:`~socket.socket.recv_into` and :meth:`~socket.socket.recvfrom_into`
1392 methods will now write into objects that support the buffer API, most usefully
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001393 the :class:`bytearray` and :class:`memoryview` objects. (Implemented by
1394 Antoine Pitrou; :issue:`8104`.)
1395
Ezio Melotti021f3342010-04-06 03:26:49 +00001396* The :mod:`SocketServer` module's :class:`~SocketServer.TCPServer` class now
Andrew M. Kuchling85fffc32010-05-08 01:15:26 +00001397 supports socket timeouts and disabling the Nagle algorithm.
1398 The :attr:`~SocketServer.TCPServer.disable_nagle_algorithm` class attribute
1399 defaults to False; if overridden to be True,
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001400 new request connections will have the TCP_NODELAY option set to
1401 prevent buffering many small sends into a single TCP packet.
Andrew M. Kuchling85fffc32010-05-08 01:15:26 +00001402 The :attr:`~SocketServer.TCPServer.timeout` class attribute can hold
1403 a timeout in seconds that will be applied to the request socket; if
1404 no request is received within that time, :meth:`handle_timeout`
1405 will be called and :meth:`handle_request` will return.
Andrew M. Kuchlingbadc7092010-05-08 01:35:55 +00001406 (Contributed by Kristján Valur Jónsson; :issue:`6192` and :issue:`6267`.)
Andrew M. Kuchling85fffc32010-05-08 01:15:26 +00001407
1408* The XML-RPC client and server, provided by the :mod:`xmlrpclib` and
1409 :mod:`SimpleXMLRPCServer` modules, have improved performance by
1410 supporting HTTP/1.1 keep-alive and by optionally using gzip encoding
1411 to compress the XML being exchanged. The gzip compression is
1412 controlled by the :attr:`encode_threshold` attribute of
1413 :class:`SimpleXMLRPCRequestHandler`, which contains a size in bytes;
1414 responses larger than this will be compressed.
Andrew M. Kuchlingbadc7092010-05-08 01:35:55 +00001415 (Contributed by Kristján Valur Jónsson; :issue:`6267`.)
Andrew M. Kuchling85fffc32010-05-08 01:15:26 +00001416
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001417
Ezio Melotti021f3342010-04-06 03:26:49 +00001418* Updated module: the :mod:`sqlite3` module has been updated to
Andrew M. Kuchlingfed15762010-03-08 12:00:39 +00001419 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
1420 the ability to load SQLite extensions from shared libraries.
1421 Call the ``enable_load_extension(True)`` method to enable extensions,
Ezio Melotti021f3342010-04-06 03:26:49 +00001422 and then call :meth:`~sqlite3.Connection.load_extension` to load a particular shared library.
Andrew M. Kuchlingfed15762010-03-08 12:00:39 +00001423 (Updated by Gerhard Häring.)
1424
Antoine Pitroud69e6ee2010-05-07 10:15:51 +00001425* The :mod:`ssl` module's :class:`ssl.SSLSocket` objects now support the
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001426 buffer API, which fixed a test suite failure (fix by Antoine Pitrou;
1427 :issue:`7133`) and automatically set
1428 OpenSSL's :cmacro:`SSL_MODE_AUTO_RETRY`, which will prevent an error
1429 code being returned from :meth:`recv` operations that trigger an SSL
1430 renegotiation (fix by Antoine Pitrou; :issue:`8222`).
1431
Antoine Pitroud69e6ee2010-05-07 10:15:51 +00001432 The :func:`ssl.wrap_socket` constructor function now takes a
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001433 *ciphers* argument that's a string listing the encryption algorithms
1434 to be allowed; the format of the string is described
Antoine Pitroud69e6ee2010-05-07 10:15:51 +00001435 `in the OpenSSL documentation
1436 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`__.
1437 (Added by Antoine Pitrou; :issue:`8322`.)
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001438
1439 Another change makes the extension load all of OpenSSL's ciphers and
1440 digest algorithms so that they're all available. Some SSL
1441 certificates couldn't be verified, reporting an 'unknown algorithm'
1442 error. (Reported by Beda Kosata, and fixed by Antoine Pitrou;
1443 :issue:`8484`.)
1444
1445 The version of OpenSSL being used is now available as the module
Antoine Pitroud69e6ee2010-05-07 10:15:51 +00001446 attributes :data:`ssl.OPENSSL_VERSION` (a string),
1447 :data:`ssl.OPENSSL_VERSION_INFO` (a 5-tuple), and
1448 :data:`ssl.OPENSSL_VERSION_NUMBER` (an integer). (Added by Antoine
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001449 Pitrou; :issue:`8321`.)
1450
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001451* The :mod:`struct` module will no longer silently ignore overflow
1452 errors when a value is too large for a particular integer format
1453 code (one of ``bBhHiIlLqQ``); it now always raises a
1454 :exc:`struct.error` exception. (Changed by Mark Dickinson;
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001455 :issue:`1523`.) The :func:`~struct.pack` function will also
1456 attempt to use :meth:`__index__` to convert and pack non-integers
1457 before trying the :meth:`__int__` method or reporting an error.
1458 (Changed by Mark Dickinson; :issue:`8300`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001459
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001460* New function: the :mod:`subprocess` module's
Ezio Melotti021f3342010-04-06 03:26:49 +00001461 :func:`~subprocess.check_output` runs a command with a specified set of arguments
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001462 and returns the command's output as a string when the command runs without
Ezio Melotti021f3342010-04-06 03:26:49 +00001463 error, or raises a :exc:`~subprocess.CalledProcessError` exception otherwise.
Andrew M. Kuchling10b1ec92009-01-02 21:00:35 +00001464
1465 ::
1466
1467 >>> subprocess.check_output(['df', '-h', '.'])
1468 'Filesystem Size Used Avail Capacity Mounted on\n
1469 /dev/disk0s2 52G 49G 3.0G 94% /\n'
1470
1471 >>> subprocess.check_output(['df', '-h', '/bogus'])
1472 ...
1473 subprocess.CalledProcessError: Command '['df', '-h', '/bogus']' returned non-zero exit status 1
1474
1475 (Contributed by Gregory P. Smith.)
1476
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001477 The :mod:`subprocess` module will now retry its internal system calls
1478 on receiving an :const:`EINTR` signal. (Reported by several people; final
1479 patch by Gregory P. Smith in :issue:`1068268`.)
1480
Ezio Melotti021f3342010-04-06 03:26:49 +00001481* New function: :func:`~symtable.is_declared_global` in the :mod:`symtable` module
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001482 returns true for variables that are explicitly declared to be global,
1483 false for ones that are implicitly global.
1484 (Contributed by Jeremy Hylton.)
1485
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00001486* The :mod:`syslog` module will now use the value of ``sys.argv[0]`` as the
1487 identifier instead of the previous default value of ``'python'``.
1488 (Changed by Sean Reifschneider; :issue:`8451`.)
1489
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001490* The ``sys.version_info`` value is now a named tuple, with attributes
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001491 named :attr:`major`, :attr:`minor`, :attr:`micro`,
1492 :attr:`releaselevel`, and :attr:`serial`. (Contributed by Ross
1493 Light; :issue:`4285`.)
1494
1495 :func:`sys.getwindowsversion` also returns a named tuple,
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +00001496 with attributes named :attr:`major`, :attr:`minor`, :attr:`build`,
Ezio Melotti12477752010-02-08 22:22:41 +00001497 :attr:`platform`, :attr:`service_pack`, :attr:`service_pack_major`,
Eric Smithb3c54882010-02-03 14:17:50 +00001498 :attr:`service_pack_minor`, :attr:`suite_mask`, and
1499 :attr:`product_type`. (Contributed by Brian Curtin; :issue:`7766`.)
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001500
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001501* The :mod:`tarfile` module's default error handling has changed, to
1502 no longer suppress fatal errors. The default error level was previously 0,
1503 which meant that errors would only result in a message being written to the
1504 debug log, but because the debug log is not activated by default,
1505 these errors go unnoticed. The default error level is now 1,
1506 which raises an exception if there's an error.
1507 (Changed by Lars Gustäbel; :issue:`7357`.)
1508
Ezio Melotti021f3342010-04-06 03:26:49 +00001509 :mod:`tarfile` now supports filtering the :class:`~tarfile.TarInfo`
1510 objects being added to a tar file. When you call :meth:`~tarfile.TarFile.add`,
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001511 instance, you may supply an optional *filter* argument
1512 that's a callable. The *filter* callable will be passed the
Ezio Melotti021f3342010-04-06 03:26:49 +00001513 :class:`~tarfile.TarInfo` for every file being added, and can modify and return it.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001514 If the callable returns ``None``, the file will be excluded from the
1515 resulting archive. This is more powerful than the existing
1516 *exclude* argument, which has therefore been deprecated.
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001517 (Added by Lars Gustäbel; :issue:`6856`.)
Ezio Melotti021f3342010-04-06 03:26:49 +00001518 The :class:`~tarfile.TarFile` class also now supports the context manager protocol.
Andrew M. Kuchlingfed15762010-03-08 12:00:39 +00001519 (Added by Lars Gustäbel; :issue:`7232`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001520
Ezio Melotti021f3342010-04-06 03:26:49 +00001521* The :meth:`~threading.Event.wait` method of the :class:`threading.Event` class
1522 now returns the internal flag on exit. This means the method will usually
1523 return true because :meth:`~threading.Event.wait` is supposed to block until the
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001524 internal flag becomes true. The return value will only be false if
1525 a timeout was provided and the operation timed out.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001526 (Contributed by Tim Lesher; :issue:`1674032`.)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001527
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001528* The Unicode database provided by the :mod:`unicodedata` module is
1529 now used internally to determine which characters are numeric,
1530 whitespace, or represent line breaks. The database also
1531 includes information from the :file:`Unihan.txt` data file (patch
1532 by Anders Chrigström and Amaury Forgeot d'Arc; :issue:`1571184`)
1533 and has been updated to version 5.2.0 (updated by
1534 Florent Xicluna; :issue:`8024`).
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001535
Andrew M. Kuchling04b99cc2010-05-04 01:24:22 +00001536* The :mod:`urlparse` module's :func:`~urlparse.urlsplit` now handles
1537 unknown URL schemes in a fashion compliant with :rfc:`3986`: if the
1538 URL is of the form ``"<something>://..."``, the text before the
1539 ``://`` is treated as the scheme, even if it's a made-up scheme that
1540 the module doesn't know about. This change may break code that
1541 worked around the old behaviour. For example, Python 2.6.4 or 2.5
1542 will return the following:
1543
1544 >>> import urlparse
1545 >>> urlparse.urlsplit('invented://host/filename?query')
1546 ('invented', '', '//host/filename?query', '', '')
1547
1548 Python 2.7 (and Python 2.6.5) will return:
1549
1550 >>> import urlparse
1551 >>> urlparse.urlsplit('invented://host/filename?query')
1552 ('invented', 'host', '/filename?query', '', '')
1553
1554 (Python 2.7 actually produces slightly different output, since it
1555 returns a named tuple instead of a standard tuple.)
1556
1557 The :mod:`urlparse` module also supports IPv6 literal addresses as defined by
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001558 :rfc:`2732` (contributed by Senthil Kumaran; :issue:`2987`). ::
1559
1560 >>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo')
1561 ParseResult(scheme='http', netloc='[1080::8:800:200C:417A]',
1562 path='/foo', params='', query='', fragment='')
1563
Ezio Melotti021f3342010-04-06 03:26:49 +00001564* The :class:`~UserDict.UserDict` class is now a new-style class. (Changed by
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001565 Benjamin Peterson.)
1566
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00001567* New class: the :class:`~weakref.WeakSet` class in the :mod:`weakref`
1568 module is a set that only holds weak references to its elements; elements
1569 will be removed once there are no references pointing to them.
1570 (Originally implemented in Python 3.x by Raymond Hettinger, and backported
1571 to 2.7 by Michael Foord.)
1572
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001573* The ElementTree library, :mod:`xml.etree`, no longer escapes
1574 ampersands and angle brackets when outputting an XML processing
Ezio Melotti021f3342010-04-06 03:26:49 +00001575 instruction (which looks like ``<?xml-stylesheet href="#style1"?>``)
1576 or comment (which looks like ``<!-- comment -->``).
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001577 (Patch by Neil Muller; :issue:`2746`.)
1578
Andrew M. Kuchling85fffc32010-05-08 01:15:26 +00001579* The XML-RPC client and server, provided by the :mod:`xmlrpclib` and
1580 :mod:`SimpleXMLRPCServer` modules, have improved performance by
1581 supporting HTTP/1.1 keep-alive and by optionally using gzip encoding
1582 to compress the XML being exchanged. The gzip compression is
1583 controlled by the :attr:`encode_threshold` attribute of
1584 :class:`SimpleXMLRPCRequestHandler`, which contains a size in bytes;
1585 responses larger than this will be compressed.
Andrew M. Kuchlingbadc7092010-05-08 01:35:55 +00001586 (Contributed by Kristján Valur Jónsson; :issue:`6267`.)
Andrew M. Kuchling85fffc32010-05-08 01:15:26 +00001587
Ezio Melotti021f3342010-04-06 03:26:49 +00001588* The :mod:`zipfile` module's :class:`~zipfile.ZipFile` now supports the context
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001589 management protocol, so you can write ``with zipfile.ZipFile(...) as f: ...``.
1590 (Contributed by Brian Curtin; :issue:`5511`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001591
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001592 :mod:`zipfile` now also supports archiving empty directories and
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001593 extracts them correctly. (Fixed by Kuba Wieczorek; :issue:`4710`.)
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001594 Reading files out of an archive is faster, and interleaving
Ezio Melotti021f3342010-04-06 03:26:49 +00001595 :meth:`~zipfile.ZipFile.read` and :meth:`~zipfile.ZipFile.readline` now works correctly.
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001596 (Contributed by Nir Aides; :issue:`7610`.)
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001597
Ezio Melotti021f3342010-04-06 03:26:49 +00001598 The :func:`~zipfile.is_zipfile` function now
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001599 accepts a file object, in addition to the path names accepted in earlier
1600 versions. (Contributed by Gabriel Genellina; :issue:`4756`.)
1601
Ezio Melotti021f3342010-04-06 03:26:49 +00001602 The :meth:`~zipfile.ZipFile.writestr` method now has an optional *compress_type* parameter
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001603 that lets you override the default compression method specified in the
Ezio Melotti021f3342010-04-06 03:26:49 +00001604 :class:`~zipfile.ZipFile` constructor. (Contributed by Ronald Oussoren;
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001605 :issue:`6003`.)
1606
1607
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001608.. ======================================================================
1609.. whole new modules get described in subsections here
1610
1611
1612.. _importlib-section:
1613
1614New module: importlib
1615------------------------------
1616
1617Python 3.1 includes the :mod:`importlib` package, a re-implementation
1618of the logic underlying Python's :keyword:`import` statement.
1619:mod:`importlib` is useful for implementors of Python interpreters and
1620to users who wish to write new importers that can participate in the
1621import process. Python 2.7 doesn't contain the complete
1622:mod:`importlib` package, but instead has a tiny subset that contains
1623a single function, :func:`~importlib.import_module`.
1624
1625``import_module(name, package=None)`` imports a module. *name* is
1626a string containing the module or package's name. It's possible to do
1627relative imports by providing a string that begins with a ``.``
1628character, such as ``..utils.errors``. For relative imports, the
1629*package* argument must be provided and is the name of the package that
1630will be used as the anchor for
1631the relative import. :func:`~importlib.import_module` both inserts the imported
1632module into ``sys.modules`` and returns the module object.
1633
1634Here are some examples::
1635
1636 >>> from importlib import import_module
1637 >>> anydbm = import_module('anydbm') # Standard absolute import
1638 >>> anydbm
1639 <module 'anydbm' from '/p/python/Lib/anydbm.py'>
1640 >>> # Relative import
1641 >>> sysconfig = import_module('..sysconfig', 'distutils.command')
1642 >>> sysconfig
1643 <module 'distutils.sysconfig' from '/p/python/Lib/distutils/sysconfig.pyc'>
1644
1645:mod:`importlib` was implemented by Brett Cannon and introduced in
1646Python 3.1.
1647
1648
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00001649New module: sysconfig
1650---------------------------------
1651
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001652The :mod:`sysconfig` module has been pulled out of the Distutils
1653package, becoming a new top-level module in its own right.
1654:mod:`sysconfig` provides functions for getting information about
1655Python's build process: compiler switches, installation paths, the
1656platform name, and whether Python is running from its source
1657directory.
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00001658
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001659Some of the functions in the module are:
1660
1661* :func:`~sysconfig.get_config_var` returns variables from Python's
1662 Makefile and the :file:`pyconfig.h` file.
1663* :func:`~sysconfig.get_config_vars` returns a dictionary containing
1664 all of the configuration variables.
1665* :func:`~sysconfig.getpath` returns the configured path for
1666 a particular type of module: the standard library,
1667 site-specific modules, platform-specific modules, etc.
1668* :func:`~sysconfig.is_python_build` returns true if you're running a
1669 binary from a Python source tree, and false otherwise.
1670
1671Consult the :mod:`sysconfig` documentation for more details and for
1672a complete list of functions.
1673
Andrew M. Kuchling8e343862010-05-08 13:28:03 +00001674The Distutils package and :mod:`sysconfig` are now maintained by Tarek
1675Ziadé, who has also started a Distutils2 package (source repository at
1676http://hg.python.org/distutils2/) for developing a next-generation
1677version of Distutils.
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001678
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00001679
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001680ttk: Themed Widgets for Tk
1681--------------------------
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001682
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001683Tcl/Tk 8.5 includes a set of themed widgets that re-implement basic Tk
1684widgets but have a more customizable appearance and can therefore more
1685closely resemble the native platform's widgets. This widget
1686set was originally called Tile, but was renamed to Ttk (for "themed Tk")
1687on being added to Tcl/Tck release 8.5.
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001688
Andrew M. Kuchling8e343862010-05-08 13:28:03 +00001689To learn more, read the :mod:`ttk` module documentation. You may also
1690wish to read Tcl/Tk manual page describing the
1691Ttk theme engine, available at
1692http://www.tcl.tk/man/tcl8.5/TkCmd/ttk_intro.htm. Some
1693screenshots of the Python/Ttk code in use are at
1694http://code.google.com/p/python-ttk/wiki/Screenshots.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001695
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001696The :mod:`ttk` module was written by Guilherme Polo and added in
1697:issue:`2983`. An alternate version called ``Tile.py``, written by
1698Martin Franklin and maintained by Kevin Walzer, was proposed for
1699inclusion in :issue:`2618`, but the authors argued that Guilherme
1700Polo's work was more comprehensive.
1701
1702
1703.. _unittest-section:
Tarek Ziadé2b210692010-02-02 23:39:40 +00001704
Andrew M. Kuchlingacab9402010-05-06 17:27:57 +00001705Updated module: unittest
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001706---------------------------------
1707
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001708The :mod:`unittest` module was greatly enhanced; many
1709new features were added. Most of these features were implemented
Andrew M. Kuchlingacab9402010-05-06 17:27:57 +00001710by Michael Foord, unless otherwise noted. The enhanced version of
1711the module is downloadable separately for use with Python versions 2.4 to 2.6,
1712packaged as the :mod:`unittest2` package, from
1713http://pypi.python.org/pypi/unittest2.
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001714
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001715When used from the command line, the module can automatically discover
1716tests. It's not as fancy as `py.test <http://pytest.org>`__ or
1717`nose <http://code.google.com/p/python-nose/>`__, but provides a simple way
1718to run tests kept within a set of package directories. For example,
1719the following command will search the :file:`test/` subdirectory for
1720any importable test files named ``test*.py``::
1721
1722 python -m unittest discover -s test
1723
1724Consult the :mod:`unittest` module documentation for more details.
1725(Developed in :issue:`6001`.)
1726
1727The :func:`main` function supports some other new options:
1728
1729* :option:`-b` or :option:`--buffer` will buffer the standard output
1730 and standard error streams during each test. If the test passes,
1731 any resulting output will be discard; on failure, the buffered
1732 output will be displayed.
1733
1734* :option:`-c` or :option:`--catch` will cause the control-C interrupt
1735 to be handled more gracefully. Instead of interrupting the test
1736 process immediately, the currently running test will be completed
1737 and then the resulting partial results will be reported. If you're
1738 impatient, a second press of control-C will cause an immediate
1739 interruption.
1740
1741 This control-C handler tries to avoid interfering when the code
1742 being tested or the tests being run have defined a signal handler of
1743 their own, by noticing that a signal handler was already set and
1744 calling it. If this doesn't work for you, there's a
1745 :func:`removeHandler` decorator that can be used to mark tests that
1746 should have the control-C handling disabled.
1747
1748* :option:`-f` or :option:`--failfast` makes
1749 test execution stop immediately when a test fails instead of
1750 continuing to execute further tests. (Suggested by Cliff Dyer and
1751 implemented by Michael Foord; :issue:`8074`.)
1752
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001753The progress messages now shows 'x' for expected failures
1754and 'u' for unexpected successes when run in verbose mode.
1755(Contributed by Benjamin Peterson.)
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001756
1757Test cases can raise the :exc:`~unittest.SkipTest` exception to skip a
1758test. (:issue:`1034053`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001759
Ezio Melotti021f3342010-04-06 03:26:49 +00001760The error messages for :meth:`~unittest.TestCase.assertEqual`,
1761:meth:`~unittest.TestCase.assertTrue`, and :meth:`~unittest.TestCase.assertFalse`
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001762failures now provide more information. If you set the
Ezio Melotti021f3342010-04-06 03:26:49 +00001763:attr:`~unittest.TestCase.longMessage` attribute of your :class:`~unittest.TestCase` classes to
1764True, both the standard error message and any additional message you
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001765provide will be printed for failures. (Added by Michael Foord; :issue:`5663`.)
1766
Ezio Melotti021f3342010-04-06 03:26:49 +00001767The :meth:`~unittest.TestCase.assertRaises` method now
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001768return a context handler when called without providing a callable
1769object to run. For example, you can write this::
1770
1771 with self.assertRaises(KeyError):
Ezio Melotti021f3342010-04-06 03:26:49 +00001772 {}['foo']
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001773
1774(Implemented by Antoine Pitrou; :issue:`4444`.)
1775
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001776.. rev 78774
1777
1778Module- and class-level setup and teardown fixtures are now supported.
Ezio Melotti021f3342010-04-06 03:26:49 +00001779Modules can contain :func:`~unittest.setUpModule` and :func:`~unittest.tearDownModule`
1780functions. Classes can have :meth:`~unittest.TestCase.setUpClass` and
1781:meth:`~unittest.TestCase.tearDownClass` methods that must be defined as class methods
1782(using ``@classmethod`` or equivalent). These functions and
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001783methods are invoked when the test runner switches to a test case in a
1784different module or class.
1785
Ezio Melotti021f3342010-04-06 03:26:49 +00001786The methods :meth:`~unittest.TestCase.addCleanup` and
1787:meth:`~unittest.TestCase.doCleanups` were added.
1788:meth:`~unittest.TestCase.addCleanup` allows you to add cleanup functions that
1789will be called unconditionally (after :meth:`~unittest.TestCase.setUp` if
1790:meth:`~unittest.TestCase.setUp` fails, otherwise after :meth:`~unittest.TestCase.tearDown`). This allows
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001791for much simpler resource allocation and deallocation during tests
1792(:issue:`5679`).
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001793
1794A number of new methods were added that provide more specialized
1795tests. Many of these methods were written by Google engineers
1796for use in their test suites; Gregory P. Smith, Michael Foord, and
1797GvR worked on merging them into Python's version of :mod:`unittest`.
1798
Ezio Melotti021f3342010-04-06 03:26:49 +00001799* :meth:`~unittest.TestCase.assertIsNone` and :meth:`~unittest.TestCase.assertIsNotNone` take one
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001800 expression and verify that the result is or is not ``None``.
1801
Ezio Melotti021f3342010-04-06 03:26:49 +00001802* :meth:`~unittest.TestCase.assertIs` and :meth:`~unittest.TestCase.assertIsNot`
1803 take two values and check whether the two values evaluate to the same object or not.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001804 (Added by Michael Foord; :issue:`2578`.)
1805
Ezio Melotti021f3342010-04-06 03:26:49 +00001806* :meth:`~unittest.TestCase.assertIsInstance` and
1807 :meth:`~unittest.TestCase.assertNotIsInstance` check whether
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00001808 the resulting object is an instance of a particular class, or of
1809 one of a tuple of classes. (Added by Georg Brandl; :issue:`7031`.)
1810
Ezio Melotti021f3342010-04-06 03:26:49 +00001811* :meth:`~unittest.TestCase.assertGreater`, :meth:`~unittest.TestCase.assertGreaterEqual`,
1812 :meth:`~unittest.TestCase.assertLess`, and :meth:`~unittest.TestCase.assertLessEqual` compare
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001813 two quantities.
1814
Ezio Melotti021f3342010-04-06 03:26:49 +00001815* :meth:`~unittest.TestCase.assertMultiLineEqual` compares two strings, and if they're
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001816 not equal, displays a helpful comparison that highlights the
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001817 differences in the two strings. This comparison is now used by
Ezio Melotti021f3342010-04-06 03:26:49 +00001818 default when Unicode strings are compared with :meth:`~unittest.TestCase.assertEqual`.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001819
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001820* :meth:`~unittest.TestCase.assertRegexpMatches` and
1821 :meth:`~unittest.TestCase.assertNotRegexpMatches` checks whether the
1822 first argument is a string matching or not matching the regular
1823 expression provided as the second argument (:issue:`8038`).
Ezio Melotti021f3342010-04-06 03:26:49 +00001824
1825* :meth:`~unittest.TestCase.assertRaisesRegexp` checks whether a particular exception
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001826 is raised, and then also checks that the string representation of
1827 the exception matches the provided regular expression.
1828
Ezio Melotti021f3342010-04-06 03:26:49 +00001829* :meth:`~unittest.TestCase.assertIn` and :meth:`~unittest.TestCase.assertNotIn`
1830 tests whether *first* is or is not in *second*.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001831
Ezio Melotti021f3342010-04-06 03:26:49 +00001832* :meth:`~unittest.TestCase.assertItemsEqual` tests whether two provided sequences
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001833 contain the same elements.
1834
Ezio Melotti021f3342010-04-06 03:26:49 +00001835* :meth:`~unittest.TestCase.assertSetEqual` compares whether two sets are equal, and
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001836 only reports the differences between the sets in case of error.
1837
Ezio Melotti021f3342010-04-06 03:26:49 +00001838* Similarly, :meth:`~unittest.TestCase.assertListEqual` and :meth:`~unittest.TestCase.assertTupleEqual`
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001839 compare the specified types and explain any differences without necessarily
1840 printing their full values; these methods are now used by default
Ezio Melotti021f3342010-04-06 03:26:49 +00001841 when comparing lists and tuples using :meth:`~unittest.TestCase.assertEqual`.
1842 More generally, :meth:`~unittest.TestCase.assertSequenceEqual` compares two sequences
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001843 and can optionally check whether both sequences are of a
1844 particular type.
1845
Ezio Melotti021f3342010-04-06 03:26:49 +00001846* :meth:`~unittest.TestCase.assertDictEqual` compares two dictionaries and reports the
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001847 differences; it's now used by default when you compare two dictionaries
Ezio Melotti021f3342010-04-06 03:26:49 +00001848 using :meth:`~unittest.TestCase.assertEqual`. :meth:`~unittest.TestCase.assertDictContainsSubset` checks whether
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001849 all of the key/value pairs in *first* are found in *second*.
1850
Ezio Melotti021f3342010-04-06 03:26:49 +00001851* :meth:`~unittest.TestCase.assertAlmostEqual` and :meth:`~unittest.TestCase.assertNotAlmostEqual` test
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001852 whether *first* and *second* are approximately equal. This method
1853 can either round their difference to an optionally-specified number
1854 of *places* (the default is 7) and compare it to zero, or require
1855 the difference to be smaller than a supplied *delta* value.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001856
Ezio Melotti021f3342010-04-06 03:26:49 +00001857* :meth:`~unittest.TestLoader.loadTestsFromName` properly honors the
1858 :attr:`~unittest.TestLoader.suiteClass` attribute of
1859 the :class:`~unittest.TestLoader`. (Fixed by Mark Roddy; :issue:`6866`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001860
Ezio Melotti021f3342010-04-06 03:26:49 +00001861* A new hook lets you extend the :meth:`~unittest.TestCase.assertEqual` method to handle
1862 new data types. The :meth:`~unittest.TestCase.addTypeEqualityFunc` method takes a type
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001863 object and a function. The function will be used when both of the
1864 objects being compared are of the specified type. This function
1865 should compare the two objects and raise an exception if they don't
1866 match; it's a good idea for the function to provide additional
1867 information about why the two objects are matching, much as the new
1868 sequence comparison methods do.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001869
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001870:func:`unittest.main` now takes an optional ``exit`` argument. If
Ezio Melotti021f3342010-04-06 03:26:49 +00001871False, :func:`~unittest.main` doesn't call :func:`sys.exit`, allowing it to be
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001872used from the interactive interpreter. (Contributed by J. Pablo
1873Fernández; :issue:`3379`.)
1874
Ezio Melotti021f3342010-04-06 03:26:49 +00001875:class:`~unittest.TestResult` has new :meth:`~unittest.TestResult.startTestRun` and
1876:meth:`~unittest.TestResult.stopTestRun` methods that are called immediately before
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001877and after a test run. (Contributed by Robert Collins; :issue:`5728`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001878
1879With all these changes, the :file:`unittest.py` was becoming awkwardly
1880large, so the module was turned into a package and the code split into
1881several files (by Benjamin Peterson). This doesn't affect how the
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001882module is imported or used.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001883
1884
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001885.. _elementtree-section:
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001886
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001887Updated module: ElementTree 1.3
1888---------------------------------
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001889
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001890The version of the ElementTree library included with Python was updated to
1891version 1.3. Some of the new features in ElementTree 1.3 are:
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001892
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001893* The various parsing functions now take a *parser* keyword argument
1894 that can be used to provide an :class:`XMLParser` instance that will
1895 be used. This makes it possible to override the file's internal encoding:
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001896
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001897 p = ET.XMLParser(encoding='utf-8')
1898 t = ET.XML("""<root/>""", parser=p)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001899
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001900 Errors in parsing XML now raise a :exc:`ParseError` exception.
1901 Instances of :exc:`ParseError` have a :attr:`position` attribute
1902 containing a (*line*, *column*) tuple giving the location of the problem.
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001903
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001904* ElementTree's code for converting trees to a string has been
1905 significantly reworked, making it roughly twice as fast in many
1906 cases. The :class:`ElementTree` :meth:`write` and :class:`Element`
1907 :meth:`write` methods now have a *method* parameter that can be
1908 "xml" (the default), "html", or "text". HTML mode will output empty
1909 elements as ``<empty></empty>`` instead of ``<empty/>``, and text
1910 mode will skip over elements and only output the text chunks. If
1911 you set the :attr:`tag` attribute of an element to ``None`` but
1912 leaves its children in place, the element will be omitted when the
1913 tree is written out, so you don't need to do more extensive rearrangement
1914 to remove a single element.
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001915
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001916 Namespace aspects have also been improved. All the ``xmlns:<whatever>``
1917 declarations are now put on the root element and not scattered throughout
1918 the resulting output. You can set the default namespace for a tree
1919 by setting the :attr:`default_namespace` attribute and can
1920 register new prefixes with :meth:`regsiter_namespace`. In XML mode,
1921 you can use the true/false *xml_declaration* parameter to suppress the
1922 XML declaration.
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001923
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001924* New :class:`Element` method: :meth:`extend` appends the items from a
1925 sequence to the element's children. Elements themselves behave like
1926 sequences, so it's easy to move children from one element to
1927 another::
Andrew M. Kuchlinga17cd4a2009-01-31 02:50:09 +00001928
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001929 from xml.etree import ElementTree as ET
Andrew M. Kuchlinga17cd4a2009-01-31 02:50:09 +00001930
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001931 t = ET.XML("""<list>
1932 <item>1</item> <item>2</item> <item>3</item>
1933 </list>""")
1934 new = ET.XML('<root/>')
1935 new.extend(t)
Andrew M. Kuchlinga17cd4a2009-01-31 02:50:09 +00001936
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001937 # Outputs <root><item>1</item>...</root>
1938 print ET.tostring(new)
Andrew M. Kuchlinga17cd4a2009-01-31 02:50:09 +00001939
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001940* New :class:`Element` method: :meth:`iter` yields the children of the
1941 element as a generator. It's also possible to write ``for child in
1942 elem: ...`` to loop over an element's children. The existing method
1943 :meth:`getiterator` is now deprecated. :meth:`getchildren` is
1944 another similar method that constructs and returns a list of
1945 children; it's also deprecated.
Georg Brandl0516f812009-11-18 18:52:35 +00001946
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001947* New :class:`Element` method: :meth:`itertext` yields all chunks of
1948 text that are descendants of the element. For example::
Georg Brandl0516f812009-11-18 18:52:35 +00001949
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001950 t = ET.XML("""<list>
1951 <item>1</item> <item>2</item> <item>3</item>
1952 </list>""")
1953
1954 # Outputs ['\n ', '1', ' ', '2', ' ', '3', '\n']
1955 print list(t.itertext())
1956
1957* Deprecated: using an element as a Boolean (i.e., ``if elem: ...``)
1958 would return true if the element had any children, or false if
1959 there were no children. This behaviour will eventually change or be removed
1960 because it's confusing (``None`` is false, but so is a childless element?),
1961 so it will now trigger a :exc:`FutureWarning`. In your code,
1962 you should be explicit: write ``len(elem) != 0`` if you're interested in
1963 the number of children, or ``elem is not None`` Instead,
1964
1965Fredrik Lundh develops ElementTree and produced the 1.3 version;
1966you can read his article describing 1.3 at
1967http://effbot.org/zone/elementtree-13-intro.htm.
1968Florent Xicluna updated the version included with
1969Python, after discussions on python-dev and in :issue:`6472`.)
Georg Brandl0516f812009-11-18 18:52:35 +00001970
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001971.. ======================================================================
1972
1973
1974Build and C API Changes
1975=======================
1976
1977Changes to Python's build process and to the C API include:
1978
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001979* The latest release of the GNU Debugger, GDB 7, can be `scripted
1980 using Python
1981 <http://sourceware.org/gdb/current/onlinedocs/gdb/Python.html>`__.
1982 When you begin debugging an executable program P, GDB will look for
1983 a file named ``P-gdb.py`` and automatically read it. Dave Malcolm
1984 contributed a :file:`python-gdb.py` that adds a number of useful
1985 commands when debugging Python itself. For example, there are
1986 ``py-up`` and ``py-down`` that go up or down one Python stack frame,
1987 which usually corresponds to several C stack frames. ``py-print``
1988 prints the value of a Python variable, and ``py-bt`` prints the
1989 Python stack trace. (Added as a result of :issue:`8032`.)
1990
Andrew M. Kuchling10b1ec92009-01-02 21:00:35 +00001991* If you use the :file:`.gdbinit` file provided with Python,
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001992 the "pyo" macro in the 2.7 version now works correctly when the thread being
1993 debugged doesn't hold the GIL; the macro now acquires it before printing.
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001994 (Contributed by Victor Stinner; :issue:`3632`.)
1995
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001996* :cfunc:`Py_AddPendingCall` is now thread-safe, letting any
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001997 worker thread submit notifications to the main Python thread. This
1998 is particularly useful for asynchronous IO operations.
Andrew M. Kuchlingbadc7092010-05-08 01:35:55 +00001999 (Contributed by Kristján Valur Jónsson; :issue:`4293`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00002000
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002001* New function: :cfunc:`PyCode_NewEmpty` creates an empty code object;
2002 only the filename, function name, and first line number are required.
2003 This is useful to extension modules that are attempting to
2004 construct a more useful traceback stack. Previously such
2005 extensions needed to call :cfunc:`PyCode_New`, which had many
2006 more arguments. (Added by Jeffrey Yasskin.)
2007
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00002008* New function: :cfunc:`PyErr_NewExceptionWithDoc` creates a new
2009 exception class, just as the existing :cfunc:`PyErr_NewException` does,
2010 but takes an extra ``char *`` argument containing the docstring for the
2011 new exception class. (Added by the 'lekma' user on the Python bug tracker;
2012 :issue:`7033`.)
2013
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002014* New function: :cfunc:`PyFrame_GetLineNumber` takes a frame object
2015 and returns the line number that the frame is currently executing.
2016 Previously code would need to get the index of the bytecode
2017 instruction currently executing, and then look up the line number
2018 corresponding to that address. (Added by Jeffrey Yasskin.)
2019
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00002020* New functions: :cfunc:`PyLong_AsLongAndOverflow` and
2021 :cfunc:`PyLong_AsLongLongAndOverflow` approximates a Python long
2022 integer as a C :ctype:`long` or :ctype:`long long`.
2023 If the number is too large to fit into
2024 the output type, an *overflow* flag is set and returned to the caller.
2025 (Contributed by Case Van Horsen; :issue:`7528` and :issue:`7767`.)
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00002026
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00002027* New function: stemming from the rewrite of string-to-float conversion,
2028 a new :cfunc:`PyOS_string_to_double` function was added. The old
2029 :cfunc:`PyOS_ascii_strtod` and :cfunc:`PyOS_ascii_atof` functions
2030 are now deprecated.
2031
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002032* New macros: the Python header files now define the following macros:
2033 :cmacro:`Py_ISALNUM`,
2034 :cmacro:`Py_ISALPHA`,
2035 :cmacro:`Py_ISDIGIT`,
2036 :cmacro:`Py_ISLOWER`,
2037 :cmacro:`Py_ISSPACE`,
2038 :cmacro:`Py_ISUPPER`,
2039 :cmacro:`Py_ISXDIGIT`,
2040 and :cmacro:`Py_TOLOWER`, :cmacro:`Py_TOUPPER`.
2041 All of these functions are analogous to the C
2042 standard macros for classifying characters, but ignore the current
2043 locale setting, because in
2044 several places Python needs to analyze characters in a
2045 locale-independent way. (Added by Eric Smith;
2046 :issue:`5793`.)
2047
2048 .. XXX these macros don't seem to be described in the c-api docs.
2049
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00002050* Removed function: :cmacro:`PyEval_CallObject` is now only available
2051 as a macro. A function version was being kept around to preserve
2052 ABI linking compatibility, but that was in 1997; it can certainly be
2053 deleted. (Removed by Antoine Pitrou; :issue:`8276`.)
2054
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00002055* New format codes: the :cfunc:`PyFormat_FromString`,
2056 :cfunc:`PyFormat_FromStringV`, and :cfunc:`PyErr_Format` now
2057 accepts ``%lld`` and ``%llu`` format codes for displaying values of
2058 C's :ctype:`long long` types.
2059 (Contributed by Mark Dickinson; :issue:`7228`.)
2060
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002061* The complicated interaction between threads and process forking has
2062 been changed. Previously, the child process created by
2063 :func:`os.fork` might fail because the child is created with only a
2064 single thread running, the thread performing the :func:`os.fork`.
2065 If other threads were holding a lock, such as Python's import lock,
2066 when the fork was performed, the lock would still be marked as
2067 "held" in the new process. But in the child process nothing would
2068 ever release the lock, since the other threads weren't replicated,
2069 and the child process would no longer be able to perform imports.
2070
2071 Python 2.7 now acquires the import lock before performing an
2072 :func:`os.fork`, and will also clean up any locks created using the
2073 :mod:`threading` module. C extension modules that have internal
2074 locks, or that call :cfunc:`fork()` themselves, will not benefit
2075 from this clean-up.
2076
2077 (Fixed by Thomas Wouters; :issue:`1590864`.)
2078
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00002079* The :cfunc:`Py_Finalize` function now calls the internal
2080 :func:`threading._shutdown` function; this prevents some exceptions from
2081 being raised when an interpreter shuts down.
2082 (Patch by Adam Olsen; :issue:`1722344`.)
2083
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002084* When using the :ctype:`PyMemberDef` structure to define attributes
2085 of a type, Python will no longer let you try to delete or set a
2086 :const:`T_STRING_INPLACE` attribute.
2087
2088 .. rev 79644
2089
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00002090* Global symbols defined by the :mod:`ctypes` module are now prefixed
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002091 with ``Py``, or with ``_ctypes``. (Implemented by Thomas
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00002092 Heller; :issue:`3102`.)
2093
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00002094* New configure option: the :option:`--with-system-expat` switch allows
2095 building the :mod:`pyexpat` module to use the system Expat library.
2096 (Contributed by Arfrever Frehtes Taifersar Arahesis; :issue:`7609`.)
2097
Andrew M. Kuchlingce690522010-04-13 01:32:51 +00002098* New configure option: compiling Python with the
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00002099 :option:`--with-valgrind` option will now disable the pymalloc
Andrew M. Kuchlingce690522010-04-13 01:32:51 +00002100 allocator, which is difficult for the Valgrind memory-error detector
2101 to analyze correctly.
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00002102 Valgrind will therefore be better at detecting memory leaks and
2103 overruns. (Contributed by James Henstridge; :issue:`2422`.)
2104
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +00002105* New configure option: you can now supply no arguments to
2106 :option:`--with-dbmliborder=` in order to build none of the various
2107 DBM modules. (Added by Arfrever Frehtes Taifersar Arahesis;
2108 :issue:`6491`.)
2109
Andrew M. Kuchling77069572009-03-31 01:21:01 +00002110* The :program:`configure` script now checks for floating-point rounding bugs
2111 on certain 32-bit Intel chips and defines a :cmacro:`X87_DOUBLE_ROUNDING`
2112 preprocessor definition. No code currently uses this definition,
2113 but it's available if anyone wishes to use it.
2114 (Added by Mark Dickinson; :issue:`2937`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002115
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00002116 :program:`configure` also now sets a :envvar:`LDCXXSHARED` Makefile
2117 variable for supporting C++ linking. (Contributed by Arfrever
2118 Frehtes Taifersar Arahesis; :issue:`1222585`.)
2119
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002120* The build process now creates the necessary files for pkg-config
2121 support. (Contributed by Clinton Roy; :issue:`3585`.)
2122
2123* The build process now supports Subversion 1.7. (Contributed by
2124 Arfrever Frehtes Taifersar Arahesis; :issue:`6094`.)
2125
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00002126
Andrew M. Kuchling85fffc32010-05-08 01:15:26 +00002127.. _whatsnew27-capsules:
2128
2129Capsules
2130-------------------
2131
2132Python 3.1 adds a new C datatype, :ctype:`PyCapsule`, for providing a
2133C API to an extension module. A capsule is essentially the holder for
2134a C ``void *`` pointer, and is bound to a module attribute; for
Andrew M. Kuchling304500c2010-05-08 13:29:46 +00002135example, the :mod:`socket` module's API is exposed as ``socket.CAPI``,
Andrew M. Kuchling85fffc32010-05-08 01:15:26 +00002136and :mod:`unicodedata` calls it ``ucnhash_CAPI``. Other extensions
2137can import the module, access its dictionary to get the capsule
2138object, and then get the ``void *`` pointer, which will usually point
2139to an array of pointers to the various API functions.
2140
2141There is an existing data type that already does this,
2142:ctype:`PyCObject`, but it doesn't provide type safety. Evil code
2143written in pure Python could cause a segmentation fault by taking a
2144:ctype:`PyCObject` from module A and somehow substituting it for the
2145:ctype:`PyCObject` in module B. Capsules know their own name,
2146and getting the pointer requires providing the name::
2147
2148 void *vtable;
2149
2150 if (!PyCapsule_IsValid(capsule, "mymodule.CAPI") {
2151 PyErr_SetString(PyExc_ValueError, "argument type invalid");
2152 return NULL;
2153 }
2154
2155 vtable = PyCapsule_GetPointer(capsule, "mymodule.CAPI");
2156
2157You are assured that ``vtable`` points to whatever you're expecting.
2158If a different capsule was passed in, :cfunc:`PyCapsule_IsValid` would
2159detect the mismatched name and return false. Refer to
2160:ref:`using-capsules` for more information on using these objects.
2161
2162Python 2.7 now uses capsules internally to provide various
2163extension-module APIs, but the :cfunc:`PyCObject_AsVoidPtr` was
2164modified to handle capsules, preserving compile-time compatibility
2165with the :ctype:`CObject` interface. Use of
2166:cfunc:`PyCObject_AsVoidPtr` will signal a
2167:exc:`PendingDeprecationWarning`, which is silent by default.
2168
2169Implemented in Python 3.1 and backported to 2.7 by Larry Hastings;
2170discussed in :issue:`5630`.
2171
2172
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002173.. ======================================================================
2174
2175Port-Specific Changes: Windows
2176-----------------------------------
2177
Andrew M. Kuchling10b1ec92009-01-02 21:00:35 +00002178* The :mod:`msvcrt` module now contains some constants from
2179 the :file:`crtassem.h` header file:
2180 :data:`CRT_ASSEMBLY_VERSION`,
2181 :data:`VC_ASSEMBLY_PUBLICKEYTOKEN`,
2182 and :data:`LIBRARIES_ASSEMBLY_NAME_PREFIX`.
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00002183 (Contributed by David Cournapeau; :issue:`4365`.)
2184
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002185* The :mod:`_winreg` module for accessing the registry now implements
2186 the :func:`CreateKeyEx` and :func:`DeleteKeyEx` functions, extended
2187 versions of previously-supported functions that take several extra
2188 arguments. The :func:`DisableReflectionKey`,
2189 :func:`EnableReflectionKey`, and :func:`QueryReflectionKey` were also
2190 tested and documented.
2191 (Implemented by Brian Curtin: :issue:`7347`.)
2192
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00002193* The new :cfunc:`_beginthreadex` API is used to start threads, and
2194 the native thread-local storage functions are now used.
Andrew M. Kuchlingbadc7092010-05-08 01:35:55 +00002195 (Contributed by Kristján Valur Jónsson; :issue:`3582`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002196
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +00002197* The :func:`os.kill` function now works on Windows. The signal value
2198 can be the constants :const:`CTRL_C_EVENT`,
2199 :const:`CTRL_BREAK_EVENT`, or any integer. The Control-C and
2200 Control-Break keystroke events can be sent to subprocesses; any
2201 other value will use the :cfunc:`TerminateProcess` API.
2202 (Contributed by Miki Tebeka; :issue:`1220212`.)
2203
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002204* The :func:`os.listdir` function now correctly fails
2205 for an empty path. (Fixed by Hirokazu Yamamoto; :issue:`5913`.)
2206
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00002207* The :mod:`mimelib` module will now read the MIME database from
2208 the Windows registry when initializing.
2209 (Patch by Gabriel Genellina; :issue:`4969`.)
2210
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002211.. ======================================================================
2212
2213Port-Specific Changes: Mac OS X
2214-----------------------------------
2215
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002216* The path ``/Library/Python/2.7/site-packages`` is now appended to
Andrew M. Kuchling77069572009-03-31 01:21:01 +00002217 ``sys.path``, in order to share added packages between the system
2218 installation and a user-installed copy of the same version.
2219 (Changed by Ronald Oussoren; :issue:`4865`.)
2220
Andrew M. Kuchling04b99cc2010-05-04 01:24:22 +00002221Port-Specific Changes: FreeBSD
2222-----------------------------------
2223
2224* FreeBSD 7.1's :const:`SO_SETFIB` constant, used with
2225 :func:`~socket.getsockopt`/:func:`~socket.setsockopt` to select an
2226 alternate routing table, is now available in the :mod:`socket`
2227 module. (Added by Kyle VanderBeek; :issue:`8235`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002228
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00002229Other Changes and Fixes
2230=======================
2231
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00002232* Two benchmark scripts, :file:`iobench` and :file:`ccbench`, were
2233 added to the :file:`Tools` directory. :file:`iobench` measures the
Antoine Pitroudde96e62010-02-08 20:25:47 +00002234 speed of built-in file I/O objects (as returned by :func:`open`)
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00002235 while performing various operations, and :file:`ccbench` is a
2236 concurrency benchmark that tries to measure computing throughput,
2237 thread switching latency, and IO processing bandwidth when
2238 performing several tasks using a varying number of threads.
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00002239
Andrew M. Kuchling77069572009-03-31 01:21:01 +00002240* When importing a module from a :file:`.pyc` or :file:`.pyo` file
2241 with an existing :file:`.py` counterpart, the :attr:`co_filename`
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00002242 attributes of the resulting code objects are overwritten when the
2243 original filename is obsolete. This can happen if the file has been
2244 renamed, moved, or is accessed through different paths. (Patch by
2245 Ziga Seilnacht and Jean-Paul Calderone; :issue:`1180193`.)
Andrew M. Kuchling77069572009-03-31 01:21:01 +00002246
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00002247* The :file:`regrtest.py` script now takes a :option:`--randseed=`
2248 switch that takes an integer that will be used as the random seed
2249 for the :option:`-r` option that executes tests in random order.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002250 The :option:`-r` option also reports the seed that was used
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00002251 (Added by Collin Winter.)
2252
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00002253* Another :file:`regrtest.py` switch is :option:`-j`, which
2254 takes an integer specifying how many tests run in parallel. This
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002255 allows reducing the total runtime on multi-core machines.
Antoine Pitrou4698d992009-05-31 14:20:14 +00002256 This option is compatible with several other options, including the
2257 :option:`-R` switch which is known to produce long runtimes.
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00002258 (Added by Antoine Pitrou, :issue:`6152`.) This can also be used
2259 with a new :option:`-F` switch that runs selected tests in a loop
2260 until they fail. (Added by Antoine Pitrou; :issue:`7312`.)
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00002261
Andrew M. Kuchling85f928a2010-04-15 01:42:27 +00002262* When executed as a script, the :file:`py_compile.py` module now
2263 accepts ``'-'`` as an argument, which will read standard input for
2264 the list of filenames to be compiled. (Contributed by Piotr
2265 Ożarowski; :issue:`8233`.)
2266
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002267.. ======================================================================
2268
2269Porting to Python 2.7
2270=====================
2271
2272This section lists previously described changes and other bugfixes
2273that may require changes to your code:
2274
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00002275* The :func:`range` function processes its arguments more
2276 consistently; it will now call :meth:`__int__` on non-float,
2277 non-integer arguments that are supplied to it. (Fixed by Alexander
2278 Belopolsky; :issue:`1533`.)
2279
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002280* The string :meth:`format` method changed the default precision used
2281 for floating-point and complex numbers from 6 decimal
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002282 places to 12, which matches the precision used by :func:`str`.
2283 (Changed by Eric Smith; :issue:`5920`.)
2284
Amaury Forgeot d'Arc901f2002009-06-09 23:08:13 +00002285* Because of an optimization for the :keyword:`with` statement, the special
2286 methods :meth:`__enter__` and :meth:`__exit__` must belong to the object's
2287 type, and cannot be directly attached to the object's instance. This
Amaury Forgeot d'Arcd81333c2009-06-10 20:30:19 +00002288 affects new-style classes (derived from :class:`object`) and C extension
Amaury Forgeot d'Arc901f2002009-06-09 23:08:13 +00002289 types. (:issue:`6101`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002290
Andrew M. Kuchling837a5382010-05-06 17:21:59 +00002291* Due to a bug in Python 2.6, the *exc_value* parameter to
2292 :meth:`__exit__` methods was often the string representation of the
2293 exception, not an instance. This was fixed in 2.7, so *exc_value*
2294 will be an instance as expected. (Fixed by Florent Xicluna;
2295 :issue:`7853`.)
2296
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00002297* When a restricted set of attributes were set using ``__slots__``,
2298 deleting an unset attribute would not raise :exc:`AttributeError`
2299 as you would expect. Fixed by Benjamin Peterson; :issue:`7604`.)
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002300
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00002301In the standard library:
2302
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002303* When using :class:`Decimal` instances with a string's
2304 :meth:`format` method, the default alignment was previously
2305 left-alignment. This has been changed to right-alignment, which might
2306 change the output of your programs.
2307 (Changed by Mark Dickinson; :issue:`6857`.)
2308
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00002309 Comparisons involving a signaling NaN value (or ``sNAN``) now signal
2310 :const:`InvalidOperation` instead of silently returning a true or
2311 false value depending on the comparison operator. Quiet NaN values
2312 (or ``NaN``) are now hashable. (Fixed by Mark Dickinson;
2313 :issue:`7279`.)
2314
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00002315* The ElementTree library, :mod:`xml.etree`, no longer escapes
2316 ampersands and angle brackets when outputting an XML processing
2317 instruction (which looks like `<?xml-stylesheet href="#style1"?>`)
2318 or comment (which looks like `<!-- comment -->`).
2319 (Patch by Neil Muller; :issue:`2746`.)
2320
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00002321* The :meth:`readline` method of :class:`StringIO` objects now does
2322 nothing when a negative length is requested, as other file-like
2323 objects do. (:issue:`7348`).
2324
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002325* The :mod:`syslog` module will now use the value of ``sys.argv[0]`` as the
2326 identifier instead of the previous default value of ``'python'``.
2327 (Changed by Sean Reifschneider; :issue:`8451`.)
2328
Andrew M. Kuchling04b99cc2010-05-04 01:24:22 +00002329* The :mod:`urlparse` module's :func:`~urlparse.urlsplit` now handles
2330 unknown URL schemes in a fashion compliant with :rfc:`3986`: if the
2331 URL is of the form ``"<something>://..."``, the text before the
2332 ``://`` is treated as the scheme, even if it's a made-up scheme that
2333 the module doesn't know about. This change may break code that
2334 worked around the old behaviour. For example, Python 2.6.4 or 2.5
2335 will return the following:
2336
2337 >>> import urlparse
2338 >>> urlparse.urlsplit('invented://host/filename?query')
2339 ('invented', '', '//host/filename?query', '', '')
2340
2341 Python 2.7 (and Python 2.6.5) will return:
2342
2343 >>> import urlparse
2344 >>> urlparse.urlsplit('invented://host/filename?query')
2345 ('invented', 'host', '/filename?query', '', '')
2346
2347 (Python 2.7 actually produces slightly different output, since it
2348 returns a named tuple instead of a standard tuple.)
2349
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00002350For C extensions:
2351
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +00002352* C extensions that use integer format codes with the ``PyArg_Parse*``
2353 family of functions will now raise a :exc:`TypeError` exception
2354 instead of triggering a :exc:`DeprecationWarning` (:issue:`5080`).
2355
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00002356* Use the new :cfunc:`PyOS_string_to_double` function instead of the old
2357 :cfunc:`PyOS_ascii_strtod` and :cfunc:`PyOS_ascii_atof` functions,
2358 which are now deprecated.
2359
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +00002360
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002361.. ======================================================================
2362
2363
2364.. _acks27:
2365
2366Acknowledgements
2367================
2368
2369The author would like to thank the following people for offering
2370suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00002371article: Nick Coghlan, Ryan Lovett, R. David Murray, Hugh Secker-Walker.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002372