blob: d1ee0b35578f5d76f2a9c395f141afcbdde3b03e [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. Kuchling039c8992010-02-01 02:04:26 +00009.. Fix accents on Kristjan Valur Jonsson, Fuerstenau
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +000010
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +000011.. Big jobs: pep 391, PyCapsule
Andrew M. Kuchling837a5382010-05-06 17:21:59 +000012
Andrew M. Kuchling6d7dfa22010-04-11 12:49:37 +000013.. hyperlink all the methods & functions.
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +000014
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +000015.. T_STRING_INPLACE not described in main docs
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +000016.. XXX "Format String Syntax" in string.rst could use many more examples.
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +000017
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000018.. $Id$
19 Rules for maintenance:
20
21 * Anyone can add text to this document. Do not spend very much time
22 on the wording of your changes, because your text will probably
23 get rewritten to some degree.
24
25 * The maintainer will go through Misc/NEWS periodically and add
26 changes; it's therefore more important to add your changes to
27 Misc/NEWS than to this file.
28
29 * This is not a complete list of every single change; completeness
30 is the purpose of Misc/NEWS. Some changes I consider too small
31 or esoteric to include. If such a change is added to the text,
32 I'll just remove it. (This is another reason you shouldn't spend
33 too much time on writing your addition.)
34
35 * If you want to draw your new text to the attention of the
36 maintainer, add 'XXX' to the beginning of the paragraph or
37 section.
38
39 * It's OK to just add a fragmentary note about a change. For
40 example: "XXX Describe the transmogrify() function added to the
41 socket module." The maintainer will research the change and
42 write the necessary text.
43
44 * You can comment out your additions if you like, but it's not
45 necessary (especially when a final release is some months away).
46
Ezio Melotti021f3342010-04-06 03:26:49 +000047 * Credit the author of a patch or bugfix. Just the name is
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000048 sufficient; the e-mail address isn't necessary.
49
50 * It's helpful to add the bug/patch number in a parenthetical comment.
51
52 XXX Describe the transmogrify() function added to the socket
53 module.
54 (Contributed by P.Y. Developer; :issue:`12345`.)
55
56 This saves the maintainer some effort going through the SVN logs
57 when researching a change.
58
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +000059This article explains the new features in Python 2.7. The final
Andrew M. Kuchling837a5382010-05-06 17:21:59 +000060release of 2.7 is currently scheduled for July 2010; the detailed
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +000061schedule is described in :pep:`373`.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000062
63.. Compare with previous release in 2 - 3 sentences here.
64 add hyperlink when the documentation becomes available online.
65
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +000066.. _whatsnew27-python31:
67
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +000068The Future for Python 2.x
69=========================
70
71Python 2.7 is intended to be the last major release in the 2.x series.
Andrew M. Kuchlingd1e696b2010-05-07 11:30:47 +000072The Python maintainers are planning to focus their future efforts on
73the Python 3.x series.
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +000074
75This means that 2.7 will remain in place for a long time, running
76production systems that have not been ported to Python 3.x.
77Two consequences of the long-term significance of 2.7 are:
78
79* It's very likely the 2.7 release will have a longer period of
80 maintenance compared to earlier 2.x versions. Python 2.7 will
Andrew M. Kuchlingd1e696b2010-05-07 11:30:47 +000081 continue to be maintained while the transition to 3.x continues.
82 Maintenance releases for Python 2.7 will probably be made for 5
83 years.
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +000084
Andrew M. Kuchlingd1e696b2010-05-07 11:30:47 +000085* A policy decision was made to silence warnings only of interest to
86 developers by default. :exc:`DeprecationWarning` and its
87 descendants are now ignored unless otherwise requested, preventing
88 users from seeing warnings triggered by an application. (Carried
89 out in :issue:`7319`.)
90
91 In previous releases, :exc:`DeprecationWarning` messages were
92 enabled by default, providing Python developers with a clear
93 indication of where their code may break in a future major version
94 of Python.
95
96 However, there are increasingly many users of Python-based
97 applications who are not directly involved in the development of
98 those applications. :exc:`DeprecationWarning` messages are
99 irrelevant to such users, making them worry about an application
100 that's actually working correctly and burdening the developers of
101 these applications with responding to these concerns.
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +0000102
103 You can re-enable display of :exc:`DeprecationWarning` messages by
104 running Python with the :option:`-Wdefault` (short form:
105 :option:`-Wd`) switch, or you can add
106 ``warnings.simplefilter('default')`` to your code.
107
108
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000109Python 3.1 Features
110=======================
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000111
112Much as Python 2.6 incorporated features from Python 3.0,
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000113version 2.7 incorporates some of the new features
114in Python 3.1. The 2.x series continues to provide tools
115for migrating to the 3.x series.
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000116
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000117A partial list of 3.1 features that were backported to 2.7:
118
Andrew M. Kuchling837a5382010-05-06 17:21:59 +0000119* A new version of the :mod:`io` library, rewritten in C for performance.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000120* The ordered-dictionary type described in :ref:`pep-0372`.
Andrew M. Kuchling8f254e72009-12-08 02:37:05 +0000121* The new format specifier described in :ref:`pep-0378`.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000122* The :class:`memoryview` object.
123* A small subset of the :mod:`importlib` module `described below <#importlib-section>`__.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000124* Float-to-string and string-to-float conversions now round their
125 results more correctly. And :func:`repr` of a floating-point
126 number *x* returns a result that's guaranteed to round back to the
127 same number when converted back to a string.
128* The :cfunc:`PyLong_AsLongAndOverflow` C API function.
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000129
130One porting change: the :option:`-3` switch now automatically
131enables the :option:`-Qwarn` switch that causes warnings
132about using classic division with integers and long integers.
133
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000134Other new Python3-mode warnings include:
135
136* :func:`operator.isCallable` and :func:`operator.sequenceIncludes`,
137 which are not supported in 3.x.
138
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000139.. ========================================================================
140.. Large, PEP-level features and changes should be described here.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000141.. ========================================================================
142
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000143.. _pep-0372:
144
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000145PEP 372: Adding an ordered dictionary to collections
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000146====================================================
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000147
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000148Regular Python dictionaries iterate over key/value pairs in arbitrary order.
149Over the years, a number of authors have written alternative implementations
150that remember the order that the keys were originally inserted. Based on
151the experiences from those implementations, a new
Ezio Melotti021f3342010-04-06 03:26:49 +0000152:class:`~collections.OrderedDict` class has been introduced in the
153:mod:`collections` module.
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000154
Ezio Melotti021f3342010-04-06 03:26:49 +0000155The :class:`~collections.OrderedDict` API is substantially the same as regular
156dictionaries but will iterate over keys and values in a guaranteed order
157depending on when a key was first inserted::
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000158
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000159 >>> from collections import OrderedDict
160 >>> d = OrderedDict([('first', 1), ('second', 2),
161 ... ('third', 3)])
162 >>> d.items()
163 [('first', 1), ('second', 2), ('third', 3)]
164
165If a new entry overwrites an existing entry, the original insertion
166position is left unchanged::
167
168 >>> d['second'] = 4
169 >>> d.items()
170 [('first', 1), ('second', 4), ('third', 3)]
171
172Deleting an entry and reinserting it will move it to the end::
173
174 >>> del d['second']
175 >>> d['second'] = 5
176 >>> d.items()
177 [('first', 1), ('third', 3), ('second', 5)]
178
Ezio Melotti021f3342010-04-06 03:26:49 +0000179The :meth:`~collections.OrderedDict.popitem` method has an optional *last*
180argument that defaults to True. If *last* is True, the most recently
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000181added key is returned and removed; if it's False, the
182oldest key is selected::
183
184 >>> od = OrderedDict([(x,0) for x in range(20)])
185 >>> od.popitem()
186 (19, 0)
187 >>> od.popitem()
188 (18, 0)
Ezio Melotti021f3342010-04-06 03:26:49 +0000189 >>> od.popitem(last=False)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000190 (0, 0)
Ezio Melotti021f3342010-04-06 03:26:49 +0000191 >>> od.popitem(last=False)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000192 (1, 0)
193
194Comparing two ordered dictionaries checks both the keys and values,
195and requires that the insertion order was the same::
196
197 >>> od1 = OrderedDict([('first', 1), ('second', 2),
198 ... ('third', 3)])
199 >>> od2 = OrderedDict([('third', 3), ('first', 1),
200 ... ('second', 2)])
Ezio Melotti021f3342010-04-06 03:26:49 +0000201 >>> od1 == od2
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000202 False
203 >>> # Move 'third' key to the end
Ezio Melotti021f3342010-04-06 03:26:49 +0000204 >>> del od2['third']; od2['third'] = 3
205 >>> od1 == od2
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000206 True
207
Ezio Melotti021f3342010-04-06 03:26:49 +0000208Comparing an :class:`~collections.OrderedDict` with a regular dictionary
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000209ignores the insertion order and just compares the keys and values.
210
Ezio Melotti021f3342010-04-06 03:26:49 +0000211How does the :class:`~collections.OrderedDict` work? It maintains a
212doubly-linked list of keys, appending new keys to the list as they're inserted.
213A secondary dictionary maps keys to their corresponding list node, so
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000214deletion doesn't have to traverse the entire linked list and therefore
215remains O(1).
216
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000217The standard library now supports use of ordered dictionaries in several
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +0000218modules.
219
220* The :mod:`ConfigParser` module uses them by default, letting
221 configuration files be read, modified, and then written back in their original
222 order.
223
224* The :meth:`~collections.somenamedtuple._asdict()` method for
225 :func:`collections.namedtuple` now returns an ordered dictionary with the
226 values appearing in the same order as the underlying tuple indices.
227
228* The :mod:`json` module's :class:`~json.JSONDecoder` class
229 constructor was extended with an *object_pairs_hook* parameter to
230 allow :class:`OrderedDict` instances to be built by the decoder.
231 Support was also added for third-party tools like
232 `PyYAML <http://pyyaml.org/>`_.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000233
Andrew M. Kuchling7fe65a02009-10-13 15:49:33 +0000234.. seealso::
235
236 :pep:`372` - Adding an ordered dictionary to collections
237 PEP written by Armin Ronacher and Raymond Hettinger;
238 implemented by Raymond Hettinger.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000239
240.. _pep-0378:
241
242PEP 378: Format Specifier for Thousands Separator
Ezio Melotti021f3342010-04-06 03:26:49 +0000243=================================================
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000244
245To make program output more readable, it can be useful to add
246separators to large numbers and render them as
24718,446,744,073,709,551,616 instead of 18446744073709551616.
248
249The fully general solution for doing this is the :mod:`locale` module,
250which can use different separators ("," in North America, "." in
251Europe) and different grouping sizes, but :mod:`locale` is complicated
252to use and unsuitable for multi-threaded applications where different
253threads are producing output for different locales.
254
255Therefore, a simple comma-grouping mechanism has been added to the
Ezio Melotti021f3342010-04-06 03:26:49 +0000256mini-language used by the :meth:`str.format` method. When
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000257formatting a floating-point number, simply include a comma between the
258width and the precision::
259
Eric Smithc4663852010-04-06 14:30:15 +0000260 >>> '{:20,.2f}'.format(18446744073709551616.0)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000261 '18,446,744,073,709,551,616.00'
262
Eric Smith6a928602010-04-06 15:17:33 +0000263When formatting an integer, include the comma after the width:
264
265 >>> '{:20,d}'.format(18446744073709551616)
266 '18,446,744,073,709,551,616'
267
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000268This mechanism is not adaptable at all; commas are always used as the
269separator and the grouping is always into three-digit groups. The
270comma-formatting mechanism isn't as general as the :mod:`locale`
271module, but it's easier to use.
272
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000273.. seealso::
274
275 :pep:`378` - Format Specifier for Thousands Separator
276 PEP written by Raymond Hettinger; implemented by Eric Smith.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000277
Andrew M. Kuchlingab21f752010-03-02 13:55:33 +0000278PEP 389: The argparse Module for Parsing Command Lines
279======================================================
280
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000281The :mod:`argparse` module for parsing command-line arguments was
282added, intended as a more powerful replacement for the
283:mod:`optparse` module.
284
285This means Python now supports three different modules for parsing
286command-line arguments: :mod:`getopt`, :mod:`optparse`, and
287:mod:`argparse`. The :mod:`getopt` module closely resembles the C
288:cfunc:`getopt` function, so it remains useful if you're writing a
289Python prototype that will eventually be rewritten in C.
290:mod:`optparse` becomes redundant, but there are no plans to remove it
291because there are many scripts still using it, and there's no
292automated way to update these scripts. (Making the :mod:`argparse`
293API consistent with :mod:`optparse`'s interface was discussed but
294rejected as too messy and difficult.)
295
Andrew M. Kuchlingf03641a2010-04-14 01:14:59 +0000296In short, if you're writing a new script and don't need to worry
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000297about compatibility with earlier versions of Python, use
298:mod:`argparse` instead of :mod:`optparse`.
299
Andrew M. Kuchlingf03641a2010-04-14 01:14:59 +0000300Here's an example::
301
302 import argparse
303
304 parser = argparse.ArgumentParser(description='Command-line example.')
305
306 # Add optional switches
307 parser.add_argument('-v', action='store_true', dest='is_verbose',
308 help='produce verbose output')
309 parser.add_argument('-o', action='store', dest='output',
310 metavar='FILE',
311 help='direct output to FILE instead of stdout')
312 parser.add_argument('-C', action='store', type=int, dest='context',
313 metavar='NUM', default=0,
314 help='display NUM lines of added context')
315
316 # Allow any number of additional arguments.
317 parser.add_argument(nargs='*', action='store', dest='inputs',
318 help='input filenames (default is stdin)')
319
320 args = parser.parse_args()
321 print args.__dict__
322
323Unless you override it, :option:`-h` and :option:`--help` switches
324are automatically added, and produce neatly formatted output::
325
326 -> ./python.exe argparse-example.py --help
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +0000327 usage: argparse-example.py [-h] [-v] [-o FILE] [-C NUM] [inputs [inputs ...]]
Andrew M. Kuchlingf03641a2010-04-14 01:14:59 +0000328
329 Command-line example.
330
331 positional arguments:
332 inputs input filenames (default is stdin)
333
334 optional arguments:
335 -h, --help show this help message and exit
336 -v produce verbose output
337 -o FILE direct output to FILE instead of stdout
338 -C NUM display NUM lines of added context
339
340Similarly to :mod:`optparse`, the command-line switches and arguments
341are returned as an object with attributes named by the *dest* parameters::
342
343 -> ./python.exe argparse-example.py -v
344 {'output': None, 'is_verbose': True, 'context': 0, 'inputs': []}
345
346 -> ./python.exe argparse-example.py -v -o /tmp/output -C 4 file1 file2
347 {'output': '/tmp/output', 'is_verbose': True, 'context': 4,
348 'inputs': ['file1', 'file2']}
349
350:mod:`argparse` has much fancier validation than :mod:`optparse`; you
351can specify an exact number of arguments as an integer, 0 or more
352arguments by passing ``'*'``, 1 or more by passing ``'+'``, or an
353optional argument with ``'?'``. A top-level parser can contain
354sub-parsers, so you can define subcommands that have different sets of
355switches, as in ``svn commit``, ``svn checkout``, etc. You can
356specify an argument type as :class:`~argparse.FileType`, which will
357automatically open files for you and understands that ``'-'`` means
358standard input or output.
Andrew M. Kuchlingab21f752010-03-02 13:55:33 +0000359
360.. seealso::
361
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000362 `argparse module documentation <http://docs.python.org/dev/library/argparse.html>`__
363
364 `Upgrading optparse code to use argparse <http://docs.python.org/dev/library/argparse.html#upgrading-optparse-code>`__
365
Andrew M. Kuchlingab21f752010-03-02 13:55:33 +0000366 :pep:`389` - argparse - New Command Line Parsing Module
367 PEP written and implemented by Steven Bethard.
368
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000369PEP 391: Dictionary-Based Configuration For Logging
370====================================================
371
Andrew M. Kuchlingb6c1aeb2010-04-14 14:28:31 +0000372.. not documented in library reference yet.
373
374The :mod:`logging` module is very flexible; an application can define
375a tree of logging subsystems, and each logger in this tree can filter
376out certain messages, format them differently, and direct messages to
377a varying number of handlers.
378
379All this flexibility can require a lot of configuration. You can
380write Python statements to create objects and set their properties,
381but a complex set-up would require verbose but boring code.
382:mod:`logging` also supports a :func:`~logging.config.fileConfig`
383function that parses a file, but the file format doesn't support
384configuring filters, and it's messier to generate programmatically.
385
386Python 2.7 adds a :func:`~logging.config.dictConfig` function that
387uses a dictionary, and there are many ways to produce a dictionary
388from different sources. You can construct one with code, of course.
389Python's standard library now includes a JSON parser, so you could
390parse a file containing JSON, or you could use a YAML parsing library
391if one is installed.
392
393XXX describe an example.
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000394
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +0000395Three smaller enhancements to the :mod:`logging` module, all
396implemented by Vinay Sajip, are:
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000397
398.. rev79293
399
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +0000400* The :class:`~logging.handlers.SysLogHandler` class now supports
401 syslogging over TCP. The constructor has a *socktype* parameter
402 giving the type of socket to use, either :const:`socket.SOCK_DGRAM`
403 for UDP or :const:`socket.SOCK_STREAM` for TCP. The default
404 protocol remains UDP.
405
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +0000406* :class:`Logger` instances gained a :meth:`getChild` method that retrieves a
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000407 descendant logger using a relative path. For example,
408 once you retrieve a logger by doing ``log = getLogger('app')``,
409 calling ``log.getChild('network.listen')`` is equivalent to
410 ``getLogger('app.network.listen')``.
411
412* The :class:`LoggerAdapter` class gained a :meth:`isEnabledFor` method
413 that takes a *level* and returns whether the underlying logger would
414 process a message of that level of importance.
415
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000416.. seealso::
417
418 :pep:`391` - Dictionary-Based Configuration For Logging
419 PEP written and implemented by Vinay Sajip.
420
421PEP 3106: Dictionary Views
422====================================================
423
Andrew M. Kuchling85f928a2010-04-15 01:42:27 +0000424The dictionary methods :meth:`keys`, :meth:`values`, and :meth:`items`
425are different in Python 3.x. They return an object called a :dfn:`view`
426instead of a fully materialized list.
427
Andrew M. Kuchling85f928a2010-04-15 01:42:27 +0000428It's not possible to change the return values of :meth:`keys`,
429:meth:`values`, and :meth:`items` in Python 2.7 because too much code
430would break. Instead the 3.x versions were added under the new names
431of :meth:`viewkeys`, :meth:`viewvalues`, and :meth:`viewitems`.
432
433::
434
435 >>> d = dict((i*10, chr(65+i)) for i in range(26))
436 >>> d
437 {0: 'A', 130: 'N', 10: 'B', 140: 'O', 20: ..., 250: 'Z'}
438 >>> d.viewkeys()
439 dict_keys([0, 130, 10, 140, 20, 150, 30, ..., 250])
440
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +0000441Views can be iterated over, but they also behave like sets. The ``&``
442operator performs intersection, and ``|`` performs a union::
443
444 >>> d1 = dict((i*10, chr(65+i)) for i in range(26))
445 >>> d2 = dict((i**.5, i) for i in range(1000))
446 >>> d1.viewkeys() & d2.viewkeys()
447 set([0.0, 10.0, 20.0, 30.0])
448 >>> d1.viewkeys() | range(0, 30)
449 set([0, 1, 130, 3, 4, 5, 6, ..., 120, 250])
450
Andrew M. Kuchling85f928a2010-04-15 01:42:27 +0000451The view keeps track of the dictionary and its contents change as the
452dictionary is modified::
453
454 >>> vk = d.viewkeys()
455 >>> vk
456 dict_keys([0, 130, 10, ..., 250])
457 >>> d[260] = '&'
458 >>> vk
459 dict_keys([0, 130, 260, 10, ..., 250])
460
461However, note that you can't add or remove keys while you're iterating
462over the view::
463
464 >>> for k in vk:
465 ... d[k*2] = k
466 ...
467 Traceback (most recent call last):
468 File "<stdin>", line 1, in <module>
469 RuntimeError: dictionary changed size during iteration
470
471You can use the view methods in Python 2.x code, and the 2to3
472converter will change them to the standard :meth:`keys`,
473:meth:`values`, and :meth:`items` methods.
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000474
475.. seealso::
476
477 :pep:`3106` - Revamping dict.keys(), .values() and .items()
478 PEP written by Guido van Rossum.
479 Backported to 2.7 by Alexandre Vassalotti; :issue:`1967`.
480
481
Andrew M. Kuchling9fbbd3b2010-05-01 12:06:51 +0000482PEP 3137: The memoryview Object
483====================================================
484
485The :class:`memoryview` object provides a view of another object's
486memory content that matches the :class:`bytes` type's interface.
487
488 >>> import string
489 >>> m = memoryview(string.letters)
490 >>> m
491 <memory at 0x37f850>
492 >>> len(m) # Returns length of underlying object
493 52
494 >>> m[0], m[25], m[26] # Indexing returns one byte
495 ('a', 'z', 'A')
496 >>> m2 = m[0:26] # Slicing returns another memoryview
497 >>> m2
498 <memory at 0x37f080>
499
500The content of the view can be converted to a string of bytes or to
501a list of integers:
502
503 >>> m2.tobytes()
504 'abcdefghijklmnopqrstuvwxyz'
505 >>> m2.tolist()
506 [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]
507 >>>
508
509:class:`memoryview` objects allow modifying the underlying object if
510it's a mutable object.
511
512 >>> m2[0] = 75
513 Traceback (most recent call last):
514 File "<stdin>", line 1, in <module>
515 TypeError: cannot modify read-only memory
516 >>> b = bytearray(string.letters) # Creating a mutable object
517 >>> b
518 bytearray(b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
519 >>> mb = memoryview(b)
520 >>> mb[0] = '*' # Assign to view, changing the bytearray.
521 >>> b[0:5] # The bytearray has been changed.
522 bytearray(b'*bcde')
523 >>>
524
525.. seealso::
526
527 :pep:`3137` - Immutable Bytes and Mutable Buffer
528 PEP written by Guido van Rossum.
Antoine Pitrou5cace782010-05-01 12:16:39 +0000529 Implemented by Travis Oliphant, Antoine Pitrou and others.
Andrew M. Kuchling9fbbd3b2010-05-01 12:06:51 +0000530 Backported to 2.7 by Antoine Pitrou; :issue:`2396`.
531
532
533
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000534Other Language Changes
535======================
536
537Some smaller changes made to the core Python language are:
538
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000539* The syntax for set literals has been backported from Python 3.x.
540 Curly brackets are used to surround the contents of the resulting
541 mutable set; set literals are
542 distinguished from dictionaries by not containing colons and values.
543 ``{}`` continues to represent an empty dictionary; use
544 ``set()`` for an empty set.
545
546 >>> {1,2,3,4,5}
547 set([1, 2, 3, 4, 5])
Ezio Melotti021f3342010-04-06 03:26:49 +0000548 >>> set() # empty set
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000549 set([])
Ezio Melotti021f3342010-04-06 03:26:49 +0000550 >>> {} # empty dict
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000551 {}
552
553 Backported by Alexandre Vassalotti; :issue:`2335`.
554
555* Dictionary and set comprehensions are another feature backported from
556 3.x, generalizing list/generator comprehensions to use
557 the literal syntax for sets and dictionaries.
558
559 >>> {x:x*x for x in range(6)}
560 {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
561 >>> {'a'*x for x in range(6)}
562 set(['', 'a', 'aa', 'aaa', 'aaaa', 'aaaaa'])
563
564 Backported by Alexandre Vassalotti; :issue:`2333`.
565
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000566* The :keyword:`with` statement can now use multiple context managers
567 in one statement. Context managers are processed from left to right
568 and each one is treated as beginning a new :keyword:`with` statement.
569 This means that::
570
571 with A() as a, B() as b:
572 ... suite of statements ...
573
574 is equivalent to::
575
576 with A() as a:
577 with B() as b:
578 ... suite of statements ...
579
580 The :func:`contextlib.nested` function provides a very similar
581 function, so it's no longer necessary and has been deprecated.
582
583 (Proposed in http://codereview.appspot.com/53094; implemented by
584 Georg Brandl.)
585
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000586* Conversions between floating-point numbers and strings are
587 now correctly rounded on most platforms. These conversions occur
588 in many different places: :func:`str` on
589 floats and complex numbers; the :class:`float` and :class:`complex`
590 constructors;
591 numeric formatting; serialization and
592 deserialization of floats and complex numbers using the
593 :mod:`marshal`, :mod:`pickle`
594 and :mod:`json` modules;
595 parsing of float and imaginary literals in Python code;
Ezio Melotti021f3342010-04-06 03:26:49 +0000596 and :class:`~decimal.Decimal`-to-float conversion.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000597
598 Related to this, the :func:`repr` of a floating-point number *x*
599 now returns a result based on the shortest decimal string that's
600 guaranteed to round back to *x* under correct rounding (with
601 round-half-to-even rounding mode). Previously it gave a string
602 based on rounding x to 17 decimal digits.
603
Ezio Melotti021f3342010-04-06 03:26:49 +0000604 .. maybe add an example?
605
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000606 The rounding library responsible for this improvement works on
607 Windows, and on Unix platforms using the gcc, icc, or suncc
608 compilers. There may be a small number of platforms where correct
609 operation of this code cannot be guaranteed, so the code is not
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +0000610 used on such systems. You can find out which code is being used
611 by checking :data:`sys.float_repr_style`, which will be ``short``
612 if the new code is in use and ``legacy`` if it isn't.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000613
Mark Dickinsonbdd863d2010-01-07 09:28:29 +0000614 Implemented by Eric Smith and Mark Dickinson, using David Gay's
615 :file:`dtoa.c` library; :issue:`7117`.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000616
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000617* The :meth:`str.format` method now supports automatic numbering of the replacement
Benjamin Petersonaa0a0b92009-04-11 20:27:15 +0000618 fields. This makes using :meth:`str.format` more closely resemble using
619 ``%s`` formatting::
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000620
621 >>> '{}:{}:{}'.format(2009, 04, 'Sunday')
622 '2009:4:Sunday'
623 >>> '{}:{}:{day}'.format(2009, 4, day='Sunday')
624 '2009:4:Sunday'
625
Benjamin Petersonaa0a0b92009-04-11 20:27:15 +0000626 The auto-numbering takes the fields from left to right, so the first ``{...}``
627 specifier will use the first argument to :meth:`str.format`, the next
628 specifier will use the next argument, and so on. You can't mix auto-numbering
629 and explicit numbering -- either number all of your specifier fields or none
630 of them -- but you can mix auto-numbering and named fields, as in the second
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000631 example above. (Contributed by Eric Smith; :issue:`5237`.)
632
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000633 Complex numbers now correctly support usage with :func:`format`,
634 and default to being right-aligned.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000635 Specifying a precision or comma-separation applies to both the real
636 and imaginary parts of the number, but a specified field width and
637 alignment is applied to the whole of the resulting ``1.5+3j``
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000638 output. (Contributed by Eric Smith; :issue:`1588` and :issue:`7988`.)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000639
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000640 The 'F' format code now always formats its output using uppercase characters,
641 so it will now produce 'INF' and 'NAN'.
642 (Contributed by Eric Smith; :issue:`3382`.)
643
Andrew M. Kuchlingc4ae73e2010-04-30 13:47:34 +0000644 A low-level change: the :meth:`object.__format__` method now triggers
645 a :exc:`PendingDeprecationWarning` if it's passed a format string,
646 because the :meth:`__format__` method for :class:`object` converts
647 the object to a string representation and formats that. The method
648 used to silently apply the format string to the string
649 representation, but that could hide mistakes in Python code. If
650 you're supplying formatting information such as an alignment or
651 precision, presumably you're expecting the formatting to be applied
652 in some object-specific way. (Fixed by Eric Smith; :issue:`7994`.)
653
Mark Dickinson1a707982008-12-17 16:14:37 +0000654* The :func:`int` and :func:`long` types gained a ``bit_length``
Georg Brandl64e1c752009-04-11 18:19:27 +0000655 method that returns the number of bits necessary to represent
Mark Dickinson1a707982008-12-17 16:14:37 +0000656 its argument in binary::
657
658 >>> n = 37
Ezio Melotti021f3342010-04-06 03:26:49 +0000659 >>> bin(n)
Mark Dickinson1a707982008-12-17 16:14:37 +0000660 '0b100101'
661 >>> n.bit_length()
662 6
663 >>> n = 2**123-1
664 >>> n.bit_length()
665 123
666 >>> (n+1).bit_length()
667 124
668
669 (Contributed by Fredrik Johansson and Victor Stinner; :issue:`3439`.)
670
Andrew M. Kuchling92b97002009-05-02 17:12:15 +0000671* Conversions from long integers and regular integers to floating
672 point now round differently, returning the floating-point number
673 closest to the number. This doesn't matter for small integers that
674 can be converted exactly, but for large numbers that will
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000675 unavoidably lose precision, Python 2.7 now approximates more
Andrew M. Kuchling92b97002009-05-02 17:12:15 +0000676 closely. For example, Python 2.6 computed the following::
677
678 >>> n = 295147905179352891391
679 >>> float(n)
680 2.9514790517935283e+20
681 >>> n - long(float(n))
682 65535L
683
684 Python 2.7's floating-point result is larger, but much closer to the
685 true value::
686
687 >>> n = 295147905179352891391
688 >>> float(n)
689 2.9514790517935289e+20
Ezio Melotti021f3342010-04-06 03:26:49 +0000690 >>> n - long(float(n))
Andrew M. Kuchling92b97002009-05-02 17:12:15 +0000691 -1L
692
693 (Implemented by Mark Dickinson; :issue:`3166`.)
694
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000695 Integer division is also more accurate in its rounding behaviours. (Also
696 implemented by Mark Dickinson; :issue:`1811`.)
697
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000698* It's now possible for a subclass of the built-in :class:`unicode` type
699 to override the :meth:`__unicode__` method. (Implemented by
700 Victor Stinner; :issue:`1583863`.)
701
Ezio Melotti021f3342010-04-06 03:26:49 +0000702* The :class:`bytearray` type's :meth:`~bytearray.translate` method now accepts
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000703 ``None`` as its first argument. (Fixed by Georg Brandl;
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000704 :issue:`4759`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000705
Ezio Melotti021f3342010-04-06 03:26:49 +0000706 .. bytearray doesn't seem to be documented
707
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000708* When using ``@classmethod`` and ``@staticmethod`` to wrap
709 methods as class or static methods, the wrapper object now
710 exposes the wrapped function as their :attr:`__func__` attribute.
711 (Contributed by Amaury Forgeot d'Arc, after a suggestion by
712 George Sakkis; :issue:`5982`.)
713
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +0000714* When a restricted set of attributes were set using ``__slots__``,
715 deleting an unset attribute would not raise :exc:`AttributeError`
716 as you would expect. Fixed by Benjamin Peterson; :issue:`7604`.)
717
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000718* A new encoding named "cp720", used primarily for Arabic text, is now
719 supported. (Contributed by Alexander Belchenko and Amaury Forgeot
720 d'Arc; :issue:`1616979`.)
721
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000722* The :class:`file` object will now set the :attr:`filename` attribute
723 on the :exc:`IOError` exception when trying to open a directory
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +0000724 on POSIX platforms (noted by Jan Kaliszewski; :issue:`4764`), and
725 now explicitly checks for and forbids writing to read-only file objects
726 instead of trusting the C library to catch and report the error
727 (fixed by Stefan Krah; :issue:`5677`).
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000728
Benjamin Petersonae9a0a02009-12-31 16:49:37 +0000729* The Python tokenizer now translates line endings itself, so the
730 :func:`compile` built-in function can now accept code using any
731 line-ending convention. Additionally, it no longer requires that the
732 code end in a newline.
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +0000733
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000734* Extra parentheses in function definitions are illegal in Python 3.x,
735 meaning that you get a syntax error from ``def f((x)): pass``. In
736 Python3-warning mode, Python 2.7 will now warn about this odd usage.
737 (Noted by James Lingard; :issue:`7362`.)
738
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +0000739* It's now possible to create weak references to old-style class
740 objects. New-style classes were always weak-referenceable. (Fixed
741 by Antoine Pitrou; :issue:`8268`.)
742
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000743* When a module object is garbage-collected, the module's dictionary is
744 now only cleared if no one else is holding a reference to the
745 dictionary (:issue:`7140`).
746
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000747.. ======================================================================
748
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000749.. _new-27-interpreter:
750
751Interpreter Changes
752-------------------------------
753
754A new environment variable, :envvar:`PYTHONWARNINGS`,
755allows controlling warnings. It should be set to a string
756containing warning settings, equivalent to those
757used with the :option:`-W` switch, separated by commas.
758(Contributed by Brian Curtin; :issue:`7301`.)
759
760For example, the following setting will print warnings every time
761they occur, but turn warnings from the :mod:`Cookie` module into an
762error. (The exact syntax for setting an environment variable varies
763across operating systems and shells, so it may be different for you.)
764
765::
766
767 export PYTHONWARNINGS=all,error:::Cookie:0
768
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +0000769When running a module using the interpreter's :option:`-m` switch,
770``sys.argv[0]`` will now be set to the string ``'-m'`` while the
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +0000771module is being located, while executing the :file:`__init__.py` files
772for any parent packages of the module to be executed.
773(Suggested by Michael Foord; implemented by Nick Coghlan;
774:issue:`8202`.)
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000775
776.. ======================================================================
777
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000778
779Optimizations
780-------------
781
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000782Several performance enhancements have been added:
783
784.. * A new :program:`configure` option, :option:`--with-computed-gotos`,
785 compiles the main bytecode interpreter loop using a new dispatch
786 mechanism that gives speedups of up to 20%, depending on the system
787 and benchmark. The new mechanism is only supported on certain
788 compilers, such as gcc, SunPro, and icc.
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000789
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000790* A new opcode was added to perform the initial setup for
791 :keyword:`with` statements, looking up the :meth:`__enter__` and
792 :meth:`__exit__` methods. (Contributed by Benjamin Peterson.)
793
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000794* The garbage collector now performs better for one common usage
795 pattern: when many objects are being allocated without deallocating
796 any of them. This would previously take quadratic
797 time for garbage collection, but now the number of full garbage collections
798 is reduced as the number of objects on the heap grows.
799 The new logic is to only perform a full garbage collection pass when
800 the middle generation has been collected 10 times and when the
801 number of survivor objects from the middle generation exceeds 10% of
802 the number of objects in the oldest generation. (Suggested by Martin
Ezio Melotti021f3342010-04-06 03:26:49 +0000803 von Löwis and implemented by Antoine Pitrou; :issue:`4074`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000804
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000805* The garbage collector tries to avoid tracking simple containers
806 which can't be part of a cycle. In Python 2.7, this is now true for
807 tuples and dicts containing atomic types (such as ints, strings,
808 etc.). Transitively, a dict containing tuples of atomic types won't
809 be tracked either. This helps reduce the cost of each
810 garbage collection by decreasing the number of objects to be
811 considered and traversed by the collector.
Antoine Pitrouc18f6b02009-03-28 19:10:13 +0000812 (Contributed by Antoine Pitrou; :issue:`4688`.)
813
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000814* Long integers are now stored internally either in base 2**15 or in base
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000815 2**30, the base being determined at build time. Previously, they
816 were always stored in base 2**15. Using base 2**30 gives
817 significant performance improvements on 64-bit machines, but
818 benchmark results on 32-bit machines have been mixed. Therefore,
819 the default is to use base 2**30 on 64-bit machines and base 2**15
820 on 32-bit machines; on Unix, there's a new configure option
821 :option:`--enable-big-digits` that can be used to override this default.
822
823 Apart from the performance improvements this change should be
824 invisible to end users, with one exception: for testing and
Ezio Melotti021f3342010-04-06 03:26:49 +0000825 debugging purposes there's a new structseq :data:`sys.long_info` that
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000826 provides information about the internal format, giving the number of
827 bits per digit and the size in bytes of the C type used to store
828 each digit::
829
830 >>> import sys
831 >>> sys.long_info
832 sys.long_info(bits_per_digit=30, sizeof_digit=4)
833
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000834 (Contributed by Mark Dickinson; :issue:`4258`.)
835
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000836 Another set of changes made long objects a few bytes smaller: 2 bytes
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000837 smaller on 32-bit systems and 6 bytes on 64-bit.
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000838 (Contributed by Mark Dickinson; :issue:`5260`.)
839
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000840* The division algorithm for long integers has been made faster
841 by tightening the inner loop, doing shifts instead of multiplications,
842 and fixing an unnecessary extra iteration.
843 Various benchmarks show speedups of between 50% and 150% for long
844 integer divisions and modulo operations.
845 (Contributed by Mark Dickinson; :issue:`5512`.)
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +0000846 Bitwise operations are also significantly faster (initial patch by
847 Gregory Smith; :issue:`1087418`).
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000848
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000849* The implementation of ``%`` checks for the left-side operand being
850 a Python string and special-cases it; this results in a 1-3%
851 performance increase for applications that frequently use ``%``
852 with strings, such as templating libraries.
853 (Implemented by Collin Winter; :issue:`5176`.)
854
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000855* List comprehensions with an ``if`` condition are compiled into
856 faster bytecode. (Patch by Antoine Pitrou, back-ported to 2.7
857 by Jeffrey Yasskin; :issue:`4715`.)
858
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +0000859* Converting an integer or long integer to a decimal string was made
860 faster by special-casing base 10 instead of using a generalized
861 conversion function that supports arbitrary bases.
862 (Patch by Gawain Bolton; :issue:`6713`.)
863
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +0000864* The :meth:`split`, :meth:`replace`, :meth:`rindex`,
865 :meth:`rpartition`, and :meth:`rsplit` methods of string-like types
866 (strings, Unicode strings, and :class:`bytearray` objects) now use a
867 fast reverse-search algorithm instead of a character-by-character
868 scan. This is sometimes faster by a factor of 10. (Added by
869 Florent Xicluna; :issue:`7462` and :issue:`7622`.)
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +0000870
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000871* The :mod:`pickle` and :mod:`cPickle` modules now automatically
872 intern the strings used for attribute names, reducing memory usage
873 of the objects resulting from unpickling. (Contributed by Jake
874 McGuire; :issue:`5084`.)
875
876* The :mod:`cPickle` module now special-cases dictionaries,
877 nearly halving the time required to pickle them.
878 (Contributed by Collin Winter; :issue:`5670`.)
879
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000880.. ======================================================================
881
Georg Brandl0516f812009-11-18 18:52:35 +0000882New and Improved Modules
883========================
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000884
885As in every release, Python's standard library received a number of
886enhancements and bug fixes. Here's a partial list of the most notable
887changes, sorted alphabetically by module name. Consult the
888:file:`Misc/NEWS` file in the source tree for a more complete list of
889changes, or look through the Subversion logs for all the details.
890
Ezio Melotti021f3342010-04-06 03:26:49 +0000891* The :mod:`bdb` module's base debugging class :class:`~bdb.Bdb`
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000892 gained a feature for skipping modules. The constructor
893 now takes an iterable containing glob-style patterns such as
894 ``django.*``; the debugger will not step into stack frames
895 from a module that matches one of these patterns.
896 (Contributed by Maru Newby after a suggestion by
897 Senthil Kumaran; :issue:`5142`.)
898
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +0000899* The :mod:`binascii` module now supports the buffer API, so it can be
900 used with :class:`memoryview` instances and other similar buffer objects.
901 (Backported from 3.x by Florent Xicluna; :issue:`7703`.)
902
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000903* Updated module: the :mod:`bsddb` module has been updated from 4.7.2devel9
904 to version 4.8.4 of
905 `the pybsddb package <http://www.jcea.es/programacion/pybsddb.htm>`__.
906 The new version features better Python 3.x compatibility, various bug fixes,
907 and adds several new BerkeleyDB flags and methods.
Ezio Melotti021f3342010-04-06 03:26:49 +0000908 (Updated by Jesús Cea Avión; :issue:`8156`. The pybsddb
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000909 changelog can be browsed at http://hg.jcea.es/pybsddb/file/tip/ChangeLog.)
910
Ezio Melotti021f3342010-04-06 03:26:49 +0000911* The :mod:`bz2` module's :class:`~bz2.BZ2File` now supports the context
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000912 management protocol, so you can write ``with bz2.BZ2File(...) as f: ...``.
913 (Contributed by Hagen Fuerstenau; :issue:`3860`.)
914
Ezio Melotti021f3342010-04-06 03:26:49 +0000915* New class: the :class:`~collections.Counter` class in the :mod:`collections`
916 module is useful for tallying data. :class:`~collections.Counter` instances
917 behave mostly like dictionaries but return zero for missing keys instead of
Georg Brandlf6dab952009-04-28 21:48:35 +0000918 raising a :exc:`KeyError`:
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000919
Georg Brandlf6dab952009-04-28 21:48:35 +0000920 .. doctest::
921 :options: +NORMALIZE_WHITESPACE
922
923 >>> from collections import Counter
924 >>> c = Counter()
925 >>> for letter in 'here is a sample of english text':
926 ... c[letter] += 1
927 ...
928 >>> c
929 Counter({' ': 6, 'e': 5, 's': 3, 'a': 2, 'i': 2, 'h': 2,
930 'l': 2, 't': 2, 'g': 1, 'f': 1, 'm': 1, 'o': 1, 'n': 1,
931 'p': 1, 'r': 1, 'x': 1})
932 >>> c['e']
933 5
934 >>> c['z']
935 0
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000936
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +0000937 There are three additional :class:`~collections.Counter` methods:
938 :meth:`~collections.Counter.most_common` returns the N most common
939 elements and their counts. :meth:`~collections.Counter.elements`
940 returns an iterator over the contained elements, repeating each
941 element as many times as its count.
942 :meth:`~collections.Counter.subtract` takes an iterable and
943 subtracts one for each element instead of adding; if the argument is
944 a dictionary or another :class:`Counter`, the counts are
945 subtracted. ::
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000946
947 >>> c.most_common(5)
948 [(' ', 6), ('e', 5), ('s', 3), ('a', 2), ('i', 2)]
949 >>> c.elements() ->
950 'a', 'a', ' ', ' ', ' ', ' ', ' ', ' ',
951 'e', 'e', 'e', 'e', 'e', 'g', 'f', 'i', 'i',
952 'h', 'h', 'm', 'l', 'l', 'o', 'n', 'p', 's',
Georg Brandlf6dab952009-04-28 21:48:35 +0000953 's', 's', 'r', 't', 't', 'x'
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +0000954 >>> c['e']
955 5
956 >>> c.subtract('very heavy on the letter e')
957 >>> c['e'] # Count is now lower
958 -1
Ezio Melotti021f3342010-04-06 03:26:49 +0000959
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000960 Contributed by Raymond Hettinger; :issue:`1696199`.
961
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +0000962 .. revision 79660
963
Ezio Melotti021f3342010-04-06 03:26:49 +0000964 The new :class:`~collections.OrderedDict` class is described in the earlier
965 section :ref:`pep-0372`.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000966
Ezio Melotti021f3342010-04-06 03:26:49 +0000967 The :class:`~collections.namedtuple` class now has an optional *rename* parameter.
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000968 If *rename* is true, field names that are invalid because they've
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000969 been repeated or that aren't legal Python identifiers will be
970 renamed to legal names that are derived from the field's
971 position within the list of fields:
972
Georg Brandlf6dab952009-04-28 21:48:35 +0000973 >>> from collections import namedtuple
974 >>> T = namedtuple('T', ['field1', '$illegal', 'for', 'field2'], rename=True)
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000975 >>> T._fields
976 ('field1', '_1', '_2', 'field2')
977
978 (Added by Raymond Hettinger; :issue:`1818`.)
979
Andrew M. Kuchling6d7dfa22010-04-11 12:49:37 +0000980 The :class:`~collections.deque` data type now has a
981 :meth:`~collections.deque.count` method that returns the number of
982 contained elements equal to the supplied argument *x*, and a
983 :meth:`~collections.deque.reverse` method that reverses the elements
984 of the deque in-place. :class:`deque` also exposes its maximum
985 length as the read-only :attr:`~collections.deque.maxlen` attribute.
986 (Both features added by Raymond Hettinger.)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000987
Andrew M. Kuchling02f7b992010-05-07 01:45:14 +0000988* Constructors for the parsing classes in the :mod:`ConfigParser` module now
989 take a *allow_no_value* parameter, defaulting to false; if true,
990 options without values will be allowed. For example::
991
992 >>> import ConfigParser, StringIO
993 >>> sample_config = """
994 ... [mysqld]
995 ... user = mysql
996 ... pid-file = /var/run/mysqld/mysqld.pid
997 ... skip-bdb
998 ... """
999 >>> config = ConfigParser.RawConfigParser(allow_no_value=True)
1000 >>> config.readfp(StringIO.StringIO(sample_config))
1001 >>> config.get('mysqld', 'user')
1002 'mysql'
1003 >>> print config.get('mysqld', 'skip-bdb')
1004 None
1005 >>> print config.get('mysqld', 'unknown')
1006 Traceback (most recent call last):
1007 ...
1008 ConfigParser.NoOptionError: No option 'unknown' in section: 'mysqld'
1009
1010 (Contributed by Mats Kindahl; :issue:`7005`.)
1011
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001012* Deprecated function: :func:`contextlib.nested`, which allows
1013 handling more than one context manager with a single :keyword:`with`
1014 statement, has been deprecated, because :keyword:`with` supports
1015 multiple context managers syntactically now.
1016
Ezio Melotti021f3342010-04-06 03:26:49 +00001017* The :mod:`copy` module's :func:`~copy.deepcopy` function will now
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001018 correctly copy bound instance methods. (Implemented by
1019 Robert Collins; :issue:`1515`.)
1020
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001021* The :mod:`ctypes` module now always converts ``None`` to a C NULL
1022 pointer for arguments declared as pointers. (Changed by Thomas
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001023 Heller; :issue:`4606`.) The underlying `libffi library
1024 <http://sourceware.org/libffi/>`__ has been updated to version
1025 3.0.9, containing various fixes for different platforms. (Updated
1026 by Matthias Klose; :issue:`8142`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001027
Ezio Melotti021f3342010-04-06 03:26:49 +00001028* New method: the :mod:`datetime` module's :class:`~datetime.timedelta` class
1029 gained a :meth:`~datetime.timedelta.total_seconds` method that returns the
1030 number of seconds in the duration. (Contributed by Brian Quinlan; :issue:`5788`.)
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001031
Ezio Melotti021f3342010-04-06 03:26:49 +00001032* New method: the :class:`~decimal.Decimal` class gained a
1033 :meth:`~decimal.Decimal.from_float` class method that performs an exact
1034 conversion of a floating-point number to a :class:`~decimal.Decimal`.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001035 Note that this is an **exact** conversion that strives for the
1036 closest decimal approximation to the floating-point representation's value;
1037 the resulting decimal value will therefore still include the inaccuracy,
1038 if any.
1039 For example, ``Decimal.from_float(0.1)`` returns
1040 ``Decimal('0.1000000000000000055511151231257827021181583404541015625')``.
1041 (Implemented by Raymond Hettinger; :issue:`4796`.)
1042
Andrew M. Kuchling04b99cc2010-05-04 01:24:22 +00001043 Comparing instances of :class:`Decimal` with floating-point
1044 numbers now produces sensible results based on the numeric values
1045 of the operands. Previously such comparisons would fall back to
1046 Python's default rules for comparing objects, which produced arbitrary
1047 results based on their type. Note that you still cannot combine
1048 :class:`Decimal` and floating-point in other operations such as addition,
1049 since you should be explicitly choosing how to convert between float and
1050 :class:`Decimal`.
1051 (Fixed by Mark Dickinson; :issue:`2531`.)
1052
Ezio Melotti021f3342010-04-06 03:26:49 +00001053 Most of the methods of the :class:`~decimal.Context` class now accept integers
1054 as well as :class:`~decimal.Decimal` instances; the only exceptions are the
1055 :meth:`~decimal.Context.canonical` and :meth:`~decimal.Context.is_canonical`
1056 methods. (Patch by Juan José Conti; :issue:`7633`.)
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001057
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001058 The constructor for :class:`~decimal.Decimal` now accepts
1059 floating-point numbers (added by Raymond Hettinger; :issue:`8257`)
1060 and non-European Unicode characters such as Arabic-Indic digits
1061 (contributed by Mark Dickinson; :issue:`6595`).
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001062
Ezio Melotti021f3342010-04-06 03:26:49 +00001063 When using :class:`~decimal.Decimal` instances with a string's
1064 :meth:`~str.format` method, the default alignment was previously
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001065 left-alignment. This has been changed to right-alignment, which seems
1066 more sensible for numeric types. (Changed by Mark Dickinson; :issue:`6857`.)
1067
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001068 Comparisons involving a signaling NaN value (or ``sNAN``) now signal
1069 :const:`InvalidOperation` instead of silently returning a true or
1070 false value depending on the comparison operator. Quiet NaN values
1071 (or ``NaN``) are now hashable. (Fixed by Mark Dickinson;
1072 :issue:`7279`.)
1073
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +00001074* The :mod:`difflib` module now produces output that is more
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00001075 compatible with modern :command:`diff`/:command:`patch` tools
1076 through one small change, using a tab character instead of spaces as
1077 a separator in the header giving the filename. (Fixed by Anatoly
1078 Techtonik; :issue:`7585`.)
1079
1080* The :mod:`doctest` module's :const:`IGNORE_EXCEPTION_DETAIL` flag
1081 will now ignore the name of the module containing the exception
1082 being tested. (Patch by Lennart Regebro; :issue:`7490`.)
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +00001083
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001084* The :class:`~fractions.Fraction` class now accepts a single float or
1085 :class:`~decimal.Decimal` instance, or two rational numbers, as
1086 arguments to its constructor. (Implemented by Mark Dickinson;
1087 rationals added in :issue:`5812`, and float/decimal in
1088 :issue:`8294`.)
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00001089
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +00001090 An oversight was fixed, making the :class:`Fraction` match the other
1091 numeric types; ordering comparisons (``<``, ``<=``, ``>``, ``>=``) between
1092 fractions and complex numbers now raise a :exc:`TypeError`.
1093
1094 .. revision 79455
1095
Ezio Melotti021f3342010-04-06 03:26:49 +00001096* New class: a new :class:`~ftplib.FTP_TLS` class in
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001097 the :mod:`ftplib` module provides secure FTP
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001098 connections using TLS encapsulation of authentication as well as
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001099 subsequent control and data transfers.
1100 (Contributed by Giampaolo Rodola', :issue:`2054`.)
1101
Ezio Melotti021f3342010-04-06 03:26:49 +00001102 The :meth:`~ftplib.FTP.storbinary` method for binary uploads can now restart
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001103 uploads thanks to an added *rest* parameter (patch by Pablo Mouzo;
1104 :issue:`6845`.)
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001105
Andrew M. Kuchling6d7dfa22010-04-11 12:49:37 +00001106* New class decorator: :func:`total_ordering` in the :mod:`functools`
1107 module takes a class that defines an :meth:`__eq__` method and one of
1108 :meth:`__lt__`, :meth:`__le__`, :meth:`__gt__`, or :meth:`__ge__`,
1109 and generates the missing comparison methods. Since the
1110 :meth:`__cmp__` method is being deprecated in Python 3.x,
1111 this decorator makes it easier to define ordered classes.
1112 (Added by Raymond Hettinger; :issue:`5479`.)
1113
1114 New function: :func:`cmp_to_key` will take an old-style comparison
1115 function that expects two arguments and return a new callable that
1116 can be used as the *key* parameter to functions such as
1117 :func:`sorted`, :func:`min` and :func:`max`, etc. The primary
1118 intended use is to help with making code compatible with Python 3.x.
1119 (Added by Raymond Hettinger.)
1120
Ezio Melotti021f3342010-04-06 03:26:49 +00001121* New function: the :mod:`gc` module's :func:`~gc.is_tracked` returns
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001122 true if a given instance is tracked by the garbage collector, false
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001123 otherwise. (Contributed by Antoine Pitrou; :issue:`4688`.)
1124
Ezio Melotti021f3342010-04-06 03:26:49 +00001125* The :mod:`gzip` module's :class:`~gzip.GzipFile` now supports the context
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +00001126 management protocol, so you can write ``with gzip.GzipFile(...) as f: ...``
1127 (contributed by Hagen Fuerstenau; :issue:`3860`), and it now implements
1128 the :class:`io.BufferedIOBase` ABC, so you can wrap it with
1129 :class:`io.BufferedReader` for faster processing
1130 (contributed by Nir Aides; :issue:`7471`).
1131 It's also now possible to override the modification time
Andrew M. Kuchling77069572009-03-31 01:21:01 +00001132 recorded in a gzipped file by providing an optional timestamp to
1133 the constructor. (Contributed by Jacques Frechet; :issue:`4272`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001134
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001135 Files in gzip format can be padded with trailing zero bytes; the
1136 :mod:`gzip` module will now consume these trailing bytes. (Fixed by
1137 Tadek Pietraszek and Brian Curtin; :issue:`2846`.)
1138
Ezio Melotti021f3342010-04-06 03:26:49 +00001139* New attribute: the :mod:`hashlib` module now has an :attr:`~hashlib.hashlib.algorithms`
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001140 attribute containing a tuple naming the supported algorithms.
1141 In Python 2.7, ``hashlib.algorithms`` contains
1142 ``('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')``
1143 (Contributed by Carl Chenet; :issue:`7418`.)
1144
Ezio Melotti021f3342010-04-06 03:26:49 +00001145* The default :class:`~httplib.HTTPResponse` class used by the :mod:`httplib` module now
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001146 supports buffering, resulting in much faster reading of HTTP responses.
1147 (Contributed by Kristjan Valur Jonsson; :issue:`4879`.)
1148
Ezio Melotti021f3342010-04-06 03:26:49 +00001149 The :class:`~httplib.HTTPConnection` and :class:`~httplib.HTTPSConnection` classes
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001150 now support a *source_address* parameter, a ``(host, port)`` 2-tuple
1151 giving the source address that will be used for the connection.
1152 (Contributed by Eldon Ziegler; :issue:`3972`.)
1153
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00001154* The :mod:`ihooks` module now supports relative imports. Note that
1155 :mod:`ihooks` is an older module used to support customizing imports,
1156 superseded by the :mod:`imputil` module added in Python 2.0.
1157 (Relative import support added by Neil Schemenauer.)
1158
1159 .. revision 75423
1160
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001161* The :mod:`imaplib` module now supports IPv6 addresses.
1162 (Contributed by Derek Morr; :issue:`1655`.)
1163
Andrew M. Kuchlingce690522010-04-13 01:32:51 +00001164* New function: the :mod:`inspect` module's :func:`~inspect.getcallargs`
1165 takes a callable and its positional and keyword arguments,
1166 and figures out which of the callable's parameters will receive each argument,
1167 returning a dictionary mapping argument names to their values. For example::
1168
1169 >>> from inspect import getcallargs
1170 >>> def f(a, b=1, *pos, **named):
1171 ... pass
1172 >>> getcallargs(f, 1, 2, 3)
1173 {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
1174 >>> getcallargs(f, a=2, x=4)
1175 {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
1176 >>> getcallargs(f)
1177 Traceback (most recent call last):
1178 ...
1179 TypeError: f() takes at least 1 argument (0 given)
1180
1181 Contributed by George Sakkis; :issue:`3135`.
1182
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001183* Updated module: The :mod:`io` library has been upgraded to the version shipped with
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001184 Python 3.1. For 3.1, the I/O library was entirely rewritten in C
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001185 and is 2 to 20 times faster depending on the task being performed. The
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001186 original Python version was renamed to the :mod:`_pyio` module.
1187
1188 One minor resulting change: the :class:`io.TextIOBase` class now
1189 has an :attr:`errors` attribute giving the error setting
1190 used for encoding and decoding errors (one of ``'strict'``, ``'replace'``,
1191 ``'ignore'``).
1192
1193 The :class:`io.FileIO` class now raises an :exc:`OSError` when passed
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001194 an invalid file descriptor. (Implemented by Benjamin Peterson;
Ezio Melotti021f3342010-04-06 03:26:49 +00001195 :issue:`4991`.) The :meth:`~io.IOBase.truncate` method now preserves the
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001196 file position; previously it would change the file position to the
1197 end of the new file. (Fixed by Pascal Chambon; :issue:`6939`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001198
Andrew M. Kuchling5a73ff82009-12-02 14:27:11 +00001199* New function: ``itertools.compress(data, selectors)`` takes two
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001200 iterators. Elements of *data* are returned if the corresponding
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001201 value in *selectors* is true::
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001202
1203 itertools.compress('ABCDEF', [1,0,1,0,1,1]) =>
1204 A, C, E, F
1205
Ezio Melotti021f3342010-04-06 03:26:49 +00001206 .. maybe here is better to use >>> list(itertools.compress(...)) instead
1207
Andrew M. Kuchling5a73ff82009-12-02 14:27:11 +00001208 New function: ``itertools.combinations_with_replacement(iter, r)``
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001209 returns all the possible *r*-length combinations of elements from the
Ezio Melotti021f3342010-04-06 03:26:49 +00001210 iterable *iter*. Unlike :func:`~itertools.combinations`, individual elements
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001211 can be repeated in the generated combinations::
1212
1213 itertools.combinations_with_replacement('abc', 2) =>
1214 ('a', 'a'), ('a', 'b'), ('a', 'c'),
1215 ('b', 'b'), ('b', 'c'), ('c', 'c')
1216
1217 Note that elements are treated as unique depending on their position
1218 in the input, not their actual values.
1219
Ezio Melotti021f3342010-04-06 03:26:49 +00001220 The :func:`itertools.count` function now has a *step* argument that
1221 allows incrementing by values other than 1. :func:`~itertools.count` also
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001222 now allows keyword arguments, and using non-integer values such as
Ezio Melotti021f3342010-04-06 03:26:49 +00001223 floats or :class:`~decimal.Decimal` instances. (Implemented by Raymond
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001224 Hettinger; :issue:`5032`.)
1225
Andrew M. Kuchling77069572009-03-31 01:21:01 +00001226 :func:`itertools.combinations` and :func:`itertools.product` were
1227 previously raising :exc:`ValueError` for values of *r* larger than
1228 the input iterable. This was deemed a specification error, so they
1229 now return an empty iterator. (Fixed by Raymond Hettinger; :issue:`4816`.)
1230
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001231* Updated module: The :mod:`json` module was upgraded to version 2.0.9 of the
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001232 simplejson package, which includes a C extension that makes
1233 encoding and decoding faster.
1234 (Contributed by Bob Ippolito; :issue:`4136`.)
1235
Ezio Melotti021f3342010-04-06 03:26:49 +00001236 To support the new :class:`collections.OrderedDict` type, :func:`json.load`
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001237 now has an optional *object_pairs_hook* parameter that will be called
1238 with any object literal that decodes to a list of pairs.
1239 (Contributed by Raymond Hettinger; :issue:`5381`.)
1240
Andrew M. Kuchling837a5382010-05-06 17:21:59 +00001241* The :mod:`mailbox` module's :class:`Maildir` class now records the
1242 timestamp on the directories it reads, and only re-reads them if the
1243 modification time has subsequently changed. This improves
1244 performance by avoiding unneeded directory scans. (Fixed by
1245 A.M. Kuchling and Antoine Pitrou; :issue:`1607951`, :issue:`6896`.)
1246
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001247* New functions: the :mod:`math` module gained
Ezio Melotti021f3342010-04-06 03:26:49 +00001248 :func:`~math.erf` and :func:`~math.erfc` for the error function and the complementary error function,
1249 :func:`~math.expm1` which computes ``e**x - 1`` with more precision than
1250 using :func:`~math.exp` and subtracting 1,
1251 :func:`~math.gamma` for the Gamma function, and
1252 :func:`~math.lgamma` for the natural log of the Gamma function.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001253 (Contributed by Mark Dickinson and nirinA raseliarison; :issue:`3366`.)
1254
Andrew M. Kuchling24520b42009-04-09 11:22:47 +00001255* The :mod:`multiprocessing` module's :class:`Manager*` classes
1256 can now be passed a callable that will be called whenever
1257 a subprocess is started, along with a set of arguments that will be
1258 passed to the callable.
1259 (Contributed by lekma; :issue:`5585`.)
1260
Ezio Melotti021f3342010-04-06 03:26:49 +00001261 The :class:`~multiprocessing.Pool` class, which controls a pool of worker processes,
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001262 now has an optional *maxtasksperchild* parameter. Worker processes
1263 will perform the specified number of tasks and then exit, causing the
Ezio Melotti021f3342010-04-06 03:26:49 +00001264 :class:`~multiprocessing.Pool` to start a new worker. This is useful if tasks may leak
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001265 memory or other resources, or if some tasks will cause the worker to
1266 become very large.
1267 (Contributed by Charles Cazabon; :issue:`6963`.)
1268
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001269* The :mod:`nntplib` module now supports IPv6 addresses.
1270 (Contributed by Derek Morr; :issue:`1664`.)
1271
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001272* New functions: the :mod:`os` module wraps the following POSIX system
Ezio Melotti021f3342010-04-06 03:26:49 +00001273 calls: :func:`~os.getresgid` and :func:`~os.getresuid`, which return the
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001274 real, effective, and saved GIDs and UIDs;
Ezio Melotti021f3342010-04-06 03:26:49 +00001275 :func:`~os.setresgid` and :func:`~os.setresuid`, which set
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001276 real, effective, and saved GIDs and UIDs to new values;
Ezio Melotti021f3342010-04-06 03:26:49 +00001277 :func:`~os.initgroups`. (GID/UID functions
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001278 contributed by Travis H.; :issue:`6508`. Support for initgroups added
1279 by Jean-Paul Calderone; :issue:`7333`.)
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001280
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001281 The :func:`os.fork` function now re-initializes the import lock in
Ezio Melotti021f3342010-04-06 03:26:49 +00001282 the child process; this fixes problems on Solaris when :func:`~os.fork`
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001283 is called from a thread. (Fixed by Zsolt Cserna; :issue:`7242`.)
1284
Ezio Melotti021f3342010-04-06 03:26:49 +00001285* In the :mod:`os.path` module, the :func:`~os.path.normpath` and
1286 :func:`~os.path.abspath` functions now preserve Unicode; if their input path
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001287 is a Unicode string, the return value is also a Unicode string.
Ezio Melotti021f3342010-04-06 03:26:49 +00001288 (:meth:`~os.path.normpath` fixed by Matt Giuca in :issue:`5827`;
1289 :meth:`~os.path.abspath` fixed by Ezio Melotti in :issue:`3426`.)
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001290
Andrew M. Kuchling9cb42772009-01-21 02:15:43 +00001291* The :mod:`pydoc` module now has help for the various symbols that Python
1292 uses. You can now do ``help('<<')`` or ``help('@')``, for example.
1293 (Contributed by David Laban; :issue:`4739`.)
1294
Ezio Melotti021f3342010-04-06 03:26:49 +00001295* The :mod:`re` module's :func:`~re.split`, :func:`~re.sub`, and :func:`~re.subn`
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001296 now accept an optional *flags* argument, for consistency with the
1297 other functions in the module. (Added by Gregory P. Smith.)
1298
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001299* New function: :func:`~runpy.run_path` in the :mod:`runpy` module
1300 will execute the code at a provided *path* argument. *path* can be
1301 the path of a Python source file (:file:`example.py`), a compiled
1302 bytecode file (:file:`example.pyc`), a directory
1303 (:file:`./package/'), or a zip archive (:file:`example.zip`). If a
1304 directory or zip path is provided, it will be added to the front of
1305 ``sys.path`` and the module :mod:`__main__` will be imported. It's
1306 expected that the directory or zip contains a :file:`__main__.py`;
1307 if it doesn't, some other :file:`__main__.py` might be imported from
1308 a location later in ``sys.path``. This makes some of the machinery
Andrew M. Kuchling837a5382010-05-06 17:21:59 +00001309 of :mod:`runpy` available to scripts that want to mimic the way
1310 Python's :option:`-m` processes an explicit path name.
1311 (Added by Nick Coghlan; :issue:`6816`.)
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001312
Ezio Melotti021f3342010-04-06 03:26:49 +00001313* New function: in the :mod:`shutil` module, :func:`~shutil.make_archive`
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001314 takes a filename, archive type (zip or tar-format), and a directory
1315 path, and creates an archive containing the directory's contents.
1316 (Added by Tarek Ziadé.)
1317
Ezio Melotti021f3342010-04-06 03:26:49 +00001318 :mod:`shutil`'s :func:`~shutil.copyfile` and :func:`~shutil.copytree`
1319 functions now raise a :exc:`~shutil.SpecialFileError` exception when
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001320 asked to copy a named pipe. Previously the code would treat
1321 named pipes like a regular file by opening them for reading, and
1322 this would block indefinitely. (Fixed by Antoine Pitrou; :issue:`3002`.)
1323
1324* New functions: in the :mod:`site` module, three new functions
1325 return various site- and user-specific paths.
Ezio Melotti021f3342010-04-06 03:26:49 +00001326 :func:`~site.getsitepackages` returns a list containing all
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001327 global site-packages directories, and
Ezio Melotti021f3342010-04-06 03:26:49 +00001328 :func:`~site.getusersitepackages` returns the path of the user's
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001329 site-packages directory.
Ezio Melotti021f3342010-04-06 03:26:49 +00001330 :func:`~site.getuserbase` returns the value of the :envvar:`USER_BASE`
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001331 environment variable, giving the path to a directory that can be used
1332 to store data.
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001333 (Contributed by Tarek Ziadé; :issue:`6693`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001334
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001335 The :mod:`site` module now reports exceptions occurring
1336 when the :mod:`sitecustomize` module is imported, and will no longer
Florent Xiclunaad598332010-03-31 21:40:32 +00001337 catch and swallow the :exc:`KeyboardInterrupt` exception. (Fixed by
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001338 Victor Stinner; :issue:`3137`.)
1339
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001340* The :func:`~socket.create_connection` function
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +00001341 gained a *source_address* parameter, a ``(host, port)`` 2-tuple
1342 giving the source address that will be used for the connection.
1343 (Contributed by Eldon Ziegler; :issue:`3972`.)
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00001344
Ezio Melotti021f3342010-04-06 03:26:49 +00001345 The :meth:`~socket.socket.recv_into` and :meth:`~socket.socket.recvfrom_into`
1346 methods will now write into objects that support the buffer API, most usefully
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001347 the :class:`bytearray` and :class:`memoryview` objects. (Implemented by
1348 Antoine Pitrou; :issue:`8104`.)
1349
Ezio Melotti021f3342010-04-06 03:26:49 +00001350* The :mod:`SocketServer` module's :class:`~SocketServer.TCPServer` class now
1351 has a :attr:`~SocketServer.TCPServer.disable_nagle_algorithm` class attribute.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001352 The default value is False; if overridden to be True,
1353 new request connections will have the TCP_NODELAY option set to
1354 prevent buffering many small sends into a single TCP packet.
1355 (Contributed by Kristjan Valur Jonsson; :issue:`6192`.)
1356
Ezio Melotti021f3342010-04-06 03:26:49 +00001357* Updated module: the :mod:`sqlite3` module has been updated to
Andrew M. Kuchlingfed15762010-03-08 12:00:39 +00001358 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
1359 the ability to load SQLite extensions from shared libraries.
1360 Call the ``enable_load_extension(True)`` method to enable extensions,
Ezio Melotti021f3342010-04-06 03:26:49 +00001361 and then call :meth:`~sqlite3.Connection.load_extension` to load a particular shared library.
Andrew M. Kuchlingfed15762010-03-08 12:00:39 +00001362 (Updated by Gerhard Häring.)
1363
Antoine Pitroud69e6ee2010-05-07 10:15:51 +00001364* The :mod:`ssl` module's :class:`ssl.SSLSocket` objects now support the
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001365 buffer API, which fixed a test suite failure (fix by Antoine Pitrou;
1366 :issue:`7133`) and automatically set
1367 OpenSSL's :cmacro:`SSL_MODE_AUTO_RETRY`, which will prevent an error
1368 code being returned from :meth:`recv` operations that trigger an SSL
1369 renegotiation (fix by Antoine Pitrou; :issue:`8222`).
1370
Antoine Pitroud69e6ee2010-05-07 10:15:51 +00001371 The :func:`ssl.wrap_socket` constructor function now takes a
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001372 *ciphers* argument that's a string listing the encryption algorithms
1373 to be allowed; the format of the string is described
Antoine Pitroud69e6ee2010-05-07 10:15:51 +00001374 `in the OpenSSL documentation
1375 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`__.
1376 (Added by Antoine Pitrou; :issue:`8322`.)
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001377
1378 Another change makes the extension load all of OpenSSL's ciphers and
1379 digest algorithms so that they're all available. Some SSL
1380 certificates couldn't be verified, reporting an 'unknown algorithm'
1381 error. (Reported by Beda Kosata, and fixed by Antoine Pitrou;
1382 :issue:`8484`.)
1383
1384 The version of OpenSSL being used is now available as the module
Antoine Pitroud69e6ee2010-05-07 10:15:51 +00001385 attributes :data:`ssl.OPENSSL_VERSION` (a string),
1386 :data:`ssl.OPENSSL_VERSION_INFO` (a 5-tuple), and
1387 :data:`ssl.OPENSSL_VERSION_NUMBER` (an integer). (Added by Antoine
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001388 Pitrou; :issue:`8321`.)
1389
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001390* The :mod:`struct` module will no longer silently ignore overflow
1391 errors when a value is too large for a particular integer format
1392 code (one of ``bBhHiIlLqQ``); it now always raises a
1393 :exc:`struct.error` exception. (Changed by Mark Dickinson;
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001394 :issue:`1523`.) The :func:`~struct.pack` function will also
1395 attempt to use :meth:`__index__` to convert and pack non-integers
1396 before trying the :meth:`__int__` method or reporting an error.
1397 (Changed by Mark Dickinson; :issue:`8300`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001398
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001399* New function: the :mod:`subprocess` module's
Ezio Melotti021f3342010-04-06 03:26:49 +00001400 :func:`~subprocess.check_output` runs a command with a specified set of arguments
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001401 and returns the command's output as a string when the command runs without
Ezio Melotti021f3342010-04-06 03:26:49 +00001402 error, or raises a :exc:`~subprocess.CalledProcessError` exception otherwise.
Andrew M. Kuchling10b1ec92009-01-02 21:00:35 +00001403
1404 ::
1405
1406 >>> subprocess.check_output(['df', '-h', '.'])
1407 'Filesystem Size Used Avail Capacity Mounted on\n
1408 /dev/disk0s2 52G 49G 3.0G 94% /\n'
1409
1410 >>> subprocess.check_output(['df', '-h', '/bogus'])
1411 ...
1412 subprocess.CalledProcessError: Command '['df', '-h', '/bogus']' returned non-zero exit status 1
1413
1414 (Contributed by Gregory P. Smith.)
1415
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001416 The :mod:`subprocess` module will now retry its internal system calls
1417 on receiving an :const:`EINTR` signal. (Reported by several people; final
1418 patch by Gregory P. Smith in :issue:`1068268`.)
1419
Ezio Melotti021f3342010-04-06 03:26:49 +00001420* New function: :func:`~symtable.is_declared_global` in the :mod:`symtable` module
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001421 returns true for variables that are explicitly declared to be global,
1422 false for ones that are implicitly global.
1423 (Contributed by Jeremy Hylton.)
1424
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00001425* The :mod:`syslog` module will now use the value of ``sys.argv[0]`` as the
1426 identifier instead of the previous default value of ``'python'``.
1427 (Changed by Sean Reifschneider; :issue:`8451`.)
1428
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001429* The ``sys.version_info`` value is now a named tuple, with attributes
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001430 named :attr:`major`, :attr:`minor`, :attr:`micro`,
1431 :attr:`releaselevel`, and :attr:`serial`. (Contributed by Ross
1432 Light; :issue:`4285`.)
1433
1434 :func:`sys.getwindowsversion` also returns a named tuple,
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +00001435 with attributes named :attr:`major`, :attr:`minor`, :attr:`build`,
Ezio Melotti12477752010-02-08 22:22:41 +00001436 :attr:`platform`, :attr:`service_pack`, :attr:`service_pack_major`,
Eric Smithb3c54882010-02-03 14:17:50 +00001437 :attr:`service_pack_minor`, :attr:`suite_mask`, and
1438 :attr:`product_type`. (Contributed by Brian Curtin; :issue:`7766`.)
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001439
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001440* The :mod:`tarfile` module's default error handling has changed, to
1441 no longer suppress fatal errors. The default error level was previously 0,
1442 which meant that errors would only result in a message being written to the
1443 debug log, but because the debug log is not activated by default,
1444 these errors go unnoticed. The default error level is now 1,
1445 which raises an exception if there's an error.
1446 (Changed by Lars Gustäbel; :issue:`7357`.)
1447
Ezio Melotti021f3342010-04-06 03:26:49 +00001448 :mod:`tarfile` now supports filtering the :class:`~tarfile.TarInfo`
1449 objects being added to a tar file. When you call :meth:`~tarfile.TarFile.add`,
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001450 instance, you may supply an optional *filter* argument
1451 that's a callable. The *filter* callable will be passed the
Ezio Melotti021f3342010-04-06 03:26:49 +00001452 :class:`~tarfile.TarInfo` for every file being added, and can modify and return it.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001453 If the callable returns ``None``, the file will be excluded from the
1454 resulting archive. This is more powerful than the existing
1455 *exclude* argument, which has therefore been deprecated.
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001456 (Added by Lars Gustäbel; :issue:`6856`.)
Ezio Melotti021f3342010-04-06 03:26:49 +00001457 The :class:`~tarfile.TarFile` class also now supports the context manager protocol.
Andrew M. Kuchlingfed15762010-03-08 12:00:39 +00001458 (Added by Lars Gustäbel; :issue:`7232`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001459
Ezio Melotti021f3342010-04-06 03:26:49 +00001460* The :meth:`~threading.Event.wait` method of the :class:`threading.Event` class
1461 now returns the internal flag on exit. This means the method will usually
1462 return true because :meth:`~threading.Event.wait` is supposed to block until the
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001463 internal flag becomes true. The return value will only be false if
1464 a timeout was provided and the operation timed out.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001465 (Contributed by Tim Lesher; :issue:`1674032`.)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001466
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001467* The Unicode database provided by the :mod:`unicodedata` module is
1468 now used internally to determine which characters are numeric,
1469 whitespace, or represent line breaks. The database also
1470 includes information from the :file:`Unihan.txt` data file (patch
1471 by Anders Chrigström and Amaury Forgeot d'Arc; :issue:`1571184`)
1472 and has been updated to version 5.2.0 (updated by
1473 Florent Xicluna; :issue:`8024`).
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001474
Andrew M. Kuchling04b99cc2010-05-04 01:24:22 +00001475* The :mod:`urlparse` module's :func:`~urlparse.urlsplit` now handles
1476 unknown URL schemes in a fashion compliant with :rfc:`3986`: if the
1477 URL is of the form ``"<something>://..."``, the text before the
1478 ``://`` is treated as the scheme, even if it's a made-up scheme that
1479 the module doesn't know about. This change may break code that
1480 worked around the old behaviour. For example, Python 2.6.4 or 2.5
1481 will return the following:
1482
1483 >>> import urlparse
1484 >>> urlparse.urlsplit('invented://host/filename?query')
1485 ('invented', '', '//host/filename?query', '', '')
1486
1487 Python 2.7 (and Python 2.6.5) will return:
1488
1489 >>> import urlparse
1490 >>> urlparse.urlsplit('invented://host/filename?query')
1491 ('invented', 'host', '/filename?query', '', '')
1492
1493 (Python 2.7 actually produces slightly different output, since it
1494 returns a named tuple instead of a standard tuple.)
1495
1496 The :mod:`urlparse` module also supports IPv6 literal addresses as defined by
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001497 :rfc:`2732` (contributed by Senthil Kumaran; :issue:`2987`). ::
1498
1499 >>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo')
1500 ParseResult(scheme='http', netloc='[1080::8:800:200C:417A]',
1501 path='/foo', params='', query='', fragment='')
1502
Ezio Melotti021f3342010-04-06 03:26:49 +00001503* The :class:`~UserDict.UserDict` class is now a new-style class. (Changed by
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001504 Benjamin Peterson.)
1505
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00001506* New class: the :class:`~weakref.WeakSet` class in the :mod:`weakref`
1507 module is a set that only holds weak references to its elements; elements
1508 will be removed once there are no references pointing to them.
1509 (Originally implemented in Python 3.x by Raymond Hettinger, and backported
1510 to 2.7 by Michael Foord.)
1511
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001512* The ElementTree library, :mod:`xml.etree`, no longer escapes
1513 ampersands and angle brackets when outputting an XML processing
Ezio Melotti021f3342010-04-06 03:26:49 +00001514 instruction (which looks like ``<?xml-stylesheet href="#style1"?>``)
1515 or comment (which looks like ``<!-- comment -->``).
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001516 (Patch by Neil Muller; :issue:`2746`.)
1517
Ezio Melotti021f3342010-04-06 03:26:49 +00001518* The :mod:`zipfile` module's :class:`~zipfile.ZipFile` now supports the context
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001519 management protocol, so you can write ``with zipfile.ZipFile(...) as f: ...``.
1520 (Contributed by Brian Curtin; :issue:`5511`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001521
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001522 :mod:`zipfile` now also supports archiving empty directories and
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001523 extracts them correctly. (Fixed by Kuba Wieczorek; :issue:`4710`.)
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001524 Reading files out of an archive is faster, and interleaving
Ezio Melotti021f3342010-04-06 03:26:49 +00001525 :meth:`~zipfile.ZipFile.read` and :meth:`~zipfile.ZipFile.readline` now works correctly.
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001526 (Contributed by Nir Aides; :issue:`7610`.)
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001527
Ezio Melotti021f3342010-04-06 03:26:49 +00001528 The :func:`~zipfile.is_zipfile` function now
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001529 accepts a file object, in addition to the path names accepted in earlier
1530 versions. (Contributed by Gabriel Genellina; :issue:`4756`.)
1531
Ezio Melotti021f3342010-04-06 03:26:49 +00001532 The :meth:`~zipfile.ZipFile.writestr` method now has an optional *compress_type* parameter
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001533 that lets you override the default compression method specified in the
Ezio Melotti021f3342010-04-06 03:26:49 +00001534 :class:`~zipfile.ZipFile` constructor. (Contributed by Ronald Oussoren;
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001535 :issue:`6003`.)
1536
1537
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001538.. ======================================================================
1539.. whole new modules get described in subsections here
1540
1541
1542.. _importlib-section:
1543
1544New module: importlib
1545------------------------------
1546
1547Python 3.1 includes the :mod:`importlib` package, a re-implementation
1548of the logic underlying Python's :keyword:`import` statement.
1549:mod:`importlib` is useful for implementors of Python interpreters and
1550to users who wish to write new importers that can participate in the
1551import process. Python 2.7 doesn't contain the complete
1552:mod:`importlib` package, but instead has a tiny subset that contains
1553a single function, :func:`~importlib.import_module`.
1554
1555``import_module(name, package=None)`` imports a module. *name* is
1556a string containing the module or package's name. It's possible to do
1557relative imports by providing a string that begins with a ``.``
1558character, such as ``..utils.errors``. For relative imports, the
1559*package* argument must be provided and is the name of the package that
1560will be used as the anchor for
1561the relative import. :func:`~importlib.import_module` both inserts the imported
1562module into ``sys.modules`` and returns the module object.
1563
1564Here are some examples::
1565
1566 >>> from importlib import import_module
1567 >>> anydbm = import_module('anydbm') # Standard absolute import
1568 >>> anydbm
1569 <module 'anydbm' from '/p/python/Lib/anydbm.py'>
1570 >>> # Relative import
1571 >>> sysconfig = import_module('..sysconfig', 'distutils.command')
1572 >>> sysconfig
1573 <module 'distutils.sysconfig' from '/p/python/Lib/distutils/sysconfig.pyc'>
1574
1575:mod:`importlib` was implemented by Brett Cannon and introduced in
1576Python 3.1.
1577
1578
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00001579New module: sysconfig
1580---------------------------------
1581
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001582The :mod:`sysconfig` module has been pulled out of the Distutils
1583package, becoming a new top-level module in its own right.
1584:mod:`sysconfig` provides functions for getting information about
1585Python's build process: compiler switches, installation paths, the
1586platform name, and whether Python is running from its source
1587directory.
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00001588
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001589Some of the functions in the module are:
1590
1591* :func:`~sysconfig.get_config_var` returns variables from Python's
1592 Makefile and the :file:`pyconfig.h` file.
1593* :func:`~sysconfig.get_config_vars` returns a dictionary containing
1594 all of the configuration variables.
1595* :func:`~sysconfig.getpath` returns the configured path for
1596 a particular type of module: the standard library,
1597 site-specific modules, platform-specific modules, etc.
1598* :func:`~sysconfig.is_python_build` returns true if you're running a
1599 binary from a Python source tree, and false otherwise.
1600
1601Consult the :mod:`sysconfig` documentation for more details and for
1602a complete list of functions.
1603
1604The Distutils package and :mod:`sysconfig` are now maintained and
1605renamed by Tarek Ziadé.
1606
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00001607
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001608ttk: Themed Widgets for Tk
1609--------------------------
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001610
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001611Tcl/Tk 8.5 includes a set of themed widgets that re-implement basic Tk
1612widgets but have a more customizable appearance and can therefore more
1613closely resemble the native platform's widgets. This widget
1614set was originally called Tile, but was renamed to Ttk (for "themed Tk")
1615on being added to Tcl/Tck release 8.5.
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001616
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001617XXX write a brief discussion and an example here.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001618
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001619The :mod:`ttk` module was written by Guilherme Polo and added in
1620:issue:`2983`. An alternate version called ``Tile.py``, written by
1621Martin Franklin and maintained by Kevin Walzer, was proposed for
1622inclusion in :issue:`2618`, but the authors argued that Guilherme
1623Polo's work was more comprehensive.
1624
1625
1626.. _unittest-section:
Tarek Ziadé2b210692010-02-02 23:39:40 +00001627
Andrew M. Kuchlingacab9402010-05-06 17:27:57 +00001628Updated module: unittest
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001629---------------------------------
1630
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001631The :mod:`unittest` module was greatly enhanced; many
1632new features were added. Most of these features were implemented
Andrew M. Kuchlingacab9402010-05-06 17:27:57 +00001633by Michael Foord, unless otherwise noted. The enhanced version of
1634the module is downloadable separately for use with Python versions 2.4 to 2.6,
1635packaged as the :mod:`unittest2` package, from
1636http://pypi.python.org/pypi/unittest2.
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001637
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001638When used from the command line, the module can automatically discover
1639tests. It's not as fancy as `py.test <http://pytest.org>`__ or
1640`nose <http://code.google.com/p/python-nose/>`__, but provides a simple way
1641to run tests kept within a set of package directories. For example,
1642the following command will search the :file:`test/` subdirectory for
1643any importable test files named ``test*.py``::
1644
1645 python -m unittest discover -s test
1646
1647Consult the :mod:`unittest` module documentation for more details.
1648(Developed in :issue:`6001`.)
1649
1650The :func:`main` function supports some other new options:
1651
1652* :option:`-b` or :option:`--buffer` will buffer the standard output
1653 and standard error streams during each test. If the test passes,
1654 any resulting output will be discard; on failure, the buffered
1655 output will be displayed.
1656
1657* :option:`-c` or :option:`--catch` will cause the control-C interrupt
1658 to be handled more gracefully. Instead of interrupting the test
1659 process immediately, the currently running test will be completed
1660 and then the resulting partial results will be reported. If you're
1661 impatient, a second press of control-C will cause an immediate
1662 interruption.
1663
1664 This control-C handler tries to avoid interfering when the code
1665 being tested or the tests being run have defined a signal handler of
1666 their own, by noticing that a signal handler was already set and
1667 calling it. If this doesn't work for you, there's a
1668 :func:`removeHandler` decorator that can be used to mark tests that
1669 should have the control-C handling disabled.
1670
1671* :option:`-f` or :option:`--failfast` makes
1672 test execution stop immediately when a test fails instead of
1673 continuing to execute further tests. (Suggested by Cliff Dyer and
1674 implemented by Michael Foord; :issue:`8074`.)
1675
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001676The progress messages now shows 'x' for expected failures
1677and 'u' for unexpected successes when run in verbose mode.
1678(Contributed by Benjamin Peterson.)
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001679
1680Test cases can raise the :exc:`~unittest.SkipTest` exception to skip a
1681test. (:issue:`1034053`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001682
Ezio Melotti021f3342010-04-06 03:26:49 +00001683The error messages for :meth:`~unittest.TestCase.assertEqual`,
1684:meth:`~unittest.TestCase.assertTrue`, and :meth:`~unittest.TestCase.assertFalse`
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001685failures now provide more information. If you set the
Ezio Melotti021f3342010-04-06 03:26:49 +00001686:attr:`~unittest.TestCase.longMessage` attribute of your :class:`~unittest.TestCase` classes to
1687True, both the standard error message and any additional message you
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001688provide will be printed for failures. (Added by Michael Foord; :issue:`5663`.)
1689
Ezio Melotti021f3342010-04-06 03:26:49 +00001690The :meth:`~unittest.TestCase.assertRaises` method now
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001691return a context handler when called without providing a callable
1692object to run. For example, you can write this::
1693
1694 with self.assertRaises(KeyError):
Ezio Melotti021f3342010-04-06 03:26:49 +00001695 {}['foo']
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001696
1697(Implemented by Antoine Pitrou; :issue:`4444`.)
1698
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001699.. rev 78774
1700
1701Module- and class-level setup and teardown fixtures are now supported.
Ezio Melotti021f3342010-04-06 03:26:49 +00001702Modules can contain :func:`~unittest.setUpModule` and :func:`~unittest.tearDownModule`
1703functions. Classes can have :meth:`~unittest.TestCase.setUpClass` and
1704:meth:`~unittest.TestCase.tearDownClass` methods that must be defined as class methods
1705(using ``@classmethod`` or equivalent). These functions and
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001706methods are invoked when the test runner switches to a test case in a
1707different module or class.
1708
Ezio Melotti021f3342010-04-06 03:26:49 +00001709The methods :meth:`~unittest.TestCase.addCleanup` and
1710:meth:`~unittest.TestCase.doCleanups` were added.
1711:meth:`~unittest.TestCase.addCleanup` allows you to add cleanup functions that
1712will be called unconditionally (after :meth:`~unittest.TestCase.setUp` if
1713:meth:`~unittest.TestCase.setUp` fails, otherwise after :meth:`~unittest.TestCase.tearDown`). This allows
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001714for much simpler resource allocation and deallocation during tests
1715(:issue:`5679`).
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001716
1717A number of new methods were added that provide more specialized
1718tests. Many of these methods were written by Google engineers
1719for use in their test suites; Gregory P. Smith, Michael Foord, and
1720GvR worked on merging them into Python's version of :mod:`unittest`.
1721
Ezio Melotti021f3342010-04-06 03:26:49 +00001722* :meth:`~unittest.TestCase.assertIsNone` and :meth:`~unittest.TestCase.assertIsNotNone` take one
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001723 expression and verify that the result is or is not ``None``.
1724
Ezio Melotti021f3342010-04-06 03:26:49 +00001725* :meth:`~unittest.TestCase.assertIs` and :meth:`~unittest.TestCase.assertIsNot`
1726 take two values and check whether the two values evaluate to the same object or not.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001727 (Added by Michael Foord; :issue:`2578`.)
1728
Ezio Melotti021f3342010-04-06 03:26:49 +00001729* :meth:`~unittest.TestCase.assertIsInstance` and
1730 :meth:`~unittest.TestCase.assertNotIsInstance` check whether
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00001731 the resulting object is an instance of a particular class, or of
1732 one of a tuple of classes. (Added by Georg Brandl; :issue:`7031`.)
1733
Ezio Melotti021f3342010-04-06 03:26:49 +00001734* :meth:`~unittest.TestCase.assertGreater`, :meth:`~unittest.TestCase.assertGreaterEqual`,
1735 :meth:`~unittest.TestCase.assertLess`, and :meth:`~unittest.TestCase.assertLessEqual` compare
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001736 two quantities.
1737
Ezio Melotti021f3342010-04-06 03:26:49 +00001738* :meth:`~unittest.TestCase.assertMultiLineEqual` compares two strings, and if they're
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001739 not equal, displays a helpful comparison that highlights the
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001740 differences in the two strings. This comparison is now used by
Ezio Melotti021f3342010-04-06 03:26:49 +00001741 default when Unicode strings are compared with :meth:`~unittest.TestCase.assertEqual`.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001742
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001743* :meth:`~unittest.TestCase.assertRegexpMatches` and
1744 :meth:`~unittest.TestCase.assertNotRegexpMatches` checks whether the
1745 first argument is a string matching or not matching the regular
1746 expression provided as the second argument (:issue:`8038`).
Ezio Melotti021f3342010-04-06 03:26:49 +00001747
1748* :meth:`~unittest.TestCase.assertRaisesRegexp` checks whether a particular exception
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001749 is raised, and then also checks that the string representation of
1750 the exception matches the provided regular expression.
1751
Ezio Melotti021f3342010-04-06 03:26:49 +00001752* :meth:`~unittest.TestCase.assertIn` and :meth:`~unittest.TestCase.assertNotIn`
1753 tests whether *first* is or is not in *second*.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001754
Ezio Melotti021f3342010-04-06 03:26:49 +00001755* :meth:`~unittest.TestCase.assertItemsEqual` tests whether two provided sequences
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001756 contain the same elements.
1757
Ezio Melotti021f3342010-04-06 03:26:49 +00001758* :meth:`~unittest.TestCase.assertSetEqual` compares whether two sets are equal, and
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001759 only reports the differences between the sets in case of error.
1760
Ezio Melotti021f3342010-04-06 03:26:49 +00001761* Similarly, :meth:`~unittest.TestCase.assertListEqual` and :meth:`~unittest.TestCase.assertTupleEqual`
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001762 compare the specified types and explain any differences without necessarily
1763 printing their full values; these methods are now used by default
Ezio Melotti021f3342010-04-06 03:26:49 +00001764 when comparing lists and tuples using :meth:`~unittest.TestCase.assertEqual`.
1765 More generally, :meth:`~unittest.TestCase.assertSequenceEqual` compares two sequences
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001766 and can optionally check whether both sequences are of a
1767 particular type.
1768
Ezio Melotti021f3342010-04-06 03:26:49 +00001769* :meth:`~unittest.TestCase.assertDictEqual` compares two dictionaries and reports the
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001770 differences; it's now used by default when you compare two dictionaries
Ezio Melotti021f3342010-04-06 03:26:49 +00001771 using :meth:`~unittest.TestCase.assertEqual`. :meth:`~unittest.TestCase.assertDictContainsSubset` checks whether
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001772 all of the key/value pairs in *first* are found in *second*.
1773
Ezio Melotti021f3342010-04-06 03:26:49 +00001774* :meth:`~unittest.TestCase.assertAlmostEqual` and :meth:`~unittest.TestCase.assertNotAlmostEqual` test
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001775 whether *first* and *second* are approximately equal. This method
1776 can either round their difference to an optionally-specified number
1777 of *places* (the default is 7) and compare it to zero, or require
1778 the difference to be smaller than a supplied *delta* value.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001779
Ezio Melotti021f3342010-04-06 03:26:49 +00001780* :meth:`~unittest.TestLoader.loadTestsFromName` properly honors the
1781 :attr:`~unittest.TestLoader.suiteClass` attribute of
1782 the :class:`~unittest.TestLoader`. (Fixed by Mark Roddy; :issue:`6866`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001783
Ezio Melotti021f3342010-04-06 03:26:49 +00001784* A new hook lets you extend the :meth:`~unittest.TestCase.assertEqual` method to handle
1785 new data types. The :meth:`~unittest.TestCase.addTypeEqualityFunc` method takes a type
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001786 object and a function. The function will be used when both of the
1787 objects being compared are of the specified type. This function
1788 should compare the two objects and raise an exception if they don't
1789 match; it's a good idea for the function to provide additional
1790 information about why the two objects are matching, much as the new
1791 sequence comparison methods do.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001792
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001793:func:`unittest.main` now takes an optional ``exit`` argument. If
Ezio Melotti021f3342010-04-06 03:26:49 +00001794False, :func:`~unittest.main` doesn't call :func:`sys.exit`, allowing it to be
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001795used from the interactive interpreter. (Contributed by J. Pablo
1796Fernández; :issue:`3379`.)
1797
Ezio Melotti021f3342010-04-06 03:26:49 +00001798:class:`~unittest.TestResult` has new :meth:`~unittest.TestResult.startTestRun` and
1799:meth:`~unittest.TestResult.stopTestRun` methods that are called immediately before
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001800and after a test run. (Contributed by Robert Collins; :issue:`5728`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001801
1802With all these changes, the :file:`unittest.py` was becoming awkwardly
1803large, so the module was turned into a package and the code split into
1804several files (by Benjamin Peterson). This doesn't affect how the
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001805module is imported or used.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001806
1807
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001808.. _elementtree-section:
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001809
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001810Updated module: ElementTree 1.3
1811---------------------------------
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001812
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001813The version of the ElementTree library included with Python was updated to
1814version 1.3. Some of the new features in ElementTree 1.3 are:
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001815
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001816* The various parsing functions now take a *parser* keyword argument
1817 that can be used to provide an :class:`XMLParser` instance that will
1818 be used. This makes it possible to override the file's internal encoding:
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001819
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001820 p = ET.XMLParser(encoding='utf-8')
1821 t = ET.XML("""<root/>""", parser=p)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001822
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001823 Errors in parsing XML now raise a :exc:`ParseError` exception.
1824 Instances of :exc:`ParseError` have a :attr:`position` attribute
1825 containing a (*line*, *column*) tuple giving the location of the problem.
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001826
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001827* ElementTree's code for converting trees to a string has been
1828 significantly reworked, making it roughly twice as fast in many
1829 cases. The :class:`ElementTree` :meth:`write` and :class:`Element`
1830 :meth:`write` methods now have a *method* parameter that can be
1831 "xml" (the default), "html", or "text". HTML mode will output empty
1832 elements as ``<empty></empty>`` instead of ``<empty/>``, and text
1833 mode will skip over elements and only output the text chunks. If
1834 you set the :attr:`tag` attribute of an element to ``None`` but
1835 leaves its children in place, the element will be omitted when the
1836 tree is written out, so you don't need to do more extensive rearrangement
1837 to remove a single element.
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001838
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001839 Namespace aspects have also been improved. All the ``xmlns:<whatever>``
1840 declarations are now put on the root element and not scattered throughout
1841 the resulting output. You can set the default namespace for a tree
1842 by setting the :attr:`default_namespace` attribute and can
1843 register new prefixes with :meth:`regsiter_namespace`. In XML mode,
1844 you can use the true/false *xml_declaration* parameter to suppress the
1845 XML declaration.
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001846
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001847* New :class:`Element` method: :meth:`extend` appends the items from a
1848 sequence to the element's children. Elements themselves behave like
1849 sequences, so it's easy to move children from one element to
1850 another::
Andrew M. Kuchlinga17cd4a2009-01-31 02:50:09 +00001851
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001852 from xml.etree import ElementTree as ET
Andrew M. Kuchlinga17cd4a2009-01-31 02:50:09 +00001853
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001854 t = ET.XML("""<list>
1855 <item>1</item> <item>2</item> <item>3</item>
1856 </list>""")
1857 new = ET.XML('<root/>')
1858 new.extend(t)
Andrew M. Kuchlinga17cd4a2009-01-31 02:50:09 +00001859
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001860 # Outputs <root><item>1</item>...</root>
1861 print ET.tostring(new)
Andrew M. Kuchlinga17cd4a2009-01-31 02:50:09 +00001862
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001863* New :class:`Element` method: :meth:`iter` yields the children of the
1864 element as a generator. It's also possible to write ``for child in
1865 elem: ...`` to loop over an element's children. The existing method
1866 :meth:`getiterator` is now deprecated. :meth:`getchildren` is
1867 another similar method that constructs and returns a list of
1868 children; it's also deprecated.
Georg Brandl0516f812009-11-18 18:52:35 +00001869
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001870* New :class:`Element` method: :meth:`itertext` yields all chunks of
1871 text that are descendants of the element. For example::
Georg Brandl0516f812009-11-18 18:52:35 +00001872
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001873 t = ET.XML("""<list>
1874 <item>1</item> <item>2</item> <item>3</item>
1875 </list>""")
1876
1877 # Outputs ['\n ', '1', ' ', '2', ' ', '3', '\n']
1878 print list(t.itertext())
1879
1880* Deprecated: using an element as a Boolean (i.e., ``if elem: ...``)
1881 would return true if the element had any children, or false if
1882 there were no children. This behaviour will eventually change or be removed
1883 because it's confusing (``None`` is false, but so is a childless element?),
1884 so it will now trigger a :exc:`FutureWarning`. In your code,
1885 you should be explicit: write ``len(elem) != 0`` if you're interested in
1886 the number of children, or ``elem is not None`` Instead,
1887
1888Fredrik Lundh develops ElementTree and produced the 1.3 version;
1889you can read his article describing 1.3 at
1890http://effbot.org/zone/elementtree-13-intro.htm.
1891Florent Xicluna updated the version included with
1892Python, after discussions on python-dev and in :issue:`6472`.)
Georg Brandl0516f812009-11-18 18:52:35 +00001893
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001894.. ======================================================================
1895
1896
1897Build and C API Changes
1898=======================
1899
1900Changes to Python's build process and to the C API include:
1901
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001902* The latest release of the GNU Debugger, GDB 7, can be `scripted
1903 using Python
1904 <http://sourceware.org/gdb/current/onlinedocs/gdb/Python.html>`__.
1905 When you begin debugging an executable program P, GDB will look for
1906 a file named ``P-gdb.py`` and automatically read it. Dave Malcolm
1907 contributed a :file:`python-gdb.py` that adds a number of useful
1908 commands when debugging Python itself. For example, there are
1909 ``py-up`` and ``py-down`` that go up or down one Python stack frame,
1910 which usually corresponds to several C stack frames. ``py-print``
1911 prints the value of a Python variable, and ``py-bt`` prints the
1912 Python stack trace. (Added as a result of :issue:`8032`.)
1913
Andrew M. Kuchling10b1ec92009-01-02 21:00:35 +00001914* If you use the :file:`.gdbinit` file provided with Python,
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001915 the "pyo" macro in the 2.7 version now works correctly when the thread being
1916 debugged doesn't hold the GIL; the macro now acquires it before printing.
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001917 (Contributed by Victor Stinner; :issue:`3632`.)
1918
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001919* :cfunc:`Py_AddPendingCall` is now thread-safe, letting any
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001920 worker thread submit notifications to the main Python thread. This
1921 is particularly useful for asynchronous IO operations.
1922 (Contributed by Kristjan Valur Jonsson; :issue:`4293`.)
1923
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001924* New function: :cfunc:`PyCode_NewEmpty` creates an empty code object;
1925 only the filename, function name, and first line number are required.
1926 This is useful to extension modules that are attempting to
1927 construct a more useful traceback stack. Previously such
1928 extensions needed to call :cfunc:`PyCode_New`, which had many
1929 more arguments. (Added by Jeffrey Yasskin.)
1930
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001931* New function: :cfunc:`PyErr_NewExceptionWithDoc` creates a new
1932 exception class, just as the existing :cfunc:`PyErr_NewException` does,
1933 but takes an extra ``char *`` argument containing the docstring for the
1934 new exception class. (Added by the 'lekma' user on the Python bug tracker;
1935 :issue:`7033`.)
1936
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001937* New function: :cfunc:`PyFrame_GetLineNumber` takes a frame object
1938 and returns the line number that the frame is currently executing.
1939 Previously code would need to get the index of the bytecode
1940 instruction currently executing, and then look up the line number
1941 corresponding to that address. (Added by Jeffrey Yasskin.)
1942
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001943* New functions: :cfunc:`PyLong_AsLongAndOverflow` and
1944 :cfunc:`PyLong_AsLongLongAndOverflow` approximates a Python long
1945 integer as a C :ctype:`long` or :ctype:`long long`.
1946 If the number is too large to fit into
1947 the output type, an *overflow* flag is set and returned to the caller.
1948 (Contributed by Case Van Horsen; :issue:`7528` and :issue:`7767`.)
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001949
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00001950* New function: stemming from the rewrite of string-to-float conversion,
1951 a new :cfunc:`PyOS_string_to_double` function was added. The old
1952 :cfunc:`PyOS_ascii_strtod` and :cfunc:`PyOS_ascii_atof` functions
1953 are now deprecated.
1954
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001955* New macros: the Python header files now define the following macros:
1956 :cmacro:`Py_ISALNUM`,
1957 :cmacro:`Py_ISALPHA`,
1958 :cmacro:`Py_ISDIGIT`,
1959 :cmacro:`Py_ISLOWER`,
1960 :cmacro:`Py_ISSPACE`,
1961 :cmacro:`Py_ISUPPER`,
1962 :cmacro:`Py_ISXDIGIT`,
1963 and :cmacro:`Py_TOLOWER`, :cmacro:`Py_TOUPPER`.
1964 All of these functions are analogous to the C
1965 standard macros for classifying characters, but ignore the current
1966 locale setting, because in
1967 several places Python needs to analyze characters in a
1968 locale-independent way. (Added by Eric Smith;
1969 :issue:`5793`.)
1970
1971 .. XXX these macros don't seem to be described in the c-api docs.
1972
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00001973* Removed function: :cmacro:`PyEval_CallObject` is now only available
1974 as a macro. A function version was being kept around to preserve
1975 ABI linking compatibility, but that was in 1997; it can certainly be
1976 deleted. (Removed by Antoine Pitrou; :issue:`8276`.)
1977
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001978* New format codes: the :cfunc:`PyFormat_FromString`,
1979 :cfunc:`PyFormat_FromStringV`, and :cfunc:`PyErr_Format` now
1980 accepts ``%lld`` and ``%llu`` format codes for displaying values of
1981 C's :ctype:`long long` types.
1982 (Contributed by Mark Dickinson; :issue:`7228`.)
1983
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001984* The complicated interaction between threads and process forking has
1985 been changed. Previously, the child process created by
1986 :func:`os.fork` might fail because the child is created with only a
1987 single thread running, the thread performing the :func:`os.fork`.
1988 If other threads were holding a lock, such as Python's import lock,
1989 when the fork was performed, the lock would still be marked as
1990 "held" in the new process. But in the child process nothing would
1991 ever release the lock, since the other threads weren't replicated,
1992 and the child process would no longer be able to perform imports.
1993
1994 Python 2.7 now acquires the import lock before performing an
1995 :func:`os.fork`, and will also clean up any locks created using the
1996 :mod:`threading` module. C extension modules that have internal
1997 locks, or that call :cfunc:`fork()` themselves, will not benefit
1998 from this clean-up.
1999
2000 (Fixed by Thomas Wouters; :issue:`1590864`.)
2001
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00002002* The :cfunc:`Py_Finalize` function now calls the internal
2003 :func:`threading._shutdown` function; this prevents some exceptions from
2004 being raised when an interpreter shuts down.
2005 (Patch by Adam Olsen; :issue:`1722344`.)
2006
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002007* When using the :ctype:`PyMemberDef` structure to define attributes
2008 of a type, Python will no longer let you try to delete or set a
2009 :const:`T_STRING_INPLACE` attribute.
2010
2011 .. rev 79644
2012
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00002013* Global symbols defined by the :mod:`ctypes` module are now prefixed
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002014 with ``Py``, or with ``_ctypes``. (Implemented by Thomas
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00002015 Heller; :issue:`3102`.)
2016
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00002017* New configure option: the :option:`--with-system-expat` switch allows
2018 building the :mod:`pyexpat` module to use the system Expat library.
2019 (Contributed by Arfrever Frehtes Taifersar Arahesis; :issue:`7609`.)
2020
Andrew M. Kuchlingce690522010-04-13 01:32:51 +00002021* New configure option: compiling Python with the
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00002022 :option:`--with-valgrind` option will now disable the pymalloc
Andrew M. Kuchlingce690522010-04-13 01:32:51 +00002023 allocator, which is difficult for the Valgrind memory-error detector
2024 to analyze correctly.
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00002025 Valgrind will therefore be better at detecting memory leaks and
2026 overruns. (Contributed by James Henstridge; :issue:`2422`.)
2027
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +00002028* New configure option: you can now supply no arguments to
2029 :option:`--with-dbmliborder=` in order to build none of the various
2030 DBM modules. (Added by Arfrever Frehtes Taifersar Arahesis;
2031 :issue:`6491`.)
2032
Andrew M. Kuchling77069572009-03-31 01:21:01 +00002033* The :program:`configure` script now checks for floating-point rounding bugs
2034 on certain 32-bit Intel chips and defines a :cmacro:`X87_DOUBLE_ROUNDING`
2035 preprocessor definition. No code currently uses this definition,
2036 but it's available if anyone wishes to use it.
2037 (Added by Mark Dickinson; :issue:`2937`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002038
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00002039 :program:`configure` also now sets a :envvar:`LDCXXSHARED` Makefile
2040 variable for supporting C++ linking. (Contributed by Arfrever
2041 Frehtes Taifersar Arahesis; :issue:`1222585`.)
2042
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002043* The build process now creates the necessary files for pkg-config
2044 support. (Contributed by Clinton Roy; :issue:`3585`.)
2045
2046* The build process now supports Subversion 1.7. (Contributed by
2047 Arfrever Frehtes Taifersar Arahesis; :issue:`6094`.)
2048
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00002049
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002050.. ======================================================================
2051
2052Port-Specific Changes: Windows
2053-----------------------------------
2054
Andrew M. Kuchling10b1ec92009-01-02 21:00:35 +00002055* The :mod:`msvcrt` module now contains some constants from
2056 the :file:`crtassem.h` header file:
2057 :data:`CRT_ASSEMBLY_VERSION`,
2058 :data:`VC_ASSEMBLY_PUBLICKEYTOKEN`,
2059 and :data:`LIBRARIES_ASSEMBLY_NAME_PREFIX`.
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00002060 (Contributed by David Cournapeau; :issue:`4365`.)
2061
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002062* The :mod:`_winreg` module for accessing the registry now implements
2063 the :func:`CreateKeyEx` and :func:`DeleteKeyEx` functions, extended
2064 versions of previously-supported functions that take several extra
2065 arguments. The :func:`DisableReflectionKey`,
2066 :func:`EnableReflectionKey`, and :func:`QueryReflectionKey` were also
2067 tested and documented.
2068 (Implemented by Brian Curtin: :issue:`7347`.)
2069
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00002070* The new :cfunc:`_beginthreadex` API is used to start threads, and
2071 the native thread-local storage functions are now used.
2072 (Contributed by Kristjan Valur Jonsson; :issue:`3582`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002073
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +00002074* The :func:`os.kill` function now works on Windows. The signal value
2075 can be the constants :const:`CTRL_C_EVENT`,
2076 :const:`CTRL_BREAK_EVENT`, or any integer. The Control-C and
2077 Control-Break keystroke events can be sent to subprocesses; any
2078 other value will use the :cfunc:`TerminateProcess` API.
2079 (Contributed by Miki Tebeka; :issue:`1220212`.)
2080
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002081* The :func:`os.listdir` function now correctly fails
2082 for an empty path. (Fixed by Hirokazu Yamamoto; :issue:`5913`.)
2083
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00002084* The :mod:`mimelib` module will now read the MIME database from
2085 the Windows registry when initializing.
2086 (Patch by Gabriel Genellina; :issue:`4969`.)
2087
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002088.. ======================================================================
2089
2090Port-Specific Changes: Mac OS X
2091-----------------------------------
2092
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002093* The path ``/Library/Python/2.7/site-packages`` is now appended to
Andrew M. Kuchling77069572009-03-31 01:21:01 +00002094 ``sys.path``, in order to share added packages between the system
2095 installation and a user-installed copy of the same version.
2096 (Changed by Ronald Oussoren; :issue:`4865`.)
2097
Andrew M. Kuchling04b99cc2010-05-04 01:24:22 +00002098Port-Specific Changes: FreeBSD
2099-----------------------------------
2100
2101* FreeBSD 7.1's :const:`SO_SETFIB` constant, used with
2102 :func:`~socket.getsockopt`/:func:`~socket.setsockopt` to select an
2103 alternate routing table, is now available in the :mod:`socket`
2104 module. (Added by Kyle VanderBeek; :issue:`8235`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002105
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00002106Other Changes and Fixes
2107=======================
2108
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00002109* Two benchmark scripts, :file:`iobench` and :file:`ccbench`, were
2110 added to the :file:`Tools` directory. :file:`iobench` measures the
Antoine Pitroudde96e62010-02-08 20:25:47 +00002111 speed of built-in file I/O objects (as returned by :func:`open`)
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00002112 while performing various operations, and :file:`ccbench` is a
2113 concurrency benchmark that tries to measure computing throughput,
2114 thread switching latency, and IO processing bandwidth when
2115 performing several tasks using a varying number of threads.
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00002116
Andrew M. Kuchling77069572009-03-31 01:21:01 +00002117* When importing a module from a :file:`.pyc` or :file:`.pyo` file
2118 with an existing :file:`.py` counterpart, the :attr:`co_filename`
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00002119 attributes of the resulting code objects are overwritten when the
2120 original filename is obsolete. This can happen if the file has been
2121 renamed, moved, or is accessed through different paths. (Patch by
2122 Ziga Seilnacht and Jean-Paul Calderone; :issue:`1180193`.)
Andrew M. Kuchling77069572009-03-31 01:21:01 +00002123
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00002124* The :file:`regrtest.py` script now takes a :option:`--randseed=`
2125 switch that takes an integer that will be used as the random seed
2126 for the :option:`-r` option that executes tests in random order.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002127 The :option:`-r` option also reports the seed that was used
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00002128 (Added by Collin Winter.)
2129
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00002130* Another :file:`regrtest.py` switch is :option:`-j`, which
2131 takes an integer specifying how many tests run in parallel. This
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002132 allows reducing the total runtime on multi-core machines.
Antoine Pitrou4698d992009-05-31 14:20:14 +00002133 This option is compatible with several other options, including the
2134 :option:`-R` switch which is known to produce long runtimes.
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00002135 (Added by Antoine Pitrou, :issue:`6152`.) This can also be used
2136 with a new :option:`-F` switch that runs selected tests in a loop
2137 until they fail. (Added by Antoine Pitrou; :issue:`7312`.)
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00002138
Andrew M. Kuchling85f928a2010-04-15 01:42:27 +00002139* When executed as a script, the :file:`py_compile.py` module now
2140 accepts ``'-'`` as an argument, which will read standard input for
2141 the list of filenames to be compiled. (Contributed by Piotr
2142 Ożarowski; :issue:`8233`.)
2143
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002144.. ======================================================================
2145
2146Porting to Python 2.7
2147=====================
2148
2149This section lists previously described changes and other bugfixes
2150that may require changes to your code:
2151
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00002152* The :func:`range` function processes its arguments more
2153 consistently; it will now call :meth:`__int__` on non-float,
2154 non-integer arguments that are supplied to it. (Fixed by Alexander
2155 Belopolsky; :issue:`1533`.)
2156
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002157* The string :meth:`format` method changed the default precision used
2158 for floating-point and complex numbers from 6 decimal
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002159 places to 12, which matches the precision used by :func:`str`.
2160 (Changed by Eric Smith; :issue:`5920`.)
2161
Amaury Forgeot d'Arc901f2002009-06-09 23:08:13 +00002162* Because of an optimization for the :keyword:`with` statement, the special
2163 methods :meth:`__enter__` and :meth:`__exit__` must belong to the object's
2164 type, and cannot be directly attached to the object's instance. This
Amaury Forgeot d'Arcd81333c2009-06-10 20:30:19 +00002165 affects new-style classes (derived from :class:`object`) and C extension
Amaury Forgeot d'Arc901f2002009-06-09 23:08:13 +00002166 types. (:issue:`6101`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002167
Andrew M. Kuchling837a5382010-05-06 17:21:59 +00002168* Due to a bug in Python 2.6, the *exc_value* parameter to
2169 :meth:`__exit__` methods was often the string representation of the
2170 exception, not an instance. This was fixed in 2.7, so *exc_value*
2171 will be an instance as expected. (Fixed by Florent Xicluna;
2172 :issue:`7853`.)
2173
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00002174* When a restricted set of attributes were set using ``__slots__``,
2175 deleting an unset attribute would not raise :exc:`AttributeError`
2176 as you would expect. Fixed by Benjamin Peterson; :issue:`7604`.)
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002177
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00002178In the standard library:
2179
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002180* When using :class:`Decimal` instances with a string's
2181 :meth:`format` method, the default alignment was previously
2182 left-alignment. This has been changed to right-alignment, which might
2183 change the output of your programs.
2184 (Changed by Mark Dickinson; :issue:`6857`.)
2185
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00002186 Comparisons involving a signaling NaN value (or ``sNAN``) now signal
2187 :const:`InvalidOperation` instead of silently returning a true or
2188 false value depending on the comparison operator. Quiet NaN values
2189 (or ``NaN``) are now hashable. (Fixed by Mark Dickinson;
2190 :issue:`7279`.)
2191
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00002192* The ElementTree library, :mod:`xml.etree`, no longer escapes
2193 ampersands and angle brackets when outputting an XML processing
2194 instruction (which looks like `<?xml-stylesheet href="#style1"?>`)
2195 or comment (which looks like `<!-- comment -->`).
2196 (Patch by Neil Muller; :issue:`2746`.)
2197
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00002198* The :meth:`readline` method of :class:`StringIO` objects now does
2199 nothing when a negative length is requested, as other file-like
2200 objects do. (:issue:`7348`).
2201
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002202* The :mod:`syslog` module will now use the value of ``sys.argv[0]`` as the
2203 identifier instead of the previous default value of ``'python'``.
2204 (Changed by Sean Reifschneider; :issue:`8451`.)
2205
Andrew M. Kuchling04b99cc2010-05-04 01:24:22 +00002206* The :mod:`urlparse` module's :func:`~urlparse.urlsplit` now handles
2207 unknown URL schemes in a fashion compliant with :rfc:`3986`: if the
2208 URL is of the form ``"<something>://..."``, the text before the
2209 ``://`` is treated as the scheme, even if it's a made-up scheme that
2210 the module doesn't know about. This change may break code that
2211 worked around the old behaviour. For example, Python 2.6.4 or 2.5
2212 will return the following:
2213
2214 >>> import urlparse
2215 >>> urlparse.urlsplit('invented://host/filename?query')
2216 ('invented', '', '//host/filename?query', '', '')
2217
2218 Python 2.7 (and Python 2.6.5) will return:
2219
2220 >>> import urlparse
2221 >>> urlparse.urlsplit('invented://host/filename?query')
2222 ('invented', 'host', '/filename?query', '', '')
2223
2224 (Python 2.7 actually produces slightly different output, since it
2225 returns a named tuple instead of a standard tuple.)
2226
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00002227For C extensions:
2228
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +00002229* C extensions that use integer format codes with the ``PyArg_Parse*``
2230 family of functions will now raise a :exc:`TypeError` exception
2231 instead of triggering a :exc:`DeprecationWarning` (:issue:`5080`).
2232
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00002233* Use the new :cfunc:`PyOS_string_to_double` function instead of the old
2234 :cfunc:`PyOS_ascii_strtod` and :cfunc:`PyOS_ascii_atof` functions,
2235 which are now deprecated.
2236
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +00002237
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002238.. ======================================================================
2239
2240
2241.. _acks27:
2242
2243Acknowledgements
2244================
2245
2246The author would like to thank the following people for offering
2247suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00002248article: Nick Coghlan, Ryan Lovett, R. David Murray, Hugh Secker-Walker.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002249