blob: 9590dce0cbe64ac7374b74c9f4b978fa0df7d6db [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. Kuchling4a0661b2010-03-25 01:35:51 +000011.. Big jobs: argparse, ElementTree 1.3, pep 391, 3106, sysconfig
12.. unittest test discovery
13
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000014.. $Id$
15 Rules for maintenance:
16
17 * Anyone can add text to this document. Do not spend very much time
18 on the wording of your changes, because your text will probably
19 get rewritten to some degree.
20
21 * The maintainer will go through Misc/NEWS periodically and add
22 changes; it's therefore more important to add your changes to
23 Misc/NEWS than to this file.
24
25 * This is not a complete list of every single change; completeness
26 is the purpose of Misc/NEWS. Some changes I consider too small
27 or esoteric to include. If such a change is added to the text,
28 I'll just remove it. (This is another reason you shouldn't spend
29 too much time on writing your addition.)
30
31 * If you want to draw your new text to the attention of the
32 maintainer, add 'XXX' to the beginning of the paragraph or
33 section.
34
35 * It's OK to just add a fragmentary note about a change. For
36 example: "XXX Describe the transmogrify() function added to the
37 socket module." The maintainer will research the change and
38 write the necessary text.
39
40 * You can comment out your additions if you like, but it's not
41 necessary (especially when a final release is some months away).
42
43 * Credit the author of a patch or bugfix. Just the name is
44 sufficient; the e-mail address isn't necessary.
45
46 * It's helpful to add the bug/patch number in a parenthetical comment.
47
48 XXX Describe the transmogrify() function added to the socket
49 module.
50 (Contributed by P.Y. Developer; :issue:`12345`.)
51
52 This saves the maintainer some effort going through the SVN logs
53 when researching a change.
54
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +000055This article explains the new features in Python 2.7. The final
56release of 2.7 is currently scheduled for June 2010; the detailed
57schedule is described in :pep:`373`.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000058
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +000059Python 2.7 is planned to be the last major release in the 2.x series.
60Though more major releases have not been absolutely ruled out, it's
61likely that the 2.7 release will have an extended period of
62maintenance compared to earlier 2.x versions.
63
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000064.. Compare with previous release in 2 - 3 sentences here.
65 add hyperlink when the documentation becomes available online.
66
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +000067.. _whatsnew27-python31:
68
69Python 3.1 Features
70=======================
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +000071
72Much as Python 2.6 incorporated features from Python 3.0,
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +000073version 2.7 incorporates some of the new features
74in Python 3.1. The 2.x series continues to provide tools
75for migrating to the 3.x series.
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +000076
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +000077A partial list of 3.1 features that were backported to 2.7:
78
79* A version of the :mod:`io` library, rewritten in C for performance.
80* The ordered-dictionary type described in :ref:`pep-0372`.
Andrew M. Kuchling8f254e72009-12-08 02:37:05 +000081* The new format specifier described in :ref:`pep-0378`.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +000082* The :class:`memoryview` object.
83* A small subset of the :mod:`importlib` module `described below <#importlib-section>`__.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +000084* Float-to-string and string-to-float conversions now round their
85 results more correctly. And :func:`repr` of a floating-point
86 number *x* returns a result that's guaranteed to round back to the
87 same number when converted back to a string.
88* The :cfunc:`PyLong_AsLongAndOverflow` C API function.
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +000089
90One porting change: the :option:`-3` switch now automatically
91enables the :option:`-Qwarn` switch that causes warnings
92about using classic division with integers and long integers.
93
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +000094Other new Python3-mode warnings include:
95
96* :func:`operator.isCallable` and :func:`operator.sequenceIncludes`,
97 which are not supported in 3.x.
98
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +000099.. ========================================================================
100.. Large, PEP-level features and changes should be described here.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000101.. ========================================================================
102
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000103.. _pep-0372:
104
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000105PEP 372: Adding an ordered dictionary to collections
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000106====================================================
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000107
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000108Regular Python dictionaries iterate over key/value pairs in arbitrary order.
109Over the years, a number of authors have written alternative implementations
110that remember the order that the keys were originally inserted. Based on
111the experiences from those implementations, a new
112:class:`collections.OrderedDict` class has been introduced.
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000113
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000114The :class:`OrderedDict` API is substantially the same as regular dictionaries
115but will iterate over keys and values in a guaranteed order depending on
116when a key was first inserted::
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000117
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000118 >>> from collections import OrderedDict
119 >>> d = OrderedDict([('first', 1), ('second', 2),
120 ... ('third', 3)])
121 >>> d.items()
122 [('first', 1), ('second', 2), ('third', 3)]
123
124If a new entry overwrites an existing entry, the original insertion
125position is left unchanged::
126
127 >>> d['second'] = 4
128 >>> d.items()
129 [('first', 1), ('second', 4), ('third', 3)]
130
131Deleting an entry and reinserting it will move it to the end::
132
133 >>> del d['second']
134 >>> d['second'] = 5
135 >>> d.items()
136 [('first', 1), ('third', 3), ('second', 5)]
137
138The :meth:`popitem` method has an optional *last* argument
139that defaults to True. If *last* is True, the most recently
140added key is returned and removed; if it's False, the
141oldest key is selected::
142
143 >>> od = OrderedDict([(x,0) for x in range(20)])
144 >>> od.popitem()
145 (19, 0)
146 >>> od.popitem()
147 (18, 0)
148 >>> od.popitem(False)
149 (0, 0)
150 >>> od.popitem(False)
151 (1, 0)
152
153Comparing two ordered dictionaries checks both the keys and values,
154and requires that the insertion order was the same::
155
156 >>> od1 = OrderedDict([('first', 1), ('second', 2),
157 ... ('third', 3)])
158 >>> od2 = OrderedDict([('third', 3), ('first', 1),
159 ... ('second', 2)])
160 >>> od1==od2
161 False
162 >>> # Move 'third' key to the end
163 >>> del od2['third'] ; od2['third'] = 3
164 >>> od1==od2
165 True
166
167Comparing an :class:`OrderedDict` with a regular dictionary
168ignores the insertion order and just compares the keys and values.
169
170How does the :class:`OrderedDict` work? It maintains a doubly-linked
171list of keys, appending new keys to the list as they're inserted. A
172secondary dictionary maps keys to their corresponding list node, so
173deletion doesn't have to traverse the entire linked list and therefore
174remains O(1).
175
176.. XXX check O(1)-ness with Raymond
177
178The standard library now supports use of ordered dictionaries in several
179modules. The :mod:`configparser` module uses them by default. This lets
180configuration files be read, modified, and then written back in their original
181order. The *_asdict()* method for :func:`collections.namedtuple` now
182returns an ordered dictionary with the values appearing in the same order as
183the underlying tuple indicies. The :mod:`json` module is being built-out with
184an *object_pairs_hook* to allow OrderedDicts to be built by the decoder.
185Support was also added for third-party tools like `PyYAML <http://pyyaml.org/>`_.
186
Andrew M. Kuchling7fe65a02009-10-13 15:49:33 +0000187.. seealso::
188
189 :pep:`372` - Adding an ordered dictionary to collections
190 PEP written by Armin Ronacher and Raymond Hettinger;
191 implemented by Raymond Hettinger.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000192
193.. _pep-0378:
194
195PEP 378: Format Specifier for Thousands Separator
196====================================================
197
198To make program output more readable, it can be useful to add
199separators to large numbers and render them as
20018,446,744,073,709,551,616 instead of 18446744073709551616.
201
202The fully general solution for doing this is the :mod:`locale` module,
203which can use different separators ("," in North America, "." in
204Europe) and different grouping sizes, but :mod:`locale` is complicated
205to use and unsuitable for multi-threaded applications where different
206threads are producing output for different locales.
207
208Therefore, a simple comma-grouping mechanism has been added to the
209mini-language used by the string :meth:`format` method. When
210formatting a floating-point number, simply include a comma between the
211width and the precision::
212
213 >>> '{:20,.2}'.format(f)
214 '18,446,744,073,709,551,616.00'
215
216This mechanism is not adaptable at all; commas are always used as the
217separator and the grouping is always into three-digit groups. The
218comma-formatting mechanism isn't as general as the :mod:`locale`
219module, but it's easier to use.
220
Andrew M. Kuchling85ea4bf2009-10-05 22:45:39 +0000221.. XXX "Format String Syntax" in string.rst could use many more examples.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000222
223.. seealso::
224
225 :pep:`378` - Format Specifier for Thousands Separator
226 PEP written by Raymond Hettinger; implemented by Eric Smith.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000227
Andrew M. Kuchlingab21f752010-03-02 13:55:33 +0000228PEP 389: The argparse Module for Parsing Command Lines
229======================================================
230
231XXX write this section.
232
233.. seealso::
234
235 :pep:`389` - argparse - New Command Line Parsing Module
236 PEP written and implemented by Steven Bethard.
237
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000238PEP 391: Dictionary-Based Configuration For Logging
239====================================================
240
241XXX write this section.
242
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000243Two smaller enhancements to the logging module are:
244
245.. rev79293
246
247* :class:`Logger` instances gained a :meth:`getChild` that retrieves a
248 descendant logger using a relative path. For example,
249 once you retrieve a logger by doing ``log = getLogger('app')``,
250 calling ``log.getChild('network.listen')`` is equivalent to
251 ``getLogger('app.network.listen')``.
252
253* The :class:`LoggerAdapter` class gained a :meth:`isEnabledFor` method
254 that takes a *level* and returns whether the underlying logger would
255 process a message of that level of importance.
256
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000257.. seealso::
258
259 :pep:`391` - Dictionary-Based Configuration For Logging
260 PEP written and implemented by Vinay Sajip.
261
262PEP 3106: Dictionary Views
263====================================================
264
265XXX write this section.
266
267.. seealso::
268
269 :pep:`3106` - Revamping dict.keys(), .values() and .items()
270 PEP written by Guido van Rossum.
271 Backported to 2.7 by Alexandre Vassalotti; :issue:`1967`.
272
273
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000274Other Language Changes
275======================
276
277Some smaller changes made to the core Python language are:
278
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000279* The syntax for set literals has been backported from Python 3.x.
280 Curly brackets are used to surround the contents of the resulting
281 mutable set; set literals are
282 distinguished from dictionaries by not containing colons and values.
283 ``{}`` continues to represent an empty dictionary; use
284 ``set()`` for an empty set.
285
286 >>> {1,2,3,4,5}
287 set([1, 2, 3, 4, 5])
288 >>> set()
289 set([])
290 >>> {}
291 {}
292
293 Backported by Alexandre Vassalotti; :issue:`2335`.
294
295* Dictionary and set comprehensions are another feature backported from
296 3.x, generalizing list/generator comprehensions to use
297 the literal syntax for sets and dictionaries.
298
299 >>> {x:x*x for x in range(6)}
300 {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
301 >>> {'a'*x for x in range(6)}
302 set(['', 'a', 'aa', 'aaa', 'aaaa', 'aaaaa'])
303
304 Backported by Alexandre Vassalotti; :issue:`2333`.
305
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000306* The :keyword:`with` statement can now use multiple context managers
307 in one statement. Context managers are processed from left to right
308 and each one is treated as beginning a new :keyword:`with` statement.
309 This means that::
310
311 with A() as a, B() as b:
312 ... suite of statements ...
313
314 is equivalent to::
315
316 with A() as a:
317 with B() as b:
318 ... suite of statements ...
319
320 The :func:`contextlib.nested` function provides a very similar
321 function, so it's no longer necessary and has been deprecated.
322
323 (Proposed in http://codereview.appspot.com/53094; implemented by
324 Georg Brandl.)
325
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000326* Conversions between floating-point numbers and strings are
327 now correctly rounded on most platforms. These conversions occur
328 in many different places: :func:`str` on
329 floats and complex numbers; the :class:`float` and :class:`complex`
330 constructors;
331 numeric formatting; serialization and
332 deserialization of floats and complex numbers using the
333 :mod:`marshal`, :mod:`pickle`
334 and :mod:`json` modules;
335 parsing of float and imaginary literals in Python code;
336 and :class:`Decimal`-to-float conversion.
337
338 Related to this, the :func:`repr` of a floating-point number *x*
339 now returns a result based on the shortest decimal string that's
340 guaranteed to round back to *x* under correct rounding (with
341 round-half-to-even rounding mode). Previously it gave a string
342 based on rounding x to 17 decimal digits.
343
344 The rounding library responsible for this improvement works on
345 Windows, and on Unix platforms using the gcc, icc, or suncc
346 compilers. There may be a small number of platforms where correct
347 operation of this code cannot be guaranteed, so the code is not
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +0000348 used on such systems. You can find out which code is being used
349 by checking :data:`sys.float_repr_style`, which will be ``short``
350 if the new code is in use and ``legacy`` if it isn't.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000351
Mark Dickinsonbdd863d2010-01-07 09:28:29 +0000352 Implemented by Eric Smith and Mark Dickinson, using David Gay's
353 :file:`dtoa.c` library; :issue:`7117`.
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000354
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000355* The :meth:`str.format` method now supports automatic numbering of the replacement
Benjamin Petersonaa0a0b92009-04-11 20:27:15 +0000356 fields. This makes using :meth:`str.format` more closely resemble using
357 ``%s`` formatting::
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000358
359 >>> '{}:{}:{}'.format(2009, 04, 'Sunday')
360 '2009:4:Sunday'
361 >>> '{}:{}:{day}'.format(2009, 4, day='Sunday')
362 '2009:4:Sunday'
363
Benjamin Petersonaa0a0b92009-04-11 20:27:15 +0000364 The auto-numbering takes the fields from left to right, so the first ``{...}``
365 specifier will use the first argument to :meth:`str.format`, the next
366 specifier will use the next argument, and so on. You can't mix auto-numbering
367 and explicit numbering -- either number all of your specifier fields or none
368 of them -- but you can mix auto-numbering and named fields, as in the second
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000369 example above. (Contributed by Eric Smith; :issue:`5237`.)
370
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000371 Complex numbers now correctly support usage with :func:`format`,
372 and default to being right-aligned.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000373 Specifying a precision or comma-separation applies to both the real
374 and imaginary parts of the number, but a specified field width and
375 alignment is applied to the whole of the resulting ``1.5+3j``
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000376 output. (Contributed by Eric Smith; :issue:`1588` and :issue:`7988`.)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000377
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000378 The 'F' format code now always formats its output using uppercase characters,
379 so it will now produce 'INF' and 'NAN'.
380 (Contributed by Eric Smith; :issue:`3382`.)
381
Mark Dickinson1a707982008-12-17 16:14:37 +0000382* The :func:`int` and :func:`long` types gained a ``bit_length``
Georg Brandl64e1c752009-04-11 18:19:27 +0000383 method that returns the number of bits necessary to represent
Mark Dickinson1a707982008-12-17 16:14:37 +0000384 its argument in binary::
385
386 >>> n = 37
387 >>> bin(37)
388 '0b100101'
389 >>> n.bit_length()
390 6
391 >>> n = 2**123-1
392 >>> n.bit_length()
393 123
394 >>> (n+1).bit_length()
395 124
396
397 (Contributed by Fredrik Johansson and Victor Stinner; :issue:`3439`.)
398
Andrew M. Kuchling92b97002009-05-02 17:12:15 +0000399* Conversions from long integers and regular integers to floating
400 point now round differently, returning the floating-point number
401 closest to the number. This doesn't matter for small integers that
402 can be converted exactly, but for large numbers that will
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000403 unavoidably lose precision, Python 2.7 now approximates more
Andrew M. Kuchling92b97002009-05-02 17:12:15 +0000404 closely. For example, Python 2.6 computed the following::
405
406 >>> n = 295147905179352891391
407 >>> float(n)
408 2.9514790517935283e+20
409 >>> n - long(float(n))
410 65535L
411
412 Python 2.7's floating-point result is larger, but much closer to the
413 true value::
414
415 >>> n = 295147905179352891391
416 >>> float(n)
417 2.9514790517935289e+20
418 >>> n-long(float(n)
419 ... )
420 -1L
421
422 (Implemented by Mark Dickinson; :issue:`3166`.)
423
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000424 Integer division is also more accurate in its rounding behaviours. (Also
425 implemented by Mark Dickinson; :issue:`1811`.)
426
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000427* It's now possible for a subclass of the built-in :class:`unicode` type
428 to override the :meth:`__unicode__` method. (Implemented by
429 Victor Stinner; :issue:`1583863`.)
430
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000431* The :class:`bytearray` type's :meth:`translate` method now accepts
432 ``None`` as its first argument. (Fixed by Georg Brandl;
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000433 :issue:`4759`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000434
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000435* When using ``@classmethod`` and ``@staticmethod`` to wrap
436 methods as class or static methods, the wrapper object now
437 exposes the wrapped function as their :attr:`__func__` attribute.
438 (Contributed by Amaury Forgeot d'Arc, after a suggestion by
439 George Sakkis; :issue:`5982`.)
440
441* A new encoding named "cp720", used primarily for Arabic text, is now
442 supported. (Contributed by Alexander Belchenko and Amaury Forgeot
443 d'Arc; :issue:`1616979`.)
444
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000445* The :class:`file` object will now set the :attr:`filename` attribute
446 on the :exc:`IOError` exception when trying to open a directory
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +0000447 on POSIX platforms (noted by Jan Kaliszewski; :issue:`4764`), and
448 now explicitly checks for and forbids writing to read-only file objects
449 instead of trusting the C library to catch and report the error
450 (fixed by Stefan Krah; :issue:`5677`).
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000451
Benjamin Petersonae9a0a02009-12-31 16:49:37 +0000452* The Python tokenizer now translates line endings itself, so the
453 :func:`compile` built-in function can now accept code using any
454 line-ending convention. Additionally, it no longer requires that the
455 code end in a newline.
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +0000456
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000457* Extra parentheses in function definitions are illegal in Python 3.x,
458 meaning that you get a syntax error from ``def f((x)): pass``. In
459 Python3-warning mode, Python 2.7 will now warn about this odd usage.
460 (Noted by James Lingard; :issue:`7362`.)
461
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000462* When a module object is garbage-collected, the module's dictionary is
463 now only cleared if no one else is holding a reference to the
464 dictionary (:issue:`7140`).
465
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000466.. ======================================================================
467
468
469Optimizations
470-------------
471
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000472Several performance enhancements have been added:
473
474.. * A new :program:`configure` option, :option:`--with-computed-gotos`,
475 compiles the main bytecode interpreter loop using a new dispatch
476 mechanism that gives speedups of up to 20%, depending on the system
477 and benchmark. The new mechanism is only supported on certain
478 compilers, such as gcc, SunPro, and icc.
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000479
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000480* A new opcode was added to perform the initial setup for
481 :keyword:`with` statements, looking up the :meth:`__enter__` and
482 :meth:`__exit__` methods. (Contributed by Benjamin Peterson.)
483
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000484* The garbage collector now performs better for one common usage
485 pattern: when many objects are being allocated without deallocating
486 any of them. This would previously take quadratic
487 time for garbage collection, but now the number of full garbage collections
488 is reduced as the number of objects on the heap grows.
489 The new logic is to only perform a full garbage collection pass when
490 the middle generation has been collected 10 times and when the
491 number of survivor objects from the middle generation exceeds 10% of
492 the number of objects in the oldest generation. (Suggested by Martin
493 von Loewis and implemented by Antoine Pitrou; :issue:`4074`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000494
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000495* The garbage collector tries to avoid tracking simple containers
496 which can't be part of a cycle. In Python 2.7, this is now true for
497 tuples and dicts containing atomic types (such as ints, strings,
498 etc.). Transitively, a dict containing tuples of atomic types won't
499 be tracked either. This helps reduce the cost of each
500 garbage collection by decreasing the number of objects to be
501 considered and traversed by the collector.
Antoine Pitrouc18f6b02009-03-28 19:10:13 +0000502 (Contributed by Antoine Pitrou; :issue:`4688`.)
503
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000504* Long integers are now stored internally either in base 2**15 or in base
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000505 2**30, the base being determined at build time. Previously, they
506 were always stored in base 2**15. Using base 2**30 gives
507 significant performance improvements on 64-bit machines, but
508 benchmark results on 32-bit machines have been mixed. Therefore,
509 the default is to use base 2**30 on 64-bit machines and base 2**15
510 on 32-bit machines; on Unix, there's a new configure option
511 :option:`--enable-big-digits` that can be used to override this default.
512
513 Apart from the performance improvements this change should be
514 invisible to end users, with one exception: for testing and
515 debugging purposes there's a new structseq ``sys.long_info`` that
516 provides information about the internal format, giving the number of
517 bits per digit and the size in bytes of the C type used to store
518 each digit::
519
520 >>> import sys
521 >>> sys.long_info
522 sys.long_info(bits_per_digit=30, sizeof_digit=4)
523
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000524 (Contributed by Mark Dickinson; :issue:`4258`.)
525
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000526 Another set of changes made long objects a few bytes smaller: 2 bytes
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000527 smaller on 32-bit systems and 6 bytes on 64-bit.
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000528 (Contributed by Mark Dickinson; :issue:`5260`.)
529
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000530* The division algorithm for long integers has been made faster
531 by tightening the inner loop, doing shifts instead of multiplications,
532 and fixing an unnecessary extra iteration.
533 Various benchmarks show speedups of between 50% and 150% for long
534 integer divisions and modulo operations.
535 (Contributed by Mark Dickinson; :issue:`5512`.)
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +0000536 Bitwise operations are also significantly faster (initial patch by
537 Gregory Smith; :issue:`1087418`).
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000538
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000539* The implementation of ``%`` checks for the left-side operand being
540 a Python string and special-cases it; this results in a 1-3%
541 performance increase for applications that frequently use ``%``
542 with strings, such as templating libraries.
543 (Implemented by Collin Winter; :issue:`5176`.)
544
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000545* List comprehensions with an ``if`` condition are compiled into
546 faster bytecode. (Patch by Antoine Pitrou, back-ported to 2.7
547 by Jeffrey Yasskin; :issue:`4715`.)
548
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +0000549* Converting an integer or long integer to a decimal string was made
550 faster by special-casing base 10 instead of using a generalized
551 conversion function that supports arbitrary bases.
552 (Patch by Gawain Bolton; :issue:`6713`.)
553
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +0000554* The :meth:`split`, :meth:`replace`, :meth:`rindex`,
555 :meth:`rpartition`, and :meth:`rsplit` methods of string-like types
556 (strings, Unicode strings, and :class:`bytearray` objects) now use a
557 fast reverse-search algorithm instead of a character-by-character
558 scan. This is sometimes faster by a factor of 10. (Added by
559 Florent Xicluna; :issue:`7462` and :issue:`7622`.)
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +0000560
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000561* The :mod:`pickle` and :mod:`cPickle` modules now automatically
562 intern the strings used for attribute names, reducing memory usage
563 of the objects resulting from unpickling. (Contributed by Jake
564 McGuire; :issue:`5084`.)
565
566* The :mod:`cPickle` module now special-cases dictionaries,
567 nearly halving the time required to pickle them.
568 (Contributed by Collin Winter; :issue:`5670`.)
569
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000570.. ======================================================================
571
Georg Brandl0516f812009-11-18 18:52:35 +0000572New and Improved Modules
573========================
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +0000574
575As in every release, Python's standard library received a number of
576enhancements and bug fixes. Here's a partial list of the most notable
577changes, sorted alphabetically by module name. Consult the
578:file:`Misc/NEWS` file in the source tree for a more complete list of
579changes, or look through the Subversion logs for all the details.
580
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000581* The :mod:`bdb` module's base debugging class :class:`Bdb`
582 gained a feature for skipping modules. The constructor
583 now takes an iterable containing glob-style patterns such as
584 ``django.*``; the debugger will not step into stack frames
585 from a module that matches one of these patterns.
586 (Contributed by Maru Newby after a suggestion by
587 Senthil Kumaran; :issue:`5142`.)
588
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +0000589* The :mod:`binascii` module now supports the buffer API, so it can be
590 used with :class:`memoryview` instances and other similar buffer objects.
591 (Backported from 3.x by Florent Xicluna; :issue:`7703`.)
592
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000593* Updated module: the :mod:`bsddb` module has been updated from 4.7.2devel9
594 to version 4.8.4 of
595 `the pybsddb package <http://www.jcea.es/programacion/pybsddb.htm>`__.
596 The new version features better Python 3.x compatibility, various bug fixes,
597 and adds several new BerkeleyDB flags and methods.
598 (Updated by Jesús Cea Avion; :issue:`8156`. The pybsddb
599 changelog can be browsed at http://hg.jcea.es/pybsddb/file/tip/ChangeLog.)
600
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000601* The :mod:`bz2` module's :class:`BZ2File` now supports the context
602 management protocol, so you can write ``with bz2.BZ2File(...) as f: ...``.
603 (Contributed by Hagen Fuerstenau; :issue:`3860`.)
604
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000605* New class: the :class:`Counter` class in the :mod:`collections` module is
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000606 useful for tallying data. :class:`Counter` instances behave mostly
607 like dictionaries but return zero for missing keys instead of
Georg Brandlf6dab952009-04-28 21:48:35 +0000608 raising a :exc:`KeyError`:
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000609
Georg Brandlf6dab952009-04-28 21:48:35 +0000610 .. doctest::
611 :options: +NORMALIZE_WHITESPACE
612
613 >>> from collections import Counter
614 >>> c = Counter()
615 >>> for letter in 'here is a sample of english text':
616 ... c[letter] += 1
617 ...
618 >>> c
619 Counter({' ': 6, 'e': 5, 's': 3, 'a': 2, 'i': 2, 'h': 2,
620 'l': 2, 't': 2, 'g': 1, 'f': 1, 'm': 1, 'o': 1, 'n': 1,
621 'p': 1, 'r': 1, 'x': 1})
622 >>> c['e']
623 5
624 >>> c['z']
625 0
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000626
627 There are two additional :class:`Counter` methods: :meth:`most_common`
628 returns the N most common elements and their counts, and :meth:`elements`
629 returns an iterator over the contained element, repeating each element
630 as many times as its count::
631
632 >>> c.most_common(5)
633 [(' ', 6), ('e', 5), ('s', 3), ('a', 2), ('i', 2)]
634 >>> c.elements() ->
635 'a', 'a', ' ', ' ', ' ', ' ', ' ', ' ',
636 'e', 'e', 'e', 'e', 'e', 'g', 'f', 'i', 'i',
637 'h', 'h', 'm', 'l', 'l', 'o', 'n', 'p', 's',
Georg Brandlf6dab952009-04-28 21:48:35 +0000638 's', 's', 'r', 't', 't', 'x'
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000639
640 Contributed by Raymond Hettinger; :issue:`1696199`.
641
Georg Brandlf6d367452010-03-12 10:02:03 +0000642 The new `~collections.OrderedDict` class is described in the earlier section
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000643 :ref:`pep-0372`.
644
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000645 The :class:`namedtuple` class now has an optional *rename* parameter.
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000646 If *rename* is true, field names that are invalid because they've
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000647 been repeated or that aren't legal Python identifiers will be
648 renamed to legal names that are derived from the field's
649 position within the list of fields:
650
Georg Brandlf6dab952009-04-28 21:48:35 +0000651 >>> from collections import namedtuple
652 >>> T = namedtuple('T', ['field1', '$illegal', 'for', 'field2'], rename=True)
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000653 >>> T._fields
654 ('field1', '_1', '_2', 'field2')
655
656 (Added by Raymond Hettinger; :issue:`1818`.)
657
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000658 The :class:`deque` data type now exposes its maximum length as the
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000659 read-only :attr:`maxlen` attribute, and has a
660 :meth:`reverse` method that reverses the elements of the deque in-place.
661 (Added by Raymond Hettinger.)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000662
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000663* The :mod:`copy` module's :func:`deepcopy` function will now
664 correctly copy bound instance methods. (Implemented by
665 Robert Collins; :issue:`1515`.)
666
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000667* The :mod:`ctypes` module now always converts ``None`` to a C NULL
668 pointer for arguments declared as pointers. (Changed by Thomas
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +0000669 Heller; :issue:`4606`.) The underlying `libffi library
670 <http://sourceware.org/libffi/>`__ has been updated to version
671 3.0.9, containing various fixes for different platforms. (Updated
672 by Matthias Klose; :issue:`8142`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000673
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000674* New method: the :mod:`datetime` module's :class:`timedelta` class
675 gained a :meth:`total_seconds` method that returns the number of seconds
676 in the duration. (Contributed by Brian Quinlan; :issue:`5788`.)
677
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000678* New method: the :class:`Decimal` class gained a
679 :meth:`from_float` class method that performs an exact conversion
680 of a floating-point number to a :class:`Decimal`.
681 Note that this is an **exact** conversion that strives for the
682 closest decimal approximation to the floating-point representation's value;
683 the resulting decimal value will therefore still include the inaccuracy,
684 if any.
685 For example, ``Decimal.from_float(0.1)`` returns
686 ``Decimal('0.1000000000000000055511151231257827021181583404541015625')``.
687 (Implemented by Raymond Hettinger; :issue:`4796`.)
688
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000689 Most of the methods of the :class:`Context` class now accept integers
690 as well as :class:`Decimal` instances; the only exceptions are the
691 :meth:`canonical` and :meth:`is_canonical` methods. (Patch by
692 Juan José Conti; :issue:`7633`.)
693
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000694 The constructor for :class:`Decimal` now accepts non-European
695 Unicode characters, such as Arabic-Indic digits. (Contributed by
696 Mark Dickinson; :issue:`6595`.)
697
698 When using :class:`Decimal` instances with a string's
699 :meth:`format` method, the default alignment was previously
700 left-alignment. This has been changed to right-alignment, which seems
701 more sensible for numeric types. (Changed by Mark Dickinson; :issue:`6857`.)
702
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000703* The :class:`Fraction` class now accepts two rational numbers
Andrew M. Kuchling92b97002009-05-02 17:12:15 +0000704 as arguments to its constructor.
705 (Implemented by Mark Dickinson; :issue:`5812`.)
706
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +0000707* New class: a new :class:`ftplib.FTP_TLS` class in
708 the :mod:`ftplib` module provides secure FTP
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000709 connections using TLS encapsulation of authentication as well as
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +0000710 subsequent control and data transfers.
711 (Contributed by Giampaolo Rodola', :issue:`2054`.)
712
713 The :meth:`storbinary` method for binary uploads can now restart
714 uploads thanks to an added *rest* parameter (patch by Pablo Mouzo;
715 :issue:`6845`.)
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000716
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000717* New function: the :mod:`gc` module's :func:`is_tracked` returns
718 true if a given instance is tracked by the garbage collector, false
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000719 otherwise. (Contributed by Antoine Pitrou; :issue:`4688`.)
720
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000721* The :mod:`gzip` module's :class:`GzipFile` now supports the context
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000722 management protocol, so you can write ``with gzip.GzipFile(...) as f: ...``
723 (contributed by Hagen Fuerstenau; :issue:`3860`), and it now implements
724 the :class:`io.BufferedIOBase` ABC, so you can wrap it with
725 :class:`io.BufferedReader` for faster processing
726 (contributed by Nir Aides; :issue:`7471`).
727 It's also now possible to override the modification time
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000728 recorded in a gzipped file by providing an optional timestamp to
729 the constructor. (Contributed by Jacques Frechet; :issue:`4272`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000730
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +0000731 Files in gzip format can be padded with trailing zero bytes; the
732 :mod:`gzip` module will now consume these trailing bytes. (Fixed by
733 Tadek Pietraszek and Brian Curtin; :issue:`2846`.)
734
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000735* New attribute: the :mod:`hashlib` module now has an :attr:`algorithms`
736 attribute containing a tuple naming the supported algorithms.
737 In Python 2.7, ``hashlib.algorithms`` contains
738 ``('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')``
739 (Contributed by Carl Chenet; :issue:`7418`.)
740
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000741* The default :class:`HTTPResponse` class used by the :mod:`httplib` module now
742 supports buffering, resulting in much faster reading of HTTP responses.
743 (Contributed by Kristjan Valur Jonsson; :issue:`4879`.)
744
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +0000745 The :class:`HTTPConnection` and :class:`HTTPSConnection` classes
746 now support a *source_address* parameter, a ``(host, port)`` 2-tuple
747 giving the source address that will be used for the connection.
748 (Contributed by Eldon Ziegler; :issue:`3972`.)
749
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000750* The :mod:`imaplib` module now supports IPv6 addresses.
751 (Contributed by Derek Morr; :issue:`1655`.)
752
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +0000753* Updated module: The :mod:`io` library has been upgraded to the version shipped with
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000754 Python 3.1. For 3.1, the I/O library was entirely rewritten in C
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +0000755 and is 2 to 20 times faster depending on the task being performed. The
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000756 original Python version was renamed to the :mod:`_pyio` module.
757
758 One minor resulting change: the :class:`io.TextIOBase` class now
759 has an :attr:`errors` attribute giving the error setting
760 used for encoding and decoding errors (one of ``'strict'``, ``'replace'``,
761 ``'ignore'``).
762
763 The :class:`io.FileIO` class now raises an :exc:`OSError` when passed
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000764 an invalid file descriptor. (Implemented by Benjamin Peterson;
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +0000765 :issue:`4991`.) The :meth:`truncate` method now preserves the
766 file position; previously it would change the file position to the
767 end of the new file. (Fixed by Pascal Chambon; :issue:`6939`.)
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +0000768
Andrew M. Kuchling5a73ff82009-12-02 14:27:11 +0000769* New function: ``itertools.compress(data, selectors)`` takes two
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000770 iterators. Elements of *data* are returned if the corresponding
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000771 value in *selectors* is true::
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000772
773 itertools.compress('ABCDEF', [1,0,1,0,1,1]) =>
774 A, C, E, F
775
Andrew M. Kuchling5a73ff82009-12-02 14:27:11 +0000776 New function: ``itertools.combinations_with_replacement(iter, r)``
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +0000777 returns all the possible *r*-length combinations of elements from the
778 iterable *iter*. Unlike :func:`combinations`, individual elements
779 can be repeated in the generated combinations::
780
781 itertools.combinations_with_replacement('abc', 2) =>
782 ('a', 'a'), ('a', 'b'), ('a', 'c'),
783 ('b', 'b'), ('b', 'c'), ('c', 'c')
784
785 Note that elements are treated as unique depending on their position
786 in the input, not their actual values.
787
788 The :class:`itertools.count` function now has a *step* argument that
789 allows incrementing by values other than 1. :func:`count` also
790 now allows keyword arguments, and using non-integer values such as
791 floats or :class:`Decimal` instances. (Implemented by Raymond
792 Hettinger; :issue:`5032`.)
793
Andrew M. Kuchling77069572009-03-31 01:21:01 +0000794 :func:`itertools.combinations` and :func:`itertools.product` were
795 previously raising :exc:`ValueError` for values of *r* larger than
796 the input iterable. This was deemed a specification error, so they
797 now return an empty iterator. (Fixed by Raymond Hettinger; :issue:`4816`.)
798
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +0000799* Updated module: The :mod:`json` module was upgraded to version 2.0.9 of the
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +0000800 simplejson package, which includes a C extension that makes
801 encoding and decoding faster.
802 (Contributed by Bob Ippolito; :issue:`4136`.)
803
804 To support the new :class:`OrderedDict` type, :func:`json.load`
805 now has an optional *object_pairs_hook* parameter that will be called
806 with any object literal that decodes to a list of pairs.
807 (Contributed by Raymond Hettinger; :issue:`5381`.)
808
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000809* New functions: the :mod:`math` module gained
810 :func:`erf` and :func:`erfc` for the error function and the complementary error function,
811 :func:`expm1` which computes ``e**x - 1`` with more precision than
812 using :func:`exp` and subtracting 1,
813 :func:`gamma` for the Gamma function, and
814 :func:`lgamma` for the natural log of the Gamma function.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000815 (Contributed by Mark Dickinson and nirinA raseliarison; :issue:`3366`.)
816
Andrew M. Kuchling24520b42009-04-09 11:22:47 +0000817* The :mod:`multiprocessing` module's :class:`Manager*` classes
818 can now be passed a callable that will be called whenever
819 a subprocess is started, along with a set of arguments that will be
820 passed to the callable.
821 (Contributed by lekma; :issue:`5585`.)
822
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +0000823 The :class:`Pool` class, which controls a pool of worker processes,
824 now has an optional *maxtasksperchild* parameter. Worker processes
825 will perform the specified number of tasks and then exit, causing the
826 :class:`Pool` to start a new worker. This is useful if tasks may leak
827 memory or other resources, or if some tasks will cause the worker to
828 become very large.
829 (Contributed by Charles Cazabon; :issue:`6963`.)
830
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000831* The :mod:`nntplib` module now supports IPv6 addresses.
832 (Contributed by Derek Morr; :issue:`1664`.)
833
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000834* New functions: the :mod:`os` module wraps the following POSIX system
835 calls: :func:`getresgid` and :func:`getresuid`, which return the
836 real, effective, and saved GIDs and UIDs;
837 :func:`setresgid` and :func:`setresuid`, which set
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +0000838 real, effective, and saved GIDs and UIDs to new values;
839 :func:`initgroups`. (GID/UID functions
840 contributed by Travis H.; :issue:`6508`. Support for initgroups added
841 by Jean-Paul Calderone; :issue:`7333`.)
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +0000842
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +0000843 The :func:`os.fork` function now re-initializes the import lock in
844 the child process; this fixes problems on Solaris when :func:`fork`
845 is called from a thread. (Fixed by Zsolt Cserna; :issue:`7242`.)
846
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000847* In the :mod:`os.path` module, the :func:`normpath` and
848 :func:`abspath` functions now preserve Unicode; if their input path
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +0000849 is a Unicode string, the return value is also a Unicode string.
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000850 (:meth:`normpath` fixed by Matt Giuca in :issue:`5827`;
851 :meth:`abspath` fixed by Ezio Melotti in :issue:`3426`.)
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +0000852
Andrew M. Kuchling9cb42772009-01-21 02:15:43 +0000853* The :mod:`pydoc` module now has help for the various symbols that Python
854 uses. You can now do ``help('<<')`` or ``help('@')``, for example.
855 (Contributed by David Laban; :issue:`4739`.)
856
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000857* The :mod:`re` module's :func:`split`, :func:`sub`, and :func:`subn`
858 now accept an optional *flags* argument, for consistency with the
859 other functions in the module. (Added by Gregory P. Smith.)
860
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +0000861* New function: in the :mod:`shutil` module, :func:`make_archive`
862 takes a filename, archive type (zip or tar-format), and a directory
863 path, and creates an archive containing the directory's contents.
864 (Added by Tarek Ziadé.)
865
866 :mod:`shutil`'s :func:`copyfile` and :func:`copytree`
867 functions now raise a :exc:`SpecialFileError` exception when
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000868 asked to copy a named pipe. Previously the code would treat
869 named pipes like a regular file by opening them for reading, and
870 this would block indefinitely. (Fixed by Antoine Pitrou; :issue:`3002`.)
871
872* New functions: in the :mod:`site` module, three new functions
873 return various site- and user-specific paths.
874 :func:`getsitepackages` returns a list containing all
875 global site-packages directories, and
876 :func:`getusersitepackages` returns the path of the user's
877 site-packages directory.
Ezio Melotti81982562010-01-04 09:00:11 +0000878 :func:`getuserbase` returns the value of the :envvar:`USER_BASE`
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000879 environment variable, giving the path to a directory that can be used
880 to store data.
Andrew M. Kuchling039c8992010-02-01 02:04:26 +0000881 (Contributed by Tarek Ziadé; :issue:`6693`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000882
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +0000883 The :mod:`site` module now reports exceptions occurring
884 when the :mod:`sitecustomize` module is imported, and will no longer
Florent Xiclunaad598332010-03-31 21:40:32 +0000885 catch and swallow the :exc:`KeyboardInterrupt` exception. (Fixed by
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +0000886 Victor Stinner; :issue:`3137`.)
887
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +0000888* The :mod:`socket` module's :class:`SSL` objects now support the
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000889 buffer API, which fixed a test suite failure. (Fixed by Antoine
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +0000890 Pitrou; :issue:`7133`.)
891
892 The :func:`create_connection` function
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000893 gained a *source_address* parameter, a ``(host, port)`` 2-tuple
894 giving the source address that will be used for the connection.
895 (Contributed by Eldon Ziegler; :issue:`3972`.)
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +0000896
Ezio Melotti9ccc5812010-04-05 08:16:41 +0000897 The :meth:`recv_into` and :meth:`recvfrom_into` methods will now write
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +0000898 into objects that support the buffer API, most usefully
899 the :class:`bytearray` and :class:`memoryview` objects. (Implemented by
900 Antoine Pitrou; :issue:`8104`.)
901
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000902* The :mod:`SocketServer` module's :class:`TCPServer` class now
903 has a :attr:`disable_nagle_algorithm` class attribute.
904 The default value is False; if overridden to be True,
905 new request connections will have the TCP_NODELAY option set to
906 prevent buffering many small sends into a single TCP packet.
907 (Contributed by Kristjan Valur Jonsson; :issue:`6192`.)
908
Andrew M. Kuchlingfed15762010-03-08 12:00:39 +0000909* Updated module: the :mod:`sqlite` module has been updated to
910 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
911 the ability to load SQLite extensions from shared libraries.
912 Call the ``enable_load_extension(True)`` method to enable extensions,
913 and then call :meth:`load_extension` to load a particular shared library.
914 (Updated by Gerhard Häring.)
915
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000916* The :mod:`struct` module will no longer silently ignore overflow
917 errors when a value is too large for a particular integer format
918 code (one of ``bBhHiIlLqQ``); it now always raises a
919 :exc:`struct.error` exception. (Changed by Mark Dickinson;
920 :issue:`1523`.)
921
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000922* New function: the :mod:`subprocess` module's
923 :func:`check_output` runs a command with a specified set of arguments
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000924 and returns the command's output as a string when the command runs without
Andrew M. Kuchling10b1ec92009-01-02 21:00:35 +0000925 error, or raises a :exc:`CalledProcessError` exception otherwise.
926
927 ::
928
929 >>> subprocess.check_output(['df', '-h', '.'])
930 'Filesystem Size Used Avail Capacity Mounted on\n
931 /dev/disk0s2 52G 49G 3.0G 94% /\n'
932
933 >>> subprocess.check_output(['df', '-h', '/bogus'])
934 ...
935 subprocess.CalledProcessError: Command '['df', '-h', '/bogus']' returned non-zero exit status 1
936
937 (Contributed by Gregory P. Smith.)
938
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +0000939 The :mod:`subprocess` module will now retry its internal system calls
940 on receiving an :const:`EINTR` signal. (Reported by several people; final
941 patch by Gregory P. Smith in :issue:`1068268`.)
942
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000943* New function: :func:`is_declared_global` in the :mod:`symtable` module
944 returns true for variables that are explicitly declared to be global,
945 false for ones that are implicitly global.
946 (Contributed by Jeremy Hylton.)
947
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000948* The ``sys.version_info`` value is now a named tuple, with attributes
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +0000949 named :attr:`major`, :attr:`minor`, :attr:`micro`,
950 :attr:`releaselevel`, and :attr:`serial`. (Contributed by Ross
951 Light; :issue:`4285`.)
952
953 :func:`sys.getwindowsversion` also returns a named tuple,
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +0000954 with attributes named :attr:`major`, :attr:`minor`, :attr:`build`,
Ezio Melotti12477752010-02-08 22:22:41 +0000955 :attr:`platform`, :attr:`service_pack`, :attr:`service_pack_major`,
Eric Smithb3c54882010-02-03 14:17:50 +0000956 :attr:`service_pack_minor`, :attr:`suite_mask`, and
957 :attr:`product_type`. (Contributed by Brian Curtin; :issue:`7766`.)
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +0000958
Andrew M. Kuchling039c8992010-02-01 02:04:26 +0000959* The :mod:`tarfile` module's default error handling has changed, to
960 no longer suppress fatal errors. The default error level was previously 0,
961 which meant that errors would only result in a message being written to the
962 debug log, but because the debug log is not activated by default,
963 these errors go unnoticed. The default error level is now 1,
964 which raises an exception if there's an error.
965 (Changed by Lars Gustäbel; :issue:`7357`.)
966
967 :mod:`tarfile` now supports filtering the :class:`TarInfo`
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000968 objects being added to a tar file. When you call :meth:`TarFile.add`,
969 instance, you may supply an optional *filter* argument
970 that's a callable. The *filter* callable will be passed the
971 :class:`TarInfo` for every file being added, and can modify and return it.
972 If the callable returns ``None``, the file will be excluded from the
973 resulting archive. This is more powerful than the existing
974 *exclude* argument, which has therefore been deprecated.
Andrew M. Kuchling039c8992010-02-01 02:04:26 +0000975 (Added by Lars Gustäbel; :issue:`6856`.)
Andrew M. Kuchlingfed15762010-03-08 12:00:39 +0000976 The :class:`TarFile` class also now supports the context manager protocol.
977 (Added by Lars Gustäbel; :issue:`7232`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000978
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000979* The :mod:`threading` module's :meth:`Event.wait` method now returns
980 the internal flag on exit. This means the method will usually
981 return true because :meth:`wait` is supposed to block until the
982 internal flag becomes true. The return value will only be false if
983 a timeout was provided and the operation timed out.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +0000984 (Contributed by Tim Lesher; :issue:`1674032`.)
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +0000985
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +0000986* The Unicode database provided by the :mod:`unicodedata` module is
987 now used internally to determine which characters are numeric,
988 whitespace, or represent line breaks. The database also
989 includes information from the :file:`Unihan.txt` data file (patch
990 by Anders Chrigström and Amaury Forgeot d'Arc; :issue:`1571184`)
991 and has been updated to version 5.2.0 (updated by
992 Florent Xicluna; :issue:`8024`).
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +0000993
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +0000994* The :class:`UserDict` class is now a new-style class. (Changed by
995 Benjamin Peterson.)
996
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +0000997* The ElementTree library, :mod:`xml.etree`, no longer escapes
998 ampersands and angle brackets when outputting an XML processing
999 instruction (which looks like `<?xml-stylesheet href="#style1"?>`)
1000 or comment (which looks like `<!-- comment -->`).
1001 (Patch by Neil Muller; :issue:`2746`.)
1002
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001003* The :mod:`zipfile` module's :class:`ZipFile` now supports the context
1004 management protocol, so you can write ``with zipfile.ZipFile(...) as f: ...``.
1005 (Contributed by Brian Curtin; :issue:`5511`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001006
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001007 :mod:`zipfile` now supports archiving empty directories and
1008 extracts them correctly. (Fixed by Kuba Wieczorek; :issue:`4710`.)
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001009 Reading files out of an archive is now faster, and interleaving
1010 :meth:`read` and :meth:`readline` now works correctly.
1011 (Contributed by Nir Aides; :issue:`7610`.)
Andrew M. Kuchling6c2633e2009-03-30 23:09:46 +00001012
Andrew M. Kuchlingf91a6792010-03-24 18:07:43 +00001013 The :func:`is_zipfile` function now
Andrew M. Kuchling039c8992010-02-01 02:04:26 +00001014 accepts a file object, in addition to the path names accepted in earlier
1015 versions. (Contributed by Gabriel Genellina; :issue:`4756`.)
1016
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001017 The :meth:`writestr` method now has an optional *compress_type* parameter
1018 that lets you override the default compression method specified in the
1019 :class:`ZipFile` constructor. (Contributed by Ronald Oussoren;
1020 :issue:`6003`.)
1021
1022
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00001023New module: sysconfig
1024---------------------------------
1025
1026XXX A new :mod:`sysconfig` module has been extracted from
1027:mod:`distutils` and put in the standard library.
1028
1029The :mod:`sysconfig` module provides access to Python's configuration
1030information like the list of installation paths and the configuration
Tarek Ziadé1e069ee2010-02-23 05:20:22 +00001031variables relevant for the current platform. (contributed by Tarek)
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00001032
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001033Updated module: ElementTree 1.3
1034---------------------------------
1035
1036XXX write this.
1037
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001038.. ======================================================================
1039.. whole new modules get described in subsections here
1040
Tarek Ziadé2b210692010-02-02 23:39:40 +00001041
Andrew M. Kuchling9e483ef2010-02-08 01:35:35 +00001042Distutils Enhancements
1043---------------------------------
1044
1045Distutils is being more actively developed, thanks to Tarek Ziadé
1046who has taken over maintenance of the package, so there are a number
1047of fixes and improvements.
1048
1049A new :file:`setup.py` subcommand, ``check``, will check that the
1050arguments being passed to the :func:`setup` function are complete
1051and correct (:issue:`5732`).
1052
1053Byte-compilation by the ``install_lib`` subcommand is now only done
1054if the ``sys.dont_write_bytecode`` setting allows it (:issue:`7071`).
1055
1056:func:`distutils.sdist.add_defaults` now uses
1057*package_dir* and *data_files* to create the MANIFEST file.
1058:mod:`distutils.sysconfig` now reads the :envvar:`AR` and
1059:envvar:`ARFLAGS` environment variables.
1060
1061.. ARFLAGS done in #5941
1062
1063It is no longer mandatory to store clear-text passwords in the
1064:file:`.pypirc` file when registering and uploading packages to PyPI. As long
1065as the username is present in that file, the :mod:`distutils` package will
1066prompt for the password if not present. (Added by Tarek Ziadé,
1067based on an initial contribution by Nathan Van Gheem; :issue:`4394`.)
1068
1069A Distutils setup can now specify that a C extension is optional by
1070setting the *optional* option setting to true. If this optional is
1071supplied, failure to build the extension will not abort the build
1072process, but instead simply not install the failing extension.
1073(Contributed by Georg Brandl; :issue:`5583`.)
1074
1075The :class:`distutils.dist.DistributionMetadata` class'
1076:meth:`read_pkg_file` method will read the contents of a package's
1077:file:`PKG-INFO` metadata file. For an example of its use, see
1078:ref:`reading-metadata`.
1079(Contributed by Tarek Ziadé; :issue:`7457`.)
1080
1081:file:`setup.py` files will now accept a :option:`--no-user-cfg` switch
1082to skip reading the :file:`~/.pydistutils.cfg` file. (Suggested by
1083by Michael Hoffman, and implemented by Paul Winkler; :issue:`1180`.)
1084
1085When creating a tar-format archive, the ``sdist`` subcommand now
1086allows specifying the user id and group that will own the files in the
1087archives using the :option:`--owner` and :option:`--group` switches
1088(:issue:`6516`).
1089
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00001090
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001091Unit Testing Enhancements
1092---------------------------------
1093
1094The :mod:`unittest` module was enhanced in several ways.
1095The progress messages now shows 'x' for expected failures
1096and 'u' for unexpected successes when run in verbose mode.
1097(Contributed by Benjamin Peterson.)
1098Test cases can raise the :exc:`SkipTest` exception to skip a test.
1099(:issue:`1034053`.)
1100
1101.. XXX describe test discovery (Contributed by Michael Foord; :issue:`6001`.)
1102
1103The error messages for :meth:`assertEqual`,
1104:meth:`assertTrue`, and :meth:`assertFalse`
1105failures now provide more information. If you set the
1106:attr:`longMessage` attribute of your :class:`TestCase` classes to
1107true, both the standard error message and any additional message you
1108provide will be printed for failures. (Added by Michael Foord; :issue:`5663`.)
1109
1110The :meth:`assertRaises` and :meth:`failUnlessRaises` methods now
1111return a context handler when called without providing a callable
1112object to run. For example, you can write this::
1113
1114 with self.assertRaises(KeyError):
1115 raise ValueError
1116
1117(Implemented by Antoine Pitrou; :issue:`4444`.)
1118
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001119.. rev 78774
1120
1121Module- and class-level setup and teardown fixtures are now supported.
1122Modules can contain :func:`setUpModule` and :func:`tearDownModule`
1123functions. Classes can have :meth:`setUpClass` and
1124:meth:`tearDownClass` methods that must be defined as class methods
1125(using ``@classmethod`` or the equivalent). These functions and
1126methods are invoked when the test runner switches to a test case in a
1127different module or class.
1128
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001129The methods :meth:`addCleanup` and :meth:`doCleanups` were added.
1130:meth:`addCleanup` allows you to add cleanup functions that
1131will be called unconditionally (after :meth:`setUp` if
1132:meth:`setUp` fails, otherwise after :meth:`tearDown`). This allows
Andrew M. Kuchling4a0661b2010-03-25 01:35:51 +00001133for much simpler resource allocation and deallocation during tests
1134(:issue:`5679`).
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001135
1136A number of new methods were added that provide more specialized
1137tests. Many of these methods were written by Google engineers
1138for use in their test suites; Gregory P. Smith, Michael Foord, and
1139GvR worked on merging them into Python's version of :mod:`unittest`.
1140
1141* :meth:`assertIsNone` and :meth:`assertIsNotNone` take one
1142 expression and verify that the result is or is not ``None``.
1143
1144* :meth:`assertIs` and :meth:`assertIsNot` take two values and check
1145 whether the two values evaluate to the same object or not.
1146 (Added by Michael Foord; :issue:`2578`.)
1147
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00001148* :meth:`assertIsInstance` and :meth:`assertNotIsInstance` check whether
1149 the resulting object is an instance of a particular class, or of
1150 one of a tuple of classes. (Added by Georg Brandl; :issue:`7031`.)
1151
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001152* :meth:`assertGreater`, :meth:`assertGreaterEqual`,
1153 :meth:`assertLess`, and :meth:`assertLessEqual` compare
1154 two quantities.
1155
1156* :meth:`assertMultiLineEqual` compares two strings, and if they're
1157 not equal, displays a helpful comparison that highlights the
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001158 differences in the two strings. This comparison is now used by
1159 default when Unicode strings are compared with :meth:`assertEqual`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001160
1161* :meth:`assertRegexpMatches` checks whether its first argument is a
1162 string matching a regular expression provided as its second argument.
1163
1164* :meth:`assertRaisesRegexp` checks whether a particular exception
1165 is raised, and then also checks that the string representation of
1166 the exception matches the provided regular expression.
1167
1168* :meth:`assertIn` and :meth:`assertNotIn` tests whether
1169 *first* is or is not in *second*.
1170
Michael Foord98e7b762010-03-20 03:00:34 +00001171* :meth:`assertItemsEqual` tests whether two provided sequences
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001172 contain the same elements.
1173
1174* :meth:`assertSetEqual` compares whether two sets are equal, and
1175 only reports the differences between the sets in case of error.
1176
1177* Similarly, :meth:`assertListEqual` and :meth:`assertTupleEqual`
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001178 compare the specified types and explain any differences without necessarily
1179 printing their full values; these methods are now used by default
1180 when comparing lists and tuples using :meth:`assertEqual`.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001181 More generally, :meth:`assertSequenceEqual` compares two sequences
1182 and can optionally check whether both sequences are of a
1183 particular type.
1184
1185* :meth:`assertDictEqual` compares two dictionaries and reports the
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001186 differences; it's now used by default when you compare two dictionaries
1187 using :meth:`assertEqual`. :meth:`assertDictContainsSubset` checks whether
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001188 all of the key/value pairs in *first* are found in *second*.
1189
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001190* :meth:`assertAlmostEqual` and :meth:`assertNotAlmostEqual` test
1191 whether *first* and *second* are approximately equal by computing
1192 their difference, rounding the result to an optionally-specified number
1193 of *places* (the default is 7), and comparing to zero.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001194
1195* :meth:`loadTestsFromName` properly honors the ``suiteClass`` attribute of
1196 the :class:`TestLoader`. (Fixed by Mark Roddy; :issue:`6866`.)
1197
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001198* A new hook lets you extend the :meth:`assertEqual` method to handle
1199 new data types. The :meth:`addTypeEqualityFunc` method takes a type
1200 object and a function. The function will be used when both of the
1201 objects being compared are of the specified type. This function
1202 should compare the two objects and raise an exception if they don't
1203 match; it's a good idea for the function to provide additional
1204 information about why the two objects are matching, much as the new
1205 sequence comparison methods do.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001206
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001207:func:`unittest.main` now takes an optional ``exit`` argument. If
1208false, :func:`main` doesn't call :func:`sys.exit`, allowing it to be
1209used from the interactive interpreter. (Contributed by J. Pablo
1210Fernández; :issue:`3379`.)
1211
1212A new command-line switch, :option:`-f` or :option:`--failfast`, makes
1213test execution stop immediately when a test fails instead of
1214continuing to execute further tests. (Suggested by Cliff Dyer and
1215implemented by Michael Foord; :issue:`8074`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001216
1217:class:`TestResult` has new :meth:`startTestRun` and
Andrew M. Kuchling9858f632010-03-23 18:39:24 +00001218:meth:`stopTestRun` methods that are called immediately before
1219and after a test run. (Contributed by Robert Collins; :issue:`5728`.)
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001220
1221With all these changes, the :file:`unittest.py` was becoming awkwardly
1222large, so the module was turned into a package and the code split into
1223several files (by Benjamin Peterson). This doesn't affect how the
1224module is imported.
1225
1226
1227.. _importlib-section:
1228
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001229importlib: Importing Modules
1230------------------------------
1231
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001232Python 3.1 includes the :mod:`importlib` package, a re-implementation
1233of the logic underlying Python's :keyword:`import` statement.
1234:mod:`importlib` is useful for implementors of Python interpreters and
Brett Cannonca2dc472009-12-22 02:37:37 +00001235to users who wish to write new importers that can participate in the
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001236import process. Python 2.7 doesn't contain the complete
1237:mod:`importlib` package, but instead has a tiny subset that contains
1238a single function, :func:`import_module`.
1239
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001240``import_module(name, package=None)`` imports a module. *name* is
Andrew M. Kuchling2c130b62009-04-11 16:12:23 +00001241a string containing the module or package's name. It's possible to do
1242relative imports by providing a string that begins with a ``.``
1243character, such as ``..utils.errors``. For relative imports, the
1244*package* argument must be provided and is the name of the package that
1245will be used as the anchor for
1246the relative import. :func:`import_module` both inserts the imported
1247module into ``sys.modules`` and returns the module object.
1248
1249Here are some examples::
1250
1251 >>> from importlib import import_module
1252 >>> anydbm = import_module('anydbm') # Standard absolute import
1253 >>> anydbm
1254 <module 'anydbm' from '/p/python/Lib/anydbm.py'>
1255 >>> # Relative import
1256 >>> sysconfig = import_module('..sysconfig', 'distutils.command')
1257 >>> sysconfig
1258 <module 'distutils.sysconfig' from '/p/python/Lib/distutils/sysconfig.pyc'>
1259
1260:mod:`importlib` was implemented by Brett Cannon and introduced in
1261Python 3.1.
1262
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001263
Andrew M. Kuchlinga17cd4a2009-01-31 02:50:09 +00001264ttk: Themed Widgets for Tk
1265--------------------------
1266
1267Tcl/Tk 8.5 includes a set of themed widgets that re-implement basic Tk
1268widgets but have a more customizable appearance and can therefore more
1269closely resemble the native platform's widgets. This widget
1270set was originally called Tile, but was renamed to Ttk (for "themed Tk")
1271on being added to Tcl/Tck release 8.5.
1272
1273XXX write a brief discussion and an example here.
1274
1275The :mod:`ttk` module was written by Guilherme Polo and added in
1276:issue:`2983`. An alternate version called ``Tile.py``, written by
1277Martin Franklin and maintained by Kevin Walzer, was proposed for
1278inclusion in :issue:`2618`, but the authors argued that Guilherme
1279Polo's work was more comprehensive.
1280
Georg Brandl0516f812009-11-18 18:52:35 +00001281
1282Deprecations and Removals
1283=========================
1284
1285* :func:`contextlib.nested`, which allows handling more than one context manager
1286 with one :keyword:`with` statement, has been deprecated; :keyword:`with`
1287 supports multiple context managers syntactically now.
1288
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001289.. ======================================================================
1290
1291
1292Build and C API Changes
1293=======================
1294
1295Changes to Python's build process and to the C API include:
1296
Andrew M. Kuchling10b1ec92009-01-02 21:00:35 +00001297* If you use the :file:`.gdbinit` file provided with Python,
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001298 the "pyo" macro in the 2.7 version now works correctly when the thread being
1299 debugged doesn't hold the GIL; the macro now acquires it before printing.
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001300 (Contributed by Victor Stinner; :issue:`3632`.)
1301
Andrew M. Kuchling9a4b94c2009-04-03 21:43:00 +00001302* :cfunc:`Py_AddPendingCall` is now thread-safe, letting any
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001303 worker thread submit notifications to the main Python thread. This
1304 is particularly useful for asynchronous IO operations.
1305 (Contributed by Kristjan Valur Jonsson; :issue:`4293`.)
1306
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001307* New function: :cfunc:`PyCode_NewEmpty` creates an empty code object;
1308 only the filename, function name, and first line number are required.
1309 This is useful to extension modules that are attempting to
1310 construct a more useful traceback stack. Previously such
1311 extensions needed to call :cfunc:`PyCode_New`, which had many
1312 more arguments. (Added by Jeffrey Yasskin.)
1313
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001314* New function: :cfunc:`PyErr_NewExceptionWithDoc` creates a new
1315 exception class, just as the existing :cfunc:`PyErr_NewException` does,
1316 but takes an extra ``char *`` argument containing the docstring for the
1317 new exception class. (Added by the 'lekma' user on the Python bug tracker;
1318 :issue:`7033`.)
1319
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001320* New function: :cfunc:`PyFrame_GetLineNumber` takes a frame object
1321 and returns the line number that the frame is currently executing.
1322 Previously code would need to get the index of the bytecode
1323 instruction currently executing, and then look up the line number
1324 corresponding to that address. (Added by Jeffrey Yasskin.)
1325
Andrew M. Kuchling17ae2ba2010-02-03 02:19:14 +00001326* New functions: :cfunc:`PyLong_AsLongAndOverflow` and
1327 :cfunc:`PyLong_AsLongLongAndOverflow` approximates a Python long
1328 integer as a C :ctype:`long` or :ctype:`long long`.
1329 If the number is too large to fit into
1330 the output type, an *overflow* flag is set and returned to the caller.
1331 (Contributed by Case Van Horsen; :issue:`7528` and :issue:`7767`.)
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001332
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00001333* New function: stemming from the rewrite of string-to-float conversion,
1334 a new :cfunc:`PyOS_string_to_double` function was added. The old
1335 :cfunc:`PyOS_ascii_strtod` and :cfunc:`PyOS_ascii_atof` functions
1336 are now deprecated.
1337
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001338* New macros: the Python header files now define the following macros:
1339 :cmacro:`Py_ISALNUM`,
1340 :cmacro:`Py_ISALPHA`,
1341 :cmacro:`Py_ISDIGIT`,
1342 :cmacro:`Py_ISLOWER`,
1343 :cmacro:`Py_ISSPACE`,
1344 :cmacro:`Py_ISUPPER`,
1345 :cmacro:`Py_ISXDIGIT`,
1346 and :cmacro:`Py_TOLOWER`, :cmacro:`Py_TOUPPER`.
1347 All of these functions are analogous to the C
1348 standard macros for classifying characters, but ignore the current
1349 locale setting, because in
1350 several places Python needs to analyze characters in a
1351 locale-independent way. (Added by Eric Smith;
1352 :issue:`5793`.)
1353
1354 .. XXX these macros don't seem to be described in the c-api docs.
1355
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001356* New format codes: the :cfunc:`PyFormat_FromString`,
1357 :cfunc:`PyFormat_FromStringV`, and :cfunc:`PyErr_Format` now
1358 accepts ``%lld`` and ``%llu`` format codes for displaying values of
1359 C's :ctype:`long long` types.
1360 (Contributed by Mark Dickinson; :issue:`7228`.)
1361
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001362* The complicated interaction between threads and process forking has
1363 been changed. Previously, the child process created by
1364 :func:`os.fork` might fail because the child is created with only a
1365 single thread running, the thread performing the :func:`os.fork`.
1366 If other threads were holding a lock, such as Python's import lock,
1367 when the fork was performed, the lock would still be marked as
1368 "held" in the new process. But in the child process nothing would
1369 ever release the lock, since the other threads weren't replicated,
1370 and the child process would no longer be able to perform imports.
1371
1372 Python 2.7 now acquires the import lock before performing an
1373 :func:`os.fork`, and will also clean up any locks created using the
1374 :mod:`threading` module. C extension modules that have internal
1375 locks, or that call :cfunc:`fork()` themselves, will not benefit
1376 from this clean-up.
1377
1378 (Fixed by Thomas Wouters; :issue:`1590864`.)
1379
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00001380* The :cfunc:`Py_Finalize` function now calls the internal
1381 :func:`threading._shutdown` function; this prevents some exceptions from
1382 being raised when an interpreter shuts down.
1383 (Patch by Adam Olsen; :issue:`1722344`.)
1384
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00001385* Global symbols defined by the :mod:`ctypes` module are now prefixed
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001386 with ``Py``, or with ``_ctypes``. (Implemented by Thomas
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00001387 Heller; :issue:`3102`.)
1388
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00001389* New configure option: the :option:`--with-system-expat` switch allows
1390 building the :mod:`pyexpat` module to use the system Expat library.
1391 (Contributed by Arfrever Frehtes Taifersar Arahesis; :issue:`7609`.)
1392
1393* New configure option: Compiling Python with the
1394 :option:`--with-valgrind` option will now disable the pymalloc
1395 allocator, which is difficult for the Valgrind to analyze correctly.
1396 Valgrind will therefore be better at detecting memory leaks and
1397 overruns. (Contributed by James Henstridge; :issue:`2422`.)
1398
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +00001399* New configure option: you can now supply no arguments to
1400 :option:`--with-dbmliborder=` in order to build none of the various
1401 DBM modules. (Added by Arfrever Frehtes Taifersar Arahesis;
1402 :issue:`6491`.)
1403
Andrew M. Kuchling77069572009-03-31 01:21:01 +00001404* The :program:`configure` script now checks for floating-point rounding bugs
1405 on certain 32-bit Intel chips and defines a :cmacro:`X87_DOUBLE_ROUNDING`
1406 preprocessor definition. No code currently uses this definition,
1407 but it's available if anyone wishes to use it.
1408 (Added by Mark Dickinson; :issue:`2937`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001409
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001410* The build process now creates the necessary files for pkg-config
1411 support. (Contributed by Clinton Roy; :issue:`3585`.)
1412
1413* The build process now supports Subversion 1.7. (Contributed by
1414 Arfrever Frehtes Taifersar Arahesis; :issue:`6094`.)
1415
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001416
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001417.. ======================================================================
1418
1419Port-Specific Changes: Windows
1420-----------------------------------
1421
Andrew M. Kuchling10b1ec92009-01-02 21:00:35 +00001422* The :mod:`msvcrt` module now contains some constants from
1423 the :file:`crtassem.h` header file:
1424 :data:`CRT_ASSEMBLY_VERSION`,
1425 :data:`VC_ASSEMBLY_PUBLICKEYTOKEN`,
1426 and :data:`LIBRARIES_ASSEMBLY_NAME_PREFIX`.
Andrew M. Kuchling466bd9d2009-01-24 03:28:18 +00001427 (Contributed by David Cournapeau; :issue:`4365`.)
1428
1429* The new :cfunc:`_beginthreadex` API is used to start threads, and
1430 the native thread-local storage functions are now used.
1431 (Contributed by Kristjan Valur Jonsson; :issue:`3582`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001432
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001433* The :func:`os.listdir` function now correctly fails
1434 for an empty path. (Fixed by Hirokazu Yamamoto; :issue:`5913`.)
1435
Andrew M. Kuchling3c8a24e2009-12-29 23:41:04 +00001436* The :mod:`mimelib` module will now read the MIME database from
1437 the Windows registry when initializing.
1438 (Patch by Gabriel Genellina; :issue:`4969`.)
1439
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001440.. ======================================================================
1441
1442Port-Specific Changes: Mac OS X
1443-----------------------------------
1444
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001445* The path ``/Library/Python/2.7/site-packages`` is now appended to
Andrew M. Kuchling77069572009-03-31 01:21:01 +00001446 ``sys.path``, in order to share added packages between the system
1447 installation and a user-installed copy of the same version.
1448 (Changed by Ronald Oussoren; :issue:`4865`.)
1449
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001450
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001451Other Changes and Fixes
1452=======================
1453
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00001454* Two benchmark scripts, :file:`iobench` and :file:`ccbench`, were
1455 added to the :file:`Tools` directory. :file:`iobench` measures the
Antoine Pitroudde96e62010-02-08 20:25:47 +00001456 speed of built-in file I/O objects (as returned by :func:`open`)
Andrew M. Kuchling46c2db52010-03-21 18:47:12 +00001457 while performing various operations, and :file:`ccbench` is a
1458 concurrency benchmark that tries to measure computing throughput,
1459 thread switching latency, and IO processing bandwidth when
1460 performing several tasks using a varying number of threads.
Andrew M. Kuchling0e7123f2010-02-08 13:22:24 +00001461
Andrew M. Kuchling77069572009-03-31 01:21:01 +00001462* When importing a module from a :file:`.pyc` or :file:`.pyo` file
1463 with an existing :file:`.py` counterpart, the :attr:`co_filename`
Andrew M. Kuchling92b97002009-05-02 17:12:15 +00001464 attributes of the resulting code objects are overwritten when the
1465 original filename is obsolete. This can happen if the file has been
1466 renamed, moved, or is accessed through different paths. (Patch by
1467 Ziga Seilnacht and Jean-Paul Calderone; :issue:`1180193`.)
Andrew M. Kuchling77069572009-03-31 01:21:01 +00001468
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001469* The :file:`regrtest.py` script now takes a :option:`--randseed=`
1470 switch that takes an integer that will be used as the random seed
1471 for the :option:`-r` option that executes tests in random order.
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001472 The :option:`-r` option also reports the seed that was used
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001473 (Added by Collin Winter.)
1474
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00001475* Another :file:`regrtest.py` switch is :option:`-j`, which
1476 takes an integer specifying how many tests run in parallel. This
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001477 allows reducing the total runtime on multi-core machines.
Antoine Pitrou4698d992009-05-31 14:20:14 +00001478 This option is compatible with several other options, including the
1479 :option:`-R` switch which is known to produce long runtimes.
Andrew M. Kuchling91e0db82009-12-31 16:17:05 +00001480 (Added by Antoine Pitrou, :issue:`6152`.) This can also be used
1481 with a new :option:`-F` switch that runs selected tests in a loop
1482 until they fail. (Added by Antoine Pitrou; :issue:`7312`.)
Andrew M. Kuchling71d5c282009-03-30 22:30:20 +00001483
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001484.. ======================================================================
1485
1486Porting to Python 2.7
1487=====================
1488
1489This section lists previously described changes and other bugfixes
1490that may require changes to your code:
1491
Andrew M. Kuchling5a9c40b2009-10-05 22:30:22 +00001492* When using :class:`Decimal` instances with a string's
1493 :meth:`format` method, the default alignment was previously
1494 left-alignment. This has been changed to right-alignment, which might
1495 change the output of your programs.
1496 (Changed by Mark Dickinson; :issue:`6857`.)
1497
1498 Another :meth:`format`-related change: the default precision used
1499 for floating-point and complex numbers was changed from 6 decimal
1500 places to 12, which matches the precision used by :func:`str`.
1501 (Changed by Eric Smith; :issue:`5920`.)
1502
Amaury Forgeot d'Arc901f2002009-06-09 23:08:13 +00001503* Because of an optimization for the :keyword:`with` statement, the special
1504 methods :meth:`__enter__` and :meth:`__exit__` must belong to the object's
1505 type, and cannot be directly attached to the object's instance. This
Amaury Forgeot d'Arcd81333c2009-06-10 20:30:19 +00001506 affects new-style classes (derived from :class:`object`) and C extension
Amaury Forgeot d'Arc901f2002009-06-09 23:08:13 +00001507 types. (:issue:`6101`.)
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001508
Andrew M. Kuchlingb4a4f512009-12-29 20:10:16 +00001509* The :meth:`readline` method of :class:`StringIO` objects now does
1510 nothing when a negative length is requested, as other file-like
1511 objects do. (:issue:`7348`).
1512
Andrew M. Kuchlinge41e4db2010-02-18 14:16:48 +00001513In the standard library:
1514
1515* The ElementTree library, :mod:`xml.etree`, no longer escapes
1516 ampersands and angle brackets when outputting an XML processing
1517 instruction (which looks like `<?xml-stylesheet href="#style1"?>`)
1518 or comment (which looks like `<!-- comment -->`).
1519 (Patch by Neil Muller; :issue:`2746`.)
1520
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00001521For C extensions:
1522
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +00001523* C extensions that use integer format codes with the ``PyArg_Parse*``
1524 family of functions will now raise a :exc:`TypeError` exception
1525 instead of triggering a :exc:`DeprecationWarning` (:issue:`5080`).
1526
Andrew M. Kuchlinga7f59472009-12-31 16:38:53 +00001527* Use the new :cfunc:`PyOS_string_to_double` function instead of the old
1528 :cfunc:`PyOS_ascii_strtod` and :cfunc:`PyOS_ascii_atof` functions,
1529 which are now deprecated.
1530
Andrew M. Kuchling7f8ebdb2010-01-03 01:15:21 +00001531
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001532.. ======================================================================
1533
1534
1535.. _acks27:
1536
1537Acknowledgements
1538================
1539
1540The author would like to thank the following people for offering
1541suggestions, corrections and assistance with various drafts of this
Andrew M. Kuchling8f254e72009-12-08 02:37:05 +00001542article: Ryan Lovett, Hugh Secker-Walker.
Andrew M. Kuchlingce1882b2008-10-04 16:52:31 +00001543