blob: cc073c28dca8537be58d79b23d77db225925402b [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. Kuchlingca485622010-05-06 01:10:56 +000011.. Big jobs: ElementTree 1.3, pep 391
Andrew M. Kuchling6d7dfa22010-04-11 12:49:37 +000012.. hyperlink all the methods & functions.
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +000013
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +000014.. T_STRING_INPLACE not described in main docs
15
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000016.. $Id$
17 Rules for maintenance:
18
19 * Anyone can add text to this document. Do not spend very much time
20 on the wording of your changes, because your text will probably
21 get rewritten to some degree.
22
23 * The maintainer will go through Misc/NEWS periodically and add
24 changes; it's therefore more important to add your changes to
25 Misc/NEWS than to this file.
26
27 * This is not a complete list of every single change; completeness
28 is the purpose of Misc/NEWS. Some changes I consider too small
29 or esoteric to include. If such a change is added to the text,
30 I'll just remove it. (This is another reason you shouldn't spend
31 too much time on writing your addition.)
32
33 * If you want to draw your new text to the attention of the
34 maintainer, add 'XXX' to the beginning of the paragraph or
35 section.
36
37 * It's OK to just add a fragmentary note about a change. For
38 example: "XXX Describe the transmogrify() function added to the
39 socket module." The maintainer will research the change and
40 write the necessary text.
41
42 * You can comment out your additions if you like, but it's not
43 necessary (especially when a final release is some months away).
44
Ezio Melotti021f3342010-04-06 03:26:49 +000045 * Credit the author of a patch or bugfix. Just the name is
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000046 sufficient; the e-mail address isn't necessary.
47
48 * It's helpful to add the bug/patch number in a parenthetical comment.
49
50 XXX Describe the transmogrify() function added to the socket
51 module.
52 (Contributed by P.Y. Developer; :issue:`12345`.)
53
54 This saves the maintainer some effort going through the SVN logs
55 when researching a change.
56
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +000057This article explains the new features in Python 2.7. The final
58release of 2.7 is currently scheduled for June 2010; the detailed
59schedule is described in :pep:`373`.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000060
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +000061Python 2.7 is planned to be the last major release in the 2.x series.
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +000062Though more major releases have not been absolutely ruled out, the
63Python maintainers are planning to focus more on Python 3.x. Despite
64that, it's likely that the 2.7 release will have a longer period of
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +000065maintenance compared to earlier 2.x versions.
66
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000067.. Compare with previous release in 2 - 3 sentences here.
68 add hyperlink when the documentation becomes available online.
69
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +000070.. _whatsnew27-python31:
71
72Python 3.1 Features
73=======================
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +000074
75Much as Python 2.6 incorporated features from Python 3.0,
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +000076version 2.7 incorporates some of the new features
77in Python 3.1. The 2.x series continues to provide tools
78for migrating to the 3.x series.
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +000079
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +000080A partial list of 3.1 features that were backported to 2.7:
81
82* A version of the :mod:`io` library, rewritten in C for performance.
83* The ordered-dictionary type described in :ref:`pep-0372`.
Andrew M. Kuchling8f254e72009-12-08 02:37:05 +000084* The new format specifier described in :ref:`pep-0378`.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +000085* The :class:`memoryview` object.
86* A small subset of the :mod:`importlib` module `described below <#importlib-section>`__.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +000087* Float-to-string and string-to-float conversions now round their
88 results more correctly. And :func:`repr` of a floating-point
89 number *x* returns a result that's guaranteed to round back to the
90 same number when converted back to a string.
91* The :cfunc:`PyLong_AsLongAndOverflow` C API function.
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +000092
93One porting change: the :option:`-3` switch now automatically
94enables the :option:`-Qwarn` switch that causes warnings
95about using classic division with integers and long integers.
96
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +000097Other new Python3-mode warnings include:
98
99* :func:`operator.isCallable` and :func:`operator.sequenceIncludes`,
100 which are not supported in 3.x.
101
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000102.. ========================================================================
103.. Large, PEP-level features and changes should be described here.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000104.. ========================================================================
105
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000106.. _pep-0372:
107
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000108PEP 372: Adding an ordered dictionary to collections
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000109====================================================
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000110
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000111Regular Python dictionaries iterate over key/value pairs in arbitrary order.
112Over the years, a number of authors have written alternative implementations
113that remember the order that the keys were originally inserted. Based on
114the experiences from those implementations, a new
Ezio Melotti021f3342010-04-06 03:26:49 +0000115:class:`~collections.OrderedDict` class has been introduced in the
116:mod:`collections` module.
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000117
Ezio Melotti021f3342010-04-06 03:26:49 +0000118The :class:`~collections.OrderedDict` API is substantially the same as regular
119dictionaries but will iterate over keys and values in a guaranteed order
120depending on when a key was first inserted::
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000121
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000122 >>> from collections import OrderedDict
123 >>> d = OrderedDict([('first', 1), ('second', 2),
124 ... ('third', 3)])
125 >>> d.items()
126 [('first', 1), ('second', 2), ('third', 3)]
127
128If a new entry overwrites an existing entry, the original insertion
129position is left unchanged::
130
131 >>> d['second'] = 4
132 >>> d.items()
133 [('first', 1), ('second', 4), ('third', 3)]
134
135Deleting an entry and reinserting it will move it to the end::
136
137 >>> del d['second']
138 >>> d['second'] = 5
139 >>> d.items()
140 [('first', 1), ('third', 3), ('second', 5)]
141
Ezio Melotti021f3342010-04-06 03:26:49 +0000142The :meth:`~collections.OrderedDict.popitem` method has an optional *last*
143argument that defaults to True. If *last* is True, the most recently
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000144added key is returned and removed; if it's False, the
145oldest key is selected::
146
147 >>> od = OrderedDict([(x,0) for x in range(20)])
148 >>> od.popitem()
149 (19, 0)
150 >>> od.popitem()
151 (18, 0)
Ezio Melotti021f3342010-04-06 03:26:49 +0000152 >>> od.popitem(last=False)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000153 (0, 0)
Ezio Melotti021f3342010-04-06 03:26:49 +0000154 >>> od.popitem(last=False)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000155 (1, 0)
156
157Comparing two ordered dictionaries checks both the keys and values,
158and requires that the insertion order was the same::
159
160 >>> od1 = OrderedDict([('first', 1), ('second', 2),
161 ... ('third', 3)])
162 >>> od2 = OrderedDict([('third', 3), ('first', 1),
163 ... ('second', 2)])
Ezio Melotti021f3342010-04-06 03:26:49 +0000164 >>> od1 == od2
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000165 False
166 >>> # Move 'third' key to the end
Ezio Melotti021f3342010-04-06 03:26:49 +0000167 >>> del od2['third']; od2['third'] = 3
168 >>> od1 == od2
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000169 True
170
Ezio Melotti021f3342010-04-06 03:26:49 +0000171Comparing an :class:`~collections.OrderedDict` with a regular dictionary
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000172ignores the insertion order and just compares the keys and values.
173
Ezio Melotti021f3342010-04-06 03:26:49 +0000174How does the :class:`~collections.OrderedDict` work? It maintains a
175doubly-linked list of keys, appending new keys to the list as they're inserted.
176A secondary dictionary maps keys to their corresponding list node, so
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000177deletion doesn't have to traverse the entire linked list and therefore
178remains O(1).
179
180.. XXX check O(1)-ness with Raymond
Ezio Melotti021f3342010-04-06 03:26:49 +0000181.. Also check if the 'somenamedtuple' in the collection module should
182.. be replaced/removed in order to use
183.. :meth:`~collections.namedtuple._asdict()` (see below)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000184
185The standard library now supports use of ordered dictionaries in several
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +0000186modules.
187
188* The :mod:`ConfigParser` module uses them by default, letting
189 configuration files be read, modified, and then written back in their original
190 order.
191
192* The :meth:`~collections.somenamedtuple._asdict()` method for
193 :func:`collections.namedtuple` now returns an ordered dictionary with the
194 values appearing in the same order as the underlying tuple indices.
195
196* The :mod:`json` module's :class:`~json.JSONDecoder` class
197 constructor was extended with an *object_pairs_hook* parameter to
198 allow :class:`OrderedDict` instances to be built by the decoder.
199 Support was also added for third-party tools like
200 `PyYAML <http://pyyaml.org/>`_.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000201
Andrew M. Kuchling7fe65a02009-10-13 15:49:33 +0000202.. seealso::
203
204 :pep:`372` - Adding an ordered dictionary to collections
205 PEP written by Armin Ronacher and Raymond Hettinger;
206 implemented by Raymond Hettinger.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000207
208.. _pep-0378:
209
210PEP 378: Format Specifier for Thousands Separator
Ezio Melotti021f3342010-04-06 03:26:49 +0000211=================================================
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000212
213To make program output more readable, it can be useful to add
214separators to large numbers and render them as
21518,446,744,073,709,551,616 instead of 18446744073709551616.
216
217The fully general solution for doing this is the :mod:`locale` module,
218which can use different separators ("," in North America, "." in
219Europe) and different grouping sizes, but :mod:`locale` is complicated
220to use and unsuitable for multi-threaded applications where different
221threads are producing output for different locales.
222
223Therefore, a simple comma-grouping mechanism has been added to the
Ezio Melotti021f3342010-04-06 03:26:49 +0000224mini-language used by the :meth:`str.format` method. When
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000225formatting a floating-point number, simply include a comma between the
226width and the precision::
227
Eric Smithc4663852010-04-06 14:30:15 +0000228 >>> '{:20,.2f}'.format(18446744073709551616.0)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000229 '18,446,744,073,709,551,616.00'
230
Eric Smith6a928602010-04-06 15:17:33 +0000231When formatting an integer, include the comma after the width:
232
233 >>> '{:20,d}'.format(18446744073709551616)
234 '18,446,744,073,709,551,616'
235
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000236This mechanism is not adaptable at all; commas are always used as the
237separator and the grouping is always into three-digit groups. The
238comma-formatting mechanism isn't as general as the :mod:`locale`
239module, but it's easier to use.
240
Andrew M. Kuchling85ea4bf2009-10-05 22:45:39 +0000241.. XXX "Format String Syntax" in string.rst could use many more examples.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000242
243.. seealso::
244
245 :pep:`378` - Format Specifier for Thousands Separator
246 PEP written by Raymond Hettinger; implemented by Eric Smith.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000247
Andrew M. Kuchlingab21f752010-03-02 13:55:33 +0000248PEP 389: The argparse Module for Parsing Command Lines
249======================================================
250
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000251The :mod:`argparse` module for parsing command-line arguments was
252added, intended as a more powerful replacement for the
253:mod:`optparse` module.
254
255This means Python now supports three different modules for parsing
256command-line arguments: :mod:`getopt`, :mod:`optparse`, and
257:mod:`argparse`. The :mod:`getopt` module closely resembles the C
258:cfunc:`getopt` function, so it remains useful if you're writing a
259Python prototype that will eventually be rewritten in C.
260:mod:`optparse` becomes redundant, but there are no plans to remove it
261because there are many scripts still using it, and there's no
262automated way to update these scripts. (Making the :mod:`argparse`
263API consistent with :mod:`optparse`'s interface was discussed but
264rejected as too messy and difficult.)
265
Andrew M. Kuchlingf03641a2010-04-14 01:14:59 +0000266In short, if you're writing a new script and don't need to worry
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000267about compatibility with earlier versions of Python, use
268:mod:`argparse` instead of :mod:`optparse`.
269
Andrew M. Kuchlingf03641a2010-04-14 01:14:59 +0000270Here's an example::
271
272 import argparse
273
274 parser = argparse.ArgumentParser(description='Command-line example.')
275
276 # Add optional switches
277 parser.add_argument('-v', action='store_true', dest='is_verbose',
278 help='produce verbose output')
279 parser.add_argument('-o', action='store', dest='output',
280 metavar='FILE',
281 help='direct output to FILE instead of stdout')
282 parser.add_argument('-C', action='store', type=int, dest='context',
283 metavar='NUM', default=0,
284 help='display NUM lines of added context')
285
286 # Allow any number of additional arguments.
287 parser.add_argument(nargs='*', action='store', dest='inputs',
288 help='input filenames (default is stdin)')
289
290 args = parser.parse_args()
291 print args.__dict__
292
293Unless you override it, :option:`-h` and :option:`--help` switches
294are automatically added, and produce neatly formatted output::
295
296 -> ./python.exe argparse-example.py --help
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +0000297 usage: argparse-example.py [-h] [-v] [-o FILE] [-C NUM] [inputs [inputs ...]]
Andrew M. Kuchlingf03641a2010-04-14 01:14:59 +0000298
299 Command-line example.
300
301 positional arguments:
302 inputs input filenames (default is stdin)
303
304 optional arguments:
305 -h, --help show this help message and exit
306 -v produce verbose output
307 -o FILE direct output to FILE instead of stdout
308 -C NUM display NUM lines of added context
309
310Similarly to :mod:`optparse`, the command-line switches and arguments
311are returned as an object with attributes named by the *dest* parameters::
312
313 -> ./python.exe argparse-example.py -v
314 {'output': None, 'is_verbose': True, 'context': 0, 'inputs': []}
315
316 -> ./python.exe argparse-example.py -v -o /tmp/output -C 4 file1 file2
317 {'output': '/tmp/output', 'is_verbose': True, 'context': 4,
318 'inputs': ['file1', 'file2']}
319
320:mod:`argparse` has much fancier validation than :mod:`optparse`; you
321can specify an exact number of arguments as an integer, 0 or more
322arguments by passing ``'*'``, 1 or more by passing ``'+'``, or an
323optional argument with ``'?'``. A top-level parser can contain
324sub-parsers, so you can define subcommands that have different sets of
325switches, as in ``svn commit``, ``svn checkout``, etc. You can
326specify an argument type as :class:`~argparse.FileType`, which will
327automatically open files for you and understands that ``'-'`` means
328standard input or output.
Andrew M. Kuchlingab21f752010-03-02 13:55:33 +0000329
330.. seealso::
331
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000332 `argparse module documentation <http://docs.python.org/dev/library/argparse.html>`__
333
334 `Upgrading optparse code to use argparse <http://docs.python.org/dev/library/argparse.html#upgrading-optparse-code>`__
335
Andrew M. Kuchlingab21f752010-03-02 13:55:33 +0000336 :pep:`389` - argparse - New Command Line Parsing Module
337 PEP written and implemented by Steven Bethard.
338
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000339PEP 391: Dictionary-Based Configuration For Logging
340====================================================
341
Andrew M. Kuchlingb6c1aeb2010-04-14 14:28:31 +0000342.. not documented in library reference yet.
343
344The :mod:`logging` module is very flexible; an application can define
345a tree of logging subsystems, and each logger in this tree can filter
346out certain messages, format them differently, and direct messages to
347a varying number of handlers.
348
349All this flexibility can require a lot of configuration. You can
350write Python statements to create objects and set their properties,
351but a complex set-up would require verbose but boring code.
352:mod:`logging` also supports a :func:`~logging.config.fileConfig`
353function that parses a file, but the file format doesn't support
354configuring filters, and it's messier to generate programmatically.
355
356Python 2.7 adds a :func:`~logging.config.dictConfig` function that
357uses a dictionary, and there are many ways to produce a dictionary
358from different sources. You can construct one with code, of course.
359Python's standard library now includes a JSON parser, so you could
360parse a file containing JSON, or you could use a YAML parsing library
361if one is installed.
362
363XXX describe an example.
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000364
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000365Two smaller enhancements to the logging module are:
366
367.. rev79293
368
369* :class:`Logger` instances gained a :meth:`getChild` that retrieves a
370 descendant logger using a relative path. For example,
371 once you retrieve a logger by doing ``log = getLogger('app')``,
372 calling ``log.getChild('network.listen')`` is equivalent to
373 ``getLogger('app.network.listen')``.
374
375* The :class:`LoggerAdapter` class gained a :meth:`isEnabledFor` method
376 that takes a *level* and returns whether the underlying logger would
377 process a message of that level of importance.
378
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000379.. seealso::
380
381 :pep:`391` - Dictionary-Based Configuration For Logging
382 PEP written and implemented by Vinay Sajip.
383
384PEP 3106: Dictionary Views
385====================================================
386
Andrew M. Kuchling85f928a2010-04-15 01:42:27 +0000387The dictionary methods :meth:`keys`, :meth:`values`, and :meth:`items`
388are different in Python 3.x. They return an object called a :dfn:`view`
389instead of a fully materialized list.
390
391.. Views can be iterated over, but they also behave like sets. XXX not working.
392
393It's not possible to change the return values of :meth:`keys`,
394:meth:`values`, and :meth:`items` in Python 2.7 because too much code
395would break. Instead the 3.x versions were added under the new names
396of :meth:`viewkeys`, :meth:`viewvalues`, and :meth:`viewitems`.
397
398::
399
400 >>> d = dict((i*10, chr(65+i)) for i in range(26))
401 >>> d
402 {0: 'A', 130: 'N', 10: 'B', 140: 'O', 20: ..., 250: 'Z'}
403 >>> d.viewkeys()
404 dict_keys([0, 130, 10, 140, 20, 150, 30, ..., 250])
405
406The view keeps track of the dictionary and its contents change as the
407dictionary is modified::
408
409 >>> vk = d.viewkeys()
410 >>> vk
411 dict_keys([0, 130, 10, ..., 250])
412 >>> d[260] = '&'
413 >>> vk
414 dict_keys([0, 130, 260, 10, ..., 250])
415
416However, note that you can't add or remove keys while you're iterating
417over the view::
418
419 >>> for k in vk:
420 ... d[k*2] = k
421 ...
422 Traceback (most recent call last):
423 File "<stdin>", line 1, in <module>
424 RuntimeError: dictionary changed size during iteration
425
426You can use the view methods in Python 2.x code, and the 2to3
427converter will change them to the standard :meth:`keys`,
428:meth:`values`, and :meth:`items` methods.
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000429
430.. seealso::
431
432 :pep:`3106` - Revamping dict.keys(), .values() and .items()
433 PEP written by Guido van Rossum.
434 Backported to 2.7 by Alexandre Vassalotti; :issue:`1967`.
435
436
Andrew M. Kuchling9fbbd3b2010-05-01 12:06:51 +0000437PEP 3137: The memoryview Object
438====================================================
439
440The :class:`memoryview` object provides a view of another object's
441memory content that matches the :class:`bytes` type's interface.
442
443 >>> import string
444 >>> m = memoryview(string.letters)
445 >>> m
446 <memory at 0x37f850>
447 >>> len(m) # Returns length of underlying object
448 52
449 >>> m[0], m[25], m[26] # Indexing returns one byte
450 ('a', 'z', 'A')
451 >>> m2 = m[0:26] # Slicing returns another memoryview
452 >>> m2
453 <memory at 0x37f080>
454
455The content of the view can be converted to a string of bytes or to
456a list of integers:
457
458 >>> m2.tobytes()
459 'abcdefghijklmnopqrstuvwxyz'
460 >>> m2.tolist()
461 [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]
462 >>>
463
464:class:`memoryview` objects allow modifying the underlying object if
465it's a mutable object.
466
467 >>> m2[0] = 75
468 Traceback (most recent call last):
469 File "<stdin>", line 1, in <module>
470 TypeError: cannot modify read-only memory
471 >>> b = bytearray(string.letters) # Creating a mutable object
472 >>> b
473 bytearray(b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
474 >>> mb = memoryview(b)
475 >>> mb[0] = '*' # Assign to view, changing the bytearray.
476 >>> b[0:5] # The bytearray has been changed.
477 bytearray(b'*bcde')
478 >>>
479
480.. seealso::
481
482 :pep:`3137` - Immutable Bytes and Mutable Buffer
483 PEP written by Guido van Rossum.
Antoine Pitrou5cace782010-05-01 12:16:39 +0000484 Implemented by Travis Oliphant, Antoine Pitrou and others.
Andrew M. Kuchling9fbbd3b2010-05-01 12:06:51 +0000485 Backported to 2.7 by Antoine Pitrou; :issue:`2396`.
486
487
488
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000489Other Language Changes
490======================
491
492Some smaller changes made to the core Python language are:
493
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000494* The syntax for set literals has been backported from Python 3.x.
495 Curly brackets are used to surround the contents of the resulting
496 mutable set; set literals are
497 distinguished from dictionaries by not containing colons and values.
498 ``{}`` continues to represent an empty dictionary; use
499 ``set()`` for an empty set.
500
501 >>> {1,2,3,4,5}
502 set([1, 2, 3, 4, 5])
Ezio Melotti021f3342010-04-06 03:26:49 +0000503 >>> set() # empty set
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000504 set([])
Ezio Melotti021f3342010-04-06 03:26:49 +0000505 >>> {} # empty dict
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000506 {}
507
508 Backported by Alexandre Vassalotti; :issue:`2335`.
509
510* Dictionary and set comprehensions are another feature backported from
511 3.x, generalizing list/generator comprehensions to use
512 the literal syntax for sets and dictionaries.
513
514 >>> {x:x*x for x in range(6)}
515 {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
516 >>> {'a'*x for x in range(6)}
517 set(['', 'a', 'aa', 'aaa', 'aaaa', 'aaaaa'])
518
519 Backported by Alexandre Vassalotti; :issue:`2333`.
520
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000521* The :keyword:`with` statement can now use multiple context managers
522 in one statement. Context managers are processed from left to right
523 and each one is treated as beginning a new :keyword:`with` statement.
524 This means that::
525
526 with A() as a, B() as b:
527 ... suite of statements ...
528
529 is equivalent to::
530
531 with A() as a:
532 with B() as b:
533 ... suite of statements ...
534
535 The :func:`contextlib.nested` function provides a very similar
536 function, so it's no longer necessary and has been deprecated.
537
538 (Proposed in http://codereview.appspot.com/53094; implemented by
539 Georg Brandl.)
540
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000541* Conversions between floating-point numbers and strings are
542 now correctly rounded on most platforms. These conversions occur
543 in many different places: :func:`str` on
544 floats and complex numbers; the :class:`float` and :class:`complex`
545 constructors;
546 numeric formatting; serialization and
547 deserialization of floats and complex numbers using the
548 :mod:`marshal`, :mod:`pickle`
549 and :mod:`json` modules;
550 parsing of float and imaginary literals in Python code;
Ezio Melotti021f3342010-04-06 03:26:49 +0000551 and :class:`~decimal.Decimal`-to-float conversion.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000552
553 Related to this, the :func:`repr` of a floating-point number *x*
554 now returns a result based on the shortest decimal string that's
555 guaranteed to round back to *x* under correct rounding (with
556 round-half-to-even rounding mode). Previously it gave a string
557 based on rounding x to 17 decimal digits.
558
Ezio Melotti021f3342010-04-06 03:26:49 +0000559 .. maybe add an example?
560
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000561 The rounding library responsible for this improvement works on
562 Windows, and on Unix platforms using the gcc, icc, or suncc
563 compilers. There may be a small number of platforms where correct
564 operation of this code cannot be guaranteed, so the code is not
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +0000565 used on such systems. You can find out which code is being used
566 by checking :data:`sys.float_repr_style`, which will be ``short``
567 if the new code is in use and ``legacy`` if it isn't.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000568
Mark Dickinsonbdd863d2010-01-07 09:28:29 +0000569 Implemented by Eric Smith and Mark Dickinson, using David Gay's
570 :file:`dtoa.c` library; :issue:`7117`.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000571
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000572* The :meth:`str.format` method now supports automatic numbering of the replacement
Benjamin Petersonaa0a0b92009-04-11 20:27:15 +0000573 fields. This makes using :meth:`str.format` more closely resemble using
574 ``%s`` formatting::
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000575
576 >>> '{}:{}:{}'.format(2009, 04, 'Sunday')
577 '2009:4:Sunday'
578 >>> '{}:{}:{day}'.format(2009, 4, day='Sunday')
579 '2009:4:Sunday'
580
Benjamin Petersonaa0a0b92009-04-11 20:27:15 +0000581 The auto-numbering takes the fields from left to right, so the first ``{...}``
582 specifier will use the first argument to :meth:`str.format`, the next
583 specifier will use the next argument, and so on. You can't mix auto-numbering
584 and explicit numbering -- either number all of your specifier fields or none
585 of them -- but you can mix auto-numbering and named fields, as in the second
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000586 example above. (Contributed by Eric Smith; :issue:`5237`.)
587
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000588 Complex numbers now correctly support usage with :func:`format`,
589 and default to being right-aligned.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000590 Specifying a precision or comma-separation applies to both the real
591 and imaginary parts of the number, but a specified field width and
592 alignment is applied to the whole of the resulting ``1.5+3j``
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000593 output. (Contributed by Eric Smith; :issue:`1588` and :issue:`7988`.)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000594
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000595 The 'F' format code now always formats its output using uppercase characters,
596 so it will now produce 'INF' and 'NAN'.
597 (Contributed by Eric Smith; :issue:`3382`.)
598
Andrew M. Kuchlingc4ae73e2010-04-30 13:47:34 +0000599 A low-level change: the :meth:`object.__format__` method now triggers
600 a :exc:`PendingDeprecationWarning` if it's passed a format string,
601 because the :meth:`__format__` method for :class:`object` converts
602 the object to a string representation and formats that. The method
603 used to silently apply the format string to the string
604 representation, but that could hide mistakes in Python code. If
605 you're supplying formatting information such as an alignment or
606 precision, presumably you're expecting the formatting to be applied
607 in some object-specific way. (Fixed by Eric Smith; :issue:`7994`.)
608
Mark Dickinson1a707982008-12-17 16:14:37 +0000609* The :func:`int` and :func:`long` types gained a ``bit_length``
Georg Brandl64e1c752009-04-11 18:19:27 +0000610 method that returns the number of bits necessary to represent
Mark Dickinson1a707982008-12-17 16:14:37 +0000611 its argument in binary::
612
613 >>> n = 37
Ezio Melotti021f3342010-04-06 03:26:49 +0000614 >>> bin(n)
Mark Dickinson1a707982008-12-17 16:14:37 +0000615 '0b100101'
616 >>> n.bit_length()
617 6
618 >>> n = 2**123-1
619 >>> n.bit_length()
620 123
621 >>> (n+1).bit_length()
622 124
623
624 (Contributed by Fredrik Johansson and Victor Stinner; :issue:`3439`.)
625
Andrew M. Kuchling92b97002009-05-02 17:12:15 +0000626* Conversions from long integers and regular integers to floating
627 point now round differently, returning the floating-point number
628 closest to the number. This doesn't matter for small integers that
629 can be converted exactly, but for large numbers that will
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000630 unavoidably lose precision, Python 2.7 now approximates more
Andrew M. Kuchling92b97002009-05-02 17:12:15 +0000631 closely. For example, Python 2.6 computed the following::
632
633 >>> n = 295147905179352891391
634 >>> float(n)
635 2.9514790517935283e+20
636 >>> n - long(float(n))
637 65535L
638
639 Python 2.7's floating-point result is larger, but much closer to the
640 true value::
641
642 >>> n = 295147905179352891391
643 >>> float(n)
644 2.9514790517935289e+20
Ezio Melotti021f3342010-04-06 03:26:49 +0000645 >>> n - long(float(n))
Andrew M. Kuchling92b97002009-05-02 17:12:15 +0000646 -1L
647
648 (Implemented by Mark Dickinson; :issue:`3166`.)
649
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000650 Integer division is also more accurate in its rounding behaviours. (Also
651 implemented by Mark Dickinson; :issue:`1811`.)
652
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000653* It's now possible for a subclass of the built-in :class:`unicode` type
654 to override the :meth:`__unicode__` method. (Implemented by
655 Victor Stinner; :issue:`1583863`.)
656
Ezio Melotti021f3342010-04-06 03:26:49 +0000657* The :class:`bytearray` type's :meth:`~bytearray.translate` method now accepts
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000658 ``None`` as its first argument. (Fixed by Georg Brandl;
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000659 :issue:`4759`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000660
Ezio Melotti021f3342010-04-06 03:26:49 +0000661 .. bytearray doesn't seem to be documented
662
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000663* When using ``@classmethod`` and ``@staticmethod`` to wrap
664 methods as class or static methods, the wrapper object now
665 exposes the wrapped function as their :attr:`__func__` attribute.
666 (Contributed by Amaury Forgeot d'Arc, after a suggestion by
667 George Sakkis; :issue:`5982`.)
668
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +0000669* When a restricted set of attributes were set using ``__slots__``,
670 deleting an unset attribute would not raise :exc:`AttributeError`
671 as you would expect. Fixed by Benjamin Peterson; :issue:`7604`.)
672
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000673* A new encoding named "cp720", used primarily for Arabic text, is now
674 supported. (Contributed by Alexander Belchenko and Amaury Forgeot
675 d'Arc; :issue:`1616979`.)
676
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000677* The :class:`file` object will now set the :attr:`filename` attribute
678 on the :exc:`IOError` exception when trying to open a directory
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +0000679 on POSIX platforms (noted by Jan Kaliszewski; :issue:`4764`), and
680 now explicitly checks for and forbids writing to read-only file objects
681 instead of trusting the C library to catch and report the error
682 (fixed by Stefan Krah; :issue:`5677`).
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000683
Benjamin Petersonae9a0a02009-12-31 16:49:37 +0000684* The Python tokenizer now translates line endings itself, so the
685 :func:`compile` built-in function can now accept code using any
686 line-ending convention. Additionally, it no longer requires that the
687 code end in a newline.
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +0000688
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000689* Extra parentheses in function definitions are illegal in Python 3.x,
690 meaning that you get a syntax error from ``def f((x)): pass``. In
691 Python3-warning mode, Python 2.7 will now warn about this odd usage.
692 (Noted by James Lingard; :issue:`7362`.)
693
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +0000694* It's now possible to create weak references to old-style class
695 objects. New-style classes were always weak-referenceable. (Fixed
696 by Antoine Pitrou; :issue:`8268`.)
697
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000698* When a module object is garbage-collected, the module's dictionary is
699 now only cleared if no one else is holding a reference to the
700 dictionary (:issue:`7140`).
701
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000702.. ======================================================================
703
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000704.. _new-27-interpreter:
705
706Interpreter Changes
707-------------------------------
708
709A new environment variable, :envvar:`PYTHONWARNINGS`,
710allows controlling warnings. It should be set to a string
711containing warning settings, equivalent to those
712used with the :option:`-W` switch, separated by commas.
713(Contributed by Brian Curtin; :issue:`7301`.)
714
715For example, the following setting will print warnings every time
716they occur, but turn warnings from the :mod:`Cookie` module into an
717error. (The exact syntax for setting an environment variable varies
718across operating systems and shells, so it may be different for you.)
719
720::
721
722 export PYTHONWARNINGS=all,error:::Cookie:0
723
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +0000724When running a module using the interpreter's :option:`-m` switch,
725``sys.argv[0]`` will now be set to the string ``'-m'`` while the
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +0000726module is being located, while executing the :file:`__init__.py` files
727for any parent packages of the module to be executed.
728(Suggested by Michael Foord; implemented by Nick Coghlan;
729:issue:`8202`.)
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000730
731.. ======================================================================
732
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000733
734Optimizations
735-------------
736
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000737Several performance enhancements have been added:
738
739.. * A new :program:`configure` option, :option:`--with-computed-gotos`,
740 compiles the main bytecode interpreter loop using a new dispatch
741 mechanism that gives speedups of up to 20%, depending on the system
742 and benchmark. The new mechanism is only supported on certain
743 compilers, such as gcc, SunPro, and icc.
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000744
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000745* A new opcode was added to perform the initial setup for
746 :keyword:`with` statements, looking up the :meth:`__enter__` and
747 :meth:`__exit__` methods. (Contributed by Benjamin Peterson.)
748
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000749* The garbage collector now performs better for one common usage
750 pattern: when many objects are being allocated without deallocating
751 any of them. This would previously take quadratic
752 time for garbage collection, but now the number of full garbage collections
753 is reduced as the number of objects on the heap grows.
754 The new logic is to only perform a full garbage collection pass when
755 the middle generation has been collected 10 times and when the
756 number of survivor objects from the middle generation exceeds 10% of
757 the number of objects in the oldest generation. (Suggested by Martin
Ezio Melotti021f3342010-04-06 03:26:49 +0000758 von Löwis and implemented by Antoine Pitrou; :issue:`4074`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000759
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000760* The garbage collector tries to avoid tracking simple containers
761 which can't be part of a cycle. In Python 2.7, this is now true for
762 tuples and dicts containing atomic types (such as ints, strings,
763 etc.). Transitively, a dict containing tuples of atomic types won't
764 be tracked either. This helps reduce the cost of each
765 garbage collection by decreasing the number of objects to be
766 considered and traversed by the collector.
Antoine Pitrouc18f6b02009-03-28 19:10:13 +0000767 (Contributed by Antoine Pitrou; :issue:`4688`.)
768
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000769* Long integers are now stored internally either in base 2**15 or in base
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000770 2**30, the base being determined at build time. Previously, they
771 were always stored in base 2**15. Using base 2**30 gives
772 significant performance improvements on 64-bit machines, but
773 benchmark results on 32-bit machines have been mixed. Therefore,
774 the default is to use base 2**30 on 64-bit machines and base 2**15
775 on 32-bit machines; on Unix, there's a new configure option
776 :option:`--enable-big-digits` that can be used to override this default.
777
778 Apart from the performance improvements this change should be
779 invisible to end users, with one exception: for testing and
Ezio Melotti021f3342010-04-06 03:26:49 +0000780 debugging purposes there's a new structseq :data:`sys.long_info` that
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000781 provides information about the internal format, giving the number of
782 bits per digit and the size in bytes of the C type used to store
783 each digit::
784
785 >>> import sys
786 >>> sys.long_info
787 sys.long_info(bits_per_digit=30, sizeof_digit=4)
788
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000789 (Contributed by Mark Dickinson; :issue:`4258`.)
790
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000791 Another set of changes made long objects a few bytes smaller: 2 bytes
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000792 smaller on 32-bit systems and 6 bytes on 64-bit.
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000793 (Contributed by Mark Dickinson; :issue:`5260`.)
794
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000795* The division algorithm for long integers has been made faster
796 by tightening the inner loop, doing shifts instead of multiplications,
797 and fixing an unnecessary extra iteration.
798 Various benchmarks show speedups of between 50% and 150% for long
799 integer divisions and modulo operations.
800 (Contributed by Mark Dickinson; :issue:`5512`.)
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +0000801 Bitwise operations are also significantly faster (initial patch by
802 Gregory Smith; :issue:`1087418`).
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000803
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000804* The implementation of ``%`` checks for the left-side operand being
805 a Python string and special-cases it; this results in a 1-3%
806 performance increase for applications that frequently use ``%``
807 with strings, such as templating libraries.
808 (Implemented by Collin Winter; :issue:`5176`.)
809
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000810* List comprehensions with an ``if`` condition are compiled into
811 faster bytecode. (Patch by Antoine Pitrou, back-ported to 2.7
812 by Jeffrey Yasskin; :issue:`4715`.)
813
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +0000814* Converting an integer or long integer to a decimal string was made
815 faster by special-casing base 10 instead of using a generalized
816 conversion function that supports arbitrary bases.
817 (Patch by Gawain Bolton; :issue:`6713`.)
818
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +0000819* The :meth:`split`, :meth:`replace`, :meth:`rindex`,
820 :meth:`rpartition`, and :meth:`rsplit` methods of string-like types
821 (strings, Unicode strings, and :class:`bytearray` objects) now use a
822 fast reverse-search algorithm instead of a character-by-character
823 scan. This is sometimes faster by a factor of 10. (Added by
824 Florent Xicluna; :issue:`7462` and :issue:`7622`.)
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +0000825
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000826* The :mod:`pickle` and :mod:`cPickle` modules now automatically
827 intern the strings used for attribute names, reducing memory usage
828 of the objects resulting from unpickling. (Contributed by Jake
829 McGuire; :issue:`5084`.)
830
831* The :mod:`cPickle` module now special-cases dictionaries,
832 nearly halving the time required to pickle them.
833 (Contributed by Collin Winter; :issue:`5670`.)
834
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000835.. ======================================================================
836
Georg Brandl0516f812009-11-18 18:52:35 +0000837New and Improved Modules
838========================
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000839
840As in every release, Python's standard library received a number of
841enhancements and bug fixes. Here's a partial list of the most notable
842changes, sorted alphabetically by module name. Consult the
843:file:`Misc/NEWS` file in the source tree for a more complete list of
844changes, or look through the Subversion logs for all the details.
845
Ezio Melotti021f3342010-04-06 03:26:49 +0000846* The :mod:`bdb` module's base debugging class :class:`~bdb.Bdb`
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000847 gained a feature for skipping modules. The constructor
848 now takes an iterable containing glob-style patterns such as
849 ``django.*``; the debugger will not step into stack frames
850 from a module that matches one of these patterns.
851 (Contributed by Maru Newby after a suggestion by
852 Senthil Kumaran; :issue:`5142`.)
853
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +0000854* The :mod:`binascii` module now supports the buffer API, so it can be
855 used with :class:`memoryview` instances and other similar buffer objects.
856 (Backported from 3.x by Florent Xicluna; :issue:`7703`.)
857
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000858* Updated module: the :mod:`bsddb` module has been updated from 4.7.2devel9
859 to version 4.8.4 of
860 `the pybsddb package <http://www.jcea.es/programacion/pybsddb.htm>`__.
861 The new version features better Python 3.x compatibility, various bug fixes,
862 and adds several new BerkeleyDB flags and methods.
Ezio Melotti021f3342010-04-06 03:26:49 +0000863 (Updated by Jesús Cea Avión; :issue:`8156`. The pybsddb
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000864 changelog can be browsed at http://hg.jcea.es/pybsddb/file/tip/ChangeLog.)
865
Ezio Melotti021f3342010-04-06 03:26:49 +0000866* The :mod:`bz2` module's :class:`~bz2.BZ2File` now supports the context
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000867 management protocol, so you can write ``with bz2.BZ2File(...) as f: ...``.
868 (Contributed by Hagen Fuerstenau; :issue:`3860`.)
869
Ezio Melotti021f3342010-04-06 03:26:49 +0000870* New class: the :class:`~collections.Counter` class in the :mod:`collections`
871 module is useful for tallying data. :class:`~collections.Counter` instances
872 behave mostly like dictionaries but return zero for missing keys instead of
Georg Brandlf6dab952009-04-28 21:48:35 +0000873 raising a :exc:`KeyError`:
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000874
Georg Brandlf6dab952009-04-28 21:48:35 +0000875 .. doctest::
876 :options: +NORMALIZE_WHITESPACE
877
878 >>> from collections import Counter
879 >>> c = Counter()
880 >>> for letter in 'here is a sample of english text':
881 ... c[letter] += 1
882 ...
883 >>> c
884 Counter({' ': 6, 'e': 5, 's': 3, 'a': 2, 'i': 2, 'h': 2,
885 'l': 2, 't': 2, 'g': 1, 'f': 1, 'm': 1, 'o': 1, 'n': 1,
886 'p': 1, 'r': 1, 'x': 1})
887 >>> c['e']
888 5
889 >>> c['z']
890 0
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000891
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +0000892 There are three additional :class:`~collections.Counter` methods:
893 :meth:`~collections.Counter.most_common` returns the N most common
894 elements and their counts. :meth:`~collections.Counter.elements`
895 returns an iterator over the contained elements, repeating each
896 element as many times as its count.
897 :meth:`~collections.Counter.subtract` takes an iterable and
898 subtracts one for each element instead of adding; if the argument is
899 a dictionary or another :class:`Counter`, the counts are
900 subtracted. ::
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000901
902 >>> c.most_common(5)
903 [(' ', 6), ('e', 5), ('s', 3), ('a', 2), ('i', 2)]
904 >>> c.elements() ->
905 'a', 'a', ' ', ' ', ' ', ' ', ' ', ' ',
906 'e', 'e', 'e', 'e', 'e', 'g', 'f', 'i', 'i',
907 'h', 'h', 'm', 'l', 'l', 'o', 'n', 'p', 's',
Georg Brandlf6dab952009-04-28 21:48:35 +0000908 's', 's', 'r', 't', 't', 'x'
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +0000909 >>> c['e']
910 5
911 >>> c.subtract('very heavy on the letter e')
912 >>> c['e'] # Count is now lower
913 -1
Ezio Melotti021f3342010-04-06 03:26:49 +0000914
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000915 Contributed by Raymond Hettinger; :issue:`1696199`.
916
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +0000917 .. revision 79660
918
Ezio Melotti021f3342010-04-06 03:26:49 +0000919 The new :class:`~collections.OrderedDict` class is described in the earlier
920 section :ref:`pep-0372`.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000921
Ezio Melotti021f3342010-04-06 03:26:49 +0000922 The :class:`~collections.namedtuple` class now has an optional *rename* parameter.
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000923 If *rename* is true, field names that are invalid because they've
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000924 been repeated or that aren't legal Python identifiers will be
925 renamed to legal names that are derived from the field's
926 position within the list of fields:
927
Georg Brandlf6dab952009-04-28 21:48:35 +0000928 >>> from collections import namedtuple
929 >>> T = namedtuple('T', ['field1', '$illegal', 'for', 'field2'], rename=True)
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000930 >>> T._fields
931 ('field1', '_1', '_2', 'field2')
932
933 (Added by Raymond Hettinger; :issue:`1818`.)
934
Andrew M. Kuchling6d7dfa22010-04-11 12:49:37 +0000935 The :class:`~collections.deque` data type now has a
936 :meth:`~collections.deque.count` method that returns the number of
937 contained elements equal to the supplied argument *x*, and a
938 :meth:`~collections.deque.reverse` method that reverses the elements
939 of the deque in-place. :class:`deque` also exposes its maximum
940 length as the read-only :attr:`~collections.deque.maxlen` attribute.
941 (Both features added by Raymond Hettinger.)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000942
Ezio Melotti021f3342010-04-06 03:26:49 +0000943* The :mod:`copy` module's :func:`~copy.deepcopy` function will now
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000944 correctly copy bound instance methods. (Implemented by
945 Robert Collins; :issue:`1515`.)
946
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000947* The :mod:`ctypes` module now always converts ``None`` to a C NULL
948 pointer for arguments declared as pointers. (Changed by Thomas
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +0000949 Heller; :issue:`4606`.) The underlying `libffi library
950 <http://sourceware.org/libffi/>`__ has been updated to version
951 3.0.9, containing various fixes for different platforms. (Updated
952 by Matthias Klose; :issue:`8142`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000953
Ezio Melotti021f3342010-04-06 03:26:49 +0000954* New method: the :mod:`datetime` module's :class:`~datetime.timedelta` class
955 gained a :meth:`~datetime.timedelta.total_seconds` method that returns the
956 number of seconds in the duration. (Contributed by Brian Quinlan; :issue:`5788`.)
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000957
Ezio Melotti021f3342010-04-06 03:26:49 +0000958* New method: the :class:`~decimal.Decimal` class gained a
959 :meth:`~decimal.Decimal.from_float` class method that performs an exact
960 conversion of a floating-point number to a :class:`~decimal.Decimal`.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000961 Note that this is an **exact** conversion that strives for the
962 closest decimal approximation to the floating-point representation's value;
963 the resulting decimal value will therefore still include the inaccuracy,
964 if any.
965 For example, ``Decimal.from_float(0.1)`` returns
966 ``Decimal('0.1000000000000000055511151231257827021181583404541015625')``.
967 (Implemented by Raymond Hettinger; :issue:`4796`.)
968
Andrew M. Kuchling04b99cc2010-05-04 01:24:22 +0000969 Comparing instances of :class:`Decimal` with floating-point
970 numbers now produces sensible results based on the numeric values
971 of the operands. Previously such comparisons would fall back to
972 Python's default rules for comparing objects, which produced arbitrary
973 results based on their type. Note that you still cannot combine
974 :class:`Decimal` and floating-point in other operations such as addition,
975 since you should be explicitly choosing how to convert between float and
976 :class:`Decimal`.
977 (Fixed by Mark Dickinson; :issue:`2531`.)
978
Ezio Melotti021f3342010-04-06 03:26:49 +0000979 Most of the methods of the :class:`~decimal.Context` class now accept integers
980 as well as :class:`~decimal.Decimal` instances; the only exceptions are the
981 :meth:`~decimal.Context.canonical` and :meth:`~decimal.Context.is_canonical`
982 methods. (Patch by Juan José Conti; :issue:`7633`.)
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000983
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +0000984 The constructor for :class:`~decimal.Decimal` now accepts
985 floating-point numbers (added by Raymond Hettinger; :issue:`8257`)
986 and non-European Unicode characters such as Arabic-Indic digits
987 (contributed by Mark Dickinson; :issue:`6595`).
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000988
Ezio Melotti021f3342010-04-06 03:26:49 +0000989 When using :class:`~decimal.Decimal` instances with a string's
990 :meth:`~str.format` method, the default alignment was previously
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000991 left-alignment. This has been changed to right-alignment, which seems
992 more sensible for numeric types. (Changed by Mark Dickinson; :issue:`6857`.)
993
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +0000994 Comparisons involving a signaling NaN value (or ``sNAN``) now signal
995 :const:`InvalidOperation` instead of silently returning a true or
996 false value depending on the comparison operator. Quiet NaN values
997 (or ``NaN``) are now hashable. (Fixed by Mark Dickinson;
998 :issue:`7279`.)
999
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +00001000* The :mod:`difflib` module now produces output that is more
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00001001 compatible with modern :command:`diff`/:command:`patch` tools
1002 through one small change, using a tab character instead of spaces as
1003 a separator in the header giving the filename. (Fixed by Anatoly
1004 Techtonik; :issue:`7585`.)
1005
1006* The :mod:`doctest` module's :const:`IGNORE_EXCEPTION_DETAIL` flag
1007 will now ignore the name of the module containing the exception
1008 being tested. (Patch by Lennart Regebro; :issue:`7490`.)
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +00001009
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001010* The :class:`~fractions.Fraction` class now accepts a single float or
1011 :class:`~decimal.Decimal` instance, or two rational numbers, as
1012 arguments to its constructor. (Implemented by Mark Dickinson;
1013 rationals added in :issue:`5812`, and float/decimal in
1014 :issue:`8294`.)
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00001015
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +00001016 An oversight was fixed, making the :class:`Fraction` match the other
1017 numeric types; ordering comparisons (``<``, ``<=``, ``>``, ``>=``) between
1018 fractions and complex numbers now raise a :exc:`TypeError`.
1019
1020 .. revision 79455
1021
Ezio Melotti021f3342010-04-06 03:26:49 +00001022* New class: a new :class:`~ftplib.FTP_TLS` class in
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001023 the :mod:`ftplib` module provides secure FTP
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001024 connections using TLS encapsulation of authentication as well as
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001025 subsequent control and data transfers.
1026 (Contributed by Giampaolo Rodola', :issue:`2054`.)
1027
Ezio Melotti021f3342010-04-06 03:26:49 +00001028 The :meth:`~ftplib.FTP.storbinary` method for binary uploads can now restart
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001029 uploads thanks to an added *rest* parameter (patch by Pablo Mouzo;
1030 :issue:`6845`.)
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001031
Andrew M. Kuchling6d7dfa22010-04-11 12:49:37 +00001032* New class decorator: :func:`total_ordering` in the :mod:`functools`
1033 module takes a class that defines an :meth:`__eq__` method and one of
1034 :meth:`__lt__`, :meth:`__le__`, :meth:`__gt__`, or :meth:`__ge__`,
1035 and generates the missing comparison methods. Since the
1036 :meth:`__cmp__` method is being deprecated in Python 3.x,
1037 this decorator makes it easier to define ordered classes.
1038 (Added by Raymond Hettinger; :issue:`5479`.)
1039
1040 New function: :func:`cmp_to_key` will take an old-style comparison
1041 function that expects two arguments and return a new callable that
1042 can be used as the *key* parameter to functions such as
1043 :func:`sorted`, :func:`min` and :func:`max`, etc. The primary
1044 intended use is to help with making code compatible with Python 3.x.
1045 (Added by Raymond Hettinger.)
1046
Ezio Melotti021f3342010-04-06 03:26:49 +00001047* New function: the :mod:`gc` module's :func:`~gc.is_tracked` returns
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001048 true if a given instance is tracked by the garbage collector, false
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001049 otherwise. (Contributed by Antoine Pitrou; :issue:`4688`.)
1050
Ezio Melotti021f3342010-04-06 03:26:49 +00001051* The :mod:`gzip` module's :class:`~gzip.GzipFile` now supports the context
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +00001052 management protocol, so you can write ``with gzip.GzipFile(...) as f: ...``
1053 (contributed by Hagen Fuerstenau; :issue:`3860`), and it now implements
1054 the :class:`io.BufferedIOBase` ABC, so you can wrap it with
1055 :class:`io.BufferedReader` for faster processing
1056 (contributed by Nir Aides; :issue:`7471`).
1057 It's also now possible to override the modification time
Andrew M. Kuchling77069572009-03-31 01:21:01 +00001058 recorded in a gzipped file by providing an optional timestamp to
1059 the constructor. (Contributed by Jacques Frechet; :issue:`4272`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001060
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001061 Files in gzip format can be padded with trailing zero bytes; the
1062 :mod:`gzip` module will now consume these trailing bytes. (Fixed by
1063 Tadek Pietraszek and Brian Curtin; :issue:`2846`.)
1064
Ezio Melotti021f3342010-04-06 03:26:49 +00001065* New attribute: the :mod:`hashlib` module now has an :attr:`~hashlib.hashlib.algorithms`
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001066 attribute containing a tuple naming the supported algorithms.
1067 In Python 2.7, ``hashlib.algorithms`` contains
1068 ``('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')``
1069 (Contributed by Carl Chenet; :issue:`7418`.)
1070
Ezio Melotti021f3342010-04-06 03:26:49 +00001071* The default :class:`~httplib.HTTPResponse` class used by the :mod:`httplib` module now
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001072 supports buffering, resulting in much faster reading of HTTP responses.
1073 (Contributed by Kristjan Valur Jonsson; :issue:`4879`.)
1074
Ezio Melotti021f3342010-04-06 03:26:49 +00001075 The :class:`~httplib.HTTPConnection` and :class:`~httplib.HTTPSConnection` classes
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001076 now support a *source_address* parameter, a ``(host, port)`` 2-tuple
1077 giving the source address that will be used for the connection.
1078 (Contributed by Eldon Ziegler; :issue:`3972`.)
1079
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00001080* The :mod:`ihooks` module now supports relative imports. Note that
1081 :mod:`ihooks` is an older module used to support customizing imports,
1082 superseded by the :mod:`imputil` module added in Python 2.0.
1083 (Relative import support added by Neil Schemenauer.)
1084
1085 .. revision 75423
1086
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001087* The :mod:`imaplib` module now supports IPv6 addresses.
1088 (Contributed by Derek Morr; :issue:`1655`.)
1089
Andrew M. Kuchlingce690522010-04-13 01:32:51 +00001090* New function: the :mod:`inspect` module's :func:`~inspect.getcallargs`
1091 takes a callable and its positional and keyword arguments,
1092 and figures out which of the callable's parameters will receive each argument,
1093 returning a dictionary mapping argument names to their values. For example::
1094
1095 >>> from inspect import getcallargs
1096 >>> def f(a, b=1, *pos, **named):
1097 ... pass
1098 >>> getcallargs(f, 1, 2, 3)
1099 {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
1100 >>> getcallargs(f, a=2, x=4)
1101 {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
1102 >>> getcallargs(f)
1103 Traceback (most recent call last):
1104 ...
1105 TypeError: f() takes at least 1 argument (0 given)
1106
1107 Contributed by George Sakkis; :issue:`3135`.
1108
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001109* Updated module: The :mod:`io` library has been upgraded to the version shipped with
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001110 Python 3.1. For 3.1, the I/O library was entirely rewritten in C
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001111 and is 2 to 20 times faster depending on the task being performed. The
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001112 original Python version was renamed to the :mod:`_pyio` module.
1113
1114 One minor resulting change: the :class:`io.TextIOBase` class now
1115 has an :attr:`errors` attribute giving the error setting
1116 used for encoding and decoding errors (one of ``'strict'``, ``'replace'``,
1117 ``'ignore'``).
1118
1119 The :class:`io.FileIO` class now raises an :exc:`OSError` when passed
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001120 an invalid file descriptor. (Implemented by Benjamin Peterson;
Ezio Melotti021f3342010-04-06 03:26:49 +00001121 :issue:`4991`.) The :meth:`~io.IOBase.truncate` method now preserves the
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001122 file position; previously it would change the file position to the
1123 end of the new file. (Fixed by Pascal Chambon; :issue:`6939`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001124
Andrew M. Kuchling5a73ff82009-12-02 14:27:11 +00001125* New function: ``itertools.compress(data, selectors)`` takes two
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001126 iterators. Elements of *data* are returned if the corresponding
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001127 value in *selectors* is true::
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001128
1129 itertools.compress('ABCDEF', [1,0,1,0,1,1]) =>
1130 A, C, E, F
1131
Ezio Melotti021f3342010-04-06 03:26:49 +00001132 .. maybe here is better to use >>> list(itertools.compress(...)) instead
1133
Andrew M. Kuchling5a73ff82009-12-02 14:27:11 +00001134 New function: ``itertools.combinations_with_replacement(iter, r)``
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001135 returns all the possible *r*-length combinations of elements from the
Ezio Melotti021f3342010-04-06 03:26:49 +00001136 iterable *iter*. Unlike :func:`~itertools.combinations`, individual elements
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001137 can be repeated in the generated combinations::
1138
1139 itertools.combinations_with_replacement('abc', 2) =>
1140 ('a', 'a'), ('a', 'b'), ('a', 'c'),
1141 ('b', 'b'), ('b', 'c'), ('c', 'c')
1142
1143 Note that elements are treated as unique depending on their position
1144 in the input, not their actual values.
1145
Ezio Melotti021f3342010-04-06 03:26:49 +00001146 The :func:`itertools.count` function now has a *step* argument that
1147 allows incrementing by values other than 1. :func:`~itertools.count` also
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001148 now allows keyword arguments, and using non-integer values such as
Ezio Melotti021f3342010-04-06 03:26:49 +00001149 floats or :class:`~decimal.Decimal` instances. (Implemented by Raymond
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001150 Hettinger; :issue:`5032`.)
1151
Andrew M. Kuchling77069572009-03-31 01:21:01 +00001152 :func:`itertools.combinations` and :func:`itertools.product` were
1153 previously raising :exc:`ValueError` for values of *r* larger than
1154 the input iterable. This was deemed a specification error, so they
1155 now return an empty iterator. (Fixed by Raymond Hettinger; :issue:`4816`.)
1156
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001157* Updated module: The :mod:`json` module was upgraded to version 2.0.9 of the
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001158 simplejson package, which includes a C extension that makes
1159 encoding and decoding faster.
1160 (Contributed by Bob Ippolito; :issue:`4136`.)
1161
Ezio Melotti021f3342010-04-06 03:26:49 +00001162 To support the new :class:`collections.OrderedDict` type, :func:`json.load`
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001163 now has an optional *object_pairs_hook* parameter that will be called
1164 with any object literal that decodes to a list of pairs.
1165 (Contributed by Raymond Hettinger; :issue:`5381`.)
1166
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001167* New functions: the :mod:`math` module gained
Ezio Melotti021f3342010-04-06 03:26:49 +00001168 :func:`~math.erf` and :func:`~math.erfc` for the error function and the complementary error function,
1169 :func:`~math.expm1` which computes ``e**x - 1`` with more precision than
1170 using :func:`~math.exp` and subtracting 1,
1171 :func:`~math.gamma` for the Gamma function, and
1172 :func:`~math.lgamma` for the natural log of the Gamma function.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001173 (Contributed by Mark Dickinson and nirinA raseliarison; :issue:`3366`.)
1174
Andrew M. Kuchling24520b42009-04-09 11:22:47 +00001175* The :mod:`multiprocessing` module's :class:`Manager*` classes
1176 can now be passed a callable that will be called whenever
1177 a subprocess is started, along with a set of arguments that will be
1178 passed to the callable.
1179 (Contributed by lekma; :issue:`5585`.)
1180
Ezio Melotti021f3342010-04-06 03:26:49 +00001181 The :class:`~multiprocessing.Pool` class, which controls a pool of worker processes,
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001182 now has an optional *maxtasksperchild* parameter. Worker processes
1183 will perform the specified number of tasks and then exit, causing the
Ezio Melotti021f3342010-04-06 03:26:49 +00001184 :class:`~multiprocessing.Pool` to start a new worker. This is useful if tasks may leak
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001185 memory or other resources, or if some tasks will cause the worker to
1186 become very large.
1187 (Contributed by Charles Cazabon; :issue:`6963`.)
1188
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001189* The :mod:`nntplib` module now supports IPv6 addresses.
1190 (Contributed by Derek Morr; :issue:`1664`.)
1191
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001192* New functions: the :mod:`os` module wraps the following POSIX system
Ezio Melotti021f3342010-04-06 03:26:49 +00001193 calls: :func:`~os.getresgid` and :func:`~os.getresuid`, which return the
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001194 real, effective, and saved GIDs and UIDs;
Ezio Melotti021f3342010-04-06 03:26:49 +00001195 :func:`~os.setresgid` and :func:`~os.setresuid`, which set
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001196 real, effective, and saved GIDs and UIDs to new values;
Ezio Melotti021f3342010-04-06 03:26:49 +00001197 :func:`~os.initgroups`. (GID/UID functions
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001198 contributed by Travis H.; :issue:`6508`. Support for initgroups added
1199 by Jean-Paul Calderone; :issue:`7333`.)
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001200
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001201 The :func:`os.fork` function now re-initializes the import lock in
Ezio Melotti021f3342010-04-06 03:26:49 +00001202 the child process; this fixes problems on Solaris when :func:`~os.fork`
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001203 is called from a thread. (Fixed by Zsolt Cserna; :issue:`7242`.)
1204
Ezio Melotti021f3342010-04-06 03:26:49 +00001205* In the :mod:`os.path` module, the :func:`~os.path.normpath` and
1206 :func:`~os.path.abspath` functions now preserve Unicode; if their input path
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001207 is a Unicode string, the return value is also a Unicode string.
Ezio Melotti021f3342010-04-06 03:26:49 +00001208 (:meth:`~os.path.normpath` fixed by Matt Giuca in :issue:`5827`;
1209 :meth:`~os.path.abspath` fixed by Ezio Melotti in :issue:`3426`.)
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001210
Andrew M. Kuchling9cb42772009-01-21 02:15:43 +00001211* The :mod:`pydoc` module now has help for the various symbols that Python
1212 uses. You can now do ``help('<<')`` or ``help('@')``, for example.
1213 (Contributed by David Laban; :issue:`4739`.)
1214
Ezio Melotti021f3342010-04-06 03:26:49 +00001215* The :mod:`re` module's :func:`~re.split`, :func:`~re.sub`, and :func:`~re.subn`
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001216 now accept an optional *flags* argument, for consistency with the
1217 other functions in the module. (Added by Gregory P. Smith.)
1218
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001219* New function: :func:`~runpy.run_path` in the :mod:`runpy` module
1220 will execute the code at a provided *path* argument. *path* can be
1221 the path of a Python source file (:file:`example.py`), a compiled
1222 bytecode file (:file:`example.pyc`), a directory
1223 (:file:`./package/'), or a zip archive (:file:`example.zip`). If a
1224 directory or zip path is provided, it will be added to the front of
1225 ``sys.path`` and the module :mod:`__main__` will be imported. It's
1226 expected that the directory or zip contains a :file:`__main__.py`;
1227 if it doesn't, some other :file:`__main__.py` might be imported from
1228 a location later in ``sys.path``. This makes some of the machinery
1229 of :mod:`runpy` available to scripts that want to mimic the behaviour
1230 of Python's :option:`-m` switch. (Added by Nick Coghlan;
1231 :issue:`6816`.)
1232
Ezio Melotti021f3342010-04-06 03:26:49 +00001233* New function: in the :mod:`shutil` module, :func:`~shutil.make_archive`
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001234 takes a filename, archive type (zip or tar-format), and a directory
1235 path, and creates an archive containing the directory's contents.
1236 (Added by Tarek Ziadé.)
1237
Ezio Melotti021f3342010-04-06 03:26:49 +00001238 :mod:`shutil`'s :func:`~shutil.copyfile` and :func:`~shutil.copytree`
1239 functions now raise a :exc:`~shutil.SpecialFileError` exception when
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001240 asked to copy a named pipe. Previously the code would treat
1241 named pipes like a regular file by opening them for reading, and
1242 this would block indefinitely. (Fixed by Antoine Pitrou; :issue:`3002`.)
1243
1244* New functions: in the :mod:`site` module, three new functions
1245 return various site- and user-specific paths.
Ezio Melotti021f3342010-04-06 03:26:49 +00001246 :func:`~site.getsitepackages` returns a list containing all
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001247 global site-packages directories, and
Ezio Melotti021f3342010-04-06 03:26:49 +00001248 :func:`~site.getusersitepackages` returns the path of the user's
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001249 site-packages directory.
Ezio Melotti021f3342010-04-06 03:26:49 +00001250 :func:`~site.getuserbase` returns the value of the :envvar:`USER_BASE`
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001251 environment variable, giving the path to a directory that can be used
1252 to store data.
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001253 (Contributed by Tarek Ziadé; :issue:`6693`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001254
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001255 The :mod:`site` module now reports exceptions occurring
1256 when the :mod:`sitecustomize` module is imported, and will no longer
Florent Xiclunaad598332010-03-31 21:40:32 +00001257 catch and swallow the :exc:`KeyboardInterrupt` exception. (Fixed by
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001258 Victor Stinner; :issue:`3137`.)
1259
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001260* The :func:`~socket.create_connection` function
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +00001261 gained a *source_address* parameter, a ``(host, port)`` 2-tuple
1262 giving the source address that will be used for the connection.
1263 (Contributed by Eldon Ziegler; :issue:`3972`.)
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00001264
Ezio Melotti021f3342010-04-06 03:26:49 +00001265 The :meth:`~socket.socket.recv_into` and :meth:`~socket.socket.recvfrom_into`
1266 methods will now write into objects that support the buffer API, most usefully
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001267 the :class:`bytearray` and :class:`memoryview` objects. (Implemented by
1268 Antoine Pitrou; :issue:`8104`.)
1269
Ezio Melotti021f3342010-04-06 03:26:49 +00001270* The :mod:`SocketServer` module's :class:`~SocketServer.TCPServer` class now
1271 has a :attr:`~SocketServer.TCPServer.disable_nagle_algorithm` class attribute.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001272 The default value is False; if overridden to be True,
1273 new request connections will have the TCP_NODELAY option set to
1274 prevent buffering many small sends into a single TCP packet.
1275 (Contributed by Kristjan Valur Jonsson; :issue:`6192`.)
1276
Ezio Melotti021f3342010-04-06 03:26:49 +00001277* Updated module: the :mod:`sqlite3` module has been updated to
Andrew M. Kuchlingfed15762010-03-08 12:00:39 +00001278 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
1279 the ability to load SQLite extensions from shared libraries.
1280 Call the ``enable_load_extension(True)`` method to enable extensions,
Ezio Melotti021f3342010-04-06 03:26:49 +00001281 and then call :meth:`~sqlite3.Connection.load_extension` to load a particular shared library.
Andrew M. Kuchlingfed15762010-03-08 12:00:39 +00001282 (Updated by Gerhard Häring.)
1283
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001284* The :mod:`ssl` module's :class:`~ssl.SSL` objects now support the
1285 buffer API, which fixed a test suite failure (fix by Antoine Pitrou;
1286 :issue:`7133`) and automatically set
1287 OpenSSL's :cmacro:`SSL_MODE_AUTO_RETRY`, which will prevent an error
1288 code being returned from :meth:`recv` operations that trigger an SSL
1289 renegotiation (fix by Antoine Pitrou; :issue:`8222`).
1290
1291 The :func:`wrap_socket` constructor function now takes a
1292 *ciphers* argument that's a string listing the encryption algorithms
1293 to be allowed; the format of the string is described
1294 `in the OpenSSL documentation <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`__. (Added by Antoine Pitrou; :issue:`8322`.)
1295
1296 Another change makes the extension load all of OpenSSL's ciphers and
1297 digest algorithms so that they're all available. Some SSL
1298 certificates couldn't be verified, reporting an 'unknown algorithm'
1299 error. (Reported by Beda Kosata, and fixed by Antoine Pitrou;
1300 :issue:`8484`.)
1301
1302 The version of OpenSSL being used is now available as the module
1303 attributes :attr:`OPENSSL_VERSION` (a string),
1304 :attr:`OPENSSL_VERSION_INFO` (a 5-tuple), and
1305 :attr:`OPENSSL_VERSION_NUMBER` (an integer). (Added by Antoine
1306 Pitrou; :issue:`8321`.)
1307
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001308* The :mod:`struct` module will no longer silently ignore overflow
1309 errors when a value is too large for a particular integer format
1310 code (one of ``bBhHiIlLqQ``); it now always raises a
1311 :exc:`struct.error` exception. (Changed by Mark Dickinson;
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001312 :issue:`1523`.) The :func:`~struct.pack` function will also
1313 attempt to use :meth:`__index__` to convert and pack non-integers
1314 before trying the :meth:`__int__` method or reporting an error.
1315 (Changed by Mark Dickinson; :issue:`8300`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001316
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001317* New function: the :mod:`subprocess` module's
Ezio Melotti021f3342010-04-06 03:26:49 +00001318 :func:`~subprocess.check_output` runs a command with a specified set of arguments
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001319 and returns the command's output as a string when the command runs without
Ezio Melotti021f3342010-04-06 03:26:49 +00001320 error, or raises a :exc:`~subprocess.CalledProcessError` exception otherwise.
Andrew M. Kuchling10b1ec92009-01-02 21:00:35 +00001321
1322 ::
1323
1324 >>> subprocess.check_output(['df', '-h', '.'])
1325 'Filesystem Size Used Avail Capacity Mounted on\n
1326 /dev/disk0s2 52G 49G 3.0G 94% /\n'
1327
1328 >>> subprocess.check_output(['df', '-h', '/bogus'])
1329 ...
1330 subprocess.CalledProcessError: Command '['df', '-h', '/bogus']' returned non-zero exit status 1
1331
1332 (Contributed by Gregory P. Smith.)
1333
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001334 The :mod:`subprocess` module will now retry its internal system calls
1335 on receiving an :const:`EINTR` signal. (Reported by several people; final
1336 patch by Gregory P. Smith in :issue:`1068268`.)
1337
Ezio Melotti021f3342010-04-06 03:26:49 +00001338* New function: :func:`~symtable.is_declared_global` in the :mod:`symtable` module
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001339 returns true for variables that are explicitly declared to be global,
1340 false for ones that are implicitly global.
1341 (Contributed by Jeremy Hylton.)
1342
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00001343* The :mod:`syslog` module will now use the value of ``sys.argv[0]`` as the
1344 identifier instead of the previous default value of ``'python'``.
1345 (Changed by Sean Reifschneider; :issue:`8451`.)
1346
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001347* The ``sys.version_info`` value is now a named tuple, with attributes
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001348 named :attr:`major`, :attr:`minor`, :attr:`micro`,
1349 :attr:`releaselevel`, and :attr:`serial`. (Contributed by Ross
1350 Light; :issue:`4285`.)
1351
1352 :func:`sys.getwindowsversion` also returns a named tuple,
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +00001353 with attributes named :attr:`major`, :attr:`minor`, :attr:`build`,
Ezio Melotti12477752010-02-08 22:22:41 +00001354 :attr:`platform`, :attr:`service_pack`, :attr:`service_pack_major`,
Eric Smithb3c54882010-02-03 14:17:50 +00001355 :attr:`service_pack_minor`, :attr:`suite_mask`, and
1356 :attr:`product_type`. (Contributed by Brian Curtin; :issue:`7766`.)
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001357
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001358* The :mod:`tarfile` module's default error handling has changed, to
1359 no longer suppress fatal errors. The default error level was previously 0,
1360 which meant that errors would only result in a message being written to the
1361 debug log, but because the debug log is not activated by default,
1362 these errors go unnoticed. The default error level is now 1,
1363 which raises an exception if there's an error.
1364 (Changed by Lars Gustäbel; :issue:`7357`.)
1365
Ezio Melotti021f3342010-04-06 03:26:49 +00001366 :mod:`tarfile` now supports filtering the :class:`~tarfile.TarInfo`
1367 objects being added to a tar file. When you call :meth:`~tarfile.TarFile.add`,
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001368 instance, you may supply an optional *filter* argument
1369 that's a callable. The *filter* callable will be passed the
Ezio Melotti021f3342010-04-06 03:26:49 +00001370 :class:`~tarfile.TarInfo` for every file being added, and can modify and return it.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001371 If the callable returns ``None``, the file will be excluded from the
1372 resulting archive. This is more powerful than the existing
1373 *exclude* argument, which has therefore been deprecated.
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001374 (Added by Lars Gustäbel; :issue:`6856`.)
Ezio Melotti021f3342010-04-06 03:26:49 +00001375 The :class:`~tarfile.TarFile` class also now supports the context manager protocol.
Andrew M. Kuchlingfed15762010-03-08 12:00:39 +00001376 (Added by Lars Gustäbel; :issue:`7232`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001377
Ezio Melotti021f3342010-04-06 03:26:49 +00001378* The :meth:`~threading.Event.wait` method of the :class:`threading.Event` class
1379 now returns the internal flag on exit. This means the method will usually
1380 return true because :meth:`~threading.Event.wait` is supposed to block until the
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001381 internal flag becomes true. The return value will only be false if
1382 a timeout was provided and the operation timed out.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001383 (Contributed by Tim Lesher; :issue:`1674032`.)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001384
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001385* The Unicode database provided by the :mod:`unicodedata` module is
1386 now used internally to determine which characters are numeric,
1387 whitespace, or represent line breaks. The database also
1388 includes information from the :file:`Unihan.txt` data file (patch
1389 by Anders Chrigström and Amaury Forgeot d'Arc; :issue:`1571184`)
1390 and has been updated to version 5.2.0 (updated by
1391 Florent Xicluna; :issue:`8024`).
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001392
Andrew M. Kuchling04b99cc2010-05-04 01:24:22 +00001393* The :mod:`urlparse` module's :func:`~urlparse.urlsplit` now handles
1394 unknown URL schemes in a fashion compliant with :rfc:`3986`: if the
1395 URL is of the form ``"<something>://..."``, the text before the
1396 ``://`` is treated as the scheme, even if it's a made-up scheme that
1397 the module doesn't know about. This change may break code that
1398 worked around the old behaviour. For example, Python 2.6.4 or 2.5
1399 will return the following:
1400
1401 >>> import urlparse
1402 >>> urlparse.urlsplit('invented://host/filename?query')
1403 ('invented', '', '//host/filename?query', '', '')
1404
1405 Python 2.7 (and Python 2.6.5) will return:
1406
1407 >>> import urlparse
1408 >>> urlparse.urlsplit('invented://host/filename?query')
1409 ('invented', 'host', '/filename?query', '', '')
1410
1411 (Python 2.7 actually produces slightly different output, since it
1412 returns a named tuple instead of a standard tuple.)
1413
1414 The :mod:`urlparse` module also supports IPv6 literal addresses as defined by
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001415 :rfc:`2732` (contributed by Senthil Kumaran; :issue:`2987`). ::
1416
1417 >>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo')
1418 ParseResult(scheme='http', netloc='[1080::8:800:200C:417A]',
1419 path='/foo', params='', query='', fragment='')
1420
Ezio Melotti021f3342010-04-06 03:26:49 +00001421* The :class:`~UserDict.UserDict` class is now a new-style class. (Changed by
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001422 Benjamin Peterson.)
1423
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00001424* New class: the :class:`~weakref.WeakSet` class in the :mod:`weakref`
1425 module is a set that only holds weak references to its elements; elements
1426 will be removed once there are no references pointing to them.
1427 (Originally implemented in Python 3.x by Raymond Hettinger, and backported
1428 to 2.7 by Michael Foord.)
1429
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001430* The ElementTree library, :mod:`xml.etree`, no longer escapes
1431 ampersands and angle brackets when outputting an XML processing
Ezio Melotti021f3342010-04-06 03:26:49 +00001432 instruction (which looks like ``<?xml-stylesheet href="#style1"?>``)
1433 or comment (which looks like ``<!-- comment -->``).
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001434 (Patch by Neil Muller; :issue:`2746`.)
1435
Ezio Melotti021f3342010-04-06 03:26:49 +00001436* The :mod:`zipfile` module's :class:`~zipfile.ZipFile` now supports the context
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001437 management protocol, so you can write ``with zipfile.ZipFile(...) as f: ...``.
1438 (Contributed by Brian Curtin; :issue:`5511`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001439
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001440 :mod:`zipfile` now supports archiving empty directories and
1441 extracts them correctly. (Fixed by Kuba Wieczorek; :issue:`4710`.)
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001442 Reading files out of an archive is now faster, and interleaving
Ezio Melotti021f3342010-04-06 03:26:49 +00001443 :meth:`~zipfile.ZipFile.read` and :meth:`~zipfile.ZipFile.readline` now works correctly.
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001444 (Contributed by Nir Aides; :issue:`7610`.)
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001445
Ezio Melotti021f3342010-04-06 03:26:49 +00001446 The :func:`~zipfile.is_zipfile` function now
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001447 accepts a file object, in addition to the path names accepted in earlier
1448 versions. (Contributed by Gabriel Genellina; :issue:`4756`.)
1449
Ezio Melotti021f3342010-04-06 03:26:49 +00001450 The :meth:`~zipfile.ZipFile.writestr` method now has an optional *compress_type* parameter
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001451 that lets you override the default compression method specified in the
Ezio Melotti021f3342010-04-06 03:26:49 +00001452 :class:`~zipfile.ZipFile` constructor. (Contributed by Ronald Oussoren;
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001453 :issue:`6003`.)
1454
1455
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00001456New module: sysconfig
1457---------------------------------
1458
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001459The :mod:`sysconfig` module has been pulled out of the Distutils
1460package, becoming a new top-level module in its own right.
1461:mod:`sysconfig` provides functions for getting information about
1462Python's build process: compiler switches, installation paths, the
1463platform name, and whether Python is running from its source
1464directory.
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00001465
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001466Some of the functions in the module are:
1467
1468* :func:`~sysconfig.get_config_var` returns variables from Python's
1469 Makefile and the :file:`pyconfig.h` file.
1470* :func:`~sysconfig.get_config_vars` returns a dictionary containing
1471 all of the configuration variables.
1472* :func:`~sysconfig.getpath` returns the configured path for
1473 a particular type of module: the standard library,
1474 site-specific modules, platform-specific modules, etc.
1475* :func:`~sysconfig.is_python_build` returns true if you're running a
1476 binary from a Python source tree, and false otherwise.
1477
1478Consult the :mod:`sysconfig` documentation for more details and for
1479a complete list of functions.
1480
1481The Distutils package and :mod:`sysconfig` are now maintained and
1482renamed by Tarek Ziadé.
1483
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00001484
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001485Updated module: ElementTree 1.3
1486---------------------------------
1487
1488XXX write this.
1489
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001490.. ======================================================================
1491.. whole new modules get described in subsections here
1492
Tarek Ziadé2b210692010-02-02 23:39:40 +00001493
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001494Unit Testing Enhancements
1495---------------------------------
1496
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001497The :mod:`unittest` module was greatly enhanced; many
1498new features were added. Most of these features were implemented
1499by Michael Foord, unless otherwise noted.
1500
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001501When used from the command line, the module can automatically discover
1502tests. It's not as fancy as `py.test <http://pytest.org>`__ or
1503`nose <http://code.google.com/p/python-nose/>`__, but provides a simple way
1504to run tests kept within a set of package directories. For example,
1505the following command will search the :file:`test/` subdirectory for
1506any importable test files named ``test*.py``::
1507
1508 python -m unittest discover -s test
1509
1510Consult the :mod:`unittest` module documentation for more details.
1511(Developed in :issue:`6001`.)
1512
1513The :func:`main` function supports some other new options:
1514
1515* :option:`-b` or :option:`--buffer` will buffer the standard output
1516 and standard error streams during each test. If the test passes,
1517 any resulting output will be discard; on failure, the buffered
1518 output will be displayed.
1519
1520* :option:`-c` or :option:`--catch` will cause the control-C interrupt
1521 to be handled more gracefully. Instead of interrupting the test
1522 process immediately, the currently running test will be completed
1523 and then the resulting partial results will be reported. If you're
1524 impatient, a second press of control-C will cause an immediate
1525 interruption.
1526
1527 This control-C handler tries to avoid interfering when the code
1528 being tested or the tests being run have defined a signal handler of
1529 their own, by noticing that a signal handler was already set and
1530 calling it. If this doesn't work for you, there's a
1531 :func:`removeHandler` decorator that can be used to mark tests that
1532 should have the control-C handling disabled.
1533
1534* :option:`-f` or :option:`--failfast` makes
1535 test execution stop immediately when a test fails instead of
1536 continuing to execute further tests. (Suggested by Cliff Dyer and
1537 implemented by Michael Foord; :issue:`8074`.)
1538
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001539The progress messages now shows 'x' for expected failures
1540and 'u' for unexpected successes when run in verbose mode.
1541(Contributed by Benjamin Peterson.)
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001542
1543Test cases can raise the :exc:`~unittest.SkipTest` exception to skip a
1544test. (:issue:`1034053`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001545
Ezio Melotti021f3342010-04-06 03:26:49 +00001546The error messages for :meth:`~unittest.TestCase.assertEqual`,
1547:meth:`~unittest.TestCase.assertTrue`, and :meth:`~unittest.TestCase.assertFalse`
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001548failures now provide more information. If you set the
Ezio Melotti021f3342010-04-06 03:26:49 +00001549:attr:`~unittest.TestCase.longMessage` attribute of your :class:`~unittest.TestCase` classes to
1550True, both the standard error message and any additional message you
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001551provide will be printed for failures. (Added by Michael Foord; :issue:`5663`.)
1552
Ezio Melotti021f3342010-04-06 03:26:49 +00001553The :meth:`~unittest.TestCase.assertRaises` method now
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001554return a context handler when called without providing a callable
1555object to run. For example, you can write this::
1556
1557 with self.assertRaises(KeyError):
Ezio Melotti021f3342010-04-06 03:26:49 +00001558 {}['foo']
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001559
1560(Implemented by Antoine Pitrou; :issue:`4444`.)
1561
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001562.. rev 78774
1563
1564Module- and class-level setup and teardown fixtures are now supported.
Ezio Melotti021f3342010-04-06 03:26:49 +00001565Modules can contain :func:`~unittest.setUpModule` and :func:`~unittest.tearDownModule`
1566functions. Classes can have :meth:`~unittest.TestCase.setUpClass` and
1567:meth:`~unittest.TestCase.tearDownClass` methods that must be defined as class methods
1568(using ``@classmethod`` or equivalent). These functions and
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001569methods are invoked when the test runner switches to a test case in a
1570different module or class.
1571
Ezio Melotti021f3342010-04-06 03:26:49 +00001572The methods :meth:`~unittest.TestCase.addCleanup` and
1573:meth:`~unittest.TestCase.doCleanups` were added.
1574:meth:`~unittest.TestCase.addCleanup` allows you to add cleanup functions that
1575will be called unconditionally (after :meth:`~unittest.TestCase.setUp` if
1576:meth:`~unittest.TestCase.setUp` fails, otherwise after :meth:`~unittest.TestCase.tearDown`). This allows
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001577for much simpler resource allocation and deallocation during tests
1578(:issue:`5679`).
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001579
1580A number of new methods were added that provide more specialized
1581tests. Many of these methods were written by Google engineers
1582for use in their test suites; Gregory P. Smith, Michael Foord, and
1583GvR worked on merging them into Python's version of :mod:`unittest`.
1584
Ezio Melotti021f3342010-04-06 03:26:49 +00001585* :meth:`~unittest.TestCase.assertIsNone` and :meth:`~unittest.TestCase.assertIsNotNone` take one
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001586 expression and verify that the result is or is not ``None``.
1587
Ezio Melotti021f3342010-04-06 03:26:49 +00001588* :meth:`~unittest.TestCase.assertIs` and :meth:`~unittest.TestCase.assertIsNot`
1589 take two values and check whether the two values evaluate to the same object or not.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001590 (Added by Michael Foord; :issue:`2578`.)
1591
Ezio Melotti021f3342010-04-06 03:26:49 +00001592* :meth:`~unittest.TestCase.assertIsInstance` and
1593 :meth:`~unittest.TestCase.assertNotIsInstance` check whether
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00001594 the resulting object is an instance of a particular class, or of
1595 one of a tuple of classes. (Added by Georg Brandl; :issue:`7031`.)
1596
Ezio Melotti021f3342010-04-06 03:26:49 +00001597* :meth:`~unittest.TestCase.assertGreater`, :meth:`~unittest.TestCase.assertGreaterEqual`,
1598 :meth:`~unittest.TestCase.assertLess`, and :meth:`~unittest.TestCase.assertLessEqual` compare
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001599 two quantities.
1600
Ezio Melotti021f3342010-04-06 03:26:49 +00001601* :meth:`~unittest.TestCase.assertMultiLineEqual` compares two strings, and if they're
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001602 not equal, displays a helpful comparison that highlights the
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001603 differences in the two strings. This comparison is now used by
Ezio Melotti021f3342010-04-06 03:26:49 +00001604 default when Unicode strings are compared with :meth:`~unittest.TestCase.assertEqual`.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001605
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001606* :meth:`~unittest.TestCase.assertRegexpMatches` and
1607 :meth:`~unittest.TestCase.assertNotRegexpMatches` checks whether the
1608 first argument is a string matching or not matching the regular
1609 expression provided as the second argument (:issue:`8038`).
Ezio Melotti021f3342010-04-06 03:26:49 +00001610
1611* :meth:`~unittest.TestCase.assertRaisesRegexp` checks whether a particular exception
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001612 is raised, and then also checks that the string representation of
1613 the exception matches the provided regular expression.
1614
Ezio Melotti021f3342010-04-06 03:26:49 +00001615* :meth:`~unittest.TestCase.assertIn` and :meth:`~unittest.TestCase.assertNotIn`
1616 tests whether *first* is or is not in *second*.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001617
Ezio Melotti021f3342010-04-06 03:26:49 +00001618* :meth:`~unittest.TestCase.assertItemsEqual` tests whether two provided sequences
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001619 contain the same elements.
1620
Ezio Melotti021f3342010-04-06 03:26:49 +00001621* :meth:`~unittest.TestCase.assertSetEqual` compares whether two sets are equal, and
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001622 only reports the differences between the sets in case of error.
1623
Ezio Melotti021f3342010-04-06 03:26:49 +00001624* Similarly, :meth:`~unittest.TestCase.assertListEqual` and :meth:`~unittest.TestCase.assertTupleEqual`
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001625 compare the specified types and explain any differences without necessarily
1626 printing their full values; these methods are now used by default
Ezio Melotti021f3342010-04-06 03:26:49 +00001627 when comparing lists and tuples using :meth:`~unittest.TestCase.assertEqual`.
1628 More generally, :meth:`~unittest.TestCase.assertSequenceEqual` compares two sequences
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001629 and can optionally check whether both sequences are of a
1630 particular type.
1631
Ezio Melotti021f3342010-04-06 03:26:49 +00001632* :meth:`~unittest.TestCase.assertDictEqual` compares two dictionaries and reports the
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001633 differences; it's now used by default when you compare two dictionaries
Ezio Melotti021f3342010-04-06 03:26:49 +00001634 using :meth:`~unittest.TestCase.assertEqual`. :meth:`~unittest.TestCase.assertDictContainsSubset` checks whether
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001635 all of the key/value pairs in *first* are found in *second*.
1636
Ezio Melotti021f3342010-04-06 03:26:49 +00001637* :meth:`~unittest.TestCase.assertAlmostEqual` and :meth:`~unittest.TestCase.assertNotAlmostEqual` test
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001638 whether *first* and *second* are approximately equal. This method
1639 can either round their difference to an optionally-specified number
1640 of *places* (the default is 7) and compare it to zero, or require
1641 the difference to be smaller than a supplied *delta* value.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001642
Ezio Melotti021f3342010-04-06 03:26:49 +00001643* :meth:`~unittest.TestLoader.loadTestsFromName` properly honors the
1644 :attr:`~unittest.TestLoader.suiteClass` attribute of
1645 the :class:`~unittest.TestLoader`. (Fixed by Mark Roddy; :issue:`6866`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001646
Ezio Melotti021f3342010-04-06 03:26:49 +00001647* A new hook lets you extend the :meth:`~unittest.TestCase.assertEqual` method to handle
1648 new data types. The :meth:`~unittest.TestCase.addTypeEqualityFunc` method takes a type
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001649 object and a function. The function will be used when both of the
1650 objects being compared are of the specified type. This function
1651 should compare the two objects and raise an exception if they don't
1652 match; it's a good idea for the function to provide additional
1653 information about why the two objects are matching, much as the new
1654 sequence comparison methods do.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001655
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001656:func:`unittest.main` now takes an optional ``exit`` argument. If
Ezio Melotti021f3342010-04-06 03:26:49 +00001657False, :func:`~unittest.main` doesn't call :func:`sys.exit`, allowing it to be
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001658used from the interactive interpreter. (Contributed by J. Pablo
1659Fernández; :issue:`3379`.)
1660
Ezio Melotti021f3342010-04-06 03:26:49 +00001661:class:`~unittest.TestResult` has new :meth:`~unittest.TestResult.startTestRun` and
1662:meth:`~unittest.TestResult.stopTestRun` methods that are called immediately before
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001663and after a test run. (Contributed by Robert Collins; :issue:`5728`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001664
1665With all these changes, the :file:`unittest.py` was becoming awkwardly
1666large, so the module was turned into a package and the code split into
1667several files (by Benjamin Peterson). This doesn't affect how the
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001668module is imported or used.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001669
1670
1671.. _importlib-section:
1672
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001673importlib: Importing Modules
1674------------------------------
1675
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001676Python 3.1 includes the :mod:`importlib` package, a re-implementation
1677of the logic underlying Python's :keyword:`import` statement.
1678:mod:`importlib` is useful for implementors of Python interpreters and
Brett Cannonca2dc472009-12-22 02:37:37 +00001679to users who wish to write new importers that can participate in the
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001680import process. Python 2.7 doesn't contain the complete
1681:mod:`importlib` package, but instead has a tiny subset that contains
Ezio Melotti021f3342010-04-06 03:26:49 +00001682a single function, :func:`~importlib.import_module`.
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001683
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001684``import_module(name, package=None)`` imports a module. *name* is
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001685a string containing the module or package's name. It's possible to do
1686relative imports by providing a string that begins with a ``.``
1687character, such as ``..utils.errors``. For relative imports, the
1688*package* argument must be provided and is the name of the package that
1689will be used as the anchor for
Ezio Melotti021f3342010-04-06 03:26:49 +00001690the relative import. :func:`~importlib.import_module` both inserts the imported
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001691module into ``sys.modules`` and returns the module object.
1692
1693Here are some examples::
1694
1695 >>> from importlib import import_module
1696 >>> anydbm = import_module('anydbm') # Standard absolute import
1697 >>> anydbm
1698 <module 'anydbm' from '/p/python/Lib/anydbm.py'>
1699 >>> # Relative import
1700 >>> sysconfig = import_module('..sysconfig', 'distutils.command')
1701 >>> sysconfig
1702 <module 'distutils.sysconfig' from '/p/python/Lib/distutils/sysconfig.pyc'>
1703
1704:mod:`importlib` was implemented by Brett Cannon and introduced in
1705Python 3.1.
1706
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001707
Andrew M. Kuchlinga17cd4a2009-01-31 02:50:09 +00001708ttk: Themed Widgets for Tk
1709--------------------------
1710
1711Tcl/Tk 8.5 includes a set of themed widgets that re-implement basic Tk
1712widgets but have a more customizable appearance and can therefore more
1713closely resemble the native platform's widgets. This widget
1714set was originally called Tile, but was renamed to Ttk (for "themed Tk")
1715on being added to Tcl/Tck release 8.5.
1716
1717XXX write a brief discussion and an example here.
1718
1719The :mod:`ttk` module was written by Guilherme Polo and added in
1720:issue:`2983`. An alternate version called ``Tile.py``, written by
1721Martin Franklin and maintained by Kevin Walzer, was proposed for
1722inclusion in :issue:`2618`, but the authors argued that Guilherme
1723Polo's work was more comprehensive.
1724
Georg Brandl0516f812009-11-18 18:52:35 +00001725
1726Deprecations and Removals
1727=========================
1728
1729* :func:`contextlib.nested`, which allows handling more than one context manager
1730 with one :keyword:`with` statement, has been deprecated; :keyword:`with`
1731 supports multiple context managers syntactically now.
1732
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001733.. ======================================================================
1734
1735
1736Build and C API Changes
1737=======================
1738
1739Changes to Python's build process and to the C API include:
1740
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001741* The latest release of the GNU Debugger, GDB 7, can be `scripted
1742 using Python
1743 <http://sourceware.org/gdb/current/onlinedocs/gdb/Python.html>`__.
1744 When you begin debugging an executable program P, GDB will look for
1745 a file named ``P-gdb.py`` and automatically read it. Dave Malcolm
1746 contributed a :file:`python-gdb.py` that adds a number of useful
1747 commands when debugging Python itself. For example, there are
1748 ``py-up`` and ``py-down`` that go up or down one Python stack frame,
1749 which usually corresponds to several C stack frames. ``py-print``
1750 prints the value of a Python variable, and ``py-bt`` prints the
1751 Python stack trace. (Added as a result of :issue:`8032`.)
1752
Andrew M. Kuchling10b1ec92009-01-02 21:00:35 +00001753* If you use the :file:`.gdbinit` file provided with Python,
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001754 the "pyo" macro in the 2.7 version now works correctly when the thread being
1755 debugged doesn't hold the GIL; the macro now acquires it before printing.
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001756 (Contributed by Victor Stinner; :issue:`3632`.)
1757
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001758* :cfunc:`Py_AddPendingCall` is now thread-safe, letting any
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001759 worker thread submit notifications to the main Python thread. This
1760 is particularly useful for asynchronous IO operations.
1761 (Contributed by Kristjan Valur Jonsson; :issue:`4293`.)
1762
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001763* New function: :cfunc:`PyCode_NewEmpty` creates an empty code object;
1764 only the filename, function name, and first line number are required.
1765 This is useful to extension modules that are attempting to
1766 construct a more useful traceback stack. Previously such
1767 extensions needed to call :cfunc:`PyCode_New`, which had many
1768 more arguments. (Added by Jeffrey Yasskin.)
1769
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001770* New function: :cfunc:`PyErr_NewExceptionWithDoc` creates a new
1771 exception class, just as the existing :cfunc:`PyErr_NewException` does,
1772 but takes an extra ``char *`` argument containing the docstring for the
1773 new exception class. (Added by the 'lekma' user on the Python bug tracker;
1774 :issue:`7033`.)
1775
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001776* New function: :cfunc:`PyFrame_GetLineNumber` takes a frame object
1777 and returns the line number that the frame is currently executing.
1778 Previously code would need to get the index of the bytecode
1779 instruction currently executing, and then look up the line number
1780 corresponding to that address. (Added by Jeffrey Yasskin.)
1781
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001782* New functions: :cfunc:`PyLong_AsLongAndOverflow` and
1783 :cfunc:`PyLong_AsLongLongAndOverflow` approximates a Python long
1784 integer as a C :ctype:`long` or :ctype:`long long`.
1785 If the number is too large to fit into
1786 the output type, an *overflow* flag is set and returned to the caller.
1787 (Contributed by Case Van Horsen; :issue:`7528` and :issue:`7767`.)
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001788
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00001789* New function: stemming from the rewrite of string-to-float conversion,
1790 a new :cfunc:`PyOS_string_to_double` function was added. The old
1791 :cfunc:`PyOS_ascii_strtod` and :cfunc:`PyOS_ascii_atof` functions
1792 are now deprecated.
1793
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001794* New macros: the Python header files now define the following macros:
1795 :cmacro:`Py_ISALNUM`,
1796 :cmacro:`Py_ISALPHA`,
1797 :cmacro:`Py_ISDIGIT`,
1798 :cmacro:`Py_ISLOWER`,
1799 :cmacro:`Py_ISSPACE`,
1800 :cmacro:`Py_ISUPPER`,
1801 :cmacro:`Py_ISXDIGIT`,
1802 and :cmacro:`Py_TOLOWER`, :cmacro:`Py_TOUPPER`.
1803 All of these functions are analogous to the C
1804 standard macros for classifying characters, but ignore the current
1805 locale setting, because in
1806 several places Python needs to analyze characters in a
1807 locale-independent way. (Added by Eric Smith;
1808 :issue:`5793`.)
1809
1810 .. XXX these macros don't seem to be described in the c-api docs.
1811
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00001812* Removed function: :cmacro:`PyEval_CallObject` is now only available
1813 as a macro. A function version was being kept around to preserve
1814 ABI linking compatibility, but that was in 1997; it can certainly be
1815 deleted. (Removed by Antoine Pitrou; :issue:`8276`.)
1816
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001817* New format codes: the :cfunc:`PyFormat_FromString`,
1818 :cfunc:`PyFormat_FromStringV`, and :cfunc:`PyErr_Format` now
1819 accepts ``%lld`` and ``%llu`` format codes for displaying values of
1820 C's :ctype:`long long` types.
1821 (Contributed by Mark Dickinson; :issue:`7228`.)
1822
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001823* The complicated interaction between threads and process forking has
1824 been changed. Previously, the child process created by
1825 :func:`os.fork` might fail because the child is created with only a
1826 single thread running, the thread performing the :func:`os.fork`.
1827 If other threads were holding a lock, such as Python's import lock,
1828 when the fork was performed, the lock would still be marked as
1829 "held" in the new process. But in the child process nothing would
1830 ever release the lock, since the other threads weren't replicated,
1831 and the child process would no longer be able to perform imports.
1832
1833 Python 2.7 now acquires the import lock before performing an
1834 :func:`os.fork`, and will also clean up any locks created using the
1835 :mod:`threading` module. C extension modules that have internal
1836 locks, or that call :cfunc:`fork()` themselves, will not benefit
1837 from this clean-up.
1838
1839 (Fixed by Thomas Wouters; :issue:`1590864`.)
1840
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00001841* The :cfunc:`Py_Finalize` function now calls the internal
1842 :func:`threading._shutdown` function; this prevents some exceptions from
1843 being raised when an interpreter shuts down.
1844 (Patch by Adam Olsen; :issue:`1722344`.)
1845
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00001846* When using the :ctype:`PyMemberDef` structure to define attributes
1847 of a type, Python will no longer let you try to delete or set a
1848 :const:`T_STRING_INPLACE` attribute.
1849
1850 .. rev 79644
1851
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00001852* Global symbols defined by the :mod:`ctypes` module are now prefixed
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001853 with ``Py``, or with ``_ctypes``. (Implemented by Thomas
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00001854 Heller; :issue:`3102`.)
1855
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00001856* New configure option: the :option:`--with-system-expat` switch allows
1857 building the :mod:`pyexpat` module to use the system Expat library.
1858 (Contributed by Arfrever Frehtes Taifersar Arahesis; :issue:`7609`.)
1859
Andrew M. Kuchlingce690522010-04-13 01:32:51 +00001860* New configure option: compiling Python with the
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00001861 :option:`--with-valgrind` option will now disable the pymalloc
Andrew M. Kuchlingce690522010-04-13 01:32:51 +00001862 allocator, which is difficult for the Valgrind memory-error detector
1863 to analyze correctly.
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00001864 Valgrind will therefore be better at detecting memory leaks and
1865 overruns. (Contributed by James Henstridge; :issue:`2422`.)
1866
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +00001867* New configure option: you can now supply no arguments to
1868 :option:`--with-dbmliborder=` in order to build none of the various
1869 DBM modules. (Added by Arfrever Frehtes Taifersar Arahesis;
1870 :issue:`6491`.)
1871
Andrew M. Kuchling77069572009-03-31 01:21:01 +00001872* The :program:`configure` script now checks for floating-point rounding bugs
1873 on certain 32-bit Intel chips and defines a :cmacro:`X87_DOUBLE_ROUNDING`
1874 preprocessor definition. No code currently uses this definition,
1875 but it's available if anyone wishes to use it.
1876 (Added by Mark Dickinson; :issue:`2937`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001877
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001878 :program:`configure` also now sets a :envvar:`LDCXXSHARED` Makefile
1879 variable for supporting C++ linking. (Contributed by Arfrever
1880 Frehtes Taifersar Arahesis; :issue:`1222585`.)
1881
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001882* The build process now creates the necessary files for pkg-config
1883 support. (Contributed by Clinton Roy; :issue:`3585`.)
1884
1885* The build process now supports Subversion 1.7. (Contributed by
1886 Arfrever Frehtes Taifersar Arahesis; :issue:`6094`.)
1887
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001888
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001889.. ======================================================================
1890
1891Port-Specific Changes: Windows
1892-----------------------------------
1893
Andrew M. Kuchling10b1ec92009-01-02 21:00:35 +00001894* The :mod:`msvcrt` module now contains some constants from
1895 the :file:`crtassem.h` header file:
1896 :data:`CRT_ASSEMBLY_VERSION`,
1897 :data:`VC_ASSEMBLY_PUBLICKEYTOKEN`,
1898 and :data:`LIBRARIES_ASSEMBLY_NAME_PREFIX`.
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001899 (Contributed by David Cournapeau; :issue:`4365`.)
1900
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00001901* The :mod:`_winreg` module for accessing the registry now implements
1902 the :func:`CreateKeyEx` and :func:`DeleteKeyEx` functions, extended
1903 versions of previously-supported functions that take several extra
1904 arguments. The :func:`DisableReflectionKey`,
1905 :func:`EnableReflectionKey`, and :func:`QueryReflectionKey` were also
1906 tested and documented.
1907 (Implemented by Brian Curtin: :issue:`7347`.)
1908
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001909* The new :cfunc:`_beginthreadex` API is used to start threads, and
1910 the native thread-local storage functions are now used.
1911 (Contributed by Kristjan Valur Jonsson; :issue:`3582`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001912
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +00001913* The :func:`os.kill` function now works on Windows. The signal value
1914 can be the constants :const:`CTRL_C_EVENT`,
1915 :const:`CTRL_BREAK_EVENT`, or any integer. The Control-C and
1916 Control-Break keystroke events can be sent to subprocesses; any
1917 other value will use the :cfunc:`TerminateProcess` API.
1918 (Contributed by Miki Tebeka; :issue:`1220212`.)
1919
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001920* The :func:`os.listdir` function now correctly fails
1921 for an empty path. (Fixed by Hirokazu Yamamoto; :issue:`5913`.)
1922
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001923* The :mod:`mimelib` module will now read the MIME database from
1924 the Windows registry when initializing.
1925 (Patch by Gabriel Genellina; :issue:`4969`.)
1926
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001927.. ======================================================================
1928
1929Port-Specific Changes: Mac OS X
1930-----------------------------------
1931
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001932* The path ``/Library/Python/2.7/site-packages`` is now appended to
Andrew M. Kuchling77069572009-03-31 01:21:01 +00001933 ``sys.path``, in order to share added packages between the system
1934 installation and a user-installed copy of the same version.
1935 (Changed by Ronald Oussoren; :issue:`4865`.)
1936
Andrew M. Kuchling04b99cc2010-05-04 01:24:22 +00001937Port-Specific Changes: FreeBSD
1938-----------------------------------
1939
1940* FreeBSD 7.1's :const:`SO_SETFIB` constant, used with
1941 :func:`~socket.getsockopt`/:func:`~socket.setsockopt` to select an
1942 alternate routing table, is now available in the :mod:`socket`
1943 module. (Added by Kyle VanderBeek; :issue:`8235`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001944
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001945Other Changes and Fixes
1946=======================
1947
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00001948* Two benchmark scripts, :file:`iobench` and :file:`ccbench`, were
1949 added to the :file:`Tools` directory. :file:`iobench` measures the
Antoine Pitroudde96e62010-02-08 20:25:47 +00001950 speed of built-in file I/O objects (as returned by :func:`open`)
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001951 while performing various operations, and :file:`ccbench` is a
1952 concurrency benchmark that tries to measure computing throughput,
1953 thread switching latency, and IO processing bandwidth when
1954 performing several tasks using a varying number of threads.
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00001955
Andrew M. Kuchling77069572009-03-31 01:21:01 +00001956* When importing a module from a :file:`.pyc` or :file:`.pyo` file
1957 with an existing :file:`.py` counterpart, the :attr:`co_filename`
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00001958 attributes of the resulting code objects are overwritten when the
1959 original filename is obsolete. This can happen if the file has been
1960 renamed, moved, or is accessed through different paths. (Patch by
1961 Ziga Seilnacht and Jean-Paul Calderone; :issue:`1180193`.)
Andrew M. Kuchling77069572009-03-31 01:21:01 +00001962
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001963* The :file:`regrtest.py` script now takes a :option:`--randseed=`
1964 switch that takes an integer that will be used as the random seed
1965 for the :option:`-r` option that executes tests in random order.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001966 The :option:`-r` option also reports the seed that was used
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001967 (Added by Collin Winter.)
1968
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00001969* Another :file:`regrtest.py` switch is :option:`-j`, which
1970 takes an integer specifying how many tests run in parallel. This
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001971 allows reducing the total runtime on multi-core machines.
Antoine Pitrou4698d992009-05-31 14:20:14 +00001972 This option is compatible with several other options, including the
1973 :option:`-R` switch which is known to produce long runtimes.
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00001974 (Added by Antoine Pitrou, :issue:`6152`.) This can also be used
1975 with a new :option:`-F` switch that runs selected tests in a loop
1976 until they fail. (Added by Antoine Pitrou; :issue:`7312`.)
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001977
Andrew M. Kuchling85f928a2010-04-15 01:42:27 +00001978* When executed as a script, the :file:`py_compile.py` module now
1979 accepts ``'-'`` as an argument, which will read standard input for
1980 the list of filenames to be compiled. (Contributed by Piotr
1981 Ożarowski; :issue:`8233`.)
1982
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001983.. ======================================================================
1984
1985Porting to Python 2.7
1986=====================
1987
1988This section lists previously described changes and other bugfixes
1989that may require changes to your code:
1990
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00001991* The string :meth:`format` method changed the default precision used
1992 for floating-point and complex numbers from 6 decimal
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001993 places to 12, which matches the precision used by :func:`str`.
1994 (Changed by Eric Smith; :issue:`5920`.)
1995
Amaury Forgeot d'Arc901f2002009-06-09 23:08:13 +00001996* Because of an optimization for the :keyword:`with` statement, the special
1997 methods :meth:`__enter__` and :meth:`__exit__` must belong to the object's
1998 type, and cannot be directly attached to the object's instance. This
Amaury Forgeot d'Arcd81333c2009-06-10 20:30:19 +00001999 affects new-style classes (derived from :class:`object`) and C extension
Amaury Forgeot d'Arc901f2002009-06-09 23:08:13 +00002000 types. (:issue:`6101`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002001
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00002002* When a restricted set of attributes were set using ``__slots__``,
2003 deleting an unset attribute would not raise :exc:`AttributeError`
2004 as you would expect. Fixed by Benjamin Peterson; :issue:`7604`.)
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002005
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00002006In the standard library:
2007
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002008* When using :class:`Decimal` instances with a string's
2009 :meth:`format` method, the default alignment was previously
2010 left-alignment. This has been changed to right-alignment, which might
2011 change the output of your programs.
2012 (Changed by Mark Dickinson; :issue:`6857`.)
2013
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00002014 Comparisons involving a signaling NaN value (or ``sNAN``) now signal
2015 :const:`InvalidOperation` instead of silently returning a true or
2016 false value depending on the comparison operator. Quiet NaN values
2017 (or ``NaN``) are now hashable. (Fixed by Mark Dickinson;
2018 :issue:`7279`.)
2019
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00002020* The ElementTree library, :mod:`xml.etree`, no longer escapes
2021 ampersands and angle brackets when outputting an XML processing
2022 instruction (which looks like `<?xml-stylesheet href="#style1"?>`)
2023 or comment (which looks like `<!-- comment -->`).
2024 (Patch by Neil Muller; :issue:`2746`.)
2025
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00002026* The :meth:`readline` method of :class:`StringIO` objects now does
2027 nothing when a negative length is requested, as other file-like
2028 objects do. (:issue:`7348`).
2029
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002030* The :mod:`syslog` module will now use the value of ``sys.argv[0]`` as the
2031 identifier instead of the previous default value of ``'python'``.
2032 (Changed by Sean Reifschneider; :issue:`8451`.)
2033
Andrew M. Kuchling04b99cc2010-05-04 01:24:22 +00002034* The :mod:`urlparse` module's :func:`~urlparse.urlsplit` now handles
2035 unknown URL schemes in a fashion compliant with :rfc:`3986`: if the
2036 URL is of the form ``"<something>://..."``, the text before the
2037 ``://`` is treated as the scheme, even if it's a made-up scheme that
2038 the module doesn't know about. This change may break code that
2039 worked around the old behaviour. For example, Python 2.6.4 or 2.5
2040 will return the following:
2041
2042 >>> import urlparse
2043 >>> urlparse.urlsplit('invented://host/filename?query')
2044 ('invented', '', '//host/filename?query', '', '')
2045
2046 Python 2.7 (and Python 2.6.5) will return:
2047
2048 >>> import urlparse
2049 >>> urlparse.urlsplit('invented://host/filename?query')
2050 ('invented', 'host', '/filename?query', '', '')
2051
2052 (Python 2.7 actually produces slightly different output, since it
2053 returns a named tuple instead of a standard tuple.)
2054
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00002055For C extensions:
2056
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +00002057* C extensions that use integer format codes with the ``PyArg_Parse*``
2058 family of functions will now raise a :exc:`TypeError` exception
2059 instead of triggering a :exc:`DeprecationWarning` (:issue:`5080`).
2060
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00002061* Use the new :cfunc:`PyOS_string_to_double` function instead of the old
2062 :cfunc:`PyOS_ascii_strtod` and :cfunc:`PyOS_ascii_atof` functions,
2063 which are now deprecated.
2064
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +00002065
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002066.. ======================================================================
2067
2068
2069.. _acks27:
2070
2071Acknowledgements
2072================
2073
2074The author would like to thank the following people for offering
2075suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00002076article: Nick Coghlan, Ryan Lovett, R. David Murray, Hugh Secker-Walker.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002077