blob: da15e4939735d3f0c4a2d690d11a7423f4ec48c8 [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. Kuchling71d5c282009-03-30 22:30:20 +00009.. Fix accents on Kristjan Valur Jonsson, Fuerstenau, Tarek Ziade.
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +000010
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000011.. $Id$
12 Rules for maintenance:
13
14 * Anyone can add text to this document. Do not spend very much time
15 on the wording of your changes, because your text will probably
16 get rewritten to some degree.
17
18 * The maintainer will go through Misc/NEWS periodically and add
19 changes; it's therefore more important to add your changes to
20 Misc/NEWS than to this file.
21
22 * This is not a complete list of every single change; completeness
23 is the purpose of Misc/NEWS. Some changes I consider too small
24 or esoteric to include. If such a change is added to the text,
25 I'll just remove it. (This is another reason you shouldn't spend
26 too much time on writing your addition.)
27
28 * If you want to draw your new text to the attention of the
29 maintainer, add 'XXX' to the beginning of the paragraph or
30 section.
31
32 * It's OK to just add a fragmentary note about a change. For
33 example: "XXX Describe the transmogrify() function added to the
34 socket module." The maintainer will research the change and
35 write the necessary text.
36
37 * You can comment out your additions if you like, but it's not
38 necessary (especially when a final release is some months away).
39
40 * Credit the author of a patch or bugfix. Just the name is
41 sufficient; the e-mail address isn't necessary.
42
43 * It's helpful to add the bug/patch number in a parenthetical comment.
44
45 XXX Describe the transmogrify() function added to the socket
46 module.
47 (Contributed by P.Y. Developer; :issue:`12345`.)
48
49 This saves the maintainer some effort going through the SVN logs
50 when researching a change.
51
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +000052This article explains the new features in Python 2.7. The final
53release of 2.7 is currently scheduled for June 2010; the detailed
54schedule is described in :pep:`373`.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000055
56.. Compare with previous release in 2 - 3 sentences here.
57 add hyperlink when the documentation becomes available online.
58
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +000059.. _whatsnew27-python31:
60
61Python 3.1 Features
62=======================
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +000063
64Much as Python 2.6 incorporated features from Python 3.0,
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +000065version 2.7 incorporates some of the new features
66in Python 3.1. The 2.x series continues to provide tools
67for migrating to the 3.x series.
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +000068
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +000069A partial list of 3.1 features that were backported to 2.7:
70
71* A version of the :mod:`io` library, rewritten in C for performance.
72* The ordered-dictionary type described in :ref:`pep-0372`.
Andrew M. Kuchling8f254e72009-12-08 02:37:05 +000073* The new format specifier described in :ref:`pep-0378`.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +000074* The :class:`memoryview` object.
75* A small subset of the :mod:`importlib` module `described below <#importlib-section>`__.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +000076* Float-to-string and string-to-float conversions now round their
77 results more correctly. And :func:`repr` of a floating-point
78 number *x* returns a result that's guaranteed to round back to the
79 same number when converted back to a string.
80* The :cfunc:`PyLong_AsLongAndOverflow` C API function.
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +000081
82One porting change: the :option:`-3` switch now automatically
83enables the :option:`-Qwarn` switch that causes warnings
84about using classic division with integers and long integers.
85
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +000086Other new Python3-mode warnings include:
87
88* :func:`operator.isCallable` and :func:`operator.sequenceIncludes`,
89 which are not supported in 3.x.
90
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000091.. ========================================================================
92.. Large, PEP-level features and changes should be described here.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000093.. ========================================================================
94
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +000095.. _pep-0372:
96
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +000097PEP 372: Adding an ordered dictionary to collections
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +000098====================================================
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +000099
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000100Regular Python dictionaries iterate over key/value pairs in arbitrary order.
101Over the years, a number of authors have written alternative implementations
102that remember the order that the keys were originally inserted. Based on
103the experiences from those implementations, a new
104:class:`collections.OrderedDict` class has been introduced.
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000105
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000106The :class:`OrderedDict` API is substantially the same as regular dictionaries
107but will iterate over keys and values in a guaranteed order depending on
108when a key was first inserted::
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000109
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000110 >>> from collections import OrderedDict
111 >>> d = OrderedDict([('first', 1), ('second', 2),
112 ... ('third', 3)])
113 >>> d.items()
114 [('first', 1), ('second', 2), ('third', 3)]
115
116If a new entry overwrites an existing entry, the original insertion
117position is left unchanged::
118
119 >>> d['second'] = 4
120 >>> d.items()
121 [('first', 1), ('second', 4), ('third', 3)]
122
123Deleting an entry and reinserting it will move it to the end::
124
125 >>> del d['second']
126 >>> d['second'] = 5
127 >>> d.items()
128 [('first', 1), ('third', 3), ('second', 5)]
129
130The :meth:`popitem` method has an optional *last* argument
131that defaults to True. If *last* is True, the most recently
132added key is returned and removed; if it's False, the
133oldest key is selected::
134
135 >>> od = OrderedDict([(x,0) for x in range(20)])
136 >>> od.popitem()
137 (19, 0)
138 >>> od.popitem()
139 (18, 0)
140 >>> od.popitem(False)
141 (0, 0)
142 >>> od.popitem(False)
143 (1, 0)
144
145Comparing two ordered dictionaries checks both the keys and values,
146and requires that the insertion order was the same::
147
148 >>> od1 = OrderedDict([('first', 1), ('second', 2),
149 ... ('third', 3)])
150 >>> od2 = OrderedDict([('third', 3), ('first', 1),
151 ... ('second', 2)])
152 >>> od1==od2
153 False
154 >>> # Move 'third' key to the end
155 >>> del od2['third'] ; od2['third'] = 3
156 >>> od1==od2
157 True
158
159Comparing an :class:`OrderedDict` with a regular dictionary
160ignores the insertion order and just compares the keys and values.
161
162How does the :class:`OrderedDict` work? It maintains a doubly-linked
163list of keys, appending new keys to the list as they're inserted. A
164secondary dictionary maps keys to their corresponding list node, so
165deletion doesn't have to traverse the entire linked list and therefore
166remains O(1).
167
168.. XXX check O(1)-ness with Raymond
169
170The standard library now supports use of ordered dictionaries in several
171modules. The :mod:`configparser` module uses them by default. This lets
172configuration files be read, modified, and then written back in their original
173order. The *_asdict()* method for :func:`collections.namedtuple` now
174returns an ordered dictionary with the values appearing in the same order as
175the underlying tuple indicies. The :mod:`json` module is being built-out with
176an *object_pairs_hook* to allow OrderedDicts to be built by the decoder.
177Support was also added for third-party tools like `PyYAML <http://pyyaml.org/>`_.
178
Andrew M. Kuchling7fe65a02009-10-13 15:49:33 +0000179.. seealso::
180
181 :pep:`372` - Adding an ordered dictionary to collections
182 PEP written by Armin Ronacher and Raymond Hettinger;
183 implemented by Raymond Hettinger.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000184
185.. _pep-0378:
186
187PEP 378: Format Specifier for Thousands Separator
188====================================================
189
190To make program output more readable, it can be useful to add
191separators to large numbers and render them as
19218,446,744,073,709,551,616 instead of 18446744073709551616.
193
194The fully general solution for doing this is the :mod:`locale` module,
195which can use different separators ("," in North America, "." in
196Europe) and different grouping sizes, but :mod:`locale` is complicated
197to use and unsuitable for multi-threaded applications where different
198threads are producing output for different locales.
199
200Therefore, a simple comma-grouping mechanism has been added to the
201mini-language used by the string :meth:`format` method. When
202formatting a floating-point number, simply include a comma between the
203width and the precision::
204
205 >>> '{:20,.2}'.format(f)
206 '18,446,744,073,709,551,616.00'
207
208This mechanism is not adaptable at all; commas are always used as the
209separator and the grouping is always into three-digit groups. The
210comma-formatting mechanism isn't as general as the :mod:`locale`
211module, but it's easier to use.
212
Andrew M. Kuchling85ea4bf2009-10-05 22:45:39 +0000213.. XXX "Format String Syntax" in string.rst could use many more examples.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000214
215.. seealso::
216
217 :pep:`378` - Format Specifier for Thousands Separator
218 PEP written by Raymond Hettinger; implemented by Eric Smith.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000219
220Other Language Changes
221======================
222
223Some smaller changes made to the core Python language are:
224
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000225* The :keyword:`with` statement can now use multiple context managers
226 in one statement. Context managers are processed from left to right
227 and each one is treated as beginning a new :keyword:`with` statement.
228 This means that::
229
230 with A() as a, B() as b:
231 ... suite of statements ...
232
233 is equivalent to::
234
235 with A() as a:
236 with B() as b:
237 ... suite of statements ...
238
239 The :func:`contextlib.nested` function provides a very similar
240 function, so it's no longer necessary and has been deprecated.
241
242 (Proposed in http://codereview.appspot.com/53094; implemented by
243 Georg Brandl.)
244
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000245* Conversions between floating-point numbers and strings are
246 now correctly rounded on most platforms. These conversions occur
247 in many different places: :func:`str` on
248 floats and complex numbers; the :class:`float` and :class:`complex`
249 constructors;
250 numeric formatting; serialization and
251 deserialization of floats and complex numbers using the
252 :mod:`marshal`, :mod:`pickle`
253 and :mod:`json` modules;
254 parsing of float and imaginary literals in Python code;
255 and :class:`Decimal`-to-float conversion.
256
257 Related to this, the :func:`repr` of a floating-point number *x*
258 now returns a result based on the shortest decimal string that's
259 guaranteed to round back to *x* under correct rounding (with
260 round-half-to-even rounding mode). Previously it gave a string
261 based on rounding x to 17 decimal digits.
262
263 The rounding library responsible for this improvement works on
264 Windows, and on Unix platforms using the gcc, icc, or suncc
265 compilers. There may be a small number of platforms where correct
266 operation of this code cannot be guaranteed, so the code is not
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +0000267 used on such systems. You can find out which code is being used
268 by checking :data:`sys.float_repr_style`, which will be ``short``
269 if the new code is in use and ``legacy`` if it isn't.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000270
271 Implemented by Mark Dickinson, using David Gay's :file:`dtoa.c` library;
272 :issue:`7117`.
273
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000274* The :meth:`str.format` method now supports automatic numbering of the replacement
Benjamin Petersonaa0a0b92009-04-11 20:27:15 +0000275 fields. This makes using :meth:`str.format` more closely resemble using
276 ``%s`` formatting::
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000277
278 >>> '{}:{}:{}'.format(2009, 04, 'Sunday')
279 '2009:4:Sunday'
280 >>> '{}:{}:{day}'.format(2009, 4, day='Sunday')
281 '2009:4:Sunday'
282
Benjamin Petersonaa0a0b92009-04-11 20:27:15 +0000283 The auto-numbering takes the fields from left to right, so the first ``{...}``
284 specifier will use the first argument to :meth:`str.format`, the next
285 specifier will use the next argument, and so on. You can't mix auto-numbering
286 and explicit numbering -- either number all of your specifier fields or none
287 of them -- but you can mix auto-numbering and named fields, as in the second
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000288 example above. (Contributed by Eric Smith; :issue:`5237`.)
289
290 Complex numbers now correctly support usage with :func:`format`.
291 Specifying a precision or comma-separation applies to both the real
292 and imaginary parts of the number, but a specified field width and
293 alignment is applied to the whole of the resulting ``1.5+3j``
294 output. (Contributed by Eric Smith; :issue:`1588`.)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000295
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000296 The 'F' format code now always formats its output using uppercase characters,
297 so it will now produce 'INF' and 'NAN'.
298 (Contributed by Eric Smith; :issue:`3382`.)
299
Mark Dickinson1a707982008-12-17 16:14:37 +0000300* The :func:`int` and :func:`long` types gained a ``bit_length``
Georg Brandl64e1c752009-04-11 18:19:27 +0000301 method that returns the number of bits necessary to represent
Mark Dickinson1a707982008-12-17 16:14:37 +0000302 its argument in binary::
303
304 >>> n = 37
305 >>> bin(37)
306 '0b100101'
307 >>> n.bit_length()
308 6
309 >>> n = 2**123-1
310 >>> n.bit_length()
311 123
312 >>> (n+1).bit_length()
313 124
314
315 (Contributed by Fredrik Johansson and Victor Stinner; :issue:`3439`.)
316
Andrew M. Kuchling92b97002009-05-02 17:12:15 +0000317* Conversions from long integers and regular integers to floating
318 point now round differently, returning the floating-point number
319 closest to the number. This doesn't matter for small integers that
320 can be converted exactly, but for large numbers that will
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000321 unavoidably lose precision, Python 2.7 now approximates more
Andrew M. Kuchling92b97002009-05-02 17:12:15 +0000322 closely. For example, Python 2.6 computed the following::
323
324 >>> n = 295147905179352891391
325 >>> float(n)
326 2.9514790517935283e+20
327 >>> n - long(float(n))
328 65535L
329
330 Python 2.7's floating-point result is larger, but much closer to the
331 true value::
332
333 >>> n = 295147905179352891391
334 >>> float(n)
335 2.9514790517935289e+20
336 >>> n-long(float(n)
337 ... )
338 -1L
339
340 (Implemented by Mark Dickinson; :issue:`3166`.)
341
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000342 Integer division is also more accurate in its rounding behaviours. (Also
343 implemented by Mark Dickinson; :issue:`1811`.)
344
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000345* The :class:`bytearray` type's :meth:`translate` method now accepts
346 ``None`` as its first argument. (Fixed by Georg Brandl;
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000347 :issue:`4759`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000348
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000349* When using ``@classmethod`` and ``@staticmethod`` to wrap
350 methods as class or static methods, the wrapper object now
351 exposes the wrapped function as their :attr:`__func__` attribute.
352 (Contributed by Amaury Forgeot d'Arc, after a suggestion by
353 George Sakkis; :issue:`5982`.)
354
355* A new encoding named "cp720", used primarily for Arabic text, is now
356 supported. (Contributed by Alexander Belchenko and Amaury Forgeot
357 d'Arc; :issue:`1616979`.)
358
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000359* The :class:`file` object will now set the :attr:`filename` attribute
360 on the :exc:`IOError` exception when trying to open a directory
361 on POSIX platforms. (Noted by Jan Kaliszewski; :issue:`4764`.)
362
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +0000363* The Python tokenizer now translates line endings itself, so
364 the :func:`compile` built-in function can now accept code using
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +0000365 any line-ending convention.
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +0000366
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000367* Extra parentheses in function definitions are illegal in Python 3.x,
368 meaning that you get a syntax error from ``def f((x)): pass``. In
369 Python3-warning mode, Python 2.7 will now warn about this odd usage.
370 (Noted by James Lingard; :issue:`7362`.)
371
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000372.. ======================================================================
373
374
375Optimizations
376-------------
377
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000378Several performance enhancements have been added:
379
380.. * A new :program:`configure` option, :option:`--with-computed-gotos`,
381 compiles the main bytecode interpreter loop using a new dispatch
382 mechanism that gives speedups of up to 20%, depending on the system
383 and benchmark. The new mechanism is only supported on certain
384 compilers, such as gcc, SunPro, and icc.
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000385
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000386* A new opcode was added to perform the initial setup for
387 :keyword:`with` statements, looking up the :meth:`__enter__` and
388 :meth:`__exit__` methods. (Contributed by Benjamin Peterson.)
389
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000390* The garbage collector now performs better for one common usage
391 pattern: when many objects are being allocated without deallocating
392 any of them. This would previously take quadratic
393 time for garbage collection, but now the number of full garbage collections
394 is reduced as the number of objects on the heap grows.
395 The new logic is to only perform a full garbage collection pass when
396 the middle generation has been collected 10 times and when the
397 number of survivor objects from the middle generation exceeds 10% of
398 the number of objects in the oldest generation. (Suggested by Martin
399 von Loewis and implemented by Antoine Pitrou; :issue:`4074`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000400
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000401* The garbage collector tries to avoid tracking simple containers
402 which can't be part of a cycle. In Python 2.7, this is now true for
403 tuples and dicts containing atomic types (such as ints, strings,
404 etc.). Transitively, a dict containing tuples of atomic types won't
405 be tracked either. This helps reduce the cost of each
406 garbage collection by decreasing the number of objects to be
407 considered and traversed by the collector.
Antoine Pitrouc18f6b02009-03-28 19:10:13 +0000408 (Contributed by Antoine Pitrou; :issue:`4688`.)
409
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000410* Long integers are now stored internally either in base 2**15 or in base
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000411 2**30, the base being determined at build time. Previously, they
412 were always stored in base 2**15. Using base 2**30 gives
413 significant performance improvements on 64-bit machines, but
414 benchmark results on 32-bit machines have been mixed. Therefore,
415 the default is to use base 2**30 on 64-bit machines and base 2**15
416 on 32-bit machines; on Unix, there's a new configure option
417 :option:`--enable-big-digits` that can be used to override this default.
418
419 Apart from the performance improvements this change should be
420 invisible to end users, with one exception: for testing and
421 debugging purposes there's a new structseq ``sys.long_info`` that
422 provides information about the internal format, giving the number of
423 bits per digit and the size in bytes of the C type used to store
424 each digit::
425
426 >>> import sys
427 >>> sys.long_info
428 sys.long_info(bits_per_digit=30, sizeof_digit=4)
429
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000430 (Contributed by Mark Dickinson; :issue:`4258`.)
431
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000432 Another set of changes made long objects a few bytes smaller: 2 bytes
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000433 smaller on 32-bit systems and 6 bytes on 64-bit.
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000434 (Contributed by Mark Dickinson; :issue:`5260`.)
435
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000436* The division algorithm for long integers has been made faster
437 by tightening the inner loop, doing shifts instead of multiplications,
438 and fixing an unnecessary extra iteration.
439 Various benchmarks show speedups of between 50% and 150% for long
440 integer divisions and modulo operations.
441 (Contributed by Mark Dickinson; :issue:`5512`.)
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +0000442 Bitwise operations are also significantly faster (initial patch by
443 Gregory Smith; :issue:`1087418`).
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000444
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000445* The implementation of ``%`` checks for the left-side operand being
446 a Python string and special-cases it; this results in a 1-3%
447 performance increase for applications that frequently use ``%``
448 with strings, such as templating libraries.
449 (Implemented by Collin Winter; :issue:`5176`.)
450
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000451* List comprehensions with an ``if`` condition are compiled into
452 faster bytecode. (Patch by Antoine Pitrou, back-ported to 2.7
453 by Jeffrey Yasskin; :issue:`4715`.)
454
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000455* The :mod:`pickle` and :mod:`cPickle` modules now automatically
456 intern the strings used for attribute names, reducing memory usage
457 of the objects resulting from unpickling. (Contributed by Jake
458 McGuire; :issue:`5084`.)
459
460* The :mod:`cPickle` module now special-cases dictionaries,
461 nearly halving the time required to pickle them.
462 (Contributed by Collin Winter; :issue:`5670`.)
463
464* Converting an integer or long integer to a decimal string was made
465 faster by special-casing base 10 instead of using a generalized
466 conversion function that supports arbitrary bases.
467 (Patch by Gawain Bolton; :issue:`6713`.)
468
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000469.. ======================================================================
470
Georg Brandl0516f812009-11-18 18:52:35 +0000471New and Improved Modules
472========================
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000473
474As in every release, Python's standard library received a number of
475enhancements and bug fixes. Here's a partial list of the most notable
476changes, sorted alphabetically by module name. Consult the
477:file:`Misc/NEWS` file in the source tree for a more complete list of
478changes, or look through the Subversion logs for all the details.
479
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000480* The :mod:`bdb` module's base debugging class :class:`Bdb`
481 gained a feature for skipping modules. The constructor
482 now takes an iterable containing glob-style patterns such as
483 ``django.*``; the debugger will not step into stack frames
484 from a module that matches one of these patterns.
485 (Contributed by Maru Newby after a suggestion by
486 Senthil Kumaran; :issue:`5142`.)
487
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000488* The :mod:`bz2` module's :class:`BZ2File` now supports the context
489 management protocol, so you can write ``with bz2.BZ2File(...) as f: ...``.
490 (Contributed by Hagen Fuerstenau; :issue:`3860`.)
491
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000492* New class: the :class:`Counter` class in the :mod:`collections` module is
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000493 useful for tallying data. :class:`Counter` instances behave mostly
494 like dictionaries but return zero for missing keys instead of
Georg Brandlf6dab952009-04-28 21:48:35 +0000495 raising a :exc:`KeyError`:
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000496
Georg Brandlf6dab952009-04-28 21:48:35 +0000497 .. doctest::
498 :options: +NORMALIZE_WHITESPACE
499
500 >>> from collections import Counter
501 >>> c = Counter()
502 >>> for letter in 'here is a sample of english text':
503 ... c[letter] += 1
504 ...
505 >>> c
506 Counter({' ': 6, 'e': 5, 's': 3, 'a': 2, 'i': 2, 'h': 2,
507 'l': 2, 't': 2, 'g': 1, 'f': 1, 'm': 1, 'o': 1, 'n': 1,
508 'p': 1, 'r': 1, 'x': 1})
509 >>> c['e']
510 5
511 >>> c['z']
512 0
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000513
514 There are two additional :class:`Counter` methods: :meth:`most_common`
515 returns the N most common elements and their counts, and :meth:`elements`
516 returns an iterator over the contained element, repeating each element
517 as many times as its count::
518
519 >>> c.most_common(5)
520 [(' ', 6), ('e', 5), ('s', 3), ('a', 2), ('i', 2)]
521 >>> c.elements() ->
522 'a', 'a', ' ', ' ', ' ', ' ', ' ', ' ',
523 'e', 'e', 'e', 'e', 'e', 'g', 'f', 'i', 'i',
524 'h', 'h', 'm', 'l', 'l', 'o', 'n', 'p', 's',
Georg Brandlf6dab952009-04-28 21:48:35 +0000525 's', 's', 'r', 't', 't', 'x'
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000526
527 Contributed by Raymond Hettinger; :issue:`1696199`.
528
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000529 The new `OrderedDict` class is described in the earlier section
530 :ref:`pep-0372`.
531
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000532 The :class:`namedtuple` class now has an optional *rename* parameter.
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000533 If *rename* is true, field names that are invalid because they've
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000534 been repeated or that aren't legal Python identifiers will be
535 renamed to legal names that are derived from the field's
536 position within the list of fields:
537
Georg Brandlf6dab952009-04-28 21:48:35 +0000538 >>> from collections import namedtuple
539 >>> T = namedtuple('T', ['field1', '$illegal', 'for', 'field2'], rename=True)
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000540 >>> T._fields
541 ('field1', '_1', '_2', 'field2')
542
543 (Added by Raymond Hettinger; :issue:`1818`.)
544
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000545 The :class:`deque` data type now exposes its maximum length as the
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000546 read-only :attr:`maxlen` attribute, and has a
547 :meth:`reverse` method that reverses the elements of the deque in-place.
548 (Added by Raymond Hettinger.)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000549
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000550* The :mod:`copy` module's :func:`deepcopy` function will now
551 correctly copy bound instance methods. (Implemented by
552 Robert Collins; :issue:`1515`.)
553
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000554* The :mod:`ctypes` module now always converts ``None`` to a C NULL
555 pointer for arguments declared as pointers. (Changed by Thomas
556 Heller; :issue:`4606`.)
557
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000558* New method: the :mod:`datetime` module's :class:`timedelta` class
559 gained a :meth:`total_seconds` method that returns the number of seconds
560 in the duration. (Contributed by Brian Quinlan; :issue:`5788`.)
561
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000562* New method: the :class:`Decimal` class gained a
563 :meth:`from_float` class method that performs an exact conversion
564 of a floating-point number to a :class:`Decimal`.
565 Note that this is an **exact** conversion that strives for the
566 closest decimal approximation to the floating-point representation's value;
567 the resulting decimal value will therefore still include the inaccuracy,
568 if any.
569 For example, ``Decimal.from_float(0.1)`` returns
570 ``Decimal('0.1000000000000000055511151231257827021181583404541015625')``.
571 (Implemented by Raymond Hettinger; :issue:`4796`.)
572
573 The constructor for :class:`Decimal` now accepts non-European
574 Unicode characters, such as Arabic-Indic digits. (Contributed by
575 Mark Dickinson; :issue:`6595`.)
576
577 When using :class:`Decimal` instances with a string's
578 :meth:`format` method, the default alignment was previously
579 left-alignment. This has been changed to right-alignment, which seems
580 more sensible for numeric types. (Changed by Mark Dickinson; :issue:`6857`.)
581
582* Distutils is being more actively developed, thanks to Tarek Ziade
Andrew M. Kuchling8f254e72009-12-08 02:37:05 +0000583 who has taken over maintenance of the package. A new
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000584 :file:`setup.py` subcommand, ``check``, will
585 check that the arguments being passed to the :func:`setup` function
586 are complete and correct (:issue:`5732`).
587
588 :func:`distutils.sdist.add_defaults` now uses
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000589 *package_dir* and *data_files* to create the MANIFEST file.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000590 :mod:`distutils.sysconfig` now reads the :envvar:`AR` and
591 :envvar:`ARFLAGS` environment variables.
592
593 .. ARFLAGS done in #5941
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000594
595 It is no longer mandatory to store clear-text passwords in the
596 :file:`.pypirc` file when registering and uploading packages to PyPI. As long
597 as the username is present in that file, the :mod:`distutils` package will
598 prompt for the password if not present. (Added by Tarek Ziade,
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000599 based on an initial contribution by Nathan Van Gheem; :issue:`4394`.)
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000600
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000601 A Distutils setup can now specify that a C extension is optional by
602 setting the *optional* option setting to true. If this optional is
603 supplied, failure to build the extension will not abort the build
604 process, but instead simply not install the failing extension.
Georg Brandl64e1c752009-04-11 18:19:27 +0000605 (Contributed by Georg Brandl; :issue:`5583`.)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000606
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000607 The :class:`distutils.dist.DistributionMetadata` class'
608 :meth:`read_pkg_file` method will read the contents of a package's
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000609 :file:`PKG-INFO` metadata file. For an example of its use,
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000610 XXX link to file:///MacDev/svn.python.org/python-trunk/Doc/build/html/distutils/examples.html#reading-the-metadata
611 (Contributed by Tarek Ziade; :issue:`7457`.)
Tarek Ziadéa939ecd2009-12-08 08:56:49 +0000612
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +0000613 :file:`setup.py` files will now accept a :option:`--no-user-cfg` switch
614 to skip reading the :file:`~/.pydistutils.cfg` file. (Suggested by
615 by Michael Hoffman, and implemented by Paul Winkler; :issue:`1180`.)
616
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000617* The :class:`Fraction` class now accepts two rational numbers
Andrew M. Kuchling92b97002009-05-02 17:12:15 +0000618 as arguments to its constructor.
619 (Implemented by Mark Dickinson; :issue:`5812`.)
620
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000621* The :mod:`ftplib` module gained the ability to establish secure FTP
622 connections using TLS encapsulation of authentication as well as
623 subsequent control and data transfers. This is provided by the new
624 :class:`ftplib.FTP_TLS` class.
625 (Contributed by Giampaolo Rodola', :issue:`2054`.) The :meth:`storbinary`
626 method for binary uploads can now restart uploads thanks to an added
627 *rest* parameter (patch by Pablo Mouzo; :issue:`6845`.)
628
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000629* New function: the :mod:`gc` module's :func:`is_tracked` returns
630 true if a given instance is tracked by the garbage collector, false
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000631 otherwise. (Contributed by Antoine Pitrou; :issue:`4688`.)
632
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000633* The :mod:`gzip` module's :class:`GzipFile` now supports the context
634 management protocol, so you can write ``with gzip.GzipFile(...) as f: ...``.
635 (Contributed by Hagen Fuerstenau; :issue:`3860`.)
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000636 It's now possible to override the modification time
637 recorded in a gzipped file by providing an optional timestamp to
638 the constructor. (Contributed by Jacques Frechet; :issue:`4272`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000639
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000640* The :mod:`hashlib` module was inconsistent about accepting
641 input as a Unicode object or an object that doesn't support
642 the buffer protocol. The behavior was different depending on
643 whether :mod:`hashlib` was using an external OpenSSL library
644 or its built-in implementations. Python 2.7 makes the
645 behavior consistent, always rejecting such objects by raising a
646 :exc:`TypeError`. (Fixed by Gregory P. Smith; :issue:`3745`.)
647
648* The default :class:`HTTPResponse` class used by the :mod:`httplib` module now
649 supports buffering, resulting in much faster reading of HTTP responses.
650 (Contributed by Kristjan Valur Jonsson; :issue:`4879`.)
651
652* The :mod:`imaplib` module now supports IPv6 addresses.
653 (Contributed by Derek Morr; :issue:`1655`.)
654
655* The :mod:`io` library has been upgraded to the version shipped with
656 Python 3.1. For 3.1, the I/O library was entirely rewritten in C
657 and is 2 to 20 times faster depending on the task at hand. The
658 original Python version was renamed to the :mod:`_pyio` module.
659
660 One minor resulting change: the :class:`io.TextIOBase` class now
661 has an :attr:`errors` attribute giving the error setting
662 used for encoding and decoding errors (one of ``'strict'``, ``'replace'``,
663 ``'ignore'``).
664
665 The :class:`io.FileIO` class now raises an :exc:`OSError` when passed
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000666 an invalid file descriptor. (Implemented by Benjamin Peterson;
667 :issue:`4991`.)
668
Andrew M. Kuchling5a73ff82009-12-02 14:27:11 +0000669* New function: ``itertools.compress(data, selectors)`` takes two
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000670 iterators. Elements of *data* are returned if the corresponding
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000671 value in *selectors* is true::
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000672
673 itertools.compress('ABCDEF', [1,0,1,0,1,1]) =>
674 A, C, E, F
675
Andrew M. Kuchling5a73ff82009-12-02 14:27:11 +0000676 New function: ``itertools.combinations_with_replacement(iter, r)``
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000677 returns all the possible *r*-length combinations of elements from the
678 iterable *iter*. Unlike :func:`combinations`, individual elements
679 can be repeated in the generated combinations::
680
681 itertools.combinations_with_replacement('abc', 2) =>
682 ('a', 'a'), ('a', 'b'), ('a', 'c'),
683 ('b', 'b'), ('b', 'c'), ('c', 'c')
684
685 Note that elements are treated as unique depending on their position
686 in the input, not their actual values.
687
688 The :class:`itertools.count` function now has a *step* argument that
689 allows incrementing by values other than 1. :func:`count` also
690 now allows keyword arguments, and using non-integer values such as
691 floats or :class:`Decimal` instances. (Implemented by Raymond
692 Hettinger; :issue:`5032`.)
693
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000694 :func:`itertools.combinations` and :func:`itertools.product` were
695 previously raising :exc:`ValueError` for values of *r* larger than
696 the input iterable. This was deemed a specification error, so they
697 now return an empty iterator. (Fixed by Raymond Hettinger; :issue:`4816`.)
698
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000699* The :mod:`json` module was upgraded to version 2.0.9 of the
700 simplejson package, which includes a C extension that makes
701 encoding and decoding faster.
702 (Contributed by Bob Ippolito; :issue:`4136`.)
703
704 To support the new :class:`OrderedDict` type, :func:`json.load`
705 now has an optional *object_pairs_hook* parameter that will be called
706 with any object literal that decodes to a list of pairs.
707 (Contributed by Raymond Hettinger; :issue:`5381`.)
708
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000709* New functions: the :mod:`math` module gained
710 :func:`erf` and :func:`erfc` for the error function and the complementary error function,
711 :func:`expm1` which computes ``e**x - 1`` with more precision than
712 using :func:`exp` and subtracting 1,
713 :func:`gamma` for the Gamma function, and
714 :func:`lgamma` for the natural log of the Gamma function.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000715 (Contributed by Mark Dickinson and nirinA raseliarison; :issue:`3366`.)
716
Andrew M. Kuchling24520b42009-04-09 11:22:47 +0000717* The :mod:`multiprocessing` module's :class:`Manager*` classes
718 can now be passed a callable that will be called whenever
719 a subprocess is started, along with a set of arguments that will be
720 passed to the callable.
721 (Contributed by lekma; :issue:`5585`.)
722
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000723* The :mod:`nntplib` module now supports IPv6 addresses.
724 (Contributed by Derek Morr; :issue:`1664`.)
725
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000726* New functions: the :mod:`os` module wraps the following POSIX system
727 calls: :func:`getresgid` and :func:`getresuid`, which return the
728 real, effective, and saved GIDs and UIDs;
729 :func:`setresgid` and :func:`setresuid`, which set
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000730 real, effective, and saved GIDs and UIDs to new values;
731 :func:`initgroups`. (GID/UID functions
732 contributed by Travis H.; :issue:`6508`. Support for initgroups added
733 by Jean-Paul Calderone; :issue:`7333`.)
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000734
Andrew M. Kuchling9cb42772009-01-21 02:15:43 +0000735* The :mod:`pydoc` module now has help for the various symbols that Python
736 uses. You can now do ``help('<<')`` or ``help('@')``, for example.
737 (Contributed by David Laban; :issue:`4739`.)
738
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000739* The :mod:`re` module's :func:`split`, :func:`sub`, and :func:`subn`
740 now accept an optional *flags* argument, for consistency with the
741 other functions in the module. (Added by Gregory P. Smith.)
742
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000743* The :mod:`shutil` module's :func:`copyfile` and :func:`copytree`
744 functions now raises a :exc:`SpecialFileError` exception when
745 asked to copy a named pipe. Previously the code would treat
746 named pipes like a regular file by opening them for reading, and
747 this would block indefinitely. (Fixed by Antoine Pitrou; :issue:`3002`.)
748
749* New functions: in the :mod:`site` module, three new functions
750 return various site- and user-specific paths.
751 :func:`getsitepackages` returns a list containing all
752 global site-packages directories, and
753 :func:`getusersitepackages` returns the path of the user's
754 site-packages directory.
755 :func:`getuserbase` returns the value of the :envvar:``USER_BASE``
756 environment variable, giving the path to a directory that can be used
757 to store data.
758 (Contributed by Tarek Ziade; :issue:`6693`.)
759
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +0000760* The :mod:`socket` module's :class:`SSL` objects now support the
761 buffer API, which fixed a test suite failure. (Fixed by Antoine Pitrou;
762 :issue:`7133`.)
763
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000764* The :mod:`SocketServer` module's :class:`TCPServer` class now
765 has a :attr:`disable_nagle_algorithm` class attribute.
766 The default value is False; if overridden to be True,
767 new request connections will have the TCP_NODELAY option set to
768 prevent buffering many small sends into a single TCP packet.
769 (Contributed by Kristjan Valur Jonsson; :issue:`6192`.)
770
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000771* The :mod:`struct` module will no longer silently ignore overflow
772 errors when a value is too large for a particular integer format
773 code (one of ``bBhHiIlLqQ``); it now always raises a
774 :exc:`struct.error` exception. (Changed by Mark Dickinson;
775 :issue:`1523`.)
776
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000777* New function: the :mod:`subprocess` module's
778 :func:`check_output` runs a command with a specified set of arguments
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000779 and returns the command's output as a string when the command runs without
Andrew M. Kuchling10b1ec92009-01-02 21:00:35 +0000780 error, or raises a :exc:`CalledProcessError` exception otherwise.
781
782 ::
783
784 >>> subprocess.check_output(['df', '-h', '.'])
785 'Filesystem Size Used Avail Capacity Mounted on\n
786 /dev/disk0s2 52G 49G 3.0G 94% /\n'
787
788 >>> subprocess.check_output(['df', '-h', '/bogus'])
789 ...
790 subprocess.CalledProcessError: Command '['df', '-h', '/bogus']' returned non-zero exit status 1
791
792 (Contributed by Gregory P. Smith.)
793
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000794* New function: :func:`is_declared_global` in the :mod:`symtable` module
795 returns true for variables that are explicitly declared to be global,
796 false for ones that are implicitly global.
797 (Contributed by Jeremy Hylton.)
798
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000799* The ``sys.version_info`` value is now a named tuple, with attributes
800 named ``major``, ``minor``, ``micro``, ``releaselevel``, and ``serial``.
801 (Contributed by Ross Light; :issue:`4285`.)
802
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000803* The :mod:`tarfile` module now supports filtering the :class:`TarInfo`
804 objects being added to a tar file. When you call :meth:`TarFile.add`,
805 instance, you may supply an optional *filter* argument
806 that's a callable. The *filter* callable will be passed the
807 :class:`TarInfo` for every file being added, and can modify and return it.
808 If the callable returns ``None``, the file will be excluded from the
809 resulting archive. This is more powerful than the existing
810 *exclude* argument, which has therefore been deprecated.
811 (Added by Lars Gustaebel; :issue:`6856`.)
812
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000813* The :mod:`threading` module's :meth:`Event.wait` method now returns
814 the internal flag on exit. This means the method will usually
815 return true because :meth:`wait` is supposed to block until the
816 internal flag becomes true. The return value will only be false if
817 a timeout was provided and the operation timed out.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000818 (Contributed by Tim Lesher; :issue:`1674032`.)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000819
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000820* The :func:`is_zipfile` function in the :mod:`zipfile` module now
821 accepts a file object, in addition to the path names accepted in earlier
Andrew M. Kuchling9cb42772009-01-21 02:15:43 +0000822 versions. (Contributed by Gabriel Genellina; :issue:`4756`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000823
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000824 :mod:`zipfile` now supports archiving empty directories and
825 extracts them correctly. (Fixed by Kuba Wieczorek; :issue:`4710`.)
826
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000827.. ======================================================================
828.. whole new modules get described in subsections here
829
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000830Unit Testing Enhancements
831---------------------------------
832
833The :mod:`unittest` module was enhanced in several ways.
834The progress messages now shows 'x' for expected failures
835and 'u' for unexpected successes when run in verbose mode.
836(Contributed by Benjamin Peterson.)
837Test cases can raise the :exc:`SkipTest` exception to skip a test.
838(:issue:`1034053`.)
839
840.. XXX describe test discovery (Contributed by Michael Foord; :issue:`6001`.)
841
842The error messages for :meth:`assertEqual`,
843:meth:`assertTrue`, and :meth:`assertFalse`
844failures now provide more information. If you set the
845:attr:`longMessage` attribute of your :class:`TestCase` classes to
846true, both the standard error message and any additional message you
847provide will be printed for failures. (Added by Michael Foord; :issue:`5663`.)
848
849The :meth:`assertRaises` and :meth:`failUnlessRaises` methods now
850return a context handler when called without providing a callable
851object to run. For example, you can write this::
852
853 with self.assertRaises(KeyError):
854 raise ValueError
855
856(Implemented by Antoine Pitrou; :issue:`4444`.)
857
858The methods :meth:`addCleanup` and :meth:`doCleanups` were added.
859:meth:`addCleanup` allows you to add cleanup functions that
860will be called unconditionally (after :meth:`setUp` if
861:meth:`setUp` fails, otherwise after :meth:`tearDown`). This allows
862for much simpler resource allocation and deallocation during tests.
863:issue:`5679`
864
865A number of new methods were added that provide more specialized
866tests. Many of these methods were written by Google engineers
867for use in their test suites; Gregory P. Smith, Michael Foord, and
868GvR worked on merging them into Python's version of :mod:`unittest`.
869
870* :meth:`assertIsNone` and :meth:`assertIsNotNone` take one
871 expression and verify that the result is or is not ``None``.
872
873* :meth:`assertIs` and :meth:`assertIsNot` take two values and check
874 whether the two values evaluate to the same object or not.
875 (Added by Michael Foord; :issue:`2578`.)
876
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +0000877* :meth:`assertIsInstance` and :meth:`assertNotIsInstance` check whether
878 the resulting object is an instance of a particular class, or of
879 one of a tuple of classes. (Added by Georg Brandl; :issue:`7031`.)
880
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000881* :meth:`assertGreater`, :meth:`assertGreaterEqual`,
882 :meth:`assertLess`, and :meth:`assertLessEqual` compare
883 two quantities.
884
885* :meth:`assertMultiLineEqual` compares two strings, and if they're
886 not equal, displays a helpful comparison that highlights the
887 differences in the two strings.
888
889* :meth:`assertRegexpMatches` checks whether its first argument is a
890 string matching a regular expression provided as its second argument.
891
892* :meth:`assertRaisesRegexp` checks whether a particular exception
893 is raised, and then also checks that the string representation of
894 the exception matches the provided regular expression.
895
896* :meth:`assertIn` and :meth:`assertNotIn` tests whether
897 *first* is or is not in *second*.
898
899* :meth:`assertSameElements` tests whether two provided sequences
900 contain the same elements.
901
902* :meth:`assertSetEqual` compares whether two sets are equal, and
903 only reports the differences between the sets in case of error.
904
905* Similarly, :meth:`assertListEqual` and :meth:`assertTupleEqual`
906 compare the specified types and explain the differences.
907 More generally, :meth:`assertSequenceEqual` compares two sequences
908 and can optionally check whether both sequences are of a
909 particular type.
910
911* :meth:`assertDictEqual` compares two dictionaries and reports the
912 differences. :meth:`assertDictContainsSubset` checks whether
913 all of the key/value pairs in *first* are found in *second*.
914
915* :meth:`assertAlmostEqual` and :meth:`assertNotAlmostEqual` short-circuit
916 (automatically pass or fail without checking decimal places) if the objects
917 are equal.
918
919* :meth:`loadTestsFromName` properly honors the ``suiteClass`` attribute of
920 the :class:`TestLoader`. (Fixed by Mark Roddy; :issue:`6866`.)
921
922* A new hook, :meth:`addTypeEqualityFunc` takes a type object and a
923 function. The :meth:`assertEqual` method will use the function
924 when both of the objects being compared are of the specified type.
925 This function should compare the two objects and raise an
926 exception if they don't match; it's a good idea for the function
927 to provide additional information about why the two objects are
928 matching, much as the new sequence comparison methods do.
929
930:func:`unittest.main` now takes an optional ``exit`` argument.
931If False ``main`` doesn't call :func:`sys.exit` allowing it to
932be used from the interactive interpreter. :issue:`3379`.
933
934:class:`TestResult` has new :meth:`startTestRun` and
935:meth:`stopTestRun` methods; called immediately before
936and after a test run. :issue:`5728` by Robert Collins.
937
938With all these changes, the :file:`unittest.py` was becoming awkwardly
939large, so the module was turned into a package and the code split into
940several files (by Benjamin Peterson). This doesn't affect how the
941module is imported.
942
943
944.. _importlib-section:
945
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000946importlib: Importing Modules
947------------------------------
948
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000949Python 3.1 includes the :mod:`importlib` package, a re-implementation
950of the logic underlying Python's :keyword:`import` statement.
951:mod:`importlib` is useful for implementors of Python interpreters and
Brett Cannonca2dc472009-12-22 02:37:37 +0000952to users who wish to write new importers that can participate in the
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000953import process. Python 2.7 doesn't contain the complete
954:mod:`importlib` package, but instead has a tiny subset that contains
955a single function, :func:`import_module`.
956
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000957``import_module(name, package=None)`` imports a module. *name* is
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000958a string containing the module or package's name. It's possible to do
959relative imports by providing a string that begins with a ``.``
960character, such as ``..utils.errors``. For relative imports, the
961*package* argument must be provided and is the name of the package that
962will be used as the anchor for
963the relative import. :func:`import_module` both inserts the imported
964module into ``sys.modules`` and returns the module object.
965
966Here are some examples::
967
968 >>> from importlib import import_module
969 >>> anydbm = import_module('anydbm') # Standard absolute import
970 >>> anydbm
971 <module 'anydbm' from '/p/python/Lib/anydbm.py'>
972 >>> # Relative import
973 >>> sysconfig = import_module('..sysconfig', 'distutils.command')
974 >>> sysconfig
975 <module 'distutils.sysconfig' from '/p/python/Lib/distutils/sysconfig.pyc'>
976
977:mod:`importlib` was implemented by Brett Cannon and introduced in
978Python 3.1.
979
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000980
Andrew M. Kuchlinga17cd4a2009-01-31 02:50:09 +0000981ttk: Themed Widgets for Tk
982--------------------------
983
984Tcl/Tk 8.5 includes a set of themed widgets that re-implement basic Tk
985widgets but have a more customizable appearance and can therefore more
986closely resemble the native platform's widgets. This widget
987set was originally called Tile, but was renamed to Ttk (for "themed Tk")
988on being added to Tcl/Tck release 8.5.
989
990XXX write a brief discussion and an example here.
991
992The :mod:`ttk` module was written by Guilherme Polo and added in
993:issue:`2983`. An alternate version called ``Tile.py``, written by
994Martin Franklin and maintained by Kevin Walzer, was proposed for
995inclusion in :issue:`2618`, but the authors argued that Guilherme
996Polo's work was more comprehensive.
997
Georg Brandl0516f812009-11-18 18:52:35 +0000998
999Deprecations and Removals
1000=========================
1001
1002* :func:`contextlib.nested`, which allows handling more than one context manager
1003 with one :keyword:`with` statement, has been deprecated; :keyword:`with`
1004 supports multiple context managers syntactically now.
1005
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001006.. ======================================================================
1007
1008
1009Build and C API Changes
1010=======================
1011
1012Changes to Python's build process and to the C API include:
1013
Andrew M. Kuchling10b1ec92009-01-02 21:00:35 +00001014* If you use the :file:`.gdbinit` file provided with Python,
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001015 the "pyo" macro in the 2.7 version now works correctly when the thread being
1016 debugged doesn't hold the GIL; the macro now acquires it before printing.
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001017 (Contributed by Victor Stinner; :issue:`3632`.)
1018
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001019* :cfunc:`Py_AddPendingCall` is now thread-safe, letting any
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001020 worker thread submit notifications to the main Python thread. This
1021 is particularly useful for asynchronous IO operations.
1022 (Contributed by Kristjan Valur Jonsson; :issue:`4293`.)
1023
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001024* New function: :cfunc:`PyCode_NewEmpty` creates an empty code object;
1025 only the filename, function name, and first line number are required.
1026 This is useful to extension modules that are attempting to
1027 construct a more useful traceback stack. Previously such
1028 extensions needed to call :cfunc:`PyCode_New`, which had many
1029 more arguments. (Added by Jeffrey Yasskin.)
1030
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001031* New function: :cfunc:`PyErr_NewExceptionWithDoc` creates a new
1032 exception class, just as the existing :cfunc:`PyErr_NewException` does,
1033 but takes an extra ``char *`` argument containing the docstring for the
1034 new exception class. (Added by the 'lekma' user on the Python bug tracker;
1035 :issue:`7033`.)
1036
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001037* New function: :cfunc:`PyFrame_GetLineNumber` takes a frame object
1038 and returns the line number that the frame is currently executing.
1039 Previously code would need to get the index of the bytecode
1040 instruction currently executing, and then look up the line number
1041 corresponding to that address. (Added by Jeffrey Yasskin.)
1042
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001043* New function: :cfunc:`PyLong_AsLongAndOverflow` approximates a Python long
1044 integer as a C :ctype:`long`. If the number is too large to fit into
1045 a :ctype:`long`, an *overflow* flag is set and returned to the caller.
1046 (Contributed by Case Van Horsen; :issue:`7528`.)
1047
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00001048* New function: stemming from the rewrite of string-to-float conversion,
1049 a new :cfunc:`PyOS_string_to_double` function was added. The old
1050 :cfunc:`PyOS_ascii_strtod` and :cfunc:`PyOS_ascii_atof` functions
1051 are now deprecated.
1052
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001053* New macros: the Python header files now define the following macros:
1054 :cmacro:`Py_ISALNUM`,
1055 :cmacro:`Py_ISALPHA`,
1056 :cmacro:`Py_ISDIGIT`,
1057 :cmacro:`Py_ISLOWER`,
1058 :cmacro:`Py_ISSPACE`,
1059 :cmacro:`Py_ISUPPER`,
1060 :cmacro:`Py_ISXDIGIT`,
1061 and :cmacro:`Py_TOLOWER`, :cmacro:`Py_TOUPPER`.
1062 All of these functions are analogous to the C
1063 standard macros for classifying characters, but ignore the current
1064 locale setting, because in
1065 several places Python needs to analyze characters in a
1066 locale-independent way. (Added by Eric Smith;
1067 :issue:`5793`.)
1068
1069 .. XXX these macros don't seem to be described in the c-api docs.
1070
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001071* New format codes: the :cfunc:`PyFormat_FromString`,
1072 :cfunc:`PyFormat_FromStringV`, and :cfunc:`PyErr_Format` now
1073 accepts ``%lld`` and ``%llu`` format codes for displaying values of
1074 C's :ctype:`long long` types.
1075 (Contributed by Mark Dickinson; :issue:`7228`.)
1076
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001077* The complicated interaction between threads and process forking has
1078 been changed. Previously, the child process created by
1079 :func:`os.fork` might fail because the child is created with only a
1080 single thread running, the thread performing the :func:`os.fork`.
1081 If other threads were holding a lock, such as Python's import lock,
1082 when the fork was performed, the lock would still be marked as
1083 "held" in the new process. But in the child process nothing would
1084 ever release the lock, since the other threads weren't replicated,
1085 and the child process would no longer be able to perform imports.
1086
1087 Python 2.7 now acquires the import lock before performing an
1088 :func:`os.fork`, and will also clean up any locks created using the
1089 :mod:`threading` module. C extension modules that have internal
1090 locks, or that call :cfunc:`fork()` themselves, will not benefit
1091 from this clean-up.
1092
1093 (Fixed by Thomas Wouters; :issue:`1590864`.)
1094
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00001095* The :cfunc:`Py_Finalize` function now calls the internal
1096 :func:`threading._shutdown` function; this prevents some exceptions from
1097 being raised when an interpreter shuts down.
1098 (Patch by Adam Olsen; :issue:`1722344`.)
1099
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00001100* Global symbols defined by the :mod:`ctypes` module are now prefixed
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001101 with ``Py``, or with ``_ctypes``. (Implemented by Thomas
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00001102 Heller; :issue:`3102`.)
1103
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00001104* New configure option: the :option:`--with-system-expat` switch allows
1105 building the :mod:`pyexpat` module to use the system Expat library.
1106 (Contributed by Arfrever Frehtes Taifersar Arahesis; :issue:`7609`.)
1107
1108* New configure option: Compiling Python with the
1109 :option:`--with-valgrind` option will now disable the pymalloc
1110 allocator, which is difficult for the Valgrind to analyze correctly.
1111 Valgrind will therefore be better at detecting memory leaks and
1112 overruns. (Contributed by James Henstridge; :issue:`2422`.)
1113
Andrew M. Kuchling77069572009-03-31 01:21:01 +00001114* The :program:`configure` script now checks for floating-point rounding bugs
1115 on certain 32-bit Intel chips and defines a :cmacro:`X87_DOUBLE_ROUNDING`
1116 preprocessor definition. No code currently uses this definition,
1117 but it's available if anyone wishes to use it.
1118 (Added by Mark Dickinson; :issue:`2937`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001119
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001120* The build process now creates the necessary files for pkg-config
1121 support. (Contributed by Clinton Roy; :issue:`3585`.)
1122
1123* The build process now supports Subversion 1.7. (Contributed by
1124 Arfrever Frehtes Taifersar Arahesis; :issue:`6094`.)
1125
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001126
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001127.. ======================================================================
1128
1129Port-Specific Changes: Windows
1130-----------------------------------
1131
Andrew M. Kuchling10b1ec92009-01-02 21:00:35 +00001132* The :mod:`msvcrt` module now contains some constants from
1133 the :file:`crtassem.h` header file:
1134 :data:`CRT_ASSEMBLY_VERSION`,
1135 :data:`VC_ASSEMBLY_PUBLICKEYTOKEN`,
1136 and :data:`LIBRARIES_ASSEMBLY_NAME_PREFIX`.
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001137 (Contributed by David Cournapeau; :issue:`4365`.)
1138
1139* The new :cfunc:`_beginthreadex` API is used to start threads, and
1140 the native thread-local storage functions are now used.
1141 (Contributed by Kristjan Valur Jonsson; :issue:`3582`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001142
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001143* The :func:`os.listdir` function now correctly fails
1144 for an empty path. (Fixed by Hirokazu Yamamoto; :issue:`5913`.)
1145
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001146* The :mod:`mimelib` module will now read the MIME database from
1147 the Windows registry when initializing.
1148 (Patch by Gabriel Genellina; :issue:`4969`.)
1149
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001150.. ======================================================================
1151
1152Port-Specific Changes: Mac OS X
1153-----------------------------------
1154
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001155* The path ``/Library/Python/2.7/site-packages`` is now appended to
Andrew M. Kuchling77069572009-03-31 01:21:01 +00001156 ``sys.path``, in order to share added packages between the system
1157 installation and a user-installed copy of the same version.
1158 (Changed by Ronald Oussoren; :issue:`4865`.)
1159
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001160
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001161Other Changes and Fixes
1162=======================
1163
Andrew M. Kuchling77069572009-03-31 01:21:01 +00001164* When importing a module from a :file:`.pyc` or :file:`.pyo` file
1165 with an existing :file:`.py` counterpart, the :attr:`co_filename`
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00001166 attributes of the resulting code objects are overwritten when the
1167 original filename is obsolete. This can happen if the file has been
1168 renamed, moved, or is accessed through different paths. (Patch by
1169 Ziga Seilnacht and Jean-Paul Calderone; :issue:`1180193`.)
Andrew M. Kuchling77069572009-03-31 01:21:01 +00001170
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001171* The :file:`regrtest.py` script now takes a :option:`--randseed=`
1172 switch that takes an integer that will be used as the random seed
1173 for the :option:`-r` option that executes tests in random order.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001174 The :option:`-r` option also reports the seed that was used
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001175 (Added by Collin Winter.)
1176
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00001177* Another :file:`regrtest.py` switch is :option:`-j`, which
1178 takes an integer specifying how many tests run in parallel. This
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001179 allows reducing the total runtime on multi-core machines.
Antoine Pitrou4698d992009-05-31 14:20:14 +00001180 This option is compatible with several other options, including the
1181 :option:`-R` switch which is known to produce long runtimes.
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00001182 (Added by Antoine Pitrou, :issue:`6152`.) This can also be used
1183 with a new :option:`-F` switch that runs selected tests in a loop
1184 until they fail. (Added by Antoine Pitrou; :issue:`7312`.)
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001185
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001186.. ======================================================================
1187
1188Porting to Python 2.7
1189=====================
1190
1191This section lists previously described changes and other bugfixes
1192that may require changes to your code:
1193
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001194* When using :class:`Decimal` instances with a string's
1195 :meth:`format` method, the default alignment was previously
1196 left-alignment. This has been changed to right-alignment, which might
1197 change the output of your programs.
1198 (Changed by Mark Dickinson; :issue:`6857`.)
1199
1200 Another :meth:`format`-related change: the default precision used
1201 for floating-point and complex numbers was changed from 6 decimal
1202 places to 12, which matches the precision used by :func:`str`.
1203 (Changed by Eric Smith; :issue:`5920`.)
1204
Amaury Forgeot d'Arc901f2002009-06-09 23:08:13 +00001205* Because of an optimization for the :keyword:`with` statement, the special
1206 methods :meth:`__enter__` and :meth:`__exit__` must belong to the object's
1207 type, and cannot be directly attached to the object's instance. This
Amaury Forgeot d'Arcd81333c2009-06-10 20:30:19 +00001208 affects new-style classes (derived from :class:`object`) and C extension
Amaury Forgeot d'Arc901f2002009-06-09 23:08:13 +00001209 types. (:issue:`6101`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001210
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001211* The :meth:`readline` method of :class:`StringIO` objects now does
1212 nothing when a negative length is requested, as other file-like
1213 objects do. (:issue:`7348`).
1214
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00001215For C extensions:
1216
1217* Use the new :cfunc:`PyOS_string_to_double` function instead of the old
1218 :cfunc:`PyOS_ascii_strtod` and :cfunc:`PyOS_ascii_atof` functions,
1219 which are now deprecated.
1220
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001221.. ======================================================================
1222
1223
1224.. _acks27:
1225
1226Acknowledgements
1227================
1228
1229The author would like to thank the following people for offering
1230suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchling8f254e72009-12-08 02:37:05 +00001231article: Ryan Lovett, Hugh Secker-Walker.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001232