blob: 2814915f2a00cd98d314aa5937a38741a9f01625 [file] [log] [blame]
Benjamin Petersonf10a79a2008-10-11 00:49:57 +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
Benjamin Petersond23f8222009-04-05 19:13:16 +00009.. Fix accents on Kristjan Valur Jonsson, Fuerstenau, Tarek Ziade.
Benjamin Peterson1010bf32009-01-30 04:00:29 +000010
Benjamin Petersonf10a79a2008-10-11 00:49:57 +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
Benjamin Peterson9eea4802009-12-31 03:31:15 +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`.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000055
56.. Compare with previous release in 2 - 3 sentences here.
57 add hyperlink when the documentation becomes available online.
58
Benjamin Petersonf6489f92009-11-25 17:46:26 +000059.. _whatsnew27-python31:
60
61Python 3.1 Features
62=======================
Benjamin Petersond23f8222009-04-05 19:13:16 +000063
64Much as Python 2.6 incorporated features from Python 3.0,
Benjamin Petersonf6489f92009-11-25 17:46:26 +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.
Benjamin Petersond23f8222009-04-05 19:13:16 +000068
Benjamin Petersonf6489f92009-11-25 17:46:26 +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`.
Benjamin Peterson97dd9872009-12-13 01:23:39 +000073* The new format specifier described in :ref:`pep-0378`.
Benjamin Petersonf6489f92009-11-25 17:46:26 +000074* The :class:`memoryview` object.
75* A small subset of the :mod:`importlib` module `described below <#importlib-section>`__.
Benjamin Peterson9eea4802009-12-31 03:31:15 +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.
Benjamin Petersond23f8222009-04-05 19:13:16 +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
Benjamin Petersonf6489f92009-11-25 17:46:26 +000086Other new Python3-mode warnings include:
87
88* :func:`operator.isCallable` and :func:`operator.sequenceIncludes`,
89 which are not supported in 3.x.
90
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000091.. ========================================================================
92.. Large, PEP-level features and changes should be described here.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000093.. ========================================================================
94
Benjamin Petersonf6489f92009-11-25 17:46:26 +000095.. _pep-0372:
96
Benjamin Petersond23f8222009-04-05 19:13:16 +000097PEP 372: Adding an ordered dictionary to collections
98====================================================
99
Benjamin Petersonf6489f92009-11-25 17:46:26 +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.
Benjamin Petersond23f8222009-04-05 19:13:16 +0000105
Benjamin Petersonf6489f92009-11-25 17:46:26 +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::
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000109
Benjamin Petersonf6489f92009-11-25 17:46:26 +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
179.. 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.
184
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
213.. XXX "Format String Syntax" in string.rst could use many more examples.
214
215.. seealso::
216
217 :pep:`378` - Format Specifier for Thousands Separator
218 PEP written by Raymond Hettinger; implemented by Eric Smith.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000219
220Other Language Changes
221======================
222
223Some smaller changes made to the core Python language are:
224
Benjamin Petersonf6489f92009-11-25 17:46:26 +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
Benjamin Peterson9eea4802009-12-31 03:31:15 +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
267 used on such systems.
268
Mark Dickinson0bc8f902010-01-07 09:31:48 +0000269 Implemented by Eric Smith and Mark Dickinson, using David Gay's
270 :file:`dtoa.c` library; :issue:`7117`.
Benjamin Peterson9eea4802009-12-31 03:31:15 +0000271
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000272* The :meth:`str.format` method now supports automatic numbering of the replacement
Benjamin Peterson3f96a872009-04-11 20:58:12 +0000273 fields. This makes using :meth:`str.format` more closely resemble using
274 ``%s`` formatting::
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000275
276 >>> '{}:{}:{}'.format(2009, 04, 'Sunday')
277 '2009:4:Sunday'
278 >>> '{}:{}:{day}'.format(2009, 4, day='Sunday')
279 '2009:4:Sunday'
280
Benjamin Peterson3f96a872009-04-11 20:58:12 +0000281 The auto-numbering takes the fields from left to right, so the first ``{...}``
282 specifier will use the first argument to :meth:`str.format`, the next
283 specifier will use the next argument, and so on. You can't mix auto-numbering
284 and explicit numbering -- either number all of your specifier fields or none
285 of them -- but you can mix auto-numbering and named fields, as in the second
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000286 example above. (Contributed by Eric Smith; :issue:`5237`.)
287
288 Complex numbers now correctly support usage with :func:`format`.
289 Specifying a precision or comma-separation applies to both the real
290 and imaginary parts of the number, but a specified field width and
291 alignment is applied to the whole of the resulting ``1.5+3j``
292 output. (Contributed by Eric Smith; :issue:`1588`.)
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000293
Benjamin Peterson9eea4802009-12-31 03:31:15 +0000294 The 'F' format code now always formats its output using uppercase characters,
295 so it will now produce 'INF' and 'NAN'.
296 (Contributed by Eric Smith; :issue:`3382`.)
297
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000298* The :func:`int` and :func:`long` types gained a ``bit_length``
299 method that returns the number of bits necessary to represent
300 its argument in binary::
301
302 >>> n = 37
303 >>> bin(37)
304 '0b100101'
305 >>> n.bit_length()
306 6
307 >>> n = 2**123-1
308 >>> n.bit_length()
309 123
310 >>> (n+1).bit_length()
311 124
312
313 (Contributed by Fredrik Johansson and Victor Stinner; :issue:`3439`.)
314
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000315* Conversions from long integers and regular integers to floating
316 point now round differently, returning the floating-point number
317 closest to the number. This doesn't matter for small integers that
318 can be converted exactly, but for large numbers that will
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000319 unavoidably lose precision, Python 2.7 now approximates more
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000320 closely. For example, Python 2.6 computed the following::
321
322 >>> n = 295147905179352891391
323 >>> float(n)
324 2.9514790517935283e+20
325 >>> n - long(float(n))
326 65535L
327
328 Python 2.7's floating-point result is larger, but much closer to the
329 true value::
330
331 >>> n = 295147905179352891391
332 >>> float(n)
333 2.9514790517935289e+20
334 >>> n-long(float(n)
335 ... )
336 -1L
337
338 (Implemented by Mark Dickinson; :issue:`3166`.)
339
Benjamin Peterson9eea4802009-12-31 03:31:15 +0000340 Integer division is also more accurate in its rounding behaviours. (Also
341 implemented by Mark Dickinson; :issue:`1811`.)
342
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000343* The :class:`bytearray` type's :meth:`translate` method now accepts
344 ``None`` as its first argument. (Fixed by Georg Brandl;
Benjamin Petersond23f8222009-04-05 19:13:16 +0000345 :issue:`4759`.)
Mark Dickinsond72c7b62009-03-20 16:00:49 +0000346
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000347* When using ``@classmethod`` and ``@staticmethod`` to wrap
348 methods as class or static methods, the wrapper object now
349 exposes the wrapped function as their :attr:`__func__` attribute.
350 (Contributed by Amaury Forgeot d'Arc, after a suggestion by
351 George Sakkis; :issue:`5982`.)
352
353* A new encoding named "cp720", used primarily for Arabic text, is now
354 supported. (Contributed by Alexander Belchenko and Amaury Forgeot
355 d'Arc; :issue:`1616979`.)
356
Benjamin Peterson9eea4802009-12-31 03:31:15 +0000357* The :class:`file` object will now set the :attr:`filename` attribute
358 on the :exc:`IOError` exception when trying to open a directory
359 on POSIX platforms. (Noted by Jan Kaliszewski; :issue:`4764`.)
360
361* Extra parentheses in function definitions are illegal in Python 3.x,
362 meaning that you get a syntax error from ``def f((x)): pass``. In
363 Python3-warning mode, Python 2.7 will now warn about this odd usage.
364 (Noted by James Lingard; :issue:`7362`.)
365
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000366.. ======================================================================
367
368
369Optimizations
370-------------
371
Benjamin Petersond23f8222009-04-05 19:13:16 +0000372Several performance enhancements have been added:
373
374.. * A new :program:`configure` option, :option:`--with-computed-gotos`,
375 compiles the main bytecode interpreter loop using a new dispatch
376 mechanism that gives speedups of up to 20%, depending on the system
377 and benchmark. The new mechanism is only supported on certain
378 compilers, such as gcc, SunPro, and icc.
Benjamin Peterson1010bf32009-01-30 04:00:29 +0000379
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000380* A new opcode was added to perform the initial setup for
381 :keyword:`with` statements, looking up the :meth:`__enter__` and
382 :meth:`__exit__` methods. (Contributed by Benjamin Peterson.)
383
Benjamin Peterson9eea4802009-12-31 03:31:15 +0000384* The garbage collector now performs better for one common usage
385 pattern: when many objects are being allocated without deallocating
386 any of them. This would previously take quadratic
387 time for garbage collection, but now the number of full garbage collections
388 is reduced as the number of objects on the heap grows.
389 The new logic is to only perform a full garbage collection pass when
390 the middle generation has been collected 10 times and when the
391 number of survivor objects from the middle generation exceeds 10% of
392 the number of objects in the oldest generation. (Suggested by Martin
393 von Loewis and implemented by Antoine Pitrou; :issue:`4074`.)
Benjamin Peterson1010bf32009-01-30 04:00:29 +0000394
Benjamin Petersond23f8222009-04-05 19:13:16 +0000395* The garbage collector tries to avoid tracking simple containers
396 which can't be part of a cycle. In Python 2.7, this is now true for
397 tuples and dicts containing atomic types (such as ints, strings,
398 etc.). Transitively, a dict containing tuples of atomic types won't
399 be tracked either. This helps reduce the cost of each
400 garbage collection by decreasing the number of objects to be
401 considered and traversed by the collector.
Antoine Pitrou9d81def2009-03-28 19:20:09 +0000402 (Contributed by Antoine Pitrou; :issue:`4688`.)
403
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000404* Long integers are now stored internally either in base 2**15 or in base
Benjamin Petersond23f8222009-04-05 19:13:16 +0000405 2**30, the base being determined at build time. Previously, they
406 were always stored in base 2**15. Using base 2**30 gives
407 significant performance improvements on 64-bit machines, but
408 benchmark results on 32-bit machines have been mixed. Therefore,
409 the default is to use base 2**30 on 64-bit machines and base 2**15
410 on 32-bit machines; on Unix, there's a new configure option
411 :option:`--enable-big-digits` that can be used to override this default.
412
413 Apart from the performance improvements this change should be
414 invisible to end users, with one exception: for testing and
415 debugging purposes there's a new structseq ``sys.long_info`` that
416 provides information about the internal format, giving the number of
417 bits per digit and the size in bytes of the C type used to store
418 each digit::
419
420 >>> import sys
421 >>> sys.long_info
422 sys.long_info(bits_per_digit=30, sizeof_digit=4)
423
424 (Contributed by Mark Dickinson; :issue:`4258`.)
425
426 Another set of changes made long objects a few bytes smaller: 2 bytes
427 smaller on 32-bit systems and 6 bytes on 64-bit.
428 (Contributed by Mark Dickinson; :issue:`5260`.)
429
430* The division algorithm for long integers has been made faster
431 by tightening the inner loop, doing shifts instead of multiplications,
432 and fixing an unnecessary extra iteration.
433 Various benchmarks show speedups of between 50% and 150% for long
434 integer divisions and modulo operations.
435 (Contributed by Mark Dickinson; :issue:`5512`.)
436
437* The implementation of ``%`` checks for the left-side operand being
438 a Python string and special-cases it; this results in a 1-3%
439 performance increase for applications that frequently use ``%``
440 with strings, such as templating libraries.
441 (Implemented by Collin Winter; :issue:`5176`.)
442
443* List comprehensions with an ``if`` condition are compiled into
444 faster bytecode. (Patch by Antoine Pitrou, back-ported to 2.7
445 by Jeffrey Yasskin; :issue:`4715`.)
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000446
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000447* The :mod:`pickle` and :mod:`cPickle` modules now automatically
448 intern the strings used for attribute names, reducing memory usage
449 of the objects resulting from unpickling. (Contributed by Jake
450 McGuire; :issue:`5084`.)
451
452* The :mod:`cPickle` module now special-cases dictionaries,
453 nearly halving the time required to pickle them.
454 (Contributed by Collin Winter; :issue:`5670`.)
455
456* Converting an integer or long integer to a decimal string was made
457 faster by special-casing base 10 instead of using a generalized
458 conversion function that supports arbitrary bases.
459 (Patch by Gawain Bolton; :issue:`6713`.)
460
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000461.. ======================================================================
462
Georg Brandl4d131ee2009-11-18 18:53:14 +0000463New and Improved Modules
464========================
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000465
466As in every release, Python's standard library received a number of
467enhancements and bug fixes. Here's a partial list of the most notable
468changes, sorted alphabetically by module name. Consult the
469:file:`Misc/NEWS` file in the source tree for a more complete list of
470changes, or look through the Subversion logs for all the details.
471
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000472* The :mod:`bdb` module's base debugging class :class:`Bdb`
473 gained a feature for skipping modules. The constructor
474 now takes an iterable containing glob-style patterns such as
475 ``django.*``; the debugger will not step into stack frames
476 from a module that matches one of these patterns.
477 (Contributed by Maru Newby after a suggestion by
478 Senthil Kumaran; :issue:`5142`.)
479
Benjamin Peterson1010bf32009-01-30 04:00:29 +0000480* The :mod:`bz2` module's :class:`BZ2File` now supports the context
481 management protocol, so you can write ``with bz2.BZ2File(...) as f: ...``.
482 (Contributed by Hagen Fuerstenau; :issue:`3860`.)
483
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000484* New class: the :class:`Counter` class in the :mod:`collections` module is
Benjamin Peterson1010bf32009-01-30 04:00:29 +0000485 useful for tallying data. :class:`Counter` instances behave mostly
486 like dictionaries but return zero for missing keys instead of
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000487 raising a :exc:`KeyError`:
Benjamin Peterson1010bf32009-01-30 04:00:29 +0000488
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000489 .. doctest::
490 :options: +NORMALIZE_WHITESPACE
491
492 >>> from collections import Counter
493 >>> c = Counter()
494 >>> for letter in 'here is a sample of english text':
495 ... c[letter] += 1
496 ...
497 >>> c
498 Counter({' ': 6, 'e': 5, 's': 3, 'a': 2, 'i': 2, 'h': 2,
499 'l': 2, 't': 2, 'g': 1, 'f': 1, 'm': 1, 'o': 1, 'n': 1,
500 'p': 1, 'r': 1, 'x': 1})
501 >>> c['e']
502 5
503 >>> c['z']
504 0
Benjamin Peterson1010bf32009-01-30 04:00:29 +0000505
506 There are two additional :class:`Counter` methods: :meth:`most_common`
507 returns the N most common elements and their counts, and :meth:`elements`
508 returns an iterator over the contained element, repeating each element
509 as many times as its count::
510
511 >>> c.most_common(5)
512 [(' ', 6), ('e', 5), ('s', 3), ('a', 2), ('i', 2)]
513 >>> c.elements() ->
514 'a', 'a', ' ', ' ', ' ', ' ', ' ', ' ',
515 'e', 'e', 'e', 'e', 'e', 'g', 'f', 'i', 'i',
516 'h', 'h', 'm', 'l', 'l', 'o', 'n', 'p', 's',
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000517 's', 's', 'r', 't', 't', 'x'
Benjamin Peterson1010bf32009-01-30 04:00:29 +0000518
519 Contributed by Raymond Hettinger; :issue:`1696199`.
520
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000521 The new `OrderedDict` class is described in the earlier section
522 :ref:`pep-0372`.
523
Benjamin Petersond23f8222009-04-05 19:13:16 +0000524 The :class:`namedtuple` class now has an optional *rename* parameter.
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000525 If *rename* is true, field names that are invalid because they've
Benjamin Petersond23f8222009-04-05 19:13:16 +0000526 been repeated or that aren't legal Python identifiers will be
527 renamed to legal names that are derived from the field's
528 position within the list of fields:
529
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000530 >>> from collections import namedtuple
531 >>> T = namedtuple('T', ['field1', '$illegal', 'for', 'field2'], rename=True)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000532 >>> T._fields
533 ('field1', '_1', '_2', 'field2')
534
535 (Added by Raymond Hettinger; :issue:`1818`.)
536
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000537 The :class:`deque` data type now exposes its maximum length as the
Benjamin Peterson9eea4802009-12-31 03:31:15 +0000538 read-only :attr:`maxlen` attribute, and has a
539 :meth:`reverse` method that reverses the elements of the deque in-place.
540 (Added by Raymond Hettinger.)
541
542* The :mod:`copy` module's :func:`deepcopy` function will now
543 correctly copy bound instance methods. (Implemented by
544 Robert Collins; :issue:`1515`.)
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000545
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000546* The :mod:`ctypes` module now always converts ``None`` to a C NULL
547 pointer for arguments declared as pointers. (Changed by Thomas
548 Heller; :issue:`4606`.)
549
Benjamin Peterson9eea4802009-12-31 03:31:15 +0000550* New method: the :mod:`datetime` module's :class:`timedelta` class
551 gained a :meth:`total_seconds` method that returns the number of seconds
552 in the duration. (Contributed by Brian Quinlan; :issue:`5788`.)
553
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000554* New method: the :class:`Decimal` class gained a
555 :meth:`from_float` class method that performs an exact conversion
556 of a floating-point number to a :class:`Decimal`.
557 Note that this is an **exact** conversion that strives for the
558 closest decimal approximation to the floating-point representation's value;
559 the resulting decimal value will therefore still include the inaccuracy,
560 if any.
561 For example, ``Decimal.from_float(0.1)`` returns
562 ``Decimal('0.1000000000000000055511151231257827021181583404541015625')``.
563 (Implemented by Raymond Hettinger; :issue:`4796`.)
564
565 The constructor for :class:`Decimal` now accepts non-European
566 Unicode characters, such as Arabic-Indic digits. (Contributed by
567 Mark Dickinson; :issue:`6595`.)
568
569 When using :class:`Decimal` instances with a string's
570 :meth:`format` method, the default alignment was previously
571 left-alignment. This has been changed to right-alignment, which seems
572 more sensible for numeric types. (Changed by Mark Dickinson; :issue:`6857`.)
573
574* Distutils is being more actively developed, thanks to Tarek Ziade
Benjamin Peterson97dd9872009-12-13 01:23:39 +0000575 who has taken over maintenance of the package. A new
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000576 :file:`setup.py` subcommand, ``check``, will
577 check that the arguments being passed to the :func:`setup` function
578 are complete and correct (:issue:`5732`).
579
580 :func:`distutils.sdist.add_defaults` now uses
Benjamin Petersond23f8222009-04-05 19:13:16 +0000581 *package_dir* and *data_files* to create the MANIFEST file.
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000582 :mod:`distutils.sysconfig` now reads the :envvar:`AR` and
583 :envvar:`ARFLAGS` environment variables.
584
585 .. ARFLAGS done in #5941
Benjamin Petersond23f8222009-04-05 19:13:16 +0000586
587 It is no longer mandatory to store clear-text passwords in the
588 :file:`.pypirc` file when registering and uploading packages to PyPI. As long
589 as the username is present in that file, the :mod:`distutils` package will
590 prompt for the password if not present. (Added by Tarek Ziade,
591 based on an initial contribution by Nathan Van Gheem; :issue:`4394`.)
592
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000593 A Distutils setup can now specify that a C extension is optional by
594 setting the *optional* option setting to true. If this optional is
595 supplied, failure to build the extension will not abort the build
596 process, but instead simply not install the failing extension.
597 (Contributed by Georg Brandl; :issue:`5583`.)
598
Benjamin Peterson9eea4802009-12-31 03:31:15 +0000599 The :class:`distutils.dist.DistributionMetadata` class'
600 :meth:`read_pkg_file` method will read the contents of a package's
601 :file:`PKG-INFO` metadata file. For an example of its use,
602 XXX link to file:///MacDev/svn.python.org/python-trunk/Doc/build/html/distutils/examples.html#reading-the-metadata
603 (Contributed by Tarek Ziade; :issue:`7457`.)
Tarek Ziadéb88a4962009-12-08 09:45:25 +0000604
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000605* The :class:`Fraction` class now accepts two rational numbers
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000606 as arguments to its constructor.
607 (Implemented by Mark Dickinson; :issue:`5812`.)
608
Benjamin Peterson9eea4802009-12-31 03:31:15 +0000609* The :mod:`ftplib` module gained the ability to establish secure FTP
610 connections using TLS encapsulation of authentication as well as
611 subsequent control and data transfers. This is provided by the new
612 :class:`ftplib.FTP_TLS` class.
613 (Contributed by Giampaolo Rodola', :issue:`2054`.) The :meth:`storbinary`
614 method for binary uploads can now restart uploads thanks to an added
615 *rest* parameter (patch by Pablo Mouzo; :issue:`6845`.)
616
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000617* New function: the :mod:`gc` module's :func:`is_tracked` returns
618 true if a given instance is tracked by the garbage collector, false
Benjamin Petersond23f8222009-04-05 19:13:16 +0000619 otherwise. (Contributed by Antoine Pitrou; :issue:`4688`.)
620
Benjamin Peterson1010bf32009-01-30 04:00:29 +0000621* The :mod:`gzip` module's :class:`GzipFile` now supports the context
622 management protocol, so you can write ``with gzip.GzipFile(...) as f: ...``.
623 (Contributed by Hagen Fuerstenau; :issue:`3860`.)
Benjamin Petersond23f8222009-04-05 19:13:16 +0000624 It's now possible to override the modification time
625 recorded in a gzipped file by providing an optional timestamp to
626 the constructor. (Contributed by Jacques Frechet; :issue:`4272`.)
Benjamin Peterson1010bf32009-01-30 04:00:29 +0000627
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000628* The :mod:`hashlib` module was inconsistent about accepting
629 input as a Unicode object or an object that doesn't support
630 the buffer protocol. The behavior was different depending on
631 whether :mod:`hashlib` was using an external OpenSSL library
632 or its built-in implementations. Python 2.7 makes the
633 behavior consistent, always rejecting such objects by raising a
634 :exc:`TypeError`. (Fixed by Gregory P. Smith; :issue:`3745`.)
635
636* The default :class:`HTTPResponse` class used by the :mod:`httplib` module now
637 supports buffering, resulting in much faster reading of HTTP responses.
638 (Contributed by Kristjan Valur Jonsson; :issue:`4879`.)
639
640* The :mod:`imaplib` module now supports IPv6 addresses.
641 (Contributed by Derek Morr; :issue:`1655`.)
642
643* The :mod:`io` library has been upgraded to the version shipped with
644 Python 3.1. For 3.1, the I/O library was entirely rewritten in C
645 and is 2 to 20 times faster depending on the task at hand. The
646 original Python version was renamed to the :mod:`_pyio` module.
647
648 One minor resulting change: the :class:`io.TextIOBase` class now
649 has an :attr:`errors` attribute giving the error setting
650 used for encoding and decoding errors (one of ``'strict'``, ``'replace'``,
651 ``'ignore'``).
652
653 The :class:`io.FileIO` class now raises an :exc:`OSError` when passed
Benjamin Peterson1010bf32009-01-30 04:00:29 +0000654 an invalid file descriptor. (Implemented by Benjamin Peterson;
655 :issue:`4991`.)
656
Benjamin Peterson97dd9872009-12-13 01:23:39 +0000657* New function: ``itertools.compress(data, selectors)`` takes two
Benjamin Petersond23f8222009-04-05 19:13:16 +0000658 iterators. Elements of *data* are returned if the corresponding
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000659 value in *selectors* is true::
Benjamin Petersond23f8222009-04-05 19:13:16 +0000660
661 itertools.compress('ABCDEF', [1,0,1,0,1,1]) =>
662 A, C, E, F
663
Benjamin Peterson97dd9872009-12-13 01:23:39 +0000664 New function: ``itertools.combinations_with_replacement(iter, r)``
Benjamin Petersond23f8222009-04-05 19:13:16 +0000665 returns all the possible *r*-length combinations of elements from the
666 iterable *iter*. Unlike :func:`combinations`, individual elements
667 can be repeated in the generated combinations::
668
669 itertools.combinations_with_replacement('abc', 2) =>
670 ('a', 'a'), ('a', 'b'), ('a', 'c'),
671 ('b', 'b'), ('b', 'c'), ('c', 'c')
672
673 Note that elements are treated as unique depending on their position
674 in the input, not their actual values.
675
676 The :class:`itertools.count` function now has a *step* argument that
677 allows incrementing by values other than 1. :func:`count` also
678 now allows keyword arguments, and using non-integer values such as
679 floats or :class:`Decimal` instances. (Implemented by Raymond
680 Hettinger; :issue:`5032`.)
681
682 :func:`itertools.combinations` and :func:`itertools.product` were
683 previously raising :exc:`ValueError` for values of *r* larger than
684 the input iterable. This was deemed a specification error, so they
685 now return an empty iterator. (Fixed by Raymond Hettinger; :issue:`4816`.)
686
687* The :mod:`json` module was upgraded to version 2.0.9 of the
688 simplejson package, which includes a C extension that makes
689 encoding and decoding faster.
690 (Contributed by Bob Ippolito; :issue:`4136`.)
691
692 To support the new :class:`OrderedDict` type, :func:`json.load`
693 now has an optional *object_pairs_hook* parameter that will be called
694 with any object literal that decodes to a list of pairs.
695 (Contributed by Raymond Hettinger; :issue:`5381`.)
696
Benjamin Peterson9eea4802009-12-31 03:31:15 +0000697* New functions: the :mod:`math` module gained
698 :func:`erf` and :func:`erfc` for the error function and the complementary error function,
699 :func:`expm1` which computes ``e**x - 1`` with more precision than
700 using :func:`exp` and subtracting 1,
701 :func:`gamma` for the Gamma function, and
702 :func:`lgamma` for the natural log of the Gamma function.
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000703 (Contributed by Mark Dickinson and nirinA raseliarison; :issue:`3366`.)
704
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000705* The :mod:`multiprocessing` module's :class:`Manager*` classes
706 can now be passed a callable that will be called whenever
707 a subprocess is started, along with a set of arguments that will be
708 passed to the callable.
709 (Contributed by lekma; :issue:`5585`.)
710
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000711* The :mod:`nntplib` module now supports IPv6 addresses.
712 (Contributed by Derek Morr; :issue:`1664`.)
713
Benjamin Peterson9eea4802009-12-31 03:31:15 +0000714* New functions: the :mod:`os` module wraps the following POSIX system
715 calls: :func:`getresgid` and :func:`getresuid`, which return the
716 real, effective, and saved GIDs and UIDs;
717 :func:`setresgid` and :func:`setresuid`, which set
718 real, effective, and saved GIDs and UIDs to new values;
719 :func:`initgroups`. (GID/UID functions
720 contributed by Travis H.; :issue:`6508`. Support for initgroups added
721 by Jean-Paul Calderone; :issue:`7333`.)
722
Benjamin Peterson1010bf32009-01-30 04:00:29 +0000723* The :mod:`pydoc` module now has help for the various symbols that Python
724 uses. You can now do ``help('<<')`` or ``help('@')``, for example.
725 (Contributed by David Laban; :issue:`4739`.)
726
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000727* The :mod:`re` module's :func:`split`, :func:`sub`, and :func:`subn`
728 now accept an optional *flags* argument, for consistency with the
729 other functions in the module. (Added by Gregory P. Smith.)
730
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000731* The :mod:`shutil` module's :func:`copyfile` and :func:`copytree`
732 functions now raises a :exc:`SpecialFileError` exception when
733 asked to copy a named pipe. Previously the code would treat
734 named pipes like a regular file by opening them for reading, and
735 this would block indefinitely. (Fixed by Antoine Pitrou; :issue:`3002`.)
736
737* New functions: in the :mod:`site` module, three new functions
738 return various site- and user-specific paths.
739 :func:`getsitepackages` returns a list containing all
740 global site-packages directories, and
741 :func:`getusersitepackages` returns the path of the user's
742 site-packages directory.
Ezio Melotti6e40e272010-01-04 09:29:10 +0000743 :func:`getuserbase` returns the value of the :envvar:`USER_BASE`
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000744 environment variable, giving the path to a directory that can be used
745 to store data.
746 (Contributed by Tarek Ziade; :issue:`6693`.)
747
748* The :mod:`SocketServer` module's :class:`TCPServer` class now
749 has a :attr:`disable_nagle_algorithm` class attribute.
750 The default value is False; if overridden to be True,
751 new request connections will have the TCP_NODELAY option set to
752 prevent buffering many small sends into a single TCP packet.
753 (Contributed by Kristjan Valur Jonsson; :issue:`6192`.)
754
755* The :mod:`struct` module will no longer silently ignore overflow
756 errors when a value is too large for a particular integer format
757 code (one of ``bBhHiIlLqQ``); it now always raises a
758 :exc:`struct.error` exception. (Changed by Mark Dickinson;
759 :issue:`1523`.)
760
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000761* New function: the :mod:`subprocess` module's
762 :func:`check_output` runs a command with a specified set of arguments
Benjamin Petersond23f8222009-04-05 19:13:16 +0000763 and returns the command's output as a string when the command runs without
Georg Brandl1f01deb2009-01-03 22:47:39 +0000764 error, or raises a :exc:`CalledProcessError` exception otherwise.
765
766 ::
767
768 >>> subprocess.check_output(['df', '-h', '.'])
769 'Filesystem Size Used Avail Capacity Mounted on\n
770 /dev/disk0s2 52G 49G 3.0G 94% /\n'
771
772 >>> subprocess.check_output(['df', '-h', '/bogus'])
773 ...
774 subprocess.CalledProcessError: Command '['df', '-h', '/bogus']' returned non-zero exit status 1
775
776 (Contributed by Gregory P. Smith.)
777
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000778* New function: :func:`is_declared_global` in the :mod:`symtable` module
779 returns true for variables that are explicitly declared to be global,
780 false for ones that are implicitly global.
781 (Contributed by Jeremy Hylton.)
782
Benjamin Petersond23f8222009-04-05 19:13:16 +0000783* The ``sys.version_info`` value is now a named tuple, with attributes
784 named ``major``, ``minor``, ``micro``, ``releaselevel``, and ``serial``.
785 (Contributed by Ross Light; :issue:`4285`.)
786
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000787* The :mod:`tarfile` module now supports filtering the :class:`TarInfo`
788 objects being added to a tar file. When you call :meth:`TarFile.add`,
789 instance, you may supply an optional *filter* argument
790 that's a callable. The *filter* callable will be passed the
791 :class:`TarInfo` for every file being added, and can modify and return it.
792 If the callable returns ``None``, the file will be excluded from the
793 resulting archive. This is more powerful than the existing
794 *exclude* argument, which has therefore been deprecated.
795 (Added by Lars Gustaebel; :issue:`6856`.)
796
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000797* The :mod:`threading` module's :meth:`Event.wait` method now returns
798 the internal flag on exit. This means the method will usually
799 return true because :meth:`wait` is supposed to block until the
800 internal flag becomes true. The return value will only be false if
801 a timeout was provided and the operation timed out.
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000802 (Contributed by Tim Lesher; :issue:`1674032`.)
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000803
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000804* The :func:`is_zipfile` function in the :mod:`zipfile` module now
805 accepts a file object, in addition to the path names accepted in earlier
Benjamin Peterson1010bf32009-01-30 04:00:29 +0000806 versions. (Contributed by Gabriel Genellina; :issue:`4756`.)
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000807
Benjamin Petersond23f8222009-04-05 19:13:16 +0000808 :mod:`zipfile` now supports archiving empty directories and
809 extracts them correctly. (Fixed by Kuba Wieczorek; :issue:`4710`.)
810
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000811.. ======================================================================
812.. whole new modules get described in subsections here
813
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000814Unit Testing Enhancements
815---------------------------------
816
817The :mod:`unittest` module was enhanced in several ways.
818The progress messages now shows 'x' for expected failures
819and 'u' for unexpected successes when run in verbose mode.
820(Contributed by Benjamin Peterson.)
821Test cases can raise the :exc:`SkipTest` exception to skip a test.
822(:issue:`1034053`.)
823
824.. XXX describe test discovery (Contributed by Michael Foord; :issue:`6001`.)
825
826The error messages for :meth:`assertEqual`,
827:meth:`assertTrue`, and :meth:`assertFalse`
828failures now provide more information. If you set the
829:attr:`longMessage` attribute of your :class:`TestCase` classes to
830true, both the standard error message and any additional message you
831provide will be printed for failures. (Added by Michael Foord; :issue:`5663`.)
832
833The :meth:`assertRaises` and :meth:`failUnlessRaises` methods now
834return a context handler when called without providing a callable
835object to run. For example, you can write this::
836
837 with self.assertRaises(KeyError):
838 raise ValueError
839
840(Implemented by Antoine Pitrou; :issue:`4444`.)
841
842The methods :meth:`addCleanup` and :meth:`doCleanups` were added.
843:meth:`addCleanup` allows you to add cleanup functions that
844will be called unconditionally (after :meth:`setUp` if
845:meth:`setUp` fails, otherwise after :meth:`tearDown`). This allows
846for much simpler resource allocation and deallocation during tests.
847:issue:`5679`
848
849A number of new methods were added that provide more specialized
850tests. Many of these methods were written by Google engineers
851for use in their test suites; Gregory P. Smith, Michael Foord, and
852GvR worked on merging them into Python's version of :mod:`unittest`.
853
854* :meth:`assertIsNone` and :meth:`assertIsNotNone` take one
855 expression and verify that the result is or is not ``None``.
856
857* :meth:`assertIs` and :meth:`assertIsNot` take two values and check
858 whether the two values evaluate to the same object or not.
859 (Added by Michael Foord; :issue:`2578`.)
860
861* :meth:`assertGreater`, :meth:`assertGreaterEqual`,
862 :meth:`assertLess`, and :meth:`assertLessEqual` compare
863 two quantities.
864
865* :meth:`assertMultiLineEqual` compares two strings, and if they're
866 not equal, displays a helpful comparison that highlights the
867 differences in the two strings.
868
869* :meth:`assertRegexpMatches` checks whether its first argument is a
870 string matching a regular expression provided as its second argument.
871
872* :meth:`assertRaisesRegexp` checks whether a particular exception
873 is raised, and then also checks that the string representation of
874 the exception matches the provided regular expression.
875
876* :meth:`assertIn` and :meth:`assertNotIn` tests whether
877 *first* is or is not in *second*.
878
879* :meth:`assertSameElements` tests whether two provided sequences
880 contain the same elements.
881
882* :meth:`assertSetEqual` compares whether two sets are equal, and
883 only reports the differences between the sets in case of error.
884
885* Similarly, :meth:`assertListEqual` and :meth:`assertTupleEqual`
886 compare the specified types and explain the differences.
887 More generally, :meth:`assertSequenceEqual` compares two sequences
888 and can optionally check whether both sequences are of a
889 particular type.
890
891* :meth:`assertDictEqual` compares two dictionaries and reports the
892 differences. :meth:`assertDictContainsSubset` checks whether
893 all of the key/value pairs in *first* are found in *second*.
894
895* :meth:`assertAlmostEqual` and :meth:`assertNotAlmostEqual` short-circuit
896 (automatically pass or fail without checking decimal places) if the objects
897 are equal.
898
899* :meth:`loadTestsFromName` properly honors the ``suiteClass`` attribute of
900 the :class:`TestLoader`. (Fixed by Mark Roddy; :issue:`6866`.)
901
902* A new hook, :meth:`addTypeEqualityFunc` takes a type object and a
903 function. The :meth:`assertEqual` method will use the function
904 when both of the objects being compared are of the specified type.
905 This function should compare the two objects and raise an
906 exception if they don't match; it's a good idea for the function
907 to provide additional information about why the two objects are
908 matching, much as the new sequence comparison methods do.
909
910:func:`unittest.main` now takes an optional ``exit`` argument.
911If False ``main`` doesn't call :func:`sys.exit` allowing it to
912be used from the interactive interpreter. :issue:`3379`.
913
914:class:`TestResult` has new :meth:`startTestRun` and
915:meth:`stopTestRun` methods; called immediately before
916and after a test run. :issue:`5728` by Robert Collins.
917
918With all these changes, the :file:`unittest.py` was becoming awkwardly
919large, so the module was turned into a package and the code split into
920several files (by Benjamin Peterson). This doesn't affect how the
921module is imported.
922
923
924.. _importlib-section:
925
Benjamin Petersond23f8222009-04-05 19:13:16 +0000926importlib: Importing Modules
927------------------------------
928
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000929Python 3.1 includes the :mod:`importlib` package, a re-implementation
930of the logic underlying Python's :keyword:`import` statement.
931:mod:`importlib` is useful for implementors of Python interpreters and
Benjamin Peterson9eea4802009-12-31 03:31:15 +0000932to users who wish to write new importers that can participate in the
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000933import process. Python 2.7 doesn't contain the complete
934:mod:`importlib` package, but instead has a tiny subset that contains
935a single function, :func:`import_module`.
936
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000937``import_module(name, package=None)`` imports a module. *name* is
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000938a string containing the module or package's name. It's possible to do
939relative imports by providing a string that begins with a ``.``
940character, such as ``..utils.errors``. For relative imports, the
941*package* argument must be provided and is the name of the package that
942will be used as the anchor for
943the relative import. :func:`import_module` both inserts the imported
944module into ``sys.modules`` and returns the module object.
945
946Here are some examples::
947
948 >>> from importlib import import_module
949 >>> anydbm = import_module('anydbm') # Standard absolute import
950 >>> anydbm
951 <module 'anydbm' from '/p/python/Lib/anydbm.py'>
952 >>> # Relative import
953 >>> sysconfig = import_module('..sysconfig', 'distutils.command')
954 >>> sysconfig
955 <module 'distutils.sysconfig' from '/p/python/Lib/distutils/sysconfig.pyc'>
956
957:mod:`importlib` was implemented by Brett Cannon and introduced in
958Python 3.1.
959
Benjamin Petersond23f8222009-04-05 19:13:16 +0000960
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000961ttk: Themed Widgets for Tk
962--------------------------
963
964Tcl/Tk 8.5 includes a set of themed widgets that re-implement basic Tk
965widgets but have a more customizable appearance and can therefore more
966closely resemble the native platform's widgets. This widget
967set was originally called Tile, but was renamed to Ttk (for "themed Tk")
968on being added to Tcl/Tck release 8.5.
969
970XXX write a brief discussion and an example here.
971
972The :mod:`ttk` module was written by Guilherme Polo and added in
973:issue:`2983`. An alternate version called ``Tile.py``, written by
974Martin Franklin and maintained by Kevin Walzer, was proposed for
975inclusion in :issue:`2618`, but the authors argued that Guilherme
976Polo's work was more comprehensive.
977
Georg Brandl4d131ee2009-11-18 18:53:14 +0000978
979Deprecations and Removals
980=========================
981
982* :func:`contextlib.nested`, which allows handling more than one context manager
983 with one :keyword:`with` statement, has been deprecated; :keyword:`with`
984 supports multiple context managers syntactically now.
985
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000986.. ======================================================================
987
988
989Build and C API Changes
990=======================
991
992Changes to Python's build process and to the C API include:
993
Georg Brandl1f01deb2009-01-03 22:47:39 +0000994* If you use the :file:`.gdbinit` file provided with Python,
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000995 the "pyo" macro in the 2.7 version now works correctly when the thread being
996 debugged doesn't hold the GIL; the macro now acquires it before printing.
Benjamin Peterson1010bf32009-01-30 04:00:29 +0000997 (Contributed by Victor Stinner; :issue:`3632`.)
998
Benjamin Petersond23f8222009-04-05 19:13:16 +0000999* :cfunc:`Py_AddPendingCall` is now thread-safe, letting any
Benjamin Peterson1010bf32009-01-30 04:00:29 +00001000 worker thread submit notifications to the main Python thread. This
1001 is particularly useful for asynchronous IO operations.
1002 (Contributed by Kristjan Valur Jonsson; :issue:`4293`.)
1003
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001004* New function: :cfunc:`PyCode_NewEmpty` creates an empty code object;
1005 only the filename, function name, and first line number are required.
1006 This is useful to extension modules that are attempting to
1007 construct a more useful traceback stack. Previously such
1008 extensions needed to call :cfunc:`PyCode_New`, which had many
1009 more arguments. (Added by Jeffrey Yasskin.)
1010
Benjamin Peterson9eea4802009-12-31 03:31:15 +00001011* New function: :cfunc:`PyErr_NewExceptionWithDoc` creates a new
1012 exception class, just as the existing :cfunc:`PyErr_NewException` does,
1013 but takes an extra ``char *`` argument containing the docstring for the
1014 new exception class. (Added by the 'lekma' user on the Python bug tracker;
1015 :issue:`7033`.)
1016
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001017* New function: :cfunc:`PyFrame_GetLineNumber` takes a frame object
1018 and returns the line number that the frame is currently executing.
1019 Previously code would need to get the index of the bytecode
1020 instruction currently executing, and then look up the line number
1021 corresponding to that address. (Added by Jeffrey Yasskin.)
1022
Benjamin Peterson9eea4802009-12-31 03:31:15 +00001023* New function: :cfunc:`PyLong_AsLongAndOverflow` approximates a Python long
1024 integer as a C :ctype:`long`. If the number is too large to fit into
1025 a :ctype:`long`, an *overflow* flag is set and returned to the caller.
1026 (Contributed by Case Van Horsen; :issue:`7528`.)
1027
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001028* New macros: the Python header files now define the following macros:
1029 :cmacro:`Py_ISALNUM`,
1030 :cmacro:`Py_ISALPHA`,
1031 :cmacro:`Py_ISDIGIT`,
1032 :cmacro:`Py_ISLOWER`,
1033 :cmacro:`Py_ISSPACE`,
1034 :cmacro:`Py_ISUPPER`,
1035 :cmacro:`Py_ISXDIGIT`,
1036 and :cmacro:`Py_TOLOWER`, :cmacro:`Py_TOUPPER`.
1037 All of these functions are analogous to the C
1038 standard macros for classifying characters, but ignore the current
1039 locale setting, because in
1040 several places Python needs to analyze characters in a
1041 locale-independent way. (Added by Eric Smith;
1042 :issue:`5793`.)
1043
1044 .. XXX these macros don't seem to be described in the c-api docs.
1045
Benjamin Peterson9eea4802009-12-31 03:31:15 +00001046* New format codes: the :cfunc:`PyFormat_FromString`,
1047 :cfunc:`PyFormat_FromStringV`, and :cfunc:`PyErr_Format` now
1048 accepts ``%lld`` and ``%llu`` format codes for displaying values of
1049 C's :ctype:`long long` types.
1050 (Contributed by Mark Dickinson; :issue:`7228`.)
1051
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001052* The complicated interaction between threads and process forking has
1053 been changed. Previously, the child process created by
1054 :func:`os.fork` might fail because the child is created with only a
1055 single thread running, the thread performing the :func:`os.fork`.
1056 If other threads were holding a lock, such as Python's import lock,
1057 when the fork was performed, the lock would still be marked as
1058 "held" in the new process. But in the child process nothing would
1059 ever release the lock, since the other threads weren't replicated,
1060 and the child process would no longer be able to perform imports.
1061
1062 Python 2.7 now acquires the import lock before performing an
1063 :func:`os.fork`, and will also clean up any locks created using the
1064 :mod:`threading` module. C extension modules that have internal
1065 locks, or that call :cfunc:`fork()` themselves, will not benefit
1066 from this clean-up.
1067
1068 (Fixed by Thomas Wouters; :issue:`1590864`.)
1069
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001070* Global symbols defined by the :mod:`ctypes` module are now prefixed
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001071 with ``Py``, or with ``_ctypes``. (Implemented by Thomas
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001072 Heller; :issue:`3102`.)
1073
Benjamin Petersond23f8222009-04-05 19:13:16 +00001074* The :program:`configure` script now checks for floating-point rounding bugs
1075 on certain 32-bit Intel chips and defines a :cmacro:`X87_DOUBLE_ROUNDING`
1076 preprocessor definition. No code currently uses this definition,
1077 but it's available if anyone wishes to use it.
1078 (Added by Mark Dickinson; :issue:`2937`.)
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001079
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001080* The build process now creates the necessary files for pkg-config
1081 support. (Contributed by Clinton Roy; :issue:`3585`.)
1082
1083* The build process now supports Subversion 1.7. (Contributed by
1084 Arfrever Frehtes Taifersar Arahesis; :issue:`6094`.)
1085
Benjamin Peterson9eea4802009-12-31 03:31:15 +00001086* Compiling Python with the :option:`--with-valgrind` option will now
1087 disable the pymalloc allocator, which is difficult for the Valgrind to
1088 analyze correctly. Valgrind will therefore be better at detecting
1089 memory leaks and overruns. (Contributed by James Henstridge; :issue:`2422`.)
1090
1091
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001092.. ======================================================================
1093
1094Port-Specific Changes: Windows
1095-----------------------------------
1096
Georg Brandl1f01deb2009-01-03 22:47:39 +00001097* The :mod:`msvcrt` module now contains some constants from
1098 the :file:`crtassem.h` header file:
1099 :data:`CRT_ASSEMBLY_VERSION`,
1100 :data:`VC_ASSEMBLY_PUBLICKEYTOKEN`,
1101 and :data:`LIBRARIES_ASSEMBLY_NAME_PREFIX`.
Benjamin Peterson1010bf32009-01-30 04:00:29 +00001102 (Contributed by David Cournapeau; :issue:`4365`.)
1103
1104* The new :cfunc:`_beginthreadex` API is used to start threads, and
1105 the native thread-local storage functions are now used.
1106 (Contributed by Kristjan Valur Jonsson; :issue:`3582`.)
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001107
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001108* The :func:`os.listdir` function now correctly fails
1109 for an empty path. (Fixed by Hirokazu Yamamoto; :issue:`5913`.)
1110
Benjamin Peterson9eea4802009-12-31 03:31:15 +00001111* The :mod:`mimelib` module will now read the MIME database from
1112 the Windows registry when initializing.
1113 (Patch by Gabriel Genellina; :issue:`4969`.)
1114
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001115.. ======================================================================
1116
1117Port-Specific Changes: Mac OS X
1118-----------------------------------
1119
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001120* The path ``/Library/Python/2.7/site-packages`` is now appended to
Benjamin Petersond23f8222009-04-05 19:13:16 +00001121 ``sys.path``, in order to share added packages between the system
1122 installation and a user-installed copy of the same version.
1123 (Changed by Ronald Oussoren; :issue:`4865`.)
1124
1125
1126Other Changes and Fixes
1127=======================
1128
1129* When importing a module from a :file:`.pyc` or :file:`.pyo` file
1130 with an existing :file:`.py` counterpart, the :attr:`co_filename`
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001131 attributes of the resulting code objects are overwritten when the
1132 original filename is obsolete. This can happen if the file has been
1133 renamed, moved, or is accessed through different paths. (Patch by
1134 Ziga Seilnacht and Jean-Paul Calderone; :issue:`1180193`.)
Benjamin Petersond23f8222009-04-05 19:13:16 +00001135
1136* The :file:`regrtest.py` script now takes a :option:`--randseed=`
1137 switch that takes an integer that will be used as the random seed
1138 for the :option:`-r` option that executes tests in random order.
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001139 The :option:`-r` option also reports the seed that was used
Benjamin Petersond23f8222009-04-05 19:13:16 +00001140 (Added by Collin Winter.)
1141
Antoine Pitrou88909542009-06-29 13:54:42 +00001142* The :file:`regrtest.py` script now takes a :option:`-j` switch
1143 that takes an integer specifying how many tests run in parallel. This
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001144 allows reducing the total runtime on multi-core machines.
Antoine Pitrou88909542009-06-29 13:54:42 +00001145 This option is compatible with several other options, including the
1146 :option:`-R` switch which is known to produce long runtimes.
1147 (Added by Antoine Pitrou, :issue:`6152`.)
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001148
1149.. ======================================================================
1150
1151Porting to Python 2.7
1152=====================
1153
1154This section lists previously described changes and other bugfixes
1155that may require changes to your code:
1156
Benjamin Petersonf6489f92009-11-25 17:46:26 +00001157* When using :class:`Decimal` instances with a string's
1158 :meth:`format` method, the default alignment was previously
1159 left-alignment. This has been changed to right-alignment, which might
1160 change the output of your programs.
1161 (Changed by Mark Dickinson; :issue:`6857`.)
1162
1163 Another :meth:`format`-related change: the default precision used
1164 for floating-point and complex numbers was changed from 6 decimal
1165 places to 12, which matches the precision used by :func:`str`.
1166 (Changed by Eric Smith; :issue:`5920`.)
1167
Benjamin Peterson87c8d872009-06-11 22:54:11 +00001168* Because of an optimization for the :keyword:`with` statement, the special
1169 methods :meth:`__enter__` and :meth:`__exit__` must belong to the object's
1170 type, and cannot be directly attached to the object's instance. This
1171 affects new-style classes (derived from :class:`object`) and C extension
1172 types. (:issue:`6101`.)
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001173
Benjamin Peterson9eea4802009-12-31 03:31:15 +00001174* The :meth:`readline` method of :class:`StringIO` objects now does
1175 nothing when a negative length is requested, as other file-like
1176 objects do. (:issue:`7348`).
1177
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001178.. ======================================================================
1179
1180
1181.. _acks27:
1182
1183Acknowledgements
1184================
1185
1186The author would like to thank the following people for offering
1187suggestions, corrections and assistance with various drafts of this
Benjamin Peterson97dd9872009-12-13 01:23:39 +00001188article: Ryan Lovett, Hugh Secker-Walker.
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001189