Benjamin Peterson | f10a79a | 2008-10-11 00:49:57 +0000 | [diff] [blame] | 1 | **************************** |
| 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 Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 9 | .. Fix accents on Kristjan Valur Jonsson, Fuerstenau, Tarek Ziade. |
Benjamin Peterson | 1010bf3 | 2009-01-30 04:00:29 +0000 | [diff] [blame] | 10 | |
Benjamin Peterson | f10a79a | 2008-10-11 00:49:57 +0000 | [diff] [blame] | 11 | .. $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 Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 52 | This article explains the new features in Python 2.7. No release |
| 53 | schedule has been decided yet for 2.7; the schedule will eventually be |
| 54 | described in :pep:`373`. |
Benjamin Peterson | f10a79a | 2008-10-11 00:49:57 +0000 | [diff] [blame] | 55 | |
| 56 | .. Compare with previous release in 2 - 3 sentences here. |
| 57 | add hyperlink when the documentation becomes available online. |
| 58 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 59 | .. _whatsnew27-python31: |
| 60 | |
| 61 | Python 3.1 Features |
| 62 | ======================= |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 63 | |
| 64 | Much as Python 2.6 incorporated features from Python 3.0, |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 65 | version 2.7 incorporates some of the new features |
| 66 | in Python 3.1. The 2.x series continues to provide tools |
| 67 | for migrating to the 3.x series. |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 68 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 69 | A 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`. |
| 73 | * The new format specified described in :ref:`pep-0378`. |
| 74 | * The :class:`memoryview` object. |
| 75 | * A small subset of the :mod:`importlib` module `described below <#importlib-section>`__. |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 76 | |
| 77 | One porting change: the :option:`-3` switch now automatically |
| 78 | enables the :option:`-Qwarn` switch that causes warnings |
| 79 | about using classic division with integers and long integers. |
| 80 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 81 | Other new Python3-mode warnings include: |
| 82 | |
| 83 | * :func:`operator.isCallable` and :func:`operator.sequenceIncludes`, |
| 84 | which are not supported in 3.x. |
| 85 | |
Benjamin Peterson | f10a79a | 2008-10-11 00:49:57 +0000 | [diff] [blame] | 86 | .. ======================================================================== |
| 87 | .. Large, PEP-level features and changes should be described here. |
Benjamin Peterson | f10a79a | 2008-10-11 00:49:57 +0000 | [diff] [blame] | 88 | .. ======================================================================== |
| 89 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 90 | .. _pep-0372: |
| 91 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 92 | PEP 372: Adding an ordered dictionary to collections |
| 93 | ==================================================== |
| 94 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 95 | Regular Python dictionaries iterate over key/value pairs in arbitrary order. |
| 96 | Over the years, a number of authors have written alternative implementations |
| 97 | that remember the order that the keys were originally inserted. Based on |
| 98 | the experiences from those implementations, a new |
| 99 | :class:`collections.OrderedDict` class has been introduced. |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 100 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 101 | The :class:`OrderedDict` API is substantially the same as regular dictionaries |
| 102 | but will iterate over keys and values in a guaranteed order depending on |
| 103 | when a key was first inserted:: |
Benjamin Peterson | f10a79a | 2008-10-11 00:49:57 +0000 | [diff] [blame] | 104 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 105 | >>> from collections import OrderedDict |
| 106 | >>> d = OrderedDict([('first', 1), ('second', 2), |
| 107 | ... ('third', 3)]) |
| 108 | >>> d.items() |
| 109 | [('first', 1), ('second', 2), ('third', 3)] |
| 110 | |
| 111 | If a new entry overwrites an existing entry, the original insertion |
| 112 | position is left unchanged:: |
| 113 | |
| 114 | >>> d['second'] = 4 |
| 115 | >>> d.items() |
| 116 | [('first', 1), ('second', 4), ('third', 3)] |
| 117 | |
| 118 | Deleting an entry and reinserting it will move it to the end:: |
| 119 | |
| 120 | >>> del d['second'] |
| 121 | >>> d['second'] = 5 |
| 122 | >>> d.items() |
| 123 | [('first', 1), ('third', 3), ('second', 5)] |
| 124 | |
| 125 | The :meth:`popitem` method has an optional *last* argument |
| 126 | that defaults to True. If *last* is True, the most recently |
| 127 | added key is returned and removed; if it's False, the |
| 128 | oldest key is selected:: |
| 129 | |
| 130 | >>> od = OrderedDict([(x,0) for x in range(20)]) |
| 131 | >>> od.popitem() |
| 132 | (19, 0) |
| 133 | >>> od.popitem() |
| 134 | (18, 0) |
| 135 | >>> od.popitem(False) |
| 136 | (0, 0) |
| 137 | >>> od.popitem(False) |
| 138 | (1, 0) |
| 139 | |
| 140 | Comparing two ordered dictionaries checks both the keys and values, |
| 141 | and requires that the insertion order was the same:: |
| 142 | |
| 143 | >>> od1 = OrderedDict([('first', 1), ('second', 2), |
| 144 | ... ('third', 3)]) |
| 145 | >>> od2 = OrderedDict([('third', 3), ('first', 1), |
| 146 | ... ('second', 2)]) |
| 147 | >>> od1==od2 |
| 148 | False |
| 149 | >>> # Move 'third' key to the end |
| 150 | >>> del od2['third'] ; od2['third'] = 3 |
| 151 | >>> od1==od2 |
| 152 | True |
| 153 | |
| 154 | Comparing an :class:`OrderedDict` with a regular dictionary |
| 155 | ignores the insertion order and just compares the keys and values. |
| 156 | |
| 157 | How does the :class:`OrderedDict` work? It maintains a doubly-linked |
| 158 | list of keys, appending new keys to the list as they're inserted. A |
| 159 | secondary dictionary maps keys to their corresponding list node, so |
| 160 | deletion doesn't have to traverse the entire linked list and therefore |
| 161 | remains O(1). |
| 162 | |
| 163 | .. XXX check O(1)-ness with Raymond |
| 164 | |
| 165 | The standard library now supports use of ordered dictionaries in several |
| 166 | modules. The :mod:`configparser` module uses them by default. This lets |
| 167 | configuration files be read, modified, and then written back in their original |
| 168 | order. The *_asdict()* method for :func:`collections.namedtuple` now |
| 169 | returns an ordered dictionary with the values appearing in the same order as |
| 170 | the underlying tuple indicies. The :mod:`json` module is being built-out with |
| 171 | an *object_pairs_hook* to allow OrderedDicts to be built by the decoder. |
| 172 | Support was also added for third-party tools like `PyYAML <http://pyyaml.org/>`_. |
| 173 | |
| 174 | .. seealso:: |
| 175 | |
| 176 | :pep:`372` - Adding an ordered dictionary to collections |
| 177 | PEP written by Armin Ronacher and Raymond Hettinger; |
| 178 | implemented by Raymond Hettinger. |
| 179 | |
| 180 | .. _pep-0378: |
| 181 | |
| 182 | PEP 378: Format Specifier for Thousands Separator |
| 183 | ==================================================== |
| 184 | |
| 185 | To make program output more readable, it can be useful to add |
| 186 | separators to large numbers and render them as |
| 187 | 18,446,744,073,709,551,616 instead of 18446744073709551616. |
| 188 | |
| 189 | The fully general solution for doing this is the :mod:`locale` module, |
| 190 | which can use different separators ("," in North America, "." in |
| 191 | Europe) and different grouping sizes, but :mod:`locale` is complicated |
| 192 | to use and unsuitable for multi-threaded applications where different |
| 193 | threads are producing output for different locales. |
| 194 | |
| 195 | Therefore, a simple comma-grouping mechanism has been added to the |
| 196 | mini-language used by the string :meth:`format` method. When |
| 197 | formatting a floating-point number, simply include a comma between the |
| 198 | width and the precision:: |
| 199 | |
| 200 | >>> '{:20,.2}'.format(f) |
| 201 | '18,446,744,073,709,551,616.00' |
| 202 | |
| 203 | This mechanism is not adaptable at all; commas are always used as the |
| 204 | separator and the grouping is always into three-digit groups. The |
| 205 | comma-formatting mechanism isn't as general as the :mod:`locale` |
| 206 | module, but it's easier to use. |
| 207 | |
| 208 | .. XXX "Format String Syntax" in string.rst could use many more examples. |
| 209 | |
| 210 | .. seealso:: |
| 211 | |
| 212 | :pep:`378` - Format Specifier for Thousands Separator |
| 213 | PEP written by Raymond Hettinger; implemented by Eric Smith. |
Benjamin Peterson | f10a79a | 2008-10-11 00:49:57 +0000 | [diff] [blame] | 214 | |
| 215 | Other Language Changes |
| 216 | ====================== |
| 217 | |
| 218 | Some smaller changes made to the core Python language are: |
| 219 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 220 | * The :keyword:`with` statement can now use multiple context managers |
| 221 | in one statement. Context managers are processed from left to right |
| 222 | and each one is treated as beginning a new :keyword:`with` statement. |
| 223 | This means that:: |
| 224 | |
| 225 | with A() as a, B() as b: |
| 226 | ... suite of statements ... |
| 227 | |
| 228 | is equivalent to:: |
| 229 | |
| 230 | with A() as a: |
| 231 | with B() as b: |
| 232 | ... suite of statements ... |
| 233 | |
| 234 | The :func:`contextlib.nested` function provides a very similar |
| 235 | function, so it's no longer necessary and has been deprecated. |
| 236 | |
| 237 | (Proposed in http://codereview.appspot.com/53094; implemented by |
| 238 | Georg Brandl.) |
| 239 | |
| 240 | * The :meth:`str.format` method now supports automatic numbering of the replacement |
Benjamin Peterson | 3f96a87 | 2009-04-11 20:58:12 +0000 | [diff] [blame] | 241 | fields. This makes using :meth:`str.format` more closely resemble using |
| 242 | ``%s`` formatting:: |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 243 | |
| 244 | >>> '{}:{}:{}'.format(2009, 04, 'Sunday') |
| 245 | '2009:4:Sunday' |
| 246 | >>> '{}:{}:{day}'.format(2009, 4, day='Sunday') |
| 247 | '2009:4:Sunday' |
| 248 | |
Benjamin Peterson | 3f96a87 | 2009-04-11 20:58:12 +0000 | [diff] [blame] | 249 | The auto-numbering takes the fields from left to right, so the first ``{...}`` |
| 250 | specifier will use the first argument to :meth:`str.format`, the next |
| 251 | specifier will use the next argument, and so on. You can't mix auto-numbering |
| 252 | and explicit numbering -- either number all of your specifier fields or none |
| 253 | of them -- but you can mix auto-numbering and named fields, as in the second |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 254 | example above. (Contributed by Eric Smith; :issue:`5237`.) |
| 255 | |
| 256 | Complex numbers now correctly support usage with :func:`format`. |
| 257 | Specifying a precision or comma-separation applies to both the real |
| 258 | and imaginary parts of the number, but a specified field width and |
| 259 | alignment is applied to the whole of the resulting ``1.5+3j`` |
| 260 | output. (Contributed by Eric Smith; :issue:`1588`.) |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 261 | |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame] | 262 | * The :func:`int` and :func:`long` types gained a ``bit_length`` |
| 263 | method that returns the number of bits necessary to represent |
| 264 | its argument in binary:: |
| 265 | |
| 266 | >>> n = 37 |
| 267 | >>> bin(37) |
| 268 | '0b100101' |
| 269 | >>> n.bit_length() |
| 270 | 6 |
| 271 | >>> n = 2**123-1 |
| 272 | >>> n.bit_length() |
| 273 | 123 |
| 274 | >>> (n+1).bit_length() |
| 275 | 124 |
| 276 | |
| 277 | (Contributed by Fredrik Johansson and Victor Stinner; :issue:`3439`.) |
| 278 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 279 | * Conversions from long integers and regular integers to floating |
| 280 | point now round differently, returning the floating-point number |
| 281 | closest to the number. This doesn't matter for small integers that |
| 282 | can be converted exactly, but for large numbers that will |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 283 | unavoidably lose precision, Python 2.7 now approximates more |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 284 | closely. For example, Python 2.6 computed the following:: |
| 285 | |
| 286 | >>> n = 295147905179352891391 |
| 287 | >>> float(n) |
| 288 | 2.9514790517935283e+20 |
| 289 | >>> n - long(float(n)) |
| 290 | 65535L |
| 291 | |
| 292 | Python 2.7's floating-point result is larger, but much closer to the |
| 293 | true value:: |
| 294 | |
| 295 | >>> n = 295147905179352891391 |
| 296 | >>> float(n) |
| 297 | 2.9514790517935289e+20 |
| 298 | >>> n-long(float(n) |
| 299 | ... ) |
| 300 | -1L |
| 301 | |
| 302 | (Implemented by Mark Dickinson; :issue:`3166`.) |
| 303 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 304 | * The :class:`bytearray` type's :meth:`translate` method now accepts |
| 305 | ``None`` as its first argument. (Fixed by Georg Brandl; |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 306 | :issue:`4759`.) |
Mark Dickinson | d72c7b6 | 2009-03-20 16:00:49 +0000 | [diff] [blame] | 307 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 308 | * When using ``@classmethod`` and ``@staticmethod`` to wrap |
| 309 | methods as class or static methods, the wrapper object now |
| 310 | exposes the wrapped function as their :attr:`__func__` attribute. |
| 311 | (Contributed by Amaury Forgeot d'Arc, after a suggestion by |
| 312 | George Sakkis; :issue:`5982`.) |
| 313 | |
| 314 | * A new encoding named "cp720", used primarily for Arabic text, is now |
| 315 | supported. (Contributed by Alexander Belchenko and Amaury Forgeot |
| 316 | d'Arc; :issue:`1616979`.) |
| 317 | |
Benjamin Peterson | f10a79a | 2008-10-11 00:49:57 +0000 | [diff] [blame] | 318 | .. ====================================================================== |
| 319 | |
| 320 | |
| 321 | Optimizations |
| 322 | ------------- |
| 323 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 324 | Several performance enhancements have been added: |
| 325 | |
| 326 | .. * A new :program:`configure` option, :option:`--with-computed-gotos`, |
| 327 | compiles the main bytecode interpreter loop using a new dispatch |
| 328 | mechanism that gives speedups of up to 20%, depending on the system |
| 329 | and benchmark. The new mechanism is only supported on certain |
| 330 | compilers, such as gcc, SunPro, and icc. |
Benjamin Peterson | 1010bf3 | 2009-01-30 04:00:29 +0000 | [diff] [blame] | 331 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 332 | * A new opcode was added to perform the initial setup for |
| 333 | :keyword:`with` statements, looking up the :meth:`__enter__` and |
| 334 | :meth:`__exit__` methods. (Contributed by Benjamin Peterson.) |
| 335 | |
Benjamin Peterson | 1010bf3 | 2009-01-30 04:00:29 +0000 | [diff] [blame] | 336 | * The garbage collector now performs better when many objects are |
| 337 | being allocated without deallocating any. A full garbage collection |
| 338 | pass is only performed when the middle generation has been collected |
| 339 | 10 times and when the number of survivor objects from the middle |
| 340 | generation exceeds 10% of the number of objects in the oldest |
| 341 | generation. The second condition was added to reduce the number |
| 342 | of full garbage collections as the number of objects on the heap grows, |
| 343 | avoiding quadratic performance when allocating very many objects. |
| 344 | (Suggested by Martin von Loewis and implemented by Antoine Pitrou; |
| 345 | :issue:`4074`.) |
| 346 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 347 | * The garbage collector tries to avoid tracking simple containers |
| 348 | which can't be part of a cycle. In Python 2.7, this is now true for |
| 349 | tuples and dicts containing atomic types (such as ints, strings, |
| 350 | etc.). Transitively, a dict containing tuples of atomic types won't |
| 351 | be tracked either. This helps reduce the cost of each |
| 352 | garbage collection by decreasing the number of objects to be |
| 353 | considered and traversed by the collector. |
Antoine Pitrou | 9d81def | 2009-03-28 19:20:09 +0000 | [diff] [blame] | 354 | (Contributed by Antoine Pitrou; :issue:`4688`.) |
| 355 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 356 | * Long integers are now stored internally either in base 2**15 or in base |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 357 | 2**30, the base being determined at build time. Previously, they |
| 358 | were always stored in base 2**15. Using base 2**30 gives |
| 359 | significant performance improvements on 64-bit machines, but |
| 360 | benchmark results on 32-bit machines have been mixed. Therefore, |
| 361 | the default is to use base 2**30 on 64-bit machines and base 2**15 |
| 362 | on 32-bit machines; on Unix, there's a new configure option |
| 363 | :option:`--enable-big-digits` that can be used to override this default. |
| 364 | |
| 365 | Apart from the performance improvements this change should be |
| 366 | invisible to end users, with one exception: for testing and |
| 367 | debugging purposes there's a new structseq ``sys.long_info`` that |
| 368 | provides information about the internal format, giving the number of |
| 369 | bits per digit and the size in bytes of the C type used to store |
| 370 | each digit:: |
| 371 | |
| 372 | >>> import sys |
| 373 | >>> sys.long_info |
| 374 | sys.long_info(bits_per_digit=30, sizeof_digit=4) |
| 375 | |
| 376 | (Contributed by Mark Dickinson; :issue:`4258`.) |
| 377 | |
| 378 | Another set of changes made long objects a few bytes smaller: 2 bytes |
| 379 | smaller on 32-bit systems and 6 bytes on 64-bit. |
| 380 | (Contributed by Mark Dickinson; :issue:`5260`.) |
| 381 | |
| 382 | * The division algorithm for long integers has been made faster |
| 383 | by tightening the inner loop, doing shifts instead of multiplications, |
| 384 | and fixing an unnecessary extra iteration. |
| 385 | Various benchmarks show speedups of between 50% and 150% for long |
| 386 | integer divisions and modulo operations. |
| 387 | (Contributed by Mark Dickinson; :issue:`5512`.) |
| 388 | |
| 389 | * The implementation of ``%`` checks for the left-side operand being |
| 390 | a Python string and special-cases it; this results in a 1-3% |
| 391 | performance increase for applications that frequently use ``%`` |
| 392 | with strings, such as templating libraries. |
| 393 | (Implemented by Collin Winter; :issue:`5176`.) |
| 394 | |
| 395 | * List comprehensions with an ``if`` condition are compiled into |
| 396 | faster bytecode. (Patch by Antoine Pitrou, back-ported to 2.7 |
| 397 | by Jeffrey Yasskin; :issue:`4715`.) |
Benjamin Peterson | f10a79a | 2008-10-11 00:49:57 +0000 | [diff] [blame] | 398 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 399 | * The :mod:`pickle` and :mod:`cPickle` modules now automatically |
| 400 | intern the strings used for attribute names, reducing memory usage |
| 401 | of the objects resulting from unpickling. (Contributed by Jake |
| 402 | McGuire; :issue:`5084`.) |
| 403 | |
| 404 | * The :mod:`cPickle` module now special-cases dictionaries, |
| 405 | nearly halving the time required to pickle them. |
| 406 | (Contributed by Collin Winter; :issue:`5670`.) |
| 407 | |
| 408 | * Converting an integer or long integer to a decimal string was made |
| 409 | faster by special-casing base 10 instead of using a generalized |
| 410 | conversion function that supports arbitrary bases. |
| 411 | (Patch by Gawain Bolton; :issue:`6713`.) |
| 412 | |
| 413 | |
Benjamin Peterson | f10a79a | 2008-10-11 00:49:57 +0000 | [diff] [blame] | 414 | .. ====================================================================== |
| 415 | |
Georg Brandl | 4d131ee | 2009-11-18 18:53:14 +0000 | [diff] [blame] | 416 | New and Improved Modules |
| 417 | ======================== |
Benjamin Peterson | f10a79a | 2008-10-11 00:49:57 +0000 | [diff] [blame] | 418 | |
| 419 | As in every release, Python's standard library received a number of |
| 420 | enhancements and bug fixes. Here's a partial list of the most notable |
| 421 | changes, sorted alphabetically by module name. Consult the |
| 422 | :file:`Misc/NEWS` file in the source tree for a more complete list of |
| 423 | changes, or look through the Subversion logs for all the details. |
| 424 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 425 | * The :mod:`bdb` module's base debugging class :class:`Bdb` |
| 426 | gained a feature for skipping modules. The constructor |
| 427 | now takes an iterable containing glob-style patterns such as |
| 428 | ``django.*``; the debugger will not step into stack frames |
| 429 | from a module that matches one of these patterns. |
| 430 | (Contributed by Maru Newby after a suggestion by |
| 431 | Senthil Kumaran; :issue:`5142`.) |
| 432 | |
Benjamin Peterson | 1010bf3 | 2009-01-30 04:00:29 +0000 | [diff] [blame] | 433 | * The :mod:`bz2` module's :class:`BZ2File` now supports the context |
| 434 | management protocol, so you can write ``with bz2.BZ2File(...) as f: ...``. |
| 435 | (Contributed by Hagen Fuerstenau; :issue:`3860`.) |
| 436 | |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 437 | * New class: the :class:`Counter` class in the :mod:`collections` module is |
Benjamin Peterson | 1010bf3 | 2009-01-30 04:00:29 +0000 | [diff] [blame] | 438 | useful for tallying data. :class:`Counter` instances behave mostly |
| 439 | like dictionaries but return zero for missing keys instead of |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 440 | raising a :exc:`KeyError`: |
Benjamin Peterson | 1010bf3 | 2009-01-30 04:00:29 +0000 | [diff] [blame] | 441 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 442 | .. doctest:: |
| 443 | :options: +NORMALIZE_WHITESPACE |
| 444 | |
| 445 | >>> from collections import Counter |
| 446 | >>> c = Counter() |
| 447 | >>> for letter in 'here is a sample of english text': |
| 448 | ... c[letter] += 1 |
| 449 | ... |
| 450 | >>> c |
| 451 | Counter({' ': 6, 'e': 5, 's': 3, 'a': 2, 'i': 2, 'h': 2, |
| 452 | 'l': 2, 't': 2, 'g': 1, 'f': 1, 'm': 1, 'o': 1, 'n': 1, |
| 453 | 'p': 1, 'r': 1, 'x': 1}) |
| 454 | >>> c['e'] |
| 455 | 5 |
| 456 | >>> c['z'] |
| 457 | 0 |
Benjamin Peterson | 1010bf3 | 2009-01-30 04:00:29 +0000 | [diff] [blame] | 458 | |
| 459 | There are two additional :class:`Counter` methods: :meth:`most_common` |
| 460 | returns the N most common elements and their counts, and :meth:`elements` |
| 461 | returns an iterator over the contained element, repeating each element |
| 462 | as many times as its count:: |
| 463 | |
| 464 | >>> c.most_common(5) |
| 465 | [(' ', 6), ('e', 5), ('s', 3), ('a', 2), ('i', 2)] |
| 466 | >>> c.elements() -> |
| 467 | 'a', 'a', ' ', ' ', ' ', ' ', ' ', ' ', |
| 468 | 'e', 'e', 'e', 'e', 'e', 'g', 'f', 'i', 'i', |
| 469 | 'h', 'h', 'm', 'l', 'l', 'o', 'n', 'p', 's', |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 470 | 's', 's', 'r', 't', 't', 'x' |
Benjamin Peterson | 1010bf3 | 2009-01-30 04:00:29 +0000 | [diff] [blame] | 471 | |
| 472 | Contributed by Raymond Hettinger; :issue:`1696199`. |
| 473 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 474 | The new `OrderedDict` class is described in the earlier section |
| 475 | :ref:`pep-0372`. |
| 476 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 477 | The :class:`namedtuple` class now has an optional *rename* parameter. |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 478 | If *rename* is true, field names that are invalid because they've |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 479 | been repeated or that aren't legal Python identifiers will be |
| 480 | renamed to legal names that are derived from the field's |
| 481 | position within the list of fields: |
| 482 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 483 | >>> from collections import namedtuple |
| 484 | >>> T = namedtuple('T', ['field1', '$illegal', 'for', 'field2'], rename=True) |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 485 | >>> T._fields |
| 486 | ('field1', '_1', '_2', 'field2') |
| 487 | |
| 488 | (Added by Raymond Hettinger; :issue:`1818`.) |
| 489 | |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 490 | The :class:`deque` data type now exposes its maximum length as the |
| 491 | read-only :attr:`maxlen` attribute. (Added by Raymond Hettinger.) |
| 492 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 493 | * The :mod:`ctypes` module now always converts ``None`` to a C NULL |
| 494 | pointer for arguments declared as pointers. (Changed by Thomas |
| 495 | Heller; :issue:`4606`.) |
| 496 | |
| 497 | * New method: the :class:`Decimal` class gained a |
| 498 | :meth:`from_float` class method that performs an exact conversion |
| 499 | of a floating-point number to a :class:`Decimal`. |
| 500 | Note that this is an **exact** conversion that strives for the |
| 501 | closest decimal approximation to the floating-point representation's value; |
| 502 | the resulting decimal value will therefore still include the inaccuracy, |
| 503 | if any. |
| 504 | For example, ``Decimal.from_float(0.1)`` returns |
| 505 | ``Decimal('0.1000000000000000055511151231257827021181583404541015625')``. |
| 506 | (Implemented by Raymond Hettinger; :issue:`4796`.) |
| 507 | |
| 508 | The constructor for :class:`Decimal` now accepts non-European |
| 509 | Unicode characters, such as Arabic-Indic digits. (Contributed by |
| 510 | Mark Dickinson; :issue:`6595`.) |
| 511 | |
| 512 | When using :class:`Decimal` instances with a string's |
| 513 | :meth:`format` method, the default alignment was previously |
| 514 | left-alignment. This has been changed to right-alignment, which seems |
| 515 | more sensible for numeric types. (Changed by Mark Dickinson; :issue:`6857`.) |
| 516 | |
| 517 | * Distutils is being more actively developed, thanks to Tarek Ziade |
| 518 | has taken over maintenance of the package. A new |
| 519 | :file:`setup.py` subcommand, ``check``, will |
| 520 | check that the arguments being passed to the :func:`setup` function |
| 521 | are complete and correct (:issue:`5732`). |
| 522 | |
| 523 | :func:`distutils.sdist.add_defaults` now uses |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 524 | *package_dir* and *data_files* to create the MANIFEST file. |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 525 | :mod:`distutils.sysconfig` now reads the :envvar:`AR` and |
| 526 | :envvar:`ARFLAGS` environment variables. |
| 527 | |
| 528 | .. ARFLAGS done in #5941 |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 529 | |
| 530 | It is no longer mandatory to store clear-text passwords in the |
| 531 | :file:`.pypirc` file when registering and uploading packages to PyPI. As long |
| 532 | as the username is present in that file, the :mod:`distutils` package will |
| 533 | prompt for the password if not present. (Added by Tarek Ziade, |
| 534 | based on an initial contribution by Nathan Van Gheem; :issue:`4394`.) |
| 535 | |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 536 | A Distutils setup can now specify that a C extension is optional by |
| 537 | setting the *optional* option setting to true. If this optional is |
| 538 | supplied, failure to build the extension will not abort the build |
| 539 | process, but instead simply not install the failing extension. |
| 540 | (Contributed by Georg Brandl; :issue:`5583`.) |
| 541 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 542 | * The :class:`Fraction` class now accepts two rational numbers |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 543 | as arguments to its constructor. |
| 544 | (Implemented by Mark Dickinson; :issue:`5812`.) |
| 545 | |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 546 | * New function: the :mod:`gc` module's :func:`is_tracked` returns |
| 547 | true if a given instance is tracked by the garbage collector, false |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 548 | otherwise. (Contributed by Antoine Pitrou; :issue:`4688`.) |
| 549 | |
Benjamin Peterson | 1010bf3 | 2009-01-30 04:00:29 +0000 | [diff] [blame] | 550 | * The :mod:`gzip` module's :class:`GzipFile` now supports the context |
| 551 | management protocol, so you can write ``with gzip.GzipFile(...) as f: ...``. |
| 552 | (Contributed by Hagen Fuerstenau; :issue:`3860`.) |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 553 | It's now possible to override the modification time |
| 554 | recorded in a gzipped file by providing an optional timestamp to |
| 555 | the constructor. (Contributed by Jacques Frechet; :issue:`4272`.) |
Benjamin Peterson | 1010bf3 | 2009-01-30 04:00:29 +0000 | [diff] [blame] | 556 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 557 | * The :mod:`hashlib` module was inconsistent about accepting |
| 558 | input as a Unicode object or an object that doesn't support |
| 559 | the buffer protocol. The behavior was different depending on |
| 560 | whether :mod:`hashlib` was using an external OpenSSL library |
| 561 | or its built-in implementations. Python 2.7 makes the |
| 562 | behavior consistent, always rejecting such objects by raising a |
| 563 | :exc:`TypeError`. (Fixed by Gregory P. Smith; :issue:`3745`.) |
| 564 | |
| 565 | * The default :class:`HTTPResponse` class used by the :mod:`httplib` module now |
| 566 | supports buffering, resulting in much faster reading of HTTP responses. |
| 567 | (Contributed by Kristjan Valur Jonsson; :issue:`4879`.) |
| 568 | |
| 569 | * The :mod:`imaplib` module now supports IPv6 addresses. |
| 570 | (Contributed by Derek Morr; :issue:`1655`.) |
| 571 | |
| 572 | * The :mod:`io` library has been upgraded to the version shipped with |
| 573 | Python 3.1. For 3.1, the I/O library was entirely rewritten in C |
| 574 | and is 2 to 20 times faster depending on the task at hand. The |
| 575 | original Python version was renamed to the :mod:`_pyio` module. |
| 576 | |
| 577 | One minor resulting change: the :class:`io.TextIOBase` class now |
| 578 | has an :attr:`errors` attribute giving the error setting |
| 579 | used for encoding and decoding errors (one of ``'strict'``, ``'replace'``, |
| 580 | ``'ignore'``). |
| 581 | |
| 582 | The :class:`io.FileIO` class now raises an :exc:`OSError` when passed |
Benjamin Peterson | 1010bf3 | 2009-01-30 04:00:29 +0000 | [diff] [blame] | 583 | an invalid file descriptor. (Implemented by Benjamin Peterson; |
| 584 | :issue:`4991`.) |
| 585 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 586 | * New function: ``itertools.compress(*data*, *selectors*)`` takes two |
| 587 | iterators. Elements of *data* are returned if the corresponding |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 588 | value in *selectors* is true:: |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 589 | |
| 590 | itertools.compress('ABCDEF', [1,0,1,0,1,1]) => |
| 591 | A, C, E, F |
| 592 | |
| 593 | New function: ``itertools.combinations_with_replacement(*iter*, *r*)`` |
| 594 | returns all the possible *r*-length combinations of elements from the |
| 595 | iterable *iter*. Unlike :func:`combinations`, individual elements |
| 596 | can be repeated in the generated combinations:: |
| 597 | |
| 598 | itertools.combinations_with_replacement('abc', 2) => |
| 599 | ('a', 'a'), ('a', 'b'), ('a', 'c'), |
| 600 | ('b', 'b'), ('b', 'c'), ('c', 'c') |
| 601 | |
| 602 | Note that elements are treated as unique depending on their position |
| 603 | in the input, not their actual values. |
| 604 | |
| 605 | The :class:`itertools.count` function now has a *step* argument that |
| 606 | allows incrementing by values other than 1. :func:`count` also |
| 607 | now allows keyword arguments, and using non-integer values such as |
| 608 | floats or :class:`Decimal` instances. (Implemented by Raymond |
| 609 | Hettinger; :issue:`5032`.) |
| 610 | |
| 611 | :func:`itertools.combinations` and :func:`itertools.product` were |
| 612 | previously raising :exc:`ValueError` for values of *r* larger than |
| 613 | the input iterable. This was deemed a specification error, so they |
| 614 | now return an empty iterator. (Fixed by Raymond Hettinger; :issue:`4816`.) |
| 615 | |
| 616 | * The :mod:`json` module was upgraded to version 2.0.9 of the |
| 617 | simplejson package, which includes a C extension that makes |
| 618 | encoding and decoding faster. |
| 619 | (Contributed by Bob Ippolito; :issue:`4136`.) |
| 620 | |
| 621 | To support the new :class:`OrderedDict` type, :func:`json.load` |
| 622 | now has an optional *object_pairs_hook* parameter that will be called |
| 623 | with any object literal that decodes to a list of pairs. |
| 624 | (Contributed by Raymond Hettinger; :issue:`5381`.) |
| 625 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 626 | * New functions: the :mod:`math` module now has |
| 627 | a :func:`gamma` function. |
| 628 | (Contributed by Mark Dickinson and nirinA raseliarison; :issue:`3366`.) |
| 629 | |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 630 | * The :mod:`multiprocessing` module's :class:`Manager*` classes |
| 631 | can now be passed a callable that will be called whenever |
| 632 | a subprocess is started, along with a set of arguments that will be |
| 633 | passed to the callable. |
| 634 | (Contributed by lekma; :issue:`5585`.) |
| 635 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 636 | * The :mod:`nntplib` module now supports IPv6 addresses. |
| 637 | (Contributed by Derek Morr; :issue:`1664`.) |
| 638 | |
Benjamin Peterson | 1010bf3 | 2009-01-30 04:00:29 +0000 | [diff] [blame] | 639 | * The :mod:`pydoc` module now has help for the various symbols that Python |
| 640 | uses. You can now do ``help('<<')`` or ``help('@')``, for example. |
| 641 | (Contributed by David Laban; :issue:`4739`.) |
| 642 | |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 643 | * The :mod:`re` module's :func:`split`, :func:`sub`, and :func:`subn` |
| 644 | now accept an optional *flags* argument, for consistency with the |
| 645 | other functions in the module. (Added by Gregory P. Smith.) |
| 646 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 647 | * The :mod:`shutil` module's :func:`copyfile` and :func:`copytree` |
| 648 | functions now raises a :exc:`SpecialFileError` exception when |
| 649 | asked to copy a named pipe. Previously the code would treat |
| 650 | named pipes like a regular file by opening them for reading, and |
| 651 | this would block indefinitely. (Fixed by Antoine Pitrou; :issue:`3002`.) |
| 652 | |
| 653 | * New functions: in the :mod:`site` module, three new functions |
| 654 | return various site- and user-specific paths. |
| 655 | :func:`getsitepackages` returns a list containing all |
| 656 | global site-packages directories, and |
| 657 | :func:`getusersitepackages` returns the path of the user's |
| 658 | site-packages directory. |
| 659 | :func:`getuserbase` returns the value of the :envvar:``USER_BASE`` |
| 660 | environment variable, giving the path to a directory that can be used |
| 661 | to store data. |
| 662 | (Contributed by Tarek Ziade; :issue:`6693`.) |
| 663 | |
| 664 | * The :mod:`SocketServer` module's :class:`TCPServer` class now |
| 665 | has a :attr:`disable_nagle_algorithm` class attribute. |
| 666 | The default value is False; if overridden to be True, |
| 667 | new request connections will have the TCP_NODELAY option set to |
| 668 | prevent buffering many small sends into a single TCP packet. |
| 669 | (Contributed by Kristjan Valur Jonsson; :issue:`6192`.) |
| 670 | |
| 671 | * The :mod:`struct` module will no longer silently ignore overflow |
| 672 | errors when a value is too large for a particular integer format |
| 673 | code (one of ``bBhHiIlLqQ``); it now always raises a |
| 674 | :exc:`struct.error` exception. (Changed by Mark Dickinson; |
| 675 | :issue:`1523`.) |
| 676 | |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 677 | * New function: the :mod:`subprocess` module's |
| 678 | :func:`check_output` runs a command with a specified set of arguments |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 679 | and returns the command's output as a string when the command runs without |
Georg Brandl | 1f01deb | 2009-01-03 22:47:39 +0000 | [diff] [blame] | 680 | error, or raises a :exc:`CalledProcessError` exception otherwise. |
| 681 | |
| 682 | :: |
| 683 | |
| 684 | >>> subprocess.check_output(['df', '-h', '.']) |
| 685 | 'Filesystem Size Used Avail Capacity Mounted on\n |
| 686 | /dev/disk0s2 52G 49G 3.0G 94% /\n' |
| 687 | |
| 688 | >>> subprocess.check_output(['df', '-h', '/bogus']) |
| 689 | ... |
| 690 | subprocess.CalledProcessError: Command '['df', '-h', '/bogus']' returned non-zero exit status 1 |
| 691 | |
| 692 | (Contributed by Gregory P. Smith.) |
| 693 | |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 694 | * New function: :func:`is_declared_global` in the :mod:`symtable` module |
| 695 | returns true for variables that are explicitly declared to be global, |
| 696 | false for ones that are implicitly global. |
| 697 | (Contributed by Jeremy Hylton.) |
| 698 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 699 | * The ``sys.version_info`` value is now a named tuple, with attributes |
| 700 | named ``major``, ``minor``, ``micro``, ``releaselevel``, and ``serial``. |
| 701 | (Contributed by Ross Light; :issue:`4285`.) |
| 702 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 703 | * The :mod:`tarfile` module now supports filtering the :class:`TarInfo` |
| 704 | objects being added to a tar file. When you call :meth:`TarFile.add`, |
| 705 | instance, you may supply an optional *filter* argument |
| 706 | that's a callable. The *filter* callable will be passed the |
| 707 | :class:`TarInfo` for every file being added, and can modify and return it. |
| 708 | If the callable returns ``None``, the file will be excluded from the |
| 709 | resulting archive. This is more powerful than the existing |
| 710 | *exclude* argument, which has therefore been deprecated. |
| 711 | (Added by Lars Gustaebel; :issue:`6856`.) |
| 712 | |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 713 | * The :mod:`threading` module's :meth:`Event.wait` method now returns |
| 714 | the internal flag on exit. This means the method will usually |
| 715 | return true because :meth:`wait` is supposed to block until the |
| 716 | internal flag becomes true. The return value will only be false if |
| 717 | a timeout was provided and the operation timed out. |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 718 | (Contributed by Tim Lesher; :issue:`1674032`.) |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 719 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 720 | * The :func:`is_zipfile` function in the :mod:`zipfile` module now |
| 721 | accepts a file object, in addition to the path names accepted in earlier |
Benjamin Peterson | 1010bf3 | 2009-01-30 04:00:29 +0000 | [diff] [blame] | 722 | versions. (Contributed by Gabriel Genellina; :issue:`4756`.) |
Benjamin Peterson | f10a79a | 2008-10-11 00:49:57 +0000 | [diff] [blame] | 723 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 724 | :mod:`zipfile` now supports archiving empty directories and |
| 725 | extracts them correctly. (Fixed by Kuba Wieczorek; :issue:`4710`.) |
| 726 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 727 | * The :mod:`ftplib` module gains the ability to establish secure FTP |
| 728 | connections using TLS encapsulation of authentication as well as |
| 729 | subsequent control and data transfers. This is provided by the new |
| 730 | :class:`ftplib.FTP_TLS` class. |
| 731 | (Contributed by Giampaolo Rodola', :issue:`2054`.) |
| 732 | |
Benjamin Peterson | f10a79a | 2008-10-11 00:49:57 +0000 | [diff] [blame] | 733 | .. ====================================================================== |
| 734 | .. whole new modules get described in subsections here |
| 735 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 736 | Unit Testing Enhancements |
| 737 | --------------------------------- |
| 738 | |
| 739 | The :mod:`unittest` module was enhanced in several ways. |
| 740 | The progress messages now shows 'x' for expected failures |
| 741 | and 'u' for unexpected successes when run in verbose mode. |
| 742 | (Contributed by Benjamin Peterson.) |
| 743 | Test cases can raise the :exc:`SkipTest` exception to skip a test. |
| 744 | (:issue:`1034053`.) |
| 745 | |
| 746 | .. XXX describe test discovery (Contributed by Michael Foord; :issue:`6001`.) |
| 747 | |
| 748 | The error messages for :meth:`assertEqual`, |
| 749 | :meth:`assertTrue`, and :meth:`assertFalse` |
| 750 | failures now provide more information. If you set the |
| 751 | :attr:`longMessage` attribute of your :class:`TestCase` classes to |
| 752 | true, both the standard error message and any additional message you |
| 753 | provide will be printed for failures. (Added by Michael Foord; :issue:`5663`.) |
| 754 | |
| 755 | The :meth:`assertRaises` and :meth:`failUnlessRaises` methods now |
| 756 | return a context handler when called without providing a callable |
| 757 | object to run. For example, you can write this:: |
| 758 | |
| 759 | with self.assertRaises(KeyError): |
| 760 | raise ValueError |
| 761 | |
| 762 | (Implemented by Antoine Pitrou; :issue:`4444`.) |
| 763 | |
| 764 | The methods :meth:`addCleanup` and :meth:`doCleanups` were added. |
| 765 | :meth:`addCleanup` allows you to add cleanup functions that |
| 766 | will be called unconditionally (after :meth:`setUp` if |
| 767 | :meth:`setUp` fails, otherwise after :meth:`tearDown`). This allows |
| 768 | for much simpler resource allocation and deallocation during tests. |
| 769 | :issue:`5679` |
| 770 | |
| 771 | A number of new methods were added that provide more specialized |
| 772 | tests. Many of these methods were written by Google engineers |
| 773 | for use in their test suites; Gregory P. Smith, Michael Foord, and |
| 774 | GvR worked on merging them into Python's version of :mod:`unittest`. |
| 775 | |
| 776 | * :meth:`assertIsNone` and :meth:`assertIsNotNone` take one |
| 777 | expression and verify that the result is or is not ``None``. |
| 778 | |
| 779 | * :meth:`assertIs` and :meth:`assertIsNot` take two values and check |
| 780 | whether the two values evaluate to the same object or not. |
| 781 | (Added by Michael Foord; :issue:`2578`.) |
| 782 | |
| 783 | * :meth:`assertGreater`, :meth:`assertGreaterEqual`, |
| 784 | :meth:`assertLess`, and :meth:`assertLessEqual` compare |
| 785 | two quantities. |
| 786 | |
| 787 | * :meth:`assertMultiLineEqual` compares two strings, and if they're |
| 788 | not equal, displays a helpful comparison that highlights the |
| 789 | differences in the two strings. |
| 790 | |
| 791 | * :meth:`assertRegexpMatches` checks whether its first argument is a |
| 792 | string matching a regular expression provided as its second argument. |
| 793 | |
| 794 | * :meth:`assertRaisesRegexp` checks whether a particular exception |
| 795 | is raised, and then also checks that the string representation of |
| 796 | the exception matches the provided regular expression. |
| 797 | |
| 798 | * :meth:`assertIn` and :meth:`assertNotIn` tests whether |
| 799 | *first* is or is not in *second*. |
| 800 | |
| 801 | * :meth:`assertSameElements` tests whether two provided sequences |
| 802 | contain the same elements. |
| 803 | |
| 804 | * :meth:`assertSetEqual` compares whether two sets are equal, and |
| 805 | only reports the differences between the sets in case of error. |
| 806 | |
| 807 | * Similarly, :meth:`assertListEqual` and :meth:`assertTupleEqual` |
| 808 | compare the specified types and explain the differences. |
| 809 | More generally, :meth:`assertSequenceEqual` compares two sequences |
| 810 | and can optionally check whether both sequences are of a |
| 811 | particular type. |
| 812 | |
| 813 | * :meth:`assertDictEqual` compares two dictionaries and reports the |
| 814 | differences. :meth:`assertDictContainsSubset` checks whether |
| 815 | all of the key/value pairs in *first* are found in *second*. |
| 816 | |
| 817 | * :meth:`assertAlmostEqual` and :meth:`assertNotAlmostEqual` short-circuit |
| 818 | (automatically pass or fail without checking decimal places) if the objects |
| 819 | are equal. |
| 820 | |
| 821 | * :meth:`loadTestsFromName` properly honors the ``suiteClass`` attribute of |
| 822 | the :class:`TestLoader`. (Fixed by Mark Roddy; :issue:`6866`.) |
| 823 | |
| 824 | * A new hook, :meth:`addTypeEqualityFunc` takes a type object and a |
| 825 | function. The :meth:`assertEqual` method will use the function |
| 826 | when both of the objects being compared are of the specified type. |
| 827 | This function should compare the two objects and raise an |
| 828 | exception if they don't match; it's a good idea for the function |
| 829 | to provide additional information about why the two objects are |
| 830 | matching, much as the new sequence comparison methods do. |
| 831 | |
| 832 | :func:`unittest.main` now takes an optional ``exit`` argument. |
| 833 | If False ``main`` doesn't call :func:`sys.exit` allowing it to |
| 834 | be used from the interactive interpreter. :issue:`3379`. |
| 835 | |
| 836 | :class:`TestResult` has new :meth:`startTestRun` and |
| 837 | :meth:`stopTestRun` methods; called immediately before |
| 838 | and after a test run. :issue:`5728` by Robert Collins. |
| 839 | |
| 840 | With all these changes, the :file:`unittest.py` was becoming awkwardly |
| 841 | large, so the module was turned into a package and the code split into |
| 842 | several files (by Benjamin Peterson). This doesn't affect how the |
| 843 | module is imported. |
| 844 | |
| 845 | |
| 846 | .. _importlib-section: |
| 847 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 848 | importlib: Importing Modules |
| 849 | ------------------------------ |
| 850 | |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 851 | Python 3.1 includes the :mod:`importlib` package, a re-implementation |
| 852 | of the logic underlying Python's :keyword:`import` statement. |
| 853 | :mod:`importlib` is useful for implementors of Python interpreters and |
| 854 | to user who wish to write new importers that can participate in the |
| 855 | import process. Python 2.7 doesn't contain the complete |
| 856 | :mod:`importlib` package, but instead has a tiny subset that contains |
| 857 | a single function, :func:`import_module`. |
| 858 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 859 | ``import_module(name, package=None)`` imports a module. *name* is |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 860 | a string containing the module or package's name. It's possible to do |
| 861 | relative imports by providing a string that begins with a ``.`` |
| 862 | character, such as ``..utils.errors``. For relative imports, the |
| 863 | *package* argument must be provided and is the name of the package that |
| 864 | will be used as the anchor for |
| 865 | the relative import. :func:`import_module` both inserts the imported |
| 866 | module into ``sys.modules`` and returns the module object. |
| 867 | |
| 868 | Here are some examples:: |
| 869 | |
| 870 | >>> from importlib import import_module |
| 871 | >>> anydbm = import_module('anydbm') # Standard absolute import |
| 872 | >>> anydbm |
| 873 | <module 'anydbm' from '/p/python/Lib/anydbm.py'> |
| 874 | >>> # Relative import |
| 875 | >>> sysconfig = import_module('..sysconfig', 'distutils.command') |
| 876 | >>> sysconfig |
| 877 | <module 'distutils.sysconfig' from '/p/python/Lib/distutils/sysconfig.pyc'> |
| 878 | |
| 879 | :mod:`importlib` was implemented by Brett Cannon and introduced in |
| 880 | Python 3.1. |
| 881 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 882 | |
Benjamin Peterson | 5c6d787 | 2009-02-06 02:40:07 +0000 | [diff] [blame] | 883 | ttk: Themed Widgets for Tk |
| 884 | -------------------------- |
| 885 | |
| 886 | Tcl/Tk 8.5 includes a set of themed widgets that re-implement basic Tk |
| 887 | widgets but have a more customizable appearance and can therefore more |
| 888 | closely resemble the native platform's widgets. This widget |
| 889 | set was originally called Tile, but was renamed to Ttk (for "themed Tk") |
| 890 | on being added to Tcl/Tck release 8.5. |
| 891 | |
| 892 | XXX write a brief discussion and an example here. |
| 893 | |
| 894 | The :mod:`ttk` module was written by Guilherme Polo and added in |
| 895 | :issue:`2983`. An alternate version called ``Tile.py``, written by |
| 896 | Martin Franklin and maintained by Kevin Walzer, was proposed for |
| 897 | inclusion in :issue:`2618`, but the authors argued that Guilherme |
| 898 | Polo's work was more comprehensive. |
| 899 | |
Georg Brandl | 4d131ee | 2009-11-18 18:53:14 +0000 | [diff] [blame] | 900 | |
| 901 | Deprecations and Removals |
| 902 | ========================= |
| 903 | |
| 904 | * :func:`contextlib.nested`, which allows handling more than one context manager |
| 905 | with one :keyword:`with` statement, has been deprecated; :keyword:`with` |
| 906 | supports multiple context managers syntactically now. |
| 907 | |
Benjamin Peterson | f10a79a | 2008-10-11 00:49:57 +0000 | [diff] [blame] | 908 | .. ====================================================================== |
| 909 | |
| 910 | |
| 911 | Build and C API Changes |
| 912 | ======================= |
| 913 | |
| 914 | Changes to Python's build process and to the C API include: |
| 915 | |
Georg Brandl | 1f01deb | 2009-01-03 22:47:39 +0000 | [diff] [blame] | 916 | * If you use the :file:`.gdbinit` file provided with Python, |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 917 | the "pyo" macro in the 2.7 version now works correctly when the thread being |
| 918 | debugged doesn't hold the GIL; the macro now acquires it before printing. |
Benjamin Peterson | 1010bf3 | 2009-01-30 04:00:29 +0000 | [diff] [blame] | 919 | (Contributed by Victor Stinner; :issue:`3632`.) |
| 920 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 921 | * :cfunc:`Py_AddPendingCall` is now thread-safe, letting any |
Benjamin Peterson | 1010bf3 | 2009-01-30 04:00:29 +0000 | [diff] [blame] | 922 | worker thread submit notifications to the main Python thread. This |
| 923 | is particularly useful for asynchronous IO operations. |
| 924 | (Contributed by Kristjan Valur Jonsson; :issue:`4293`.) |
| 925 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 926 | * New function: :cfunc:`PyCode_NewEmpty` creates an empty code object; |
| 927 | only the filename, function name, and first line number are required. |
| 928 | This is useful to extension modules that are attempting to |
| 929 | construct a more useful traceback stack. Previously such |
| 930 | extensions needed to call :cfunc:`PyCode_New`, which had many |
| 931 | more arguments. (Added by Jeffrey Yasskin.) |
| 932 | |
| 933 | * New function: :cfunc:`PyFrame_GetLineNumber` takes a frame object |
| 934 | and returns the line number that the frame is currently executing. |
| 935 | Previously code would need to get the index of the bytecode |
| 936 | instruction currently executing, and then look up the line number |
| 937 | corresponding to that address. (Added by Jeffrey Yasskin.) |
| 938 | |
| 939 | * New macros: the Python header files now define the following macros: |
| 940 | :cmacro:`Py_ISALNUM`, |
| 941 | :cmacro:`Py_ISALPHA`, |
| 942 | :cmacro:`Py_ISDIGIT`, |
| 943 | :cmacro:`Py_ISLOWER`, |
| 944 | :cmacro:`Py_ISSPACE`, |
| 945 | :cmacro:`Py_ISUPPER`, |
| 946 | :cmacro:`Py_ISXDIGIT`, |
| 947 | and :cmacro:`Py_TOLOWER`, :cmacro:`Py_TOUPPER`. |
| 948 | All of these functions are analogous to the C |
| 949 | standard macros for classifying characters, but ignore the current |
| 950 | locale setting, because in |
| 951 | several places Python needs to analyze characters in a |
| 952 | locale-independent way. (Added by Eric Smith; |
| 953 | :issue:`5793`.) |
| 954 | |
| 955 | .. XXX these macros don't seem to be described in the c-api docs. |
| 956 | |
| 957 | * The complicated interaction between threads and process forking has |
| 958 | been changed. Previously, the child process created by |
| 959 | :func:`os.fork` might fail because the child is created with only a |
| 960 | single thread running, the thread performing the :func:`os.fork`. |
| 961 | If other threads were holding a lock, such as Python's import lock, |
| 962 | when the fork was performed, the lock would still be marked as |
| 963 | "held" in the new process. But in the child process nothing would |
| 964 | ever release the lock, since the other threads weren't replicated, |
| 965 | and the child process would no longer be able to perform imports. |
| 966 | |
| 967 | Python 2.7 now acquires the import lock before performing an |
| 968 | :func:`os.fork`, and will also clean up any locks created using the |
| 969 | :mod:`threading` module. C extension modules that have internal |
| 970 | locks, or that call :cfunc:`fork()` themselves, will not benefit |
| 971 | from this clean-up. |
| 972 | |
| 973 | (Fixed by Thomas Wouters; :issue:`1590864`.) |
| 974 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 975 | * Global symbols defined by the :mod:`ctypes` module are now prefixed |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 976 | with ``Py``, or with ``_ctypes``. (Implemented by Thomas |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 977 | Heller; :issue:`3102`.) |
| 978 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 979 | * The :program:`configure` script now checks for floating-point rounding bugs |
| 980 | on certain 32-bit Intel chips and defines a :cmacro:`X87_DOUBLE_ROUNDING` |
| 981 | preprocessor definition. No code currently uses this definition, |
| 982 | but it's available if anyone wishes to use it. |
| 983 | (Added by Mark Dickinson; :issue:`2937`.) |
Benjamin Peterson | f10a79a | 2008-10-11 00:49:57 +0000 | [diff] [blame] | 984 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 985 | * The build process now creates the necessary files for pkg-config |
| 986 | support. (Contributed by Clinton Roy; :issue:`3585`.) |
| 987 | |
| 988 | * The build process now supports Subversion 1.7. (Contributed by |
| 989 | Arfrever Frehtes Taifersar Arahesis; :issue:`6094`.) |
| 990 | |
Benjamin Peterson | f10a79a | 2008-10-11 00:49:57 +0000 | [diff] [blame] | 991 | .. ====================================================================== |
| 992 | |
| 993 | Port-Specific Changes: Windows |
| 994 | ----------------------------------- |
| 995 | |
Georg Brandl | 1f01deb | 2009-01-03 22:47:39 +0000 | [diff] [blame] | 996 | * The :mod:`msvcrt` module now contains some constants from |
| 997 | the :file:`crtassem.h` header file: |
| 998 | :data:`CRT_ASSEMBLY_VERSION`, |
| 999 | :data:`VC_ASSEMBLY_PUBLICKEYTOKEN`, |
| 1000 | and :data:`LIBRARIES_ASSEMBLY_NAME_PREFIX`. |
Benjamin Peterson | 1010bf3 | 2009-01-30 04:00:29 +0000 | [diff] [blame] | 1001 | (Contributed by David Cournapeau; :issue:`4365`.) |
| 1002 | |
| 1003 | * The new :cfunc:`_beginthreadex` API is used to start threads, and |
| 1004 | the native thread-local storage functions are now used. |
| 1005 | (Contributed by Kristjan Valur Jonsson; :issue:`3582`.) |
Benjamin Peterson | f10a79a | 2008-10-11 00:49:57 +0000 | [diff] [blame] | 1006 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 1007 | * The :func:`os.listdir` function now correctly fails |
| 1008 | for an empty path. (Fixed by Hirokazu Yamamoto; :issue:`5913`.) |
| 1009 | |
Benjamin Peterson | f10a79a | 2008-10-11 00:49:57 +0000 | [diff] [blame] | 1010 | .. ====================================================================== |
| 1011 | |
| 1012 | Port-Specific Changes: Mac OS X |
| 1013 | ----------------------------------- |
| 1014 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 1015 | * The path ``/Library/Python/2.7/site-packages`` is now appended to |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 1016 | ``sys.path``, in order to share added packages between the system |
| 1017 | installation and a user-installed copy of the same version. |
| 1018 | (Changed by Ronald Oussoren; :issue:`4865`.) |
| 1019 | |
| 1020 | |
| 1021 | Other Changes and Fixes |
| 1022 | ======================= |
| 1023 | |
| 1024 | * When importing a module from a :file:`.pyc` or :file:`.pyo` file |
| 1025 | with an existing :file:`.py` counterpart, the :attr:`co_filename` |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 1026 | attributes of the resulting code objects are overwritten when the |
| 1027 | original filename is obsolete. This can happen if the file has been |
| 1028 | renamed, moved, or is accessed through different paths. (Patch by |
| 1029 | Ziga Seilnacht and Jean-Paul Calderone; :issue:`1180193`.) |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 1030 | |
| 1031 | * The :file:`regrtest.py` script now takes a :option:`--randseed=` |
| 1032 | switch that takes an integer that will be used as the random seed |
| 1033 | for the :option:`-r` option that executes tests in random order. |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 1034 | The :option:`-r` option also reports the seed that was used |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 1035 | (Added by Collin Winter.) |
| 1036 | |
Antoine Pitrou | 8890954 | 2009-06-29 13:54:42 +0000 | [diff] [blame] | 1037 | * The :file:`regrtest.py` script now takes a :option:`-j` switch |
| 1038 | that takes an integer specifying how many tests run in parallel. This |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 1039 | allows reducing the total runtime on multi-core machines. |
Antoine Pitrou | 8890954 | 2009-06-29 13:54:42 +0000 | [diff] [blame] | 1040 | This option is compatible with several other options, including the |
| 1041 | :option:`-R` switch which is known to produce long runtimes. |
| 1042 | (Added by Antoine Pitrou, :issue:`6152`.) |
Benjamin Peterson | f10a79a | 2008-10-11 00:49:57 +0000 | [diff] [blame] | 1043 | |
| 1044 | .. ====================================================================== |
| 1045 | |
| 1046 | Porting to Python 2.7 |
| 1047 | ===================== |
| 1048 | |
| 1049 | This section lists previously described changes and other bugfixes |
| 1050 | that may require changes to your code: |
| 1051 | |
Benjamin Peterson | f6489f9 | 2009-11-25 17:46:26 +0000 | [diff] [blame^] | 1052 | * When using :class:`Decimal` instances with a string's |
| 1053 | :meth:`format` method, the default alignment was previously |
| 1054 | left-alignment. This has been changed to right-alignment, which might |
| 1055 | change the output of your programs. |
| 1056 | (Changed by Mark Dickinson; :issue:`6857`.) |
| 1057 | |
| 1058 | Another :meth:`format`-related change: the default precision used |
| 1059 | for floating-point and complex numbers was changed from 6 decimal |
| 1060 | places to 12, which matches the precision used by :func:`str`. |
| 1061 | (Changed by Eric Smith; :issue:`5920`.) |
| 1062 | |
Benjamin Peterson | 87c8d87 | 2009-06-11 22:54:11 +0000 | [diff] [blame] | 1063 | * Because of an optimization for the :keyword:`with` statement, the special |
| 1064 | methods :meth:`__enter__` and :meth:`__exit__` must belong to the object's |
| 1065 | type, and cannot be directly attached to the object's instance. This |
| 1066 | affects new-style classes (derived from :class:`object`) and C extension |
| 1067 | types. (:issue:`6101`.) |
Benjamin Peterson | f10a79a | 2008-10-11 00:49:57 +0000 | [diff] [blame] | 1068 | |
| 1069 | .. ====================================================================== |
| 1070 | |
| 1071 | |
| 1072 | .. _acks27: |
| 1073 | |
| 1074 | Acknowledgements |
| 1075 | ================ |
| 1076 | |
| 1077 | The author would like to thank the following people for offering |
| 1078 | suggestions, corrections and assistance with various drafts of this |
| 1079 | article: no one yet. |
| 1080 | |