blob: 616191c3dcb4ac093588778d90c1d4a8350a97b0 [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. Kuchlinge86b7fe2010-05-06 14:14:09 +000011.. Big jobs: pep 391
Andrew M. Kuchling837a5382010-05-06 17:21:59 +000012.. Initial section: development plans for 2.x in future
13.. Initial section: changes in deprecation warning behaviour
14
Andrew M. Kuchling6d7dfa22010-04-11 12:49:37 +000015.. hyperlink all the methods & functions.
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +000016
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +000017.. T_STRING_INPLACE not described in main docs
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +000018.. XXX "Format String Syntax" in string.rst could use many more examples.
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +000019
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000020.. $Id$
21 Rules for maintenance:
22
23 * Anyone can add text to this document. Do not spend very much time
24 on the wording of your changes, because your text will probably
25 get rewritten to some degree.
26
27 * The maintainer will go through Misc/NEWS periodically and add
28 changes; it's therefore more important to add your changes to
29 Misc/NEWS than to this file.
30
31 * This is not a complete list of every single change; completeness
32 is the purpose of Misc/NEWS. Some changes I consider too small
33 or esoteric to include. If such a change is added to the text,
34 I'll just remove it. (This is another reason you shouldn't spend
35 too much time on writing your addition.)
36
37 * If you want to draw your new text to the attention of the
38 maintainer, add 'XXX' to the beginning of the paragraph or
39 section.
40
41 * It's OK to just add a fragmentary note about a change. For
42 example: "XXX Describe the transmogrify() function added to the
43 socket module." The maintainer will research the change and
44 write the necessary text.
45
46 * You can comment out your additions if you like, but it's not
47 necessary (especially when a final release is some months away).
48
Ezio Melotti021f3342010-04-06 03:26:49 +000049 * Credit the author of a patch or bugfix. Just the name is
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000050 sufficient; the e-mail address isn't necessary.
51
52 * It's helpful to add the bug/patch number in a parenthetical comment.
53
54 XXX Describe the transmogrify() function added to the socket
55 module.
56 (Contributed by P.Y. Developer; :issue:`12345`.)
57
58 This saves the maintainer some effort going through the SVN logs
59 when researching a change.
60
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +000061This article explains the new features in Python 2.7. The final
Andrew M. Kuchling837a5382010-05-06 17:21:59 +000062release of 2.7 is currently scheduled for July 2010; the detailed
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +000063schedule is described in :pep:`373`.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000064
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +000065Python 2.7 is planned to be the last major release in the 2.x series.
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +000066Though more major releases have not been absolutely ruled out, the
67Python maintainers are planning to focus more on Python 3.x. Despite
68that, it's likely that the 2.7 release will have a longer period of
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +000069maintenance compared to earlier 2.x versions.
70
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000071.. Compare with previous release in 2 - 3 sentences here.
72 add hyperlink when the documentation becomes available online.
73
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +000074.. _whatsnew27-python31:
75
76Python 3.1 Features
77=======================
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +000078
79Much as Python 2.6 incorporated features from Python 3.0,
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +000080version 2.7 incorporates some of the new features
81in Python 3.1. The 2.x series continues to provide tools
82for migrating to the 3.x series.
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +000083
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +000084A partial list of 3.1 features that were backported to 2.7:
85
Andrew M. Kuchling837a5382010-05-06 17:21:59 +000086* A new version of the :mod:`io` library, rewritten in C for performance.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +000087* The ordered-dictionary type described in :ref:`pep-0372`.
Andrew M. Kuchling8f254e72009-12-08 02:37:05 +000088* The new format specifier described in :ref:`pep-0378`.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +000089* The :class:`memoryview` object.
90* A small subset of the :mod:`importlib` module `described below <#importlib-section>`__.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +000091* Float-to-string and string-to-float conversions now round their
92 results more correctly. And :func:`repr` of a floating-point
93 number *x* returns a result that's guaranteed to round back to the
94 same number when converted back to a string.
95* The :cfunc:`PyLong_AsLongAndOverflow` C API function.
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +000096
97One porting change: the :option:`-3` switch now automatically
98enables the :option:`-Qwarn` switch that causes warnings
99about using classic division with integers and long integers.
100
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000101Other new Python3-mode warnings include:
102
103* :func:`operator.isCallable` and :func:`operator.sequenceIncludes`,
104 which are not supported in 3.x.
105
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000106.. ========================================================================
107.. Large, PEP-level features and changes should be described here.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000108.. ========================================================================
109
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000110.. _pep-0372:
111
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000112PEP 372: Adding an ordered dictionary to collections
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000113====================================================
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000114
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000115Regular Python dictionaries iterate over key/value pairs in arbitrary order.
116Over the years, a number of authors have written alternative implementations
117that remember the order that the keys were originally inserted. Based on
118the experiences from those implementations, a new
Ezio Melotti021f3342010-04-06 03:26:49 +0000119:class:`~collections.OrderedDict` class has been introduced in the
120:mod:`collections` module.
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000121
Ezio Melotti021f3342010-04-06 03:26:49 +0000122The :class:`~collections.OrderedDict` API is substantially the same as regular
123dictionaries but will iterate over keys and values in a guaranteed order
124depending on when a key was first inserted::
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000125
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000126 >>> from collections import OrderedDict
127 >>> d = OrderedDict([('first', 1), ('second', 2),
128 ... ('third', 3)])
129 >>> d.items()
130 [('first', 1), ('second', 2), ('third', 3)]
131
132If a new entry overwrites an existing entry, the original insertion
133position is left unchanged::
134
135 >>> d['second'] = 4
136 >>> d.items()
137 [('first', 1), ('second', 4), ('third', 3)]
138
139Deleting an entry and reinserting it will move it to the end::
140
141 >>> del d['second']
142 >>> d['second'] = 5
143 >>> d.items()
144 [('first', 1), ('third', 3), ('second', 5)]
145
Ezio Melotti021f3342010-04-06 03:26:49 +0000146The :meth:`~collections.OrderedDict.popitem` method has an optional *last*
147argument that defaults to True. If *last* is True, the most recently
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000148added key is returned and removed; if it's False, the
149oldest key is selected::
150
151 >>> od = OrderedDict([(x,0) for x in range(20)])
152 >>> od.popitem()
153 (19, 0)
154 >>> od.popitem()
155 (18, 0)
Ezio Melotti021f3342010-04-06 03:26:49 +0000156 >>> od.popitem(last=False)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000157 (0, 0)
Ezio Melotti021f3342010-04-06 03:26:49 +0000158 >>> od.popitem(last=False)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000159 (1, 0)
160
161Comparing two ordered dictionaries checks both the keys and values,
162and requires that the insertion order was the same::
163
164 >>> od1 = OrderedDict([('first', 1), ('second', 2),
165 ... ('third', 3)])
166 >>> od2 = OrderedDict([('third', 3), ('first', 1),
167 ... ('second', 2)])
Ezio Melotti021f3342010-04-06 03:26:49 +0000168 >>> od1 == od2
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000169 False
170 >>> # Move 'third' key to the end
Ezio Melotti021f3342010-04-06 03:26:49 +0000171 >>> del od2['third']; od2['third'] = 3
172 >>> od1 == od2
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000173 True
174
Ezio Melotti021f3342010-04-06 03:26:49 +0000175Comparing an :class:`~collections.OrderedDict` with a regular dictionary
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000176ignores the insertion order and just compares the keys and values.
177
Ezio Melotti021f3342010-04-06 03:26:49 +0000178How does the :class:`~collections.OrderedDict` work? It maintains a
179doubly-linked list of keys, appending new keys to the list as they're inserted.
180A secondary dictionary maps keys to their corresponding list node, so
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000181deletion doesn't have to traverse the entire linked list and therefore
182remains O(1).
183
184.. XXX check O(1)-ness with Raymond
Ezio Melotti021f3342010-04-06 03:26:49 +0000185.. Also check if the 'somenamedtuple' in the collection module should
186.. be replaced/removed in order to use
187.. :meth:`~collections.namedtuple._asdict()` (see below)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000188
189The standard library now supports use of ordered dictionaries in several
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +0000190modules.
191
192* The :mod:`ConfigParser` module uses them by default, letting
193 configuration files be read, modified, and then written back in their original
194 order.
195
196* The :meth:`~collections.somenamedtuple._asdict()` method for
197 :func:`collections.namedtuple` now returns an ordered dictionary with the
198 values appearing in the same order as the underlying tuple indices.
199
200* The :mod:`json` module's :class:`~json.JSONDecoder` class
201 constructor was extended with an *object_pairs_hook* parameter to
202 allow :class:`OrderedDict` instances to be built by the decoder.
203 Support was also added for third-party tools like
204 `PyYAML <http://pyyaml.org/>`_.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000205
Andrew M. Kuchling7fe65a02009-10-13 15:49:33 +0000206.. seealso::
207
208 :pep:`372` - Adding an ordered dictionary to collections
209 PEP written by Armin Ronacher and Raymond Hettinger;
210 implemented by Raymond Hettinger.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000211
212.. _pep-0378:
213
214PEP 378: Format Specifier for Thousands Separator
Ezio Melotti021f3342010-04-06 03:26:49 +0000215=================================================
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000216
217To make program output more readable, it can be useful to add
218separators to large numbers and render them as
21918,446,744,073,709,551,616 instead of 18446744073709551616.
220
221The fully general solution for doing this is the :mod:`locale` module,
222which can use different separators ("," in North America, "." in
223Europe) and different grouping sizes, but :mod:`locale` is complicated
224to use and unsuitable for multi-threaded applications where different
225threads are producing output for different locales.
226
227Therefore, a simple comma-grouping mechanism has been added to the
Ezio Melotti021f3342010-04-06 03:26:49 +0000228mini-language used by the :meth:`str.format` method. When
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000229formatting a floating-point number, simply include a comma between the
230width and the precision::
231
Eric Smithc4663852010-04-06 14:30:15 +0000232 >>> '{:20,.2f}'.format(18446744073709551616.0)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000233 '18,446,744,073,709,551,616.00'
234
Eric Smith6a928602010-04-06 15:17:33 +0000235When formatting an integer, include the comma after the width:
236
237 >>> '{:20,d}'.format(18446744073709551616)
238 '18,446,744,073,709,551,616'
239
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000240This mechanism is not adaptable at all; commas are always used as the
241separator and the grouping is always into three-digit groups. The
242comma-formatting mechanism isn't as general as the :mod:`locale`
243module, but it's easier to use.
244
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000245.. seealso::
246
247 :pep:`378` - Format Specifier for Thousands Separator
248 PEP written by Raymond Hettinger; implemented by Eric Smith.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000249
Andrew M. Kuchlingab21f752010-03-02 13:55:33 +0000250PEP 389: The argparse Module for Parsing Command Lines
251======================================================
252
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000253The :mod:`argparse` module for parsing command-line arguments was
254added, intended as a more powerful replacement for the
255:mod:`optparse` module.
256
257This means Python now supports three different modules for parsing
258command-line arguments: :mod:`getopt`, :mod:`optparse`, and
259:mod:`argparse`. The :mod:`getopt` module closely resembles the C
260:cfunc:`getopt` function, so it remains useful if you're writing a
261Python prototype that will eventually be rewritten in C.
262:mod:`optparse` becomes redundant, but there are no plans to remove it
263because there are many scripts still using it, and there's no
264automated way to update these scripts. (Making the :mod:`argparse`
265API consistent with :mod:`optparse`'s interface was discussed but
266rejected as too messy and difficult.)
267
Andrew M. Kuchlingf03641a2010-04-14 01:14:59 +0000268In short, if you're writing a new script and don't need to worry
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000269about compatibility with earlier versions of Python, use
270:mod:`argparse` instead of :mod:`optparse`.
271
Andrew M. Kuchlingf03641a2010-04-14 01:14:59 +0000272Here's an example::
273
274 import argparse
275
276 parser = argparse.ArgumentParser(description='Command-line example.')
277
278 # Add optional switches
279 parser.add_argument('-v', action='store_true', dest='is_verbose',
280 help='produce verbose output')
281 parser.add_argument('-o', action='store', dest='output',
282 metavar='FILE',
283 help='direct output to FILE instead of stdout')
284 parser.add_argument('-C', action='store', type=int, dest='context',
285 metavar='NUM', default=0,
286 help='display NUM lines of added context')
287
288 # Allow any number of additional arguments.
289 parser.add_argument(nargs='*', action='store', dest='inputs',
290 help='input filenames (default is stdin)')
291
292 args = parser.parse_args()
293 print args.__dict__
294
295Unless you override it, :option:`-h` and :option:`--help` switches
296are automatically added, and produce neatly formatted output::
297
298 -> ./python.exe argparse-example.py --help
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +0000299 usage: argparse-example.py [-h] [-v] [-o FILE] [-C NUM] [inputs [inputs ...]]
Andrew M. Kuchlingf03641a2010-04-14 01:14:59 +0000300
301 Command-line example.
302
303 positional arguments:
304 inputs input filenames (default is stdin)
305
306 optional arguments:
307 -h, --help show this help message and exit
308 -v produce verbose output
309 -o FILE direct output to FILE instead of stdout
310 -C NUM display NUM lines of added context
311
312Similarly to :mod:`optparse`, the command-line switches and arguments
313are returned as an object with attributes named by the *dest* parameters::
314
315 -> ./python.exe argparse-example.py -v
316 {'output': None, 'is_verbose': True, 'context': 0, 'inputs': []}
317
318 -> ./python.exe argparse-example.py -v -o /tmp/output -C 4 file1 file2
319 {'output': '/tmp/output', 'is_verbose': True, 'context': 4,
320 'inputs': ['file1', 'file2']}
321
322:mod:`argparse` has much fancier validation than :mod:`optparse`; you
323can specify an exact number of arguments as an integer, 0 or more
324arguments by passing ``'*'``, 1 or more by passing ``'+'``, or an
325optional argument with ``'?'``. A top-level parser can contain
326sub-parsers, so you can define subcommands that have different sets of
327switches, as in ``svn commit``, ``svn checkout``, etc. You can
328specify an argument type as :class:`~argparse.FileType`, which will
329automatically open files for you and understands that ``'-'`` means
330standard input or output.
Andrew M. Kuchlingab21f752010-03-02 13:55:33 +0000331
332.. seealso::
333
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000334 `argparse module documentation <http://docs.python.org/dev/library/argparse.html>`__
335
336 `Upgrading optparse code to use argparse <http://docs.python.org/dev/library/argparse.html#upgrading-optparse-code>`__
337
Andrew M. Kuchlingab21f752010-03-02 13:55:33 +0000338 :pep:`389` - argparse - New Command Line Parsing Module
339 PEP written and implemented by Steven Bethard.
340
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000341PEP 391: Dictionary-Based Configuration For Logging
342====================================================
343
Andrew M. Kuchlingb6c1aeb2010-04-14 14:28:31 +0000344.. not documented in library reference yet.
345
346The :mod:`logging` module is very flexible; an application can define
347a tree of logging subsystems, and each logger in this tree can filter
348out certain messages, format them differently, and direct messages to
349a varying number of handlers.
350
351All this flexibility can require a lot of configuration. You can
352write Python statements to create objects and set their properties,
353but a complex set-up would require verbose but boring code.
354:mod:`logging` also supports a :func:`~logging.config.fileConfig`
355function that parses a file, but the file format doesn't support
356configuring filters, and it's messier to generate programmatically.
357
358Python 2.7 adds a :func:`~logging.config.dictConfig` function that
359uses a dictionary, and there are many ways to produce a dictionary
360from different sources. You can construct one with code, of course.
361Python's standard library now includes a JSON parser, so you could
362parse a file containing JSON, or you could use a YAML parsing library
363if one is installed.
364
365XXX describe an example.
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000366
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000367Two smaller enhancements to the logging module are:
368
369.. rev79293
370
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +0000371* :class:`Logger` instances gained a :meth:`getChild` method that retrieves a
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000372 descendant logger using a relative path. For example,
373 once you retrieve a logger by doing ``log = getLogger('app')``,
374 calling ``log.getChild('network.listen')`` is equivalent to
375 ``getLogger('app.network.listen')``.
376
377* The :class:`LoggerAdapter` class gained a :meth:`isEnabledFor` method
378 that takes a *level* and returns whether the underlying logger would
379 process a message of that level of importance.
380
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000381.. seealso::
382
383 :pep:`391` - Dictionary-Based Configuration For Logging
384 PEP written and implemented by Vinay Sajip.
385
386PEP 3106: Dictionary Views
387====================================================
388
Andrew M. Kuchling85f928a2010-04-15 01:42:27 +0000389The dictionary methods :meth:`keys`, :meth:`values`, and :meth:`items`
390are different in Python 3.x. They return an object called a :dfn:`view`
391instead of a fully materialized list.
392
Andrew M. Kuchling85f928a2010-04-15 01:42:27 +0000393It'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
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +0000406Views can be iterated over, but they also behave like sets. The ``&``
407operator performs intersection, and ``|`` performs a union::
408
409 >>> d1 = dict((i*10, chr(65+i)) for i in range(26))
410 >>> d2 = dict((i**.5, i) for i in range(1000))
411 >>> d1.viewkeys() & d2.viewkeys()
412 set([0.0, 10.0, 20.0, 30.0])
413 >>> d1.viewkeys() | range(0, 30)
414 set([0, 1, 130, 3, 4, 5, 6, ..., 120, 250])
415
Andrew M. Kuchling85f928a2010-04-15 01:42:27 +0000416The view keeps track of the dictionary and its contents change as the
417dictionary is modified::
418
419 >>> vk = d.viewkeys()
420 >>> vk
421 dict_keys([0, 130, 10, ..., 250])
422 >>> d[260] = '&'
423 >>> vk
424 dict_keys([0, 130, 260, 10, ..., 250])
425
426However, note that you can't add or remove keys while you're iterating
427over the view::
428
429 >>> for k in vk:
430 ... d[k*2] = k
431 ...
432 Traceback (most recent call last):
433 File "<stdin>", line 1, in <module>
434 RuntimeError: dictionary changed size during iteration
435
436You can use the view methods in Python 2.x code, and the 2to3
437converter will change them to the standard :meth:`keys`,
438:meth:`values`, and :meth:`items` methods.
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000439
440.. seealso::
441
442 :pep:`3106` - Revamping dict.keys(), .values() and .items()
443 PEP written by Guido van Rossum.
444 Backported to 2.7 by Alexandre Vassalotti; :issue:`1967`.
445
446
Andrew M. Kuchling9fbbd3b2010-05-01 12:06:51 +0000447PEP 3137: The memoryview Object
448====================================================
449
450The :class:`memoryview` object provides a view of another object's
451memory content that matches the :class:`bytes` type's interface.
452
453 >>> import string
454 >>> m = memoryview(string.letters)
455 >>> m
456 <memory at 0x37f850>
457 >>> len(m) # Returns length of underlying object
458 52
459 >>> m[0], m[25], m[26] # Indexing returns one byte
460 ('a', 'z', 'A')
461 >>> m2 = m[0:26] # Slicing returns another memoryview
462 >>> m2
463 <memory at 0x37f080>
464
465The content of the view can be converted to a string of bytes or to
466a list of integers:
467
468 >>> m2.tobytes()
469 'abcdefghijklmnopqrstuvwxyz'
470 >>> m2.tolist()
471 [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]
472 >>>
473
474:class:`memoryview` objects allow modifying the underlying object if
475it's a mutable object.
476
477 >>> m2[0] = 75
478 Traceback (most recent call last):
479 File "<stdin>", line 1, in <module>
480 TypeError: cannot modify read-only memory
481 >>> b = bytearray(string.letters) # Creating a mutable object
482 >>> b
483 bytearray(b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
484 >>> mb = memoryview(b)
485 >>> mb[0] = '*' # Assign to view, changing the bytearray.
486 >>> b[0:5] # The bytearray has been changed.
487 bytearray(b'*bcde')
488 >>>
489
490.. seealso::
491
492 :pep:`3137` - Immutable Bytes and Mutable Buffer
493 PEP written by Guido van Rossum.
Antoine Pitrou5cace782010-05-01 12:16:39 +0000494 Implemented by Travis Oliphant, Antoine Pitrou and others.
Andrew M. Kuchling9fbbd3b2010-05-01 12:06:51 +0000495 Backported to 2.7 by Antoine Pitrou; :issue:`2396`.
496
497
498
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000499Other Language Changes
500======================
501
502Some smaller changes made to the core Python language are:
503
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000504* The syntax for set literals has been backported from Python 3.x.
505 Curly brackets are used to surround the contents of the resulting
506 mutable set; set literals are
507 distinguished from dictionaries by not containing colons and values.
508 ``{}`` continues to represent an empty dictionary; use
509 ``set()`` for an empty set.
510
511 >>> {1,2,3,4,5}
512 set([1, 2, 3, 4, 5])
Ezio Melotti021f3342010-04-06 03:26:49 +0000513 >>> set() # empty set
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000514 set([])
Ezio Melotti021f3342010-04-06 03:26:49 +0000515 >>> {} # empty dict
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000516 {}
517
518 Backported by Alexandre Vassalotti; :issue:`2335`.
519
520* Dictionary and set comprehensions are another feature backported from
521 3.x, generalizing list/generator comprehensions to use
522 the literal syntax for sets and dictionaries.
523
524 >>> {x:x*x for x in range(6)}
525 {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
526 >>> {'a'*x for x in range(6)}
527 set(['', 'a', 'aa', 'aaa', 'aaaa', 'aaaaa'])
528
529 Backported by Alexandre Vassalotti; :issue:`2333`.
530
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000531* The :keyword:`with` statement can now use multiple context managers
532 in one statement. Context managers are processed from left to right
533 and each one is treated as beginning a new :keyword:`with` statement.
534 This means that::
535
536 with A() as a, B() as b:
537 ... suite of statements ...
538
539 is equivalent to::
540
541 with A() as a:
542 with B() as b:
543 ... suite of statements ...
544
545 The :func:`contextlib.nested` function provides a very similar
546 function, so it's no longer necessary and has been deprecated.
547
548 (Proposed in http://codereview.appspot.com/53094; implemented by
549 Georg Brandl.)
550
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000551* Conversions between floating-point numbers and strings are
552 now correctly rounded on most platforms. These conversions occur
553 in many different places: :func:`str` on
554 floats and complex numbers; the :class:`float` and :class:`complex`
555 constructors;
556 numeric formatting; serialization and
557 deserialization of floats and complex numbers using the
558 :mod:`marshal`, :mod:`pickle`
559 and :mod:`json` modules;
560 parsing of float and imaginary literals in Python code;
Ezio Melotti021f3342010-04-06 03:26:49 +0000561 and :class:`~decimal.Decimal`-to-float conversion.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000562
563 Related to this, the :func:`repr` of a floating-point number *x*
564 now returns a result based on the shortest decimal string that's
565 guaranteed to round back to *x* under correct rounding (with
566 round-half-to-even rounding mode). Previously it gave a string
567 based on rounding x to 17 decimal digits.
568
Ezio Melotti021f3342010-04-06 03:26:49 +0000569 .. maybe add an example?
570
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000571 The rounding library responsible for this improvement works on
572 Windows, and on Unix platforms using the gcc, icc, or suncc
573 compilers. There may be a small number of platforms where correct
574 operation of this code cannot be guaranteed, so the code is not
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +0000575 used on such systems. You can find out which code is being used
576 by checking :data:`sys.float_repr_style`, which will be ``short``
577 if the new code is in use and ``legacy`` if it isn't.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000578
Mark Dickinsonbdd863d2010-01-07 09:28:29 +0000579 Implemented by Eric Smith and Mark Dickinson, using David Gay's
580 :file:`dtoa.c` library; :issue:`7117`.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000581
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000582* The :meth:`str.format` method now supports automatic numbering of the replacement
Benjamin Petersonaa0a0b92009-04-11 20:27:15 +0000583 fields. This makes using :meth:`str.format` more closely resemble using
584 ``%s`` formatting::
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000585
586 >>> '{}:{}:{}'.format(2009, 04, 'Sunday')
587 '2009:4:Sunday'
588 >>> '{}:{}:{day}'.format(2009, 4, day='Sunday')
589 '2009:4:Sunday'
590
Benjamin Petersonaa0a0b92009-04-11 20:27:15 +0000591 The auto-numbering takes the fields from left to right, so the first ``{...}``
592 specifier will use the first argument to :meth:`str.format`, the next
593 specifier will use the next argument, and so on. You can't mix auto-numbering
594 and explicit numbering -- either number all of your specifier fields or none
595 of them -- but you can mix auto-numbering and named fields, as in the second
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000596 example above. (Contributed by Eric Smith; :issue:`5237`.)
597
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000598 Complex numbers now correctly support usage with :func:`format`,
599 and default to being right-aligned.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000600 Specifying a precision or comma-separation applies to both the real
601 and imaginary parts of the number, but a specified field width and
602 alignment is applied to the whole of the resulting ``1.5+3j``
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000603 output. (Contributed by Eric Smith; :issue:`1588` and :issue:`7988`.)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000604
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000605 The 'F' format code now always formats its output using uppercase characters,
606 so it will now produce 'INF' and 'NAN'.
607 (Contributed by Eric Smith; :issue:`3382`.)
608
Andrew M. Kuchlingc4ae73e2010-04-30 13:47:34 +0000609 A low-level change: the :meth:`object.__format__` method now triggers
610 a :exc:`PendingDeprecationWarning` if it's passed a format string,
611 because the :meth:`__format__` method for :class:`object` converts
612 the object to a string representation and formats that. The method
613 used to silently apply the format string to the string
614 representation, but that could hide mistakes in Python code. If
615 you're supplying formatting information such as an alignment or
616 precision, presumably you're expecting the formatting to be applied
617 in some object-specific way. (Fixed by Eric Smith; :issue:`7994`.)
618
Mark Dickinson1a707982008-12-17 16:14:37 +0000619* The :func:`int` and :func:`long` types gained a ``bit_length``
Georg Brandl64e1c752009-04-11 18:19:27 +0000620 method that returns the number of bits necessary to represent
Mark Dickinson1a707982008-12-17 16:14:37 +0000621 its argument in binary::
622
623 >>> n = 37
Ezio Melotti021f3342010-04-06 03:26:49 +0000624 >>> bin(n)
Mark Dickinson1a707982008-12-17 16:14:37 +0000625 '0b100101'
626 >>> n.bit_length()
627 6
628 >>> n = 2**123-1
629 >>> n.bit_length()
630 123
631 >>> (n+1).bit_length()
632 124
633
634 (Contributed by Fredrik Johansson and Victor Stinner; :issue:`3439`.)
635
Andrew M. Kuchling92b97002009-05-02 17:12:15 +0000636* Conversions from long integers and regular integers to floating
637 point now round differently, returning the floating-point number
638 closest to the number. This doesn't matter for small integers that
639 can be converted exactly, but for large numbers that will
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000640 unavoidably lose precision, Python 2.7 now approximates more
Andrew M. Kuchling92b97002009-05-02 17:12:15 +0000641 closely. For example, Python 2.6 computed the following::
642
643 >>> n = 295147905179352891391
644 >>> float(n)
645 2.9514790517935283e+20
646 >>> n - long(float(n))
647 65535L
648
649 Python 2.7's floating-point result is larger, but much closer to the
650 true value::
651
652 >>> n = 295147905179352891391
653 >>> float(n)
654 2.9514790517935289e+20
Ezio Melotti021f3342010-04-06 03:26:49 +0000655 >>> n - long(float(n))
Andrew M. Kuchling92b97002009-05-02 17:12:15 +0000656 -1L
657
658 (Implemented by Mark Dickinson; :issue:`3166`.)
659
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000660 Integer division is also more accurate in its rounding behaviours. (Also
661 implemented by Mark Dickinson; :issue:`1811`.)
662
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000663* It's now possible for a subclass of the built-in :class:`unicode` type
664 to override the :meth:`__unicode__` method. (Implemented by
665 Victor Stinner; :issue:`1583863`.)
666
Ezio Melotti021f3342010-04-06 03:26:49 +0000667* The :class:`bytearray` type's :meth:`~bytearray.translate` method now accepts
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000668 ``None`` as its first argument. (Fixed by Georg Brandl;
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000669 :issue:`4759`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000670
Ezio Melotti021f3342010-04-06 03:26:49 +0000671 .. bytearray doesn't seem to be documented
672
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000673* When using ``@classmethod`` and ``@staticmethod`` to wrap
674 methods as class or static methods, the wrapper object now
675 exposes the wrapped function as their :attr:`__func__` attribute.
676 (Contributed by Amaury Forgeot d'Arc, after a suggestion by
677 George Sakkis; :issue:`5982`.)
678
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +0000679* When a restricted set of attributes were set using ``__slots__``,
680 deleting an unset attribute would not raise :exc:`AttributeError`
681 as you would expect. Fixed by Benjamin Peterson; :issue:`7604`.)
682
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000683* A new encoding named "cp720", used primarily for Arabic text, is now
684 supported. (Contributed by Alexander Belchenko and Amaury Forgeot
685 d'Arc; :issue:`1616979`.)
686
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000687* The :class:`file` object will now set the :attr:`filename` attribute
688 on the :exc:`IOError` exception when trying to open a directory
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +0000689 on POSIX platforms (noted by Jan Kaliszewski; :issue:`4764`), and
690 now explicitly checks for and forbids writing to read-only file objects
691 instead of trusting the C library to catch and report the error
692 (fixed by Stefan Krah; :issue:`5677`).
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000693
Benjamin Petersonae9a0a02009-12-31 16:49:37 +0000694* The Python tokenizer now translates line endings itself, so the
695 :func:`compile` built-in function can now accept code using any
696 line-ending convention. Additionally, it no longer requires that the
697 code end in a newline.
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +0000698
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000699* Extra parentheses in function definitions are illegal in Python 3.x,
700 meaning that you get a syntax error from ``def f((x)): pass``. In
701 Python3-warning mode, Python 2.7 will now warn about this odd usage.
702 (Noted by James Lingard; :issue:`7362`.)
703
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +0000704* It's now possible to create weak references to old-style class
705 objects. New-style classes were always weak-referenceable. (Fixed
706 by Antoine Pitrou; :issue:`8268`.)
707
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000708* When a module object is garbage-collected, the module's dictionary is
709 now only cleared if no one else is holding a reference to the
710 dictionary (:issue:`7140`).
711
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000712.. ======================================================================
713
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000714.. _new-27-interpreter:
715
716Interpreter Changes
717-------------------------------
718
719A new environment variable, :envvar:`PYTHONWARNINGS`,
720allows controlling warnings. It should be set to a string
721containing warning settings, equivalent to those
722used with the :option:`-W` switch, separated by commas.
723(Contributed by Brian Curtin; :issue:`7301`.)
724
725For example, the following setting will print warnings every time
726they occur, but turn warnings from the :mod:`Cookie` module into an
727error. (The exact syntax for setting an environment variable varies
728across operating systems and shells, so it may be different for you.)
729
730::
731
732 export PYTHONWARNINGS=all,error:::Cookie:0
733
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +0000734When running a module using the interpreter's :option:`-m` switch,
735``sys.argv[0]`` will now be set to the string ``'-m'`` while the
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +0000736module is being located, while executing the :file:`__init__.py` files
737for any parent packages of the module to be executed.
738(Suggested by Michael Foord; implemented by Nick Coghlan;
739:issue:`8202`.)
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +0000740
741.. ======================================================================
742
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000743
744Optimizations
745-------------
746
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000747Several performance enhancements have been added:
748
749.. * A new :program:`configure` option, :option:`--with-computed-gotos`,
750 compiles the main bytecode interpreter loop using a new dispatch
751 mechanism that gives speedups of up to 20%, depending on the system
752 and benchmark. The new mechanism is only supported on certain
753 compilers, such as gcc, SunPro, and icc.
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000754
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000755* A new opcode was added to perform the initial setup for
756 :keyword:`with` statements, looking up the :meth:`__enter__` and
757 :meth:`__exit__` methods. (Contributed by Benjamin Peterson.)
758
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000759* The garbage collector now performs better for one common usage
760 pattern: when many objects are being allocated without deallocating
761 any of them. This would previously take quadratic
762 time for garbage collection, but now the number of full garbage collections
763 is reduced as the number of objects on the heap grows.
764 The new logic is to only perform a full garbage collection pass when
765 the middle generation has been collected 10 times and when the
766 number of survivor objects from the middle generation exceeds 10% of
767 the number of objects in the oldest generation. (Suggested by Martin
Ezio Melotti021f3342010-04-06 03:26:49 +0000768 von Löwis and implemented by Antoine Pitrou; :issue:`4074`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000769
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000770* The garbage collector tries to avoid tracking simple containers
771 which can't be part of a cycle. In Python 2.7, this is now true for
772 tuples and dicts containing atomic types (such as ints, strings,
773 etc.). Transitively, a dict containing tuples of atomic types won't
774 be tracked either. This helps reduce the cost of each
775 garbage collection by decreasing the number of objects to be
776 considered and traversed by the collector.
Antoine Pitrouc18f6b02009-03-28 19:10:13 +0000777 (Contributed by Antoine Pitrou; :issue:`4688`.)
778
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000779* Long integers are now stored internally either in base 2**15 or in base
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000780 2**30, the base being determined at build time. Previously, they
781 were always stored in base 2**15. Using base 2**30 gives
782 significant performance improvements on 64-bit machines, but
783 benchmark results on 32-bit machines have been mixed. Therefore,
784 the default is to use base 2**30 on 64-bit machines and base 2**15
785 on 32-bit machines; on Unix, there's a new configure option
786 :option:`--enable-big-digits` that can be used to override this default.
787
788 Apart from the performance improvements this change should be
789 invisible to end users, with one exception: for testing and
Ezio Melotti021f3342010-04-06 03:26:49 +0000790 debugging purposes there's a new structseq :data:`sys.long_info` that
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000791 provides information about the internal format, giving the number of
792 bits per digit and the size in bytes of the C type used to store
793 each digit::
794
795 >>> import sys
796 >>> sys.long_info
797 sys.long_info(bits_per_digit=30, sizeof_digit=4)
798
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000799 (Contributed by Mark Dickinson; :issue:`4258`.)
800
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000801 Another set of changes made long objects a few bytes smaller: 2 bytes
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000802 smaller on 32-bit systems and 6 bytes on 64-bit.
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000803 (Contributed by Mark Dickinson; :issue:`5260`.)
804
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000805* The division algorithm for long integers has been made faster
806 by tightening the inner loop, doing shifts instead of multiplications,
807 and fixing an unnecessary extra iteration.
808 Various benchmarks show speedups of between 50% and 150% for long
809 integer divisions and modulo operations.
810 (Contributed by Mark Dickinson; :issue:`5512`.)
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +0000811 Bitwise operations are also significantly faster (initial patch by
812 Gregory Smith; :issue:`1087418`).
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000813
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000814* The implementation of ``%`` checks for the left-side operand being
815 a Python string and special-cases it; this results in a 1-3%
816 performance increase for applications that frequently use ``%``
817 with strings, such as templating libraries.
818 (Implemented by Collin Winter; :issue:`5176`.)
819
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000820* List comprehensions with an ``if`` condition are compiled into
821 faster bytecode. (Patch by Antoine Pitrou, back-ported to 2.7
822 by Jeffrey Yasskin; :issue:`4715`.)
823
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +0000824* Converting an integer or long integer to a decimal string was made
825 faster by special-casing base 10 instead of using a generalized
826 conversion function that supports arbitrary bases.
827 (Patch by Gawain Bolton; :issue:`6713`.)
828
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +0000829* The :meth:`split`, :meth:`replace`, :meth:`rindex`,
830 :meth:`rpartition`, and :meth:`rsplit` methods of string-like types
831 (strings, Unicode strings, and :class:`bytearray` objects) now use a
832 fast reverse-search algorithm instead of a character-by-character
833 scan. This is sometimes faster by a factor of 10. (Added by
834 Florent Xicluna; :issue:`7462` and :issue:`7622`.)
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +0000835
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000836* The :mod:`pickle` and :mod:`cPickle` modules now automatically
837 intern the strings used for attribute names, reducing memory usage
838 of the objects resulting from unpickling. (Contributed by Jake
839 McGuire; :issue:`5084`.)
840
841* The :mod:`cPickle` module now special-cases dictionaries,
842 nearly halving the time required to pickle them.
843 (Contributed by Collin Winter; :issue:`5670`.)
844
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000845.. ======================================================================
846
Georg Brandl0516f812009-11-18 18:52:35 +0000847New and Improved Modules
848========================
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000849
850As in every release, Python's standard library received a number of
851enhancements and bug fixes. Here's a partial list of the most notable
852changes, sorted alphabetically by module name. Consult the
853:file:`Misc/NEWS` file in the source tree for a more complete list of
854changes, or look through the Subversion logs for all the details.
855
Ezio Melotti021f3342010-04-06 03:26:49 +0000856* The :mod:`bdb` module's base debugging class :class:`~bdb.Bdb`
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000857 gained a feature for skipping modules. The constructor
858 now takes an iterable containing glob-style patterns such as
859 ``django.*``; the debugger will not step into stack frames
860 from a module that matches one of these patterns.
861 (Contributed by Maru Newby after a suggestion by
862 Senthil Kumaran; :issue:`5142`.)
863
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +0000864* The :mod:`binascii` module now supports the buffer API, so it can be
865 used with :class:`memoryview` instances and other similar buffer objects.
866 (Backported from 3.x by Florent Xicluna; :issue:`7703`.)
867
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000868* Updated module: the :mod:`bsddb` module has been updated from 4.7.2devel9
869 to version 4.8.4 of
870 `the pybsddb package <http://www.jcea.es/programacion/pybsddb.htm>`__.
871 The new version features better Python 3.x compatibility, various bug fixes,
872 and adds several new BerkeleyDB flags and methods.
Ezio Melotti021f3342010-04-06 03:26:49 +0000873 (Updated by Jesús Cea Avión; :issue:`8156`. The pybsddb
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000874 changelog can be browsed at http://hg.jcea.es/pybsddb/file/tip/ChangeLog.)
875
Ezio Melotti021f3342010-04-06 03:26:49 +0000876* The :mod:`bz2` module's :class:`~bz2.BZ2File` now supports the context
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000877 management protocol, so you can write ``with bz2.BZ2File(...) as f: ...``.
878 (Contributed by Hagen Fuerstenau; :issue:`3860`.)
879
Ezio Melotti021f3342010-04-06 03:26:49 +0000880* New class: the :class:`~collections.Counter` class in the :mod:`collections`
881 module is useful for tallying data. :class:`~collections.Counter` instances
882 behave mostly like dictionaries but return zero for missing keys instead of
Georg Brandlf6dab952009-04-28 21:48:35 +0000883 raising a :exc:`KeyError`:
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000884
Georg Brandlf6dab952009-04-28 21:48:35 +0000885 .. doctest::
886 :options: +NORMALIZE_WHITESPACE
887
888 >>> from collections import Counter
889 >>> c = Counter()
890 >>> for letter in 'here is a sample of english text':
891 ... c[letter] += 1
892 ...
893 >>> c
894 Counter({' ': 6, 'e': 5, 's': 3, 'a': 2, 'i': 2, 'h': 2,
895 'l': 2, 't': 2, 'g': 1, 'f': 1, 'm': 1, 'o': 1, 'n': 1,
896 'p': 1, 'r': 1, 'x': 1})
897 >>> c['e']
898 5
899 >>> c['z']
900 0
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000901
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +0000902 There are three additional :class:`~collections.Counter` methods:
903 :meth:`~collections.Counter.most_common` returns the N most common
904 elements and their counts. :meth:`~collections.Counter.elements`
905 returns an iterator over the contained elements, repeating each
906 element as many times as its count.
907 :meth:`~collections.Counter.subtract` takes an iterable and
908 subtracts one for each element instead of adding; if the argument is
909 a dictionary or another :class:`Counter`, the counts are
910 subtracted. ::
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000911
912 >>> c.most_common(5)
913 [(' ', 6), ('e', 5), ('s', 3), ('a', 2), ('i', 2)]
914 >>> c.elements() ->
915 'a', 'a', ' ', ' ', ' ', ' ', ' ', ' ',
916 'e', 'e', 'e', 'e', 'e', 'g', 'f', 'i', 'i',
917 'h', 'h', 'm', 'l', 'l', 'o', 'n', 'p', 's',
Georg Brandlf6dab952009-04-28 21:48:35 +0000918 's', 's', 'r', 't', 't', 'x'
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +0000919 >>> c['e']
920 5
921 >>> c.subtract('very heavy on the letter e')
922 >>> c['e'] # Count is now lower
923 -1
Ezio Melotti021f3342010-04-06 03:26:49 +0000924
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000925 Contributed by Raymond Hettinger; :issue:`1696199`.
926
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +0000927 .. revision 79660
928
Ezio Melotti021f3342010-04-06 03:26:49 +0000929 The new :class:`~collections.OrderedDict` class is described in the earlier
930 section :ref:`pep-0372`.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000931
Ezio Melotti021f3342010-04-06 03:26:49 +0000932 The :class:`~collections.namedtuple` class now has an optional *rename* parameter.
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000933 If *rename* is true, field names that are invalid because they've
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000934 been repeated or that aren't legal Python identifiers will be
935 renamed to legal names that are derived from the field's
936 position within the list of fields:
937
Georg Brandlf6dab952009-04-28 21:48:35 +0000938 >>> from collections import namedtuple
939 >>> T = namedtuple('T', ['field1', '$illegal', 'for', 'field2'], rename=True)
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000940 >>> T._fields
941 ('field1', '_1', '_2', 'field2')
942
943 (Added by Raymond Hettinger; :issue:`1818`.)
944
Andrew M. Kuchling6d7dfa22010-04-11 12:49:37 +0000945 The :class:`~collections.deque` data type now has a
946 :meth:`~collections.deque.count` method that returns the number of
947 contained elements equal to the supplied argument *x*, and a
948 :meth:`~collections.deque.reverse` method that reverses the elements
949 of the deque in-place. :class:`deque` also exposes its maximum
950 length as the read-only :attr:`~collections.deque.maxlen` attribute.
951 (Both features added by Raymond Hettinger.)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000952
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +0000953* Deprecated function: :func:`contextlib.nested`, which allows
954 handling more than one context manager with a single :keyword:`with`
955 statement, has been deprecated, because :keyword:`with` supports
956 multiple context managers syntactically now.
957
Ezio Melotti021f3342010-04-06 03:26:49 +0000958* The :mod:`copy` module's :func:`~copy.deepcopy` function will now
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000959 correctly copy bound instance methods. (Implemented by
960 Robert Collins; :issue:`1515`.)
961
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000962* The :mod:`ctypes` module now always converts ``None`` to a C NULL
963 pointer for arguments declared as pointers. (Changed by Thomas
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +0000964 Heller; :issue:`4606`.) The underlying `libffi library
965 <http://sourceware.org/libffi/>`__ has been updated to version
966 3.0.9, containing various fixes for different platforms. (Updated
967 by Matthias Klose; :issue:`8142`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000968
Ezio Melotti021f3342010-04-06 03:26:49 +0000969* New method: the :mod:`datetime` module's :class:`~datetime.timedelta` class
970 gained a :meth:`~datetime.timedelta.total_seconds` method that returns the
971 number of seconds in the duration. (Contributed by Brian Quinlan; :issue:`5788`.)
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000972
Ezio Melotti021f3342010-04-06 03:26:49 +0000973* New method: the :class:`~decimal.Decimal` class gained a
974 :meth:`~decimal.Decimal.from_float` class method that performs an exact
975 conversion of a floating-point number to a :class:`~decimal.Decimal`.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000976 Note that this is an **exact** conversion that strives for the
977 closest decimal approximation to the floating-point representation's value;
978 the resulting decimal value will therefore still include the inaccuracy,
979 if any.
980 For example, ``Decimal.from_float(0.1)`` returns
981 ``Decimal('0.1000000000000000055511151231257827021181583404541015625')``.
982 (Implemented by Raymond Hettinger; :issue:`4796`.)
983
Andrew M. Kuchling04b99cc2010-05-04 01:24:22 +0000984 Comparing instances of :class:`Decimal` with floating-point
985 numbers now produces sensible results based on the numeric values
986 of the operands. Previously such comparisons would fall back to
987 Python's default rules for comparing objects, which produced arbitrary
988 results based on their type. Note that you still cannot combine
989 :class:`Decimal` and floating-point in other operations such as addition,
990 since you should be explicitly choosing how to convert between float and
991 :class:`Decimal`.
992 (Fixed by Mark Dickinson; :issue:`2531`.)
993
Ezio Melotti021f3342010-04-06 03:26:49 +0000994 Most of the methods of the :class:`~decimal.Context` class now accept integers
995 as well as :class:`~decimal.Decimal` instances; the only exceptions are the
996 :meth:`~decimal.Context.canonical` and :meth:`~decimal.Context.is_canonical`
997 methods. (Patch by Juan José Conti; :issue:`7633`.)
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000998
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +0000999 The constructor for :class:`~decimal.Decimal` now accepts
1000 floating-point numbers (added by Raymond Hettinger; :issue:`8257`)
1001 and non-European Unicode characters such as Arabic-Indic digits
1002 (contributed by Mark Dickinson; :issue:`6595`).
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001003
Ezio Melotti021f3342010-04-06 03:26:49 +00001004 When using :class:`~decimal.Decimal` instances with a string's
1005 :meth:`~str.format` method, the default alignment was previously
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001006 left-alignment. This has been changed to right-alignment, which seems
1007 more sensible for numeric types. (Changed by Mark Dickinson; :issue:`6857`.)
1008
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001009 Comparisons involving a signaling NaN value (or ``sNAN``) now signal
1010 :const:`InvalidOperation` instead of silently returning a true or
1011 false value depending on the comparison operator. Quiet NaN values
1012 (or ``NaN``) are now hashable. (Fixed by Mark Dickinson;
1013 :issue:`7279`.)
1014
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +00001015* The :mod:`difflib` module now produces output that is more
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00001016 compatible with modern :command:`diff`/:command:`patch` tools
1017 through one small change, using a tab character instead of spaces as
1018 a separator in the header giving the filename. (Fixed by Anatoly
1019 Techtonik; :issue:`7585`.)
1020
1021* The :mod:`doctest` module's :const:`IGNORE_EXCEPTION_DETAIL` flag
1022 will now ignore the name of the module containing the exception
1023 being tested. (Patch by Lennart Regebro; :issue:`7490`.)
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +00001024
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001025* The :class:`~fractions.Fraction` class now accepts a single float or
1026 :class:`~decimal.Decimal` instance, or two rational numbers, as
1027 arguments to its constructor. (Implemented by Mark Dickinson;
1028 rationals added in :issue:`5812`, and float/decimal in
1029 :issue:`8294`.)
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00001030
Andrew M. Kuchlingec6393f2010-04-11 01:40:30 +00001031 An oversight was fixed, making the :class:`Fraction` match the other
1032 numeric types; ordering comparisons (``<``, ``<=``, ``>``, ``>=``) between
1033 fractions and complex numbers now raise a :exc:`TypeError`.
1034
1035 .. revision 79455
1036
Ezio Melotti021f3342010-04-06 03:26:49 +00001037* New class: a new :class:`~ftplib.FTP_TLS` class in
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001038 the :mod:`ftplib` module provides secure FTP
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001039 connections using TLS encapsulation of authentication as well as
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001040 subsequent control and data transfers.
1041 (Contributed by Giampaolo Rodola', :issue:`2054`.)
1042
Ezio Melotti021f3342010-04-06 03:26:49 +00001043 The :meth:`~ftplib.FTP.storbinary` method for binary uploads can now restart
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001044 uploads thanks to an added *rest* parameter (patch by Pablo Mouzo;
1045 :issue:`6845`.)
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001046
Andrew M. Kuchling6d7dfa22010-04-11 12:49:37 +00001047* New class decorator: :func:`total_ordering` in the :mod:`functools`
1048 module takes a class that defines an :meth:`__eq__` method and one of
1049 :meth:`__lt__`, :meth:`__le__`, :meth:`__gt__`, or :meth:`__ge__`,
1050 and generates the missing comparison methods. Since the
1051 :meth:`__cmp__` method is being deprecated in Python 3.x,
1052 this decorator makes it easier to define ordered classes.
1053 (Added by Raymond Hettinger; :issue:`5479`.)
1054
1055 New function: :func:`cmp_to_key` will take an old-style comparison
1056 function that expects two arguments and return a new callable that
1057 can be used as the *key* parameter to functions such as
1058 :func:`sorted`, :func:`min` and :func:`max`, etc. The primary
1059 intended use is to help with making code compatible with Python 3.x.
1060 (Added by Raymond Hettinger.)
1061
Ezio Melotti021f3342010-04-06 03:26:49 +00001062* New function: the :mod:`gc` module's :func:`~gc.is_tracked` returns
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001063 true if a given instance is tracked by the garbage collector, false
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001064 otherwise. (Contributed by Antoine Pitrou; :issue:`4688`.)
1065
Ezio Melotti021f3342010-04-06 03:26:49 +00001066* The :mod:`gzip` module's :class:`~gzip.GzipFile` now supports the context
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +00001067 management protocol, so you can write ``with gzip.GzipFile(...) as f: ...``
1068 (contributed by Hagen Fuerstenau; :issue:`3860`), and it now implements
1069 the :class:`io.BufferedIOBase` ABC, so you can wrap it with
1070 :class:`io.BufferedReader` for faster processing
1071 (contributed by Nir Aides; :issue:`7471`).
1072 It's also now possible to override the modification time
Andrew M. Kuchling77069572009-03-31 01:21:01 +00001073 recorded in a gzipped file by providing an optional timestamp to
1074 the constructor. (Contributed by Jacques Frechet; :issue:`4272`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001075
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001076 Files in gzip format can be padded with trailing zero bytes; the
1077 :mod:`gzip` module will now consume these trailing bytes. (Fixed by
1078 Tadek Pietraszek and Brian Curtin; :issue:`2846`.)
1079
Ezio Melotti021f3342010-04-06 03:26:49 +00001080* New attribute: the :mod:`hashlib` module now has an :attr:`~hashlib.hashlib.algorithms`
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001081 attribute containing a tuple naming the supported algorithms.
1082 In Python 2.7, ``hashlib.algorithms`` contains
1083 ``('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')``
1084 (Contributed by Carl Chenet; :issue:`7418`.)
1085
Ezio Melotti021f3342010-04-06 03:26:49 +00001086* The default :class:`~httplib.HTTPResponse` class used by the :mod:`httplib` module now
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001087 supports buffering, resulting in much faster reading of HTTP responses.
1088 (Contributed by Kristjan Valur Jonsson; :issue:`4879`.)
1089
Ezio Melotti021f3342010-04-06 03:26:49 +00001090 The :class:`~httplib.HTTPConnection` and :class:`~httplib.HTTPSConnection` classes
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001091 now support a *source_address* parameter, a ``(host, port)`` 2-tuple
1092 giving the source address that will be used for the connection.
1093 (Contributed by Eldon Ziegler; :issue:`3972`.)
1094
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00001095* The :mod:`ihooks` module now supports relative imports. Note that
1096 :mod:`ihooks` is an older module used to support customizing imports,
1097 superseded by the :mod:`imputil` module added in Python 2.0.
1098 (Relative import support added by Neil Schemenauer.)
1099
1100 .. revision 75423
1101
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001102* The :mod:`imaplib` module now supports IPv6 addresses.
1103 (Contributed by Derek Morr; :issue:`1655`.)
1104
Andrew M. Kuchlingce690522010-04-13 01:32:51 +00001105* New function: the :mod:`inspect` module's :func:`~inspect.getcallargs`
1106 takes a callable and its positional and keyword arguments,
1107 and figures out which of the callable's parameters will receive each argument,
1108 returning a dictionary mapping argument names to their values. For example::
1109
1110 >>> from inspect import getcallargs
1111 >>> def f(a, b=1, *pos, **named):
1112 ... pass
1113 >>> getcallargs(f, 1, 2, 3)
1114 {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
1115 >>> getcallargs(f, a=2, x=4)
1116 {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
1117 >>> getcallargs(f)
1118 Traceback (most recent call last):
1119 ...
1120 TypeError: f() takes at least 1 argument (0 given)
1121
1122 Contributed by George Sakkis; :issue:`3135`.
1123
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001124* Updated module: The :mod:`io` library has been upgraded to the version shipped with
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001125 Python 3.1. For 3.1, the I/O library was entirely rewritten in C
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001126 and is 2 to 20 times faster depending on the task being performed. The
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001127 original Python version was renamed to the :mod:`_pyio` module.
1128
1129 One minor resulting change: the :class:`io.TextIOBase` class now
1130 has an :attr:`errors` attribute giving the error setting
1131 used for encoding and decoding errors (one of ``'strict'``, ``'replace'``,
1132 ``'ignore'``).
1133
1134 The :class:`io.FileIO` class now raises an :exc:`OSError` when passed
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001135 an invalid file descriptor. (Implemented by Benjamin Peterson;
Ezio Melotti021f3342010-04-06 03:26:49 +00001136 :issue:`4991`.) The :meth:`~io.IOBase.truncate` method now preserves the
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001137 file position; previously it would change the file position to the
1138 end of the new file. (Fixed by Pascal Chambon; :issue:`6939`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001139
Andrew M. Kuchling5a73ff82009-12-02 14:27:11 +00001140* New function: ``itertools.compress(data, selectors)`` takes two
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001141 iterators. Elements of *data* are returned if the corresponding
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001142 value in *selectors* is true::
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001143
1144 itertools.compress('ABCDEF', [1,0,1,0,1,1]) =>
1145 A, C, E, F
1146
Ezio Melotti021f3342010-04-06 03:26:49 +00001147 .. maybe here is better to use >>> list(itertools.compress(...)) instead
1148
Andrew M. Kuchling5a73ff82009-12-02 14:27:11 +00001149 New function: ``itertools.combinations_with_replacement(iter, r)``
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001150 returns all the possible *r*-length combinations of elements from the
Ezio Melotti021f3342010-04-06 03:26:49 +00001151 iterable *iter*. Unlike :func:`~itertools.combinations`, individual elements
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001152 can be repeated in the generated combinations::
1153
1154 itertools.combinations_with_replacement('abc', 2) =>
1155 ('a', 'a'), ('a', 'b'), ('a', 'c'),
1156 ('b', 'b'), ('b', 'c'), ('c', 'c')
1157
1158 Note that elements are treated as unique depending on their position
1159 in the input, not their actual values.
1160
Ezio Melotti021f3342010-04-06 03:26:49 +00001161 The :func:`itertools.count` function now has a *step* argument that
1162 allows incrementing by values other than 1. :func:`~itertools.count` also
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001163 now allows keyword arguments, and using non-integer values such as
Ezio Melotti021f3342010-04-06 03:26:49 +00001164 floats or :class:`~decimal.Decimal` instances. (Implemented by Raymond
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001165 Hettinger; :issue:`5032`.)
1166
Andrew M. Kuchling77069572009-03-31 01:21:01 +00001167 :func:`itertools.combinations` and :func:`itertools.product` were
1168 previously raising :exc:`ValueError` for values of *r* larger than
1169 the input iterable. This was deemed a specification error, so they
1170 now return an empty iterator. (Fixed by Raymond Hettinger; :issue:`4816`.)
1171
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001172* Updated module: The :mod:`json` module was upgraded to version 2.0.9 of the
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001173 simplejson package, which includes a C extension that makes
1174 encoding and decoding faster.
1175 (Contributed by Bob Ippolito; :issue:`4136`.)
1176
Ezio Melotti021f3342010-04-06 03:26:49 +00001177 To support the new :class:`collections.OrderedDict` type, :func:`json.load`
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001178 now has an optional *object_pairs_hook* parameter that will be called
1179 with any object literal that decodes to a list of pairs.
1180 (Contributed by Raymond Hettinger; :issue:`5381`.)
1181
Andrew M. Kuchling837a5382010-05-06 17:21:59 +00001182* The :mod:`mailbox` module's :class:`Maildir` class now records the
1183 timestamp on the directories it reads, and only re-reads them if the
1184 modification time has subsequently changed. This improves
1185 performance by avoiding unneeded directory scans. (Fixed by
1186 A.M. Kuchling and Antoine Pitrou; :issue:`1607951`, :issue:`6896`.)
1187
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001188* New functions: the :mod:`math` module gained
Ezio Melotti021f3342010-04-06 03:26:49 +00001189 :func:`~math.erf` and :func:`~math.erfc` for the error function and the complementary error function,
1190 :func:`~math.expm1` which computes ``e**x - 1`` with more precision than
1191 using :func:`~math.exp` and subtracting 1,
1192 :func:`~math.gamma` for the Gamma function, and
1193 :func:`~math.lgamma` for the natural log of the Gamma function.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001194 (Contributed by Mark Dickinson and nirinA raseliarison; :issue:`3366`.)
1195
Andrew M. Kuchling24520b42009-04-09 11:22:47 +00001196* The :mod:`multiprocessing` module's :class:`Manager*` classes
1197 can now be passed a callable that will be called whenever
1198 a subprocess is started, along with a set of arguments that will be
1199 passed to the callable.
1200 (Contributed by lekma; :issue:`5585`.)
1201
Ezio Melotti021f3342010-04-06 03:26:49 +00001202 The :class:`~multiprocessing.Pool` class, which controls a pool of worker processes,
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001203 now has an optional *maxtasksperchild* parameter. Worker processes
1204 will perform the specified number of tasks and then exit, causing the
Ezio Melotti021f3342010-04-06 03:26:49 +00001205 :class:`~multiprocessing.Pool` to start a new worker. This is useful if tasks may leak
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001206 memory or other resources, or if some tasks will cause the worker to
1207 become very large.
1208 (Contributed by Charles Cazabon; :issue:`6963`.)
1209
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001210* The :mod:`nntplib` module now supports IPv6 addresses.
1211 (Contributed by Derek Morr; :issue:`1664`.)
1212
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001213* New functions: the :mod:`os` module wraps the following POSIX system
Ezio Melotti021f3342010-04-06 03:26:49 +00001214 calls: :func:`~os.getresgid` and :func:`~os.getresuid`, which return the
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001215 real, effective, and saved GIDs and UIDs;
Ezio Melotti021f3342010-04-06 03:26:49 +00001216 :func:`~os.setresgid` and :func:`~os.setresuid`, which set
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001217 real, effective, and saved GIDs and UIDs to new values;
Ezio Melotti021f3342010-04-06 03:26:49 +00001218 :func:`~os.initgroups`. (GID/UID functions
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001219 contributed by Travis H.; :issue:`6508`. Support for initgroups added
1220 by Jean-Paul Calderone; :issue:`7333`.)
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001221
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001222 The :func:`os.fork` function now re-initializes the import lock in
Ezio Melotti021f3342010-04-06 03:26:49 +00001223 the child process; this fixes problems on Solaris when :func:`~os.fork`
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001224 is called from a thread. (Fixed by Zsolt Cserna; :issue:`7242`.)
1225
Ezio Melotti021f3342010-04-06 03:26:49 +00001226* In the :mod:`os.path` module, the :func:`~os.path.normpath` and
1227 :func:`~os.path.abspath` functions now preserve Unicode; if their input path
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001228 is a Unicode string, the return value is also a Unicode string.
Ezio Melotti021f3342010-04-06 03:26:49 +00001229 (:meth:`~os.path.normpath` fixed by Matt Giuca in :issue:`5827`;
1230 :meth:`~os.path.abspath` fixed by Ezio Melotti in :issue:`3426`.)
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001231
Andrew M. Kuchling9cb42772009-01-21 02:15:43 +00001232* The :mod:`pydoc` module now has help for the various symbols that Python
1233 uses. You can now do ``help('<<')`` or ``help('@')``, for example.
1234 (Contributed by David Laban; :issue:`4739`.)
1235
Ezio Melotti021f3342010-04-06 03:26:49 +00001236* The :mod:`re` module's :func:`~re.split`, :func:`~re.sub`, and :func:`~re.subn`
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001237 now accept an optional *flags* argument, for consistency with the
1238 other functions in the module. (Added by Gregory P. Smith.)
1239
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001240* New function: :func:`~runpy.run_path` in the :mod:`runpy` module
1241 will execute the code at a provided *path* argument. *path* can be
1242 the path of a Python source file (:file:`example.py`), a compiled
1243 bytecode file (:file:`example.pyc`), a directory
1244 (:file:`./package/'), or a zip archive (:file:`example.zip`). If a
1245 directory or zip path is provided, it will be added to the front of
1246 ``sys.path`` and the module :mod:`__main__` will be imported. It's
1247 expected that the directory or zip contains a :file:`__main__.py`;
1248 if it doesn't, some other :file:`__main__.py` might be imported from
1249 a location later in ``sys.path``. This makes some of the machinery
Andrew M. Kuchling837a5382010-05-06 17:21:59 +00001250 of :mod:`runpy` available to scripts that want to mimic the way
1251 Python's :option:`-m` processes an explicit path name.
1252 (Added by Nick Coghlan; :issue:`6816`.)
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001253
Ezio Melotti021f3342010-04-06 03:26:49 +00001254* New function: in the :mod:`shutil` module, :func:`~shutil.make_archive`
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001255 takes a filename, archive type (zip or tar-format), and a directory
1256 path, and creates an archive containing the directory's contents.
1257 (Added by Tarek Ziadé.)
1258
Ezio Melotti021f3342010-04-06 03:26:49 +00001259 :mod:`shutil`'s :func:`~shutil.copyfile` and :func:`~shutil.copytree`
1260 functions now raise a :exc:`~shutil.SpecialFileError` exception when
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001261 asked to copy a named pipe. Previously the code would treat
1262 named pipes like a regular file by opening them for reading, and
1263 this would block indefinitely. (Fixed by Antoine Pitrou; :issue:`3002`.)
1264
1265* New functions: in the :mod:`site` module, three new functions
1266 return various site- and user-specific paths.
Ezio Melotti021f3342010-04-06 03:26:49 +00001267 :func:`~site.getsitepackages` returns a list containing all
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001268 global site-packages directories, and
Ezio Melotti021f3342010-04-06 03:26:49 +00001269 :func:`~site.getusersitepackages` returns the path of the user's
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001270 site-packages directory.
Ezio Melotti021f3342010-04-06 03:26:49 +00001271 :func:`~site.getuserbase` returns the value of the :envvar:`USER_BASE`
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001272 environment variable, giving the path to a directory that can be used
1273 to store data.
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001274 (Contributed by Tarek Ziadé; :issue:`6693`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001275
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001276 The :mod:`site` module now reports exceptions occurring
1277 when the :mod:`sitecustomize` module is imported, and will no longer
Florent Xiclunaad598332010-03-31 21:40:32 +00001278 catch and swallow the :exc:`KeyboardInterrupt` exception. (Fixed by
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001279 Victor Stinner; :issue:`3137`.)
1280
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001281* The :func:`~socket.create_connection` function
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +00001282 gained a *source_address* parameter, a ``(host, port)`` 2-tuple
1283 giving the source address that will be used for the connection.
1284 (Contributed by Eldon Ziegler; :issue:`3972`.)
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00001285
Ezio Melotti021f3342010-04-06 03:26:49 +00001286 The :meth:`~socket.socket.recv_into` and :meth:`~socket.socket.recvfrom_into`
1287 methods will now write into objects that support the buffer API, most usefully
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001288 the :class:`bytearray` and :class:`memoryview` objects. (Implemented by
1289 Antoine Pitrou; :issue:`8104`.)
1290
Ezio Melotti021f3342010-04-06 03:26:49 +00001291* The :mod:`SocketServer` module's :class:`~SocketServer.TCPServer` class now
1292 has a :attr:`~SocketServer.TCPServer.disable_nagle_algorithm` class attribute.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001293 The default value is False; if overridden to be True,
1294 new request connections will have the TCP_NODELAY option set to
1295 prevent buffering many small sends into a single TCP packet.
1296 (Contributed by Kristjan Valur Jonsson; :issue:`6192`.)
1297
Ezio Melotti021f3342010-04-06 03:26:49 +00001298* Updated module: the :mod:`sqlite3` module has been updated to
Andrew M. Kuchlingfed15762010-03-08 12:00:39 +00001299 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
1300 the ability to load SQLite extensions from shared libraries.
1301 Call the ``enable_load_extension(True)`` method to enable extensions,
Ezio Melotti021f3342010-04-06 03:26:49 +00001302 and then call :meth:`~sqlite3.Connection.load_extension` to load a particular shared library.
Andrew M. Kuchlingfed15762010-03-08 12:00:39 +00001303 (Updated by Gerhard Häring.)
1304
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001305* The :mod:`ssl` module's :class:`~ssl.SSL` objects now support the
1306 buffer API, which fixed a test suite failure (fix by Antoine Pitrou;
1307 :issue:`7133`) and automatically set
1308 OpenSSL's :cmacro:`SSL_MODE_AUTO_RETRY`, which will prevent an error
1309 code being returned from :meth:`recv` operations that trigger an SSL
1310 renegotiation (fix by Antoine Pitrou; :issue:`8222`).
1311
1312 The :func:`wrap_socket` constructor function now takes a
1313 *ciphers* argument that's a string listing the encryption algorithms
1314 to be allowed; the format of the string is described
1315 `in the OpenSSL documentation <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`__. (Added by Antoine Pitrou; :issue:`8322`.)
1316
1317 Another change makes the extension load all of OpenSSL's ciphers and
1318 digest algorithms so that they're all available. Some SSL
1319 certificates couldn't be verified, reporting an 'unknown algorithm'
1320 error. (Reported by Beda Kosata, and fixed by Antoine Pitrou;
1321 :issue:`8484`.)
1322
1323 The version of OpenSSL being used is now available as the module
1324 attributes :attr:`OPENSSL_VERSION` (a string),
1325 :attr:`OPENSSL_VERSION_INFO` (a 5-tuple), and
1326 :attr:`OPENSSL_VERSION_NUMBER` (an integer). (Added by Antoine
1327 Pitrou; :issue:`8321`.)
1328
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001329* The :mod:`struct` module will no longer silently ignore overflow
1330 errors when a value is too large for a particular integer format
1331 code (one of ``bBhHiIlLqQ``); it now always raises a
1332 :exc:`struct.error` exception. (Changed by Mark Dickinson;
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001333 :issue:`1523`.) The :func:`~struct.pack` function will also
1334 attempt to use :meth:`__index__` to convert and pack non-integers
1335 before trying the :meth:`__int__` method or reporting an error.
1336 (Changed by Mark Dickinson; :issue:`8300`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001337
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001338* New function: the :mod:`subprocess` module's
Ezio Melotti021f3342010-04-06 03:26:49 +00001339 :func:`~subprocess.check_output` runs a command with a specified set of arguments
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001340 and returns the command's output as a string when the command runs without
Ezio Melotti021f3342010-04-06 03:26:49 +00001341 error, or raises a :exc:`~subprocess.CalledProcessError` exception otherwise.
Andrew M. Kuchling10b1ec92009-01-02 21:00:35 +00001342
1343 ::
1344
1345 >>> subprocess.check_output(['df', '-h', '.'])
1346 'Filesystem Size Used Avail Capacity Mounted on\n
1347 /dev/disk0s2 52G 49G 3.0G 94% /\n'
1348
1349 >>> subprocess.check_output(['df', '-h', '/bogus'])
1350 ...
1351 subprocess.CalledProcessError: Command '['df', '-h', '/bogus']' returned non-zero exit status 1
1352
1353 (Contributed by Gregory P. Smith.)
1354
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001355 The :mod:`subprocess` module will now retry its internal system calls
1356 on receiving an :const:`EINTR` signal. (Reported by several people; final
1357 patch by Gregory P. Smith in :issue:`1068268`.)
1358
Ezio Melotti021f3342010-04-06 03:26:49 +00001359* New function: :func:`~symtable.is_declared_global` in the :mod:`symtable` module
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001360 returns true for variables that are explicitly declared to be global,
1361 false for ones that are implicitly global.
1362 (Contributed by Jeremy Hylton.)
1363
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00001364* The :mod:`syslog` module will now use the value of ``sys.argv[0]`` as the
1365 identifier instead of the previous default value of ``'python'``.
1366 (Changed by Sean Reifschneider; :issue:`8451`.)
1367
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001368* The ``sys.version_info`` value is now a named tuple, with attributes
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001369 named :attr:`major`, :attr:`minor`, :attr:`micro`,
1370 :attr:`releaselevel`, and :attr:`serial`. (Contributed by Ross
1371 Light; :issue:`4285`.)
1372
1373 :func:`sys.getwindowsversion` also returns a named tuple,
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +00001374 with attributes named :attr:`major`, :attr:`minor`, :attr:`build`,
Ezio Melotti12477752010-02-08 22:22:41 +00001375 :attr:`platform`, :attr:`service_pack`, :attr:`service_pack_major`,
Eric Smithb3c54882010-02-03 14:17:50 +00001376 :attr:`service_pack_minor`, :attr:`suite_mask`, and
1377 :attr:`product_type`. (Contributed by Brian Curtin; :issue:`7766`.)
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001378
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001379* The :mod:`tarfile` module's default error handling has changed, to
1380 no longer suppress fatal errors. The default error level was previously 0,
1381 which meant that errors would only result in a message being written to the
1382 debug log, but because the debug log is not activated by default,
1383 these errors go unnoticed. The default error level is now 1,
1384 which raises an exception if there's an error.
1385 (Changed by Lars Gustäbel; :issue:`7357`.)
1386
Ezio Melotti021f3342010-04-06 03:26:49 +00001387 :mod:`tarfile` now supports filtering the :class:`~tarfile.TarInfo`
1388 objects being added to a tar file. When you call :meth:`~tarfile.TarFile.add`,
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001389 instance, you may supply an optional *filter* argument
1390 that's a callable. The *filter* callable will be passed the
Ezio Melotti021f3342010-04-06 03:26:49 +00001391 :class:`~tarfile.TarInfo` for every file being added, and can modify and return it.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001392 If the callable returns ``None``, the file will be excluded from the
1393 resulting archive. This is more powerful than the existing
1394 *exclude* argument, which has therefore been deprecated.
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001395 (Added by Lars Gustäbel; :issue:`6856`.)
Ezio Melotti021f3342010-04-06 03:26:49 +00001396 The :class:`~tarfile.TarFile` class also now supports the context manager protocol.
Andrew M. Kuchlingfed15762010-03-08 12:00:39 +00001397 (Added by Lars Gustäbel; :issue:`7232`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001398
Ezio Melotti021f3342010-04-06 03:26:49 +00001399* The :meth:`~threading.Event.wait` method of the :class:`threading.Event` class
1400 now returns the internal flag on exit. This means the method will usually
1401 return true because :meth:`~threading.Event.wait` is supposed to block until the
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001402 internal flag becomes true. The return value will only be false if
1403 a timeout was provided and the operation timed out.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001404 (Contributed by Tim Lesher; :issue:`1674032`.)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001405
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001406* The Unicode database provided by the :mod:`unicodedata` module is
1407 now used internally to determine which characters are numeric,
1408 whitespace, or represent line breaks. The database also
1409 includes information from the :file:`Unihan.txt` data file (patch
1410 by Anders Chrigström and Amaury Forgeot d'Arc; :issue:`1571184`)
1411 and has been updated to version 5.2.0 (updated by
1412 Florent Xicluna; :issue:`8024`).
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001413
Andrew M. Kuchling04b99cc2010-05-04 01:24:22 +00001414* The :mod:`urlparse` module's :func:`~urlparse.urlsplit` now handles
1415 unknown URL schemes in a fashion compliant with :rfc:`3986`: if the
1416 URL is of the form ``"<something>://..."``, the text before the
1417 ``://`` is treated as the scheme, even if it's a made-up scheme that
1418 the module doesn't know about. This change may break code that
1419 worked around the old behaviour. For example, Python 2.6.4 or 2.5
1420 will return the following:
1421
1422 >>> import urlparse
1423 >>> urlparse.urlsplit('invented://host/filename?query')
1424 ('invented', '', '//host/filename?query', '', '')
1425
1426 Python 2.7 (and Python 2.6.5) will return:
1427
1428 >>> import urlparse
1429 >>> urlparse.urlsplit('invented://host/filename?query')
1430 ('invented', 'host', '/filename?query', '', '')
1431
1432 (Python 2.7 actually produces slightly different output, since it
1433 returns a named tuple instead of a standard tuple.)
1434
1435 The :mod:`urlparse` module also supports IPv6 literal addresses as defined by
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001436 :rfc:`2732` (contributed by Senthil Kumaran; :issue:`2987`). ::
1437
1438 >>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo')
1439 ParseResult(scheme='http', netloc='[1080::8:800:200C:417A]',
1440 path='/foo', params='', query='', fragment='')
1441
Ezio Melotti021f3342010-04-06 03:26:49 +00001442* The :class:`~UserDict.UserDict` class is now a new-style class. (Changed by
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001443 Benjamin Peterson.)
1444
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00001445* New class: the :class:`~weakref.WeakSet` class in the :mod:`weakref`
1446 module is a set that only holds weak references to its elements; elements
1447 will be removed once there are no references pointing to them.
1448 (Originally implemented in Python 3.x by Raymond Hettinger, and backported
1449 to 2.7 by Michael Foord.)
1450
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001451* The ElementTree library, :mod:`xml.etree`, no longer escapes
1452 ampersands and angle brackets when outputting an XML processing
Ezio Melotti021f3342010-04-06 03:26:49 +00001453 instruction (which looks like ``<?xml-stylesheet href="#style1"?>``)
1454 or comment (which looks like ``<!-- comment -->``).
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001455 (Patch by Neil Muller; :issue:`2746`.)
1456
Ezio Melotti021f3342010-04-06 03:26:49 +00001457* The :mod:`zipfile` module's :class:`~zipfile.ZipFile` now supports the context
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001458 management protocol, so you can write ``with zipfile.ZipFile(...) as f: ...``.
1459 (Contributed by Brian Curtin; :issue:`5511`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001460
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001461 :mod:`zipfile` now also supports archiving empty directories and
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001462 extracts them correctly. (Fixed by Kuba Wieczorek; :issue:`4710`.)
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001463 Reading files out of an archive is faster, and interleaving
Ezio Melotti021f3342010-04-06 03:26:49 +00001464 :meth:`~zipfile.ZipFile.read` and :meth:`~zipfile.ZipFile.readline` now works correctly.
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001465 (Contributed by Nir Aides; :issue:`7610`.)
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001466
Ezio Melotti021f3342010-04-06 03:26:49 +00001467 The :func:`~zipfile.is_zipfile` function now
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001468 accepts a file object, in addition to the path names accepted in earlier
1469 versions. (Contributed by Gabriel Genellina; :issue:`4756`.)
1470
Ezio Melotti021f3342010-04-06 03:26:49 +00001471 The :meth:`~zipfile.ZipFile.writestr` method now has an optional *compress_type* parameter
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001472 that lets you override the default compression method specified in the
Ezio Melotti021f3342010-04-06 03:26:49 +00001473 :class:`~zipfile.ZipFile` constructor. (Contributed by Ronald Oussoren;
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001474 :issue:`6003`.)
1475
1476
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001477.. ======================================================================
1478.. whole new modules get described in subsections here
1479
1480
1481.. _importlib-section:
1482
1483New module: importlib
1484------------------------------
1485
1486Python 3.1 includes the :mod:`importlib` package, a re-implementation
1487of the logic underlying Python's :keyword:`import` statement.
1488:mod:`importlib` is useful for implementors of Python interpreters and
1489to users who wish to write new importers that can participate in the
1490import process. Python 2.7 doesn't contain the complete
1491:mod:`importlib` package, but instead has a tiny subset that contains
1492a single function, :func:`~importlib.import_module`.
1493
1494``import_module(name, package=None)`` imports a module. *name* is
1495a string containing the module or package's name. It's possible to do
1496relative imports by providing a string that begins with a ``.``
1497character, such as ``..utils.errors``. For relative imports, the
1498*package* argument must be provided and is the name of the package that
1499will be used as the anchor for
1500the relative import. :func:`~importlib.import_module` both inserts the imported
1501module into ``sys.modules`` and returns the module object.
1502
1503Here are some examples::
1504
1505 >>> from importlib import import_module
1506 >>> anydbm = import_module('anydbm') # Standard absolute import
1507 >>> anydbm
1508 <module 'anydbm' from '/p/python/Lib/anydbm.py'>
1509 >>> # Relative import
1510 >>> sysconfig = import_module('..sysconfig', 'distutils.command')
1511 >>> sysconfig
1512 <module 'distutils.sysconfig' from '/p/python/Lib/distutils/sysconfig.pyc'>
1513
1514:mod:`importlib` was implemented by Brett Cannon and introduced in
1515Python 3.1.
1516
1517
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00001518New module: sysconfig
1519---------------------------------
1520
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001521The :mod:`sysconfig` module has been pulled out of the Distutils
1522package, becoming a new top-level module in its own right.
1523:mod:`sysconfig` provides functions for getting information about
1524Python's build process: compiler switches, installation paths, the
1525platform name, and whether Python is running from its source
1526directory.
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00001527
Andrew M. Kuchlingca485622010-05-06 01:10:56 +00001528Some of the functions in the module are:
1529
1530* :func:`~sysconfig.get_config_var` returns variables from Python's
1531 Makefile and the :file:`pyconfig.h` file.
1532* :func:`~sysconfig.get_config_vars` returns a dictionary containing
1533 all of the configuration variables.
1534* :func:`~sysconfig.getpath` returns the configured path for
1535 a particular type of module: the standard library,
1536 site-specific modules, platform-specific modules, etc.
1537* :func:`~sysconfig.is_python_build` returns true if you're running a
1538 binary from a Python source tree, and false otherwise.
1539
1540Consult the :mod:`sysconfig` documentation for more details and for
1541a complete list of functions.
1542
1543The Distutils package and :mod:`sysconfig` are now maintained and
1544renamed by Tarek Ziadé.
1545
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00001546
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001547ttk: Themed Widgets for Tk
1548--------------------------
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001549
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001550Tcl/Tk 8.5 includes a set of themed widgets that re-implement basic Tk
1551widgets but have a more customizable appearance and can therefore more
1552closely resemble the native platform's widgets. This widget
1553set was originally called Tile, but was renamed to Ttk (for "themed Tk")
1554on being added to Tcl/Tck release 8.5.
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001555
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001556XXX write a brief discussion and an example here.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001557
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001558The :mod:`ttk` module was written by Guilherme Polo and added in
1559:issue:`2983`. An alternate version called ``Tile.py``, written by
1560Martin Franklin and maintained by Kevin Walzer, was proposed for
1561inclusion in :issue:`2618`, but the authors argued that Guilherme
1562Polo's work was more comprehensive.
1563
1564
1565.. _unittest-section:
Tarek Ziadé2b210692010-02-02 23:39:40 +00001566
Andrew M. Kuchlingacab9402010-05-06 17:27:57 +00001567Updated module: unittest
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001568---------------------------------
1569
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001570The :mod:`unittest` module was greatly enhanced; many
1571new features were added. Most of these features were implemented
Andrew M. Kuchlingacab9402010-05-06 17:27:57 +00001572by Michael Foord, unless otherwise noted. The enhanced version of
1573the module is downloadable separately for use with Python versions 2.4 to 2.6,
1574packaged as the :mod:`unittest2` package, from
1575http://pypi.python.org/pypi/unittest2.
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001576
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00001577When used from the command line, the module can automatically discover
1578tests. It's not as fancy as `py.test <http://pytest.org>`__ or
1579`nose <http://code.google.com/p/python-nose/>`__, but provides a simple way
1580to run tests kept within a set of package directories. For example,
1581the following command will search the :file:`test/` subdirectory for
1582any importable test files named ``test*.py``::
1583
1584 python -m unittest discover -s test
1585
1586Consult the :mod:`unittest` module documentation for more details.
1587(Developed in :issue:`6001`.)
1588
1589The :func:`main` function supports some other new options:
1590
1591* :option:`-b` or :option:`--buffer` will buffer the standard output
1592 and standard error streams during each test. If the test passes,
1593 any resulting output will be discard; on failure, the buffered
1594 output will be displayed.
1595
1596* :option:`-c` or :option:`--catch` will cause the control-C interrupt
1597 to be handled more gracefully. Instead of interrupting the test
1598 process immediately, the currently running test will be completed
1599 and then the resulting partial results will be reported. If you're
1600 impatient, a second press of control-C will cause an immediate
1601 interruption.
1602
1603 This control-C handler tries to avoid interfering when the code
1604 being tested or the tests being run have defined a signal handler of
1605 their own, by noticing that a signal handler was already set and
1606 calling it. If this doesn't work for you, there's a
1607 :func:`removeHandler` decorator that can be used to mark tests that
1608 should have the control-C handling disabled.
1609
1610* :option:`-f` or :option:`--failfast` makes
1611 test execution stop immediately when a test fails instead of
1612 continuing to execute further tests. (Suggested by Cliff Dyer and
1613 implemented by Michael Foord; :issue:`8074`.)
1614
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001615The progress messages now shows 'x' for expected failures
1616and 'u' for unexpected successes when run in verbose mode.
1617(Contributed by Benjamin Peterson.)
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001618
1619Test cases can raise the :exc:`~unittest.SkipTest` exception to skip a
1620test. (:issue:`1034053`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001621
Ezio Melotti021f3342010-04-06 03:26:49 +00001622The error messages for :meth:`~unittest.TestCase.assertEqual`,
1623:meth:`~unittest.TestCase.assertTrue`, and :meth:`~unittest.TestCase.assertFalse`
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001624failures now provide more information. If you set the
Ezio Melotti021f3342010-04-06 03:26:49 +00001625:attr:`~unittest.TestCase.longMessage` attribute of your :class:`~unittest.TestCase` classes to
1626True, both the standard error message and any additional message you
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001627provide will be printed for failures. (Added by Michael Foord; :issue:`5663`.)
1628
Ezio Melotti021f3342010-04-06 03:26:49 +00001629The :meth:`~unittest.TestCase.assertRaises` method now
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001630return a context handler when called without providing a callable
1631object to run. For example, you can write this::
1632
1633 with self.assertRaises(KeyError):
Ezio Melotti021f3342010-04-06 03:26:49 +00001634 {}['foo']
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001635
1636(Implemented by Antoine Pitrou; :issue:`4444`.)
1637
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001638.. rev 78774
1639
1640Module- and class-level setup and teardown fixtures are now supported.
Ezio Melotti021f3342010-04-06 03:26:49 +00001641Modules can contain :func:`~unittest.setUpModule` and :func:`~unittest.tearDownModule`
1642functions. Classes can have :meth:`~unittest.TestCase.setUpClass` and
1643:meth:`~unittest.TestCase.tearDownClass` methods that must be defined as class methods
1644(using ``@classmethod`` or equivalent). These functions and
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001645methods are invoked when the test runner switches to a test case in a
1646different module or class.
1647
Ezio Melotti021f3342010-04-06 03:26:49 +00001648The methods :meth:`~unittest.TestCase.addCleanup` and
1649:meth:`~unittest.TestCase.doCleanups` were added.
1650:meth:`~unittest.TestCase.addCleanup` allows you to add cleanup functions that
1651will be called unconditionally (after :meth:`~unittest.TestCase.setUp` if
1652:meth:`~unittest.TestCase.setUp` fails, otherwise after :meth:`~unittest.TestCase.tearDown`). This allows
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001653for much simpler resource allocation and deallocation during tests
1654(:issue:`5679`).
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001655
1656A number of new methods were added that provide more specialized
1657tests. Many of these methods were written by Google engineers
1658for use in their test suites; Gregory P. Smith, Michael Foord, and
1659GvR worked on merging them into Python's version of :mod:`unittest`.
1660
Ezio Melotti021f3342010-04-06 03:26:49 +00001661* :meth:`~unittest.TestCase.assertIsNone` and :meth:`~unittest.TestCase.assertIsNotNone` take one
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001662 expression and verify that the result is or is not ``None``.
1663
Ezio Melotti021f3342010-04-06 03:26:49 +00001664* :meth:`~unittest.TestCase.assertIs` and :meth:`~unittest.TestCase.assertIsNot`
1665 take two values and check whether the two values evaluate to the same object or not.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001666 (Added by Michael Foord; :issue:`2578`.)
1667
Ezio Melotti021f3342010-04-06 03:26:49 +00001668* :meth:`~unittest.TestCase.assertIsInstance` and
1669 :meth:`~unittest.TestCase.assertNotIsInstance` check whether
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00001670 the resulting object is an instance of a particular class, or of
1671 one of a tuple of classes. (Added by Georg Brandl; :issue:`7031`.)
1672
Ezio Melotti021f3342010-04-06 03:26:49 +00001673* :meth:`~unittest.TestCase.assertGreater`, :meth:`~unittest.TestCase.assertGreaterEqual`,
1674 :meth:`~unittest.TestCase.assertLess`, and :meth:`~unittest.TestCase.assertLessEqual` compare
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001675 two quantities.
1676
Ezio Melotti021f3342010-04-06 03:26:49 +00001677* :meth:`~unittest.TestCase.assertMultiLineEqual` compares two strings, and if they're
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001678 not equal, displays a helpful comparison that highlights the
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001679 differences in the two strings. This comparison is now used by
Ezio Melotti021f3342010-04-06 03:26:49 +00001680 default when Unicode strings are compared with :meth:`~unittest.TestCase.assertEqual`.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001681
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001682* :meth:`~unittest.TestCase.assertRegexpMatches` and
1683 :meth:`~unittest.TestCase.assertNotRegexpMatches` checks whether the
1684 first argument is a string matching or not matching the regular
1685 expression provided as the second argument (:issue:`8038`).
Ezio Melotti021f3342010-04-06 03:26:49 +00001686
1687* :meth:`~unittest.TestCase.assertRaisesRegexp` checks whether a particular exception
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001688 is raised, and then also checks that the string representation of
1689 the exception matches the provided regular expression.
1690
Ezio Melotti021f3342010-04-06 03:26:49 +00001691* :meth:`~unittest.TestCase.assertIn` and :meth:`~unittest.TestCase.assertNotIn`
1692 tests whether *first* is or is not in *second*.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001693
Ezio Melotti021f3342010-04-06 03:26:49 +00001694* :meth:`~unittest.TestCase.assertItemsEqual` tests whether two provided sequences
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001695 contain the same elements.
1696
Ezio Melotti021f3342010-04-06 03:26:49 +00001697* :meth:`~unittest.TestCase.assertSetEqual` compares whether two sets are equal, and
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001698 only reports the differences between the sets in case of error.
1699
Ezio Melotti021f3342010-04-06 03:26:49 +00001700* Similarly, :meth:`~unittest.TestCase.assertListEqual` and :meth:`~unittest.TestCase.assertTupleEqual`
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001701 compare the specified types and explain any differences without necessarily
1702 printing their full values; these methods are now used by default
Ezio Melotti021f3342010-04-06 03:26:49 +00001703 when comparing lists and tuples using :meth:`~unittest.TestCase.assertEqual`.
1704 More generally, :meth:`~unittest.TestCase.assertSequenceEqual` compares two sequences
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001705 and can optionally check whether both sequences are of a
1706 particular type.
1707
Ezio Melotti021f3342010-04-06 03:26:49 +00001708* :meth:`~unittest.TestCase.assertDictEqual` compares two dictionaries and reports the
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001709 differences; it's now used by default when you compare two dictionaries
Ezio Melotti021f3342010-04-06 03:26:49 +00001710 using :meth:`~unittest.TestCase.assertEqual`. :meth:`~unittest.TestCase.assertDictContainsSubset` checks whether
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001711 all of the key/value pairs in *first* are found in *second*.
1712
Ezio Melotti021f3342010-04-06 03:26:49 +00001713* :meth:`~unittest.TestCase.assertAlmostEqual` and :meth:`~unittest.TestCase.assertNotAlmostEqual` test
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001714 whether *first* and *second* are approximately equal. This method
1715 can either round their difference to an optionally-specified number
1716 of *places* (the default is 7) and compare it to zero, or require
1717 the difference to be smaller than a supplied *delta* value.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001718
Ezio Melotti021f3342010-04-06 03:26:49 +00001719* :meth:`~unittest.TestLoader.loadTestsFromName` properly honors the
1720 :attr:`~unittest.TestLoader.suiteClass` attribute of
1721 the :class:`~unittest.TestLoader`. (Fixed by Mark Roddy; :issue:`6866`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001722
Ezio Melotti021f3342010-04-06 03:26:49 +00001723* A new hook lets you extend the :meth:`~unittest.TestCase.assertEqual` method to handle
1724 new data types. The :meth:`~unittest.TestCase.addTypeEqualityFunc` method takes a type
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001725 object and a function. The function will be used when both of the
1726 objects being compared are of the specified type. This function
1727 should compare the two objects and raise an exception if they don't
1728 match; it's a good idea for the function to provide additional
1729 information about why the two objects are matching, much as the new
1730 sequence comparison methods do.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001731
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001732:func:`unittest.main` now takes an optional ``exit`` argument. If
Ezio Melotti021f3342010-04-06 03:26:49 +00001733False, :func:`~unittest.main` doesn't call :func:`sys.exit`, allowing it to be
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001734used from the interactive interpreter. (Contributed by J. Pablo
1735Fernández; :issue:`3379`.)
1736
Ezio Melotti021f3342010-04-06 03:26:49 +00001737:class:`~unittest.TestResult` has new :meth:`~unittest.TestResult.startTestRun` and
1738:meth:`~unittest.TestResult.stopTestRun` methods that are called immediately before
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001739and after a test run. (Contributed by Robert Collins; :issue:`5728`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001740
1741With all these changes, the :file:`unittest.py` was becoming awkwardly
1742large, so the module was turned into a package and the code split into
1743several files (by Benjamin Peterson). This doesn't affect how the
Andrew M. Kuchlingb2454b22010-04-29 01:45:41 +00001744module is imported or used.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001745
1746
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001747.. _elementtree-section:
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001748
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001749Updated module: ElementTree 1.3
1750---------------------------------
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001751
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001752The version of the ElementTree library included with Python was updated to
1753version 1.3. Some of the new features in ElementTree 1.3 are:
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001754
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001755* The various parsing functions now take a *parser* keyword argument
1756 that can be used to provide an :class:`XMLParser` instance that will
1757 be used. This makes it possible to override the file's internal encoding:
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001758
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001759 p = ET.XMLParser(encoding='utf-8')
1760 t = ET.XML("""<root/>""", parser=p)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001761
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001762 Errors in parsing XML now raise a :exc:`ParseError` exception.
1763 Instances of :exc:`ParseError` have a :attr:`position` attribute
1764 containing a (*line*, *column*) tuple giving the location of the problem.
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001765
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001766* ElementTree's code for converting trees to a string has been
1767 significantly reworked, making it roughly twice as fast in many
1768 cases. The :class:`ElementTree` :meth:`write` and :class:`Element`
1769 :meth:`write` methods now have a *method* parameter that can be
1770 "xml" (the default), "html", or "text". HTML mode will output empty
1771 elements as ``<empty></empty>`` instead of ``<empty/>``, and text
1772 mode will skip over elements and only output the text chunks. If
1773 you set the :attr:`tag` attribute of an element to ``None`` but
1774 leaves its children in place, the element will be omitted when the
1775 tree is written out, so you don't need to do more extensive rearrangement
1776 to remove a single element.
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001777
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001778 Namespace aspects have also been improved. All the ``xmlns:<whatever>``
1779 declarations are now put on the root element and not scattered throughout
1780 the resulting output. You can set the default namespace for a tree
1781 by setting the :attr:`default_namespace` attribute and can
1782 register new prefixes with :meth:`regsiter_namespace`. In XML mode,
1783 you can use the true/false *xml_declaration* parameter to suppress the
1784 XML declaration.
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001785
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001786* New :class:`Element` method: :meth:`extend` appends the items from a
1787 sequence to the element's children. Elements themselves behave like
1788 sequences, so it's easy to move children from one element to
1789 another::
Andrew M. Kuchlinga17cd4a2009-01-31 02:50:09 +00001790
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001791 from xml.etree import ElementTree as ET
Andrew M. Kuchlinga17cd4a2009-01-31 02:50:09 +00001792
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001793 t = ET.XML("""<list>
1794 <item>1</item> <item>2</item> <item>3</item>
1795 </list>""")
1796 new = ET.XML('<root/>')
1797 new.extend(t)
Andrew M. Kuchlinga17cd4a2009-01-31 02:50:09 +00001798
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001799 # Outputs <root><item>1</item>...</root>
1800 print ET.tostring(new)
Andrew M. Kuchlinga17cd4a2009-01-31 02:50:09 +00001801
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001802* New :class:`Element` method: :meth:`iter` yields the children of the
1803 element as a generator. It's also possible to write ``for child in
1804 elem: ...`` to loop over an element's children. The existing method
1805 :meth:`getiterator` is now deprecated. :meth:`getchildren` is
1806 another similar method that constructs and returns a list of
1807 children; it's also deprecated.
Georg Brandl0516f812009-11-18 18:52:35 +00001808
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001809* New :class:`Element` method: :meth:`itertext` yields all chunks of
1810 text that are descendants of the element. For example::
Georg Brandl0516f812009-11-18 18:52:35 +00001811
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00001812 t = ET.XML("""<list>
1813 <item>1</item> <item>2</item> <item>3</item>
1814 </list>""")
1815
1816 # Outputs ['\n ', '1', ' ', '2', ' ', '3', '\n']
1817 print list(t.itertext())
1818
1819* Deprecated: using an element as a Boolean (i.e., ``if elem: ...``)
1820 would return true if the element had any children, or false if
1821 there were no children. This behaviour will eventually change or be removed
1822 because it's confusing (``None`` is false, but so is a childless element?),
1823 so it will now trigger a :exc:`FutureWarning`. In your code,
1824 you should be explicit: write ``len(elem) != 0`` if you're interested in
1825 the number of children, or ``elem is not None`` Instead,
1826
1827Fredrik Lundh develops ElementTree and produced the 1.3 version;
1828you can read his article describing 1.3 at
1829http://effbot.org/zone/elementtree-13-intro.htm.
1830Florent Xicluna updated the version included with
1831Python, after discussions on python-dev and in :issue:`6472`.)
Georg Brandl0516f812009-11-18 18:52:35 +00001832
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001833.. ======================================================================
1834
1835
1836Build and C API Changes
1837=======================
1838
1839Changes to Python's build process and to the C API include:
1840
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001841* The latest release of the GNU Debugger, GDB 7, can be `scripted
1842 using Python
1843 <http://sourceware.org/gdb/current/onlinedocs/gdb/Python.html>`__.
1844 When you begin debugging an executable program P, GDB will look for
1845 a file named ``P-gdb.py`` and automatically read it. Dave Malcolm
1846 contributed a :file:`python-gdb.py` that adds a number of useful
1847 commands when debugging Python itself. For example, there are
1848 ``py-up`` and ``py-down`` that go up or down one Python stack frame,
1849 which usually corresponds to several C stack frames. ``py-print``
1850 prints the value of a Python variable, and ``py-bt`` prints the
1851 Python stack trace. (Added as a result of :issue:`8032`.)
1852
Andrew M. Kuchling10b1ec92009-01-02 21:00:35 +00001853* If you use the :file:`.gdbinit` file provided with Python,
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001854 the "pyo" macro in the 2.7 version now works correctly when the thread being
1855 debugged doesn't hold the GIL; the macro now acquires it before printing.
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001856 (Contributed by Victor Stinner; :issue:`3632`.)
1857
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001858* :cfunc:`Py_AddPendingCall` is now thread-safe, letting any
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001859 worker thread submit notifications to the main Python thread. This
1860 is particularly useful for asynchronous IO operations.
1861 (Contributed by Kristjan Valur Jonsson; :issue:`4293`.)
1862
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001863* New function: :cfunc:`PyCode_NewEmpty` creates an empty code object;
1864 only the filename, function name, and first line number are required.
1865 This is useful to extension modules that are attempting to
1866 construct a more useful traceback stack. Previously such
1867 extensions needed to call :cfunc:`PyCode_New`, which had many
1868 more arguments. (Added by Jeffrey Yasskin.)
1869
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001870* New function: :cfunc:`PyErr_NewExceptionWithDoc` creates a new
1871 exception class, just as the existing :cfunc:`PyErr_NewException` does,
1872 but takes an extra ``char *`` argument containing the docstring for the
1873 new exception class. (Added by the 'lekma' user on the Python bug tracker;
1874 :issue:`7033`.)
1875
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001876* New function: :cfunc:`PyFrame_GetLineNumber` takes a frame object
1877 and returns the line number that the frame is currently executing.
1878 Previously code would need to get the index of the bytecode
1879 instruction currently executing, and then look up the line number
1880 corresponding to that address. (Added by Jeffrey Yasskin.)
1881
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001882* New functions: :cfunc:`PyLong_AsLongAndOverflow` and
1883 :cfunc:`PyLong_AsLongLongAndOverflow` approximates a Python long
1884 integer as a C :ctype:`long` or :ctype:`long long`.
1885 If the number is too large to fit into
1886 the output type, an *overflow* flag is set and returned to the caller.
1887 (Contributed by Case Van Horsen; :issue:`7528` and :issue:`7767`.)
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001888
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00001889* New function: stemming from the rewrite of string-to-float conversion,
1890 a new :cfunc:`PyOS_string_to_double` function was added. The old
1891 :cfunc:`PyOS_ascii_strtod` and :cfunc:`PyOS_ascii_atof` functions
1892 are now deprecated.
1893
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001894* New macros: the Python header files now define the following macros:
1895 :cmacro:`Py_ISALNUM`,
1896 :cmacro:`Py_ISALPHA`,
1897 :cmacro:`Py_ISDIGIT`,
1898 :cmacro:`Py_ISLOWER`,
1899 :cmacro:`Py_ISSPACE`,
1900 :cmacro:`Py_ISUPPER`,
1901 :cmacro:`Py_ISXDIGIT`,
1902 and :cmacro:`Py_TOLOWER`, :cmacro:`Py_TOUPPER`.
1903 All of these functions are analogous to the C
1904 standard macros for classifying characters, but ignore the current
1905 locale setting, because in
1906 several places Python needs to analyze characters in a
1907 locale-independent way. (Added by Eric Smith;
1908 :issue:`5793`.)
1909
1910 .. XXX these macros don't seem to be described in the c-api docs.
1911
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00001912* Removed function: :cmacro:`PyEval_CallObject` is now only available
1913 as a macro. A function version was being kept around to preserve
1914 ABI linking compatibility, but that was in 1997; it can certainly be
1915 deleted. (Removed by Antoine Pitrou; :issue:`8276`.)
1916
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001917* New format codes: the :cfunc:`PyFormat_FromString`,
1918 :cfunc:`PyFormat_FromStringV`, and :cfunc:`PyErr_Format` now
1919 accepts ``%lld`` and ``%llu`` format codes for displaying values of
1920 C's :ctype:`long long` types.
1921 (Contributed by Mark Dickinson; :issue:`7228`.)
1922
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001923* The complicated interaction between threads and process forking has
1924 been changed. Previously, the child process created by
1925 :func:`os.fork` might fail because the child is created with only a
1926 single thread running, the thread performing the :func:`os.fork`.
1927 If other threads were holding a lock, such as Python's import lock,
1928 when the fork was performed, the lock would still be marked as
1929 "held" in the new process. But in the child process nothing would
1930 ever release the lock, since the other threads weren't replicated,
1931 and the child process would no longer be able to perform imports.
1932
1933 Python 2.7 now acquires the import lock before performing an
1934 :func:`os.fork`, and will also clean up any locks created using the
1935 :mod:`threading` module. C extension modules that have internal
1936 locks, or that call :cfunc:`fork()` themselves, will not benefit
1937 from this clean-up.
1938
1939 (Fixed by Thomas Wouters; :issue:`1590864`.)
1940
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00001941* The :cfunc:`Py_Finalize` function now calls the internal
1942 :func:`threading._shutdown` function; this prevents some exceptions from
1943 being raised when an interpreter shuts down.
1944 (Patch by Adam Olsen; :issue:`1722344`.)
1945
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00001946* When using the :ctype:`PyMemberDef` structure to define attributes
1947 of a type, Python will no longer let you try to delete or set a
1948 :const:`T_STRING_INPLACE` attribute.
1949
1950 .. rev 79644
1951
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00001952* Global symbols defined by the :mod:`ctypes` module are now prefixed
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001953 with ``Py``, or with ``_ctypes``. (Implemented by Thomas
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00001954 Heller; :issue:`3102`.)
1955
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00001956* New configure option: the :option:`--with-system-expat` switch allows
1957 building the :mod:`pyexpat` module to use the system Expat library.
1958 (Contributed by Arfrever Frehtes Taifersar Arahesis; :issue:`7609`.)
1959
Andrew M. Kuchlingce690522010-04-13 01:32:51 +00001960* New configure option: compiling Python with the
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00001961 :option:`--with-valgrind` option will now disable the pymalloc
Andrew M. Kuchlingce690522010-04-13 01:32:51 +00001962 allocator, which is difficult for the Valgrind memory-error detector
1963 to analyze correctly.
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00001964 Valgrind will therefore be better at detecting memory leaks and
1965 overruns. (Contributed by James Henstridge; :issue:`2422`.)
1966
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +00001967* New configure option: you can now supply no arguments to
1968 :option:`--with-dbmliborder=` in order to build none of the various
1969 DBM modules. (Added by Arfrever Frehtes Taifersar Arahesis;
1970 :issue:`6491`.)
1971
Andrew M. Kuchling77069572009-03-31 01:21:01 +00001972* The :program:`configure` script now checks for floating-point rounding bugs
1973 on certain 32-bit Intel chips and defines a :cmacro:`X87_DOUBLE_ROUNDING`
1974 preprocessor definition. No code currently uses this definition,
1975 but it's available if anyone wishes to use it.
1976 (Added by Mark Dickinson; :issue:`2937`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001977
Andrew M. Kuchling4515f0d2010-04-11 20:40:09 +00001978 :program:`configure` also now sets a :envvar:`LDCXXSHARED` Makefile
1979 variable for supporting C++ linking. (Contributed by Arfrever
1980 Frehtes Taifersar Arahesis; :issue:`1222585`.)
1981
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001982* The build process now creates the necessary files for pkg-config
1983 support. (Contributed by Clinton Roy; :issue:`3585`.)
1984
1985* The build process now supports Subversion 1.7. (Contributed by
1986 Arfrever Frehtes Taifersar Arahesis; :issue:`6094`.)
1987
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001988
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001989.. ======================================================================
1990
1991Port-Specific Changes: Windows
1992-----------------------------------
1993
Andrew M. Kuchling10b1ec92009-01-02 21:00:35 +00001994* The :mod:`msvcrt` module now contains some constants from
1995 the :file:`crtassem.h` header file:
1996 :data:`CRT_ASSEMBLY_VERSION`,
1997 :data:`VC_ASSEMBLY_PUBLICKEYTOKEN`,
1998 and :data:`LIBRARIES_ASSEMBLY_NAME_PREFIX`.
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001999 (Contributed by David Cournapeau; :issue:`4365`.)
2000
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002001* The :mod:`_winreg` module for accessing the registry now implements
2002 the :func:`CreateKeyEx` and :func:`DeleteKeyEx` functions, extended
2003 versions of previously-supported functions that take several extra
2004 arguments. The :func:`DisableReflectionKey`,
2005 :func:`EnableReflectionKey`, and :func:`QueryReflectionKey` were also
2006 tested and documented.
2007 (Implemented by Brian Curtin: :issue:`7347`.)
2008
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00002009* The new :cfunc:`_beginthreadex` API is used to start threads, and
2010 the native thread-local storage functions are now used.
2011 (Contributed by Kristjan Valur Jonsson; :issue:`3582`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002012
Andrew M. Kuchling363dbcc2010-04-14 23:55:17 +00002013* The :func:`os.kill` function now works on Windows. The signal value
2014 can be the constants :const:`CTRL_C_EVENT`,
2015 :const:`CTRL_BREAK_EVENT`, or any integer. The Control-C and
2016 Control-Break keystroke events can be sent to subprocesses; any
2017 other value will use the :cfunc:`TerminateProcess` API.
2018 (Contributed by Miki Tebeka; :issue:`1220212`.)
2019
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002020* The :func:`os.listdir` function now correctly fails
2021 for an empty path. (Fixed by Hirokazu Yamamoto; :issue:`5913`.)
2022
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00002023* The :mod:`mimelib` module will now read the MIME database from
2024 the Windows registry when initializing.
2025 (Patch by Gabriel Genellina; :issue:`4969`.)
2026
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002027.. ======================================================================
2028
2029Port-Specific Changes: Mac OS X
2030-----------------------------------
2031
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002032* The path ``/Library/Python/2.7/site-packages`` is now appended to
Andrew M. Kuchling77069572009-03-31 01:21:01 +00002033 ``sys.path``, in order to share added packages between the system
2034 installation and a user-installed copy of the same version.
2035 (Changed by Ronald Oussoren; :issue:`4865`.)
2036
Andrew M. Kuchling04b99cc2010-05-04 01:24:22 +00002037Port-Specific Changes: FreeBSD
2038-----------------------------------
2039
2040* FreeBSD 7.1's :const:`SO_SETFIB` constant, used with
2041 :func:`~socket.getsockopt`/:func:`~socket.setsockopt` to select an
2042 alternate routing table, is now available in the :mod:`socket`
2043 module. (Added by Kyle VanderBeek; :issue:`8235`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002044
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00002045Other Changes and Fixes
2046=======================
2047
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00002048* Two benchmark scripts, :file:`iobench` and :file:`ccbench`, were
2049 added to the :file:`Tools` directory. :file:`iobench` measures the
Antoine Pitroudde96e62010-02-08 20:25:47 +00002050 speed of built-in file I/O objects (as returned by :func:`open`)
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00002051 while performing various operations, and :file:`ccbench` is a
2052 concurrency benchmark that tries to measure computing throughput,
2053 thread switching latency, and IO processing bandwidth when
2054 performing several tasks using a varying number of threads.
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00002055
Andrew M. Kuchling77069572009-03-31 01:21:01 +00002056* When importing a module from a :file:`.pyc` or :file:`.pyo` file
2057 with an existing :file:`.py` counterpart, the :attr:`co_filename`
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00002058 attributes of the resulting code objects are overwritten when the
2059 original filename is obsolete. This can happen if the file has been
2060 renamed, moved, or is accessed through different paths. (Patch by
2061 Ziga Seilnacht and Jean-Paul Calderone; :issue:`1180193`.)
Andrew M. Kuchling77069572009-03-31 01:21:01 +00002062
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00002063* The :file:`regrtest.py` script now takes a :option:`--randseed=`
2064 switch that takes an integer that will be used as the random seed
2065 for the :option:`-r` option that executes tests in random order.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002066 The :option:`-r` option also reports the seed that was used
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00002067 (Added by Collin Winter.)
2068
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00002069* Another :file:`regrtest.py` switch is :option:`-j`, which
2070 takes an integer specifying how many tests run in parallel. This
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002071 allows reducing the total runtime on multi-core machines.
Antoine Pitrou4698d992009-05-31 14:20:14 +00002072 This option is compatible with several other options, including the
2073 :option:`-R` switch which is known to produce long runtimes.
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00002074 (Added by Antoine Pitrou, :issue:`6152`.) This can also be used
2075 with a new :option:`-F` switch that runs selected tests in a loop
2076 until they fail. (Added by Antoine Pitrou; :issue:`7312`.)
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00002077
Andrew M. Kuchling85f928a2010-04-15 01:42:27 +00002078* When executed as a script, the :file:`py_compile.py` module now
2079 accepts ``'-'`` as an argument, which will read standard input for
2080 the list of filenames to be compiled. (Contributed by Piotr
2081 Ożarowski; :issue:`8233`.)
2082
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002083.. ======================================================================
2084
2085Porting to Python 2.7
2086=====================
2087
2088This section lists previously described changes and other bugfixes
2089that may require changes to your code:
2090
Andrew M. Kuchlinge86b7fe2010-05-06 14:14:09 +00002091* The :func:`range` function processes its arguments more
2092 consistently; it will now call :meth:`__int__` on non-float,
2093 non-integer arguments that are supplied to it. (Fixed by Alexander
2094 Belopolsky; :issue:`1533`.)
2095
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002096* The string :meth:`format` method changed the default precision used
2097 for floating-point and complex numbers from 6 decimal
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00002098 places to 12, which matches the precision used by :func:`str`.
2099 (Changed by Eric Smith; :issue:`5920`.)
2100
Amaury Forgeot d'Arc901f2002009-06-09 23:08:13 +00002101* Because of an optimization for the :keyword:`with` statement, the special
2102 methods :meth:`__enter__` and :meth:`__exit__` must belong to the object's
2103 type, and cannot be directly attached to the object's instance. This
Amaury Forgeot d'Arcd81333c2009-06-10 20:30:19 +00002104 affects new-style classes (derived from :class:`object`) and C extension
Amaury Forgeot d'Arc901f2002009-06-09 23:08:13 +00002105 types. (:issue:`6101`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002106
Andrew M. Kuchling837a5382010-05-06 17:21:59 +00002107* Due to a bug in Python 2.6, the *exc_value* parameter to
2108 :meth:`__exit__` methods was often the string representation of the
2109 exception, not an instance. This was fixed in 2.7, so *exc_value*
2110 will be an instance as expected. (Fixed by Florent Xicluna;
2111 :issue:`7853`.)
2112
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00002113* When a restricted set of attributes were set using ``__slots__``,
2114 deleting an unset attribute would not raise :exc:`AttributeError`
2115 as you would expect. Fixed by Benjamin Peterson; :issue:`7604`.)
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002116
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00002117In the standard library:
2118
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002119* When using :class:`Decimal` instances with a string's
2120 :meth:`format` method, the default alignment was previously
2121 left-alignment. This has been changed to right-alignment, which might
2122 change the output of your programs.
2123 (Changed by Mark Dickinson; :issue:`6857`.)
2124
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00002125 Comparisons involving a signaling NaN value (or ``sNAN``) now signal
2126 :const:`InvalidOperation` instead of silently returning a true or
2127 false value depending on the comparison operator. Quiet NaN values
2128 (or ``NaN``) are now hashable. (Fixed by Mark Dickinson;
2129 :issue:`7279`.)
2130
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00002131* The ElementTree library, :mod:`xml.etree`, no longer escapes
2132 ampersands and angle brackets when outputting an XML processing
2133 instruction (which looks like `<?xml-stylesheet href="#style1"?>`)
2134 or comment (which looks like `<!-- comment -->`).
2135 (Patch by Neil Muller; :issue:`2746`.)
2136
Andrew M. Kuchlingd3b60222010-05-01 01:19:16 +00002137* The :meth:`readline` method of :class:`StringIO` objects now does
2138 nothing when a negative length is requested, as other file-like
2139 objects do. (:issue:`7348`).
2140
Andrew M. Kuchling15c82d22010-04-29 00:22:16 +00002141* The :mod:`syslog` module will now use the value of ``sys.argv[0]`` as the
2142 identifier instead of the previous default value of ``'python'``.
2143 (Changed by Sean Reifschneider; :issue:`8451`.)
2144
Andrew M. Kuchling04b99cc2010-05-04 01:24:22 +00002145* The :mod:`urlparse` module's :func:`~urlparse.urlsplit` now handles
2146 unknown URL schemes in a fashion compliant with :rfc:`3986`: if the
2147 URL is of the form ``"<something>://..."``, the text before the
2148 ``://`` is treated as the scheme, even if it's a made-up scheme that
2149 the module doesn't know about. This change may break code that
2150 worked around the old behaviour. For example, Python 2.6.4 or 2.5
2151 will return the following:
2152
2153 >>> import urlparse
2154 >>> urlparse.urlsplit('invented://host/filename?query')
2155 ('invented', '', '//host/filename?query', '', '')
2156
2157 Python 2.7 (and Python 2.6.5) will return:
2158
2159 >>> import urlparse
2160 >>> urlparse.urlsplit('invented://host/filename?query')
2161 ('invented', 'host', '/filename?query', '', '')
2162
2163 (Python 2.7 actually produces slightly different output, since it
2164 returns a named tuple instead of a standard tuple.)
2165
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00002166For C extensions:
2167
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +00002168* C extensions that use integer format codes with the ``PyArg_Parse*``
2169 family of functions will now raise a :exc:`TypeError` exception
2170 instead of triggering a :exc:`DeprecationWarning` (:issue:`5080`).
2171
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00002172* Use the new :cfunc:`PyOS_string_to_double` function instead of the old
2173 :cfunc:`PyOS_ascii_strtod` and :cfunc:`PyOS_ascii_atof` functions,
2174 which are now deprecated.
2175
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +00002176
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002177.. ======================================================================
2178
2179
2180.. _acks27:
2181
2182Acknowledgements
2183================
2184
2185The author would like to thank the following people for offering
2186suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchlingc121f132010-04-30 01:33:40 +00002187article: Nick Coghlan, Ryan Lovett, R. David Murray, Hugh Secker-Walker.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00002188