[388] | 1 | ****************************
|
---|
| 2 | What's New in Python 2.7
|
---|
| 3 | ****************************
|
---|
| 4 |
|
---|
| 5 | :Author: A.M. Kuchling (amk at amk.ca)
|
---|
| 6 |
|
---|
| 7 | .. hyperlink all the methods & functions.
|
---|
| 8 |
|
---|
| 9 | .. T_STRING_INPLACE not described in main docs
|
---|
| 10 |
|
---|
| 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 |
|
---|
| 52 | This article explains the new features in Python 2.7. Python 2.7 was released
|
---|
| 53 | on July 3, 2010.
|
---|
| 54 |
|
---|
| 55 | Numeric handling has been improved in many ways, for both
|
---|
| 56 | floating-point numbers and for the :class:`~decimal.Decimal` class.
|
---|
| 57 | There are some useful additions to the standard library, such as a
|
---|
| 58 | greatly enhanced :mod:`unittest` module, the :mod:`argparse` module
|
---|
| 59 | for parsing command-line options, convenient :class:`~collections.OrderedDict`
|
---|
| 60 | and :class:`~collections.Counter` classes in the :mod:`collections` module,
|
---|
| 61 | and many other improvements.
|
---|
| 62 |
|
---|
| 63 | Python 2.7 is planned to be the last of the 2.x releases, so we worked
|
---|
| 64 | on making it a good release for the long term. To help with porting
|
---|
| 65 | to Python 3, several new features from the Python 3.x series have been
|
---|
| 66 | included in 2.7.
|
---|
| 67 |
|
---|
| 68 | This article doesn't attempt to provide a complete specification of
|
---|
| 69 | the new features, but instead provides a convenient overview. For
|
---|
| 70 | full details, you should refer to the documentation for Python 2.7 at
|
---|
| 71 | http://docs.python.org. If you want to understand the rationale for
|
---|
| 72 | the design and implementation, refer to the PEP for a particular new
|
---|
| 73 | feature or the issue on http://bugs.python.org in which a change was
|
---|
| 74 | discussed. Whenever possible, "What's New in Python" links to the
|
---|
| 75 | bug/patch item for each change.
|
---|
| 76 |
|
---|
| 77 | .. _whatsnew27-python31:
|
---|
| 78 |
|
---|
| 79 | The Future for Python 2.x
|
---|
| 80 | =========================
|
---|
| 81 |
|
---|
| 82 | Python 2.7 is intended to be the last major release in the 2.x series.
|
---|
| 83 | The Python maintainers are planning to focus their future efforts on
|
---|
| 84 | the Python 3.x series.
|
---|
| 85 |
|
---|
| 86 | This means that 2.7 will remain in place for a long time, running
|
---|
| 87 | production systems that have not been ported to Python 3.x.
|
---|
| 88 | Two consequences of the long-term significance of 2.7 are:
|
---|
| 89 |
|
---|
| 90 | * It's very likely the 2.7 release will have a longer period of
|
---|
| 91 | maintenance compared to earlier 2.x versions. Python 2.7 will
|
---|
| 92 | continue to be maintained while the transition to 3.x continues, and
|
---|
| 93 | the developers are planning to support Python 2.7 with bug-fix
|
---|
| 94 | releases beyond the typical two years.
|
---|
| 95 |
|
---|
| 96 | * A policy decision was made to silence warnings only of interest to
|
---|
| 97 | developers. :exc:`DeprecationWarning` and its
|
---|
| 98 | descendants are now ignored unless otherwise requested, preventing
|
---|
| 99 | users from seeing warnings triggered by an application. This change
|
---|
| 100 | was also made in the branch that will become Python 3.2. (Discussed
|
---|
| 101 | on stdlib-sig and carried out in :issue:`7319`.)
|
---|
| 102 |
|
---|
| 103 | In previous releases, :exc:`DeprecationWarning` messages were
|
---|
| 104 | enabled by default, providing Python developers with a clear
|
---|
| 105 | indication of where their code may break in a future major version
|
---|
| 106 | of Python.
|
---|
| 107 |
|
---|
| 108 | However, there are increasingly many users of Python-based
|
---|
| 109 | applications who are not directly involved in the development of
|
---|
| 110 | those applications. :exc:`DeprecationWarning` messages are
|
---|
| 111 | irrelevant to such users, making them worry about an application
|
---|
| 112 | that's actually working correctly and burdening application developers
|
---|
| 113 | with responding to these concerns.
|
---|
| 114 |
|
---|
| 115 | You can re-enable display of :exc:`DeprecationWarning` messages by
|
---|
| 116 | running Python with the :option:`-Wdefault <-W>` (short form:
|
---|
| 117 | :option:`-Wd <-W>`) switch, or by setting the :envvar:`PYTHONWARNINGS`
|
---|
| 118 | environment variable to ``"default"`` (or ``"d"``) before running
|
---|
| 119 | Python. Python code can also re-enable them
|
---|
| 120 | by calling ``warnings.simplefilter('default')``.
|
---|
| 121 |
|
---|
| 122 |
|
---|
| 123 | Python 3.1 Features
|
---|
| 124 | =======================
|
---|
| 125 |
|
---|
| 126 | Much as Python 2.6 incorporated features from Python 3.0,
|
---|
| 127 | version 2.7 incorporates some of the new features
|
---|
| 128 | in Python 3.1. The 2.x series continues to provide tools
|
---|
| 129 | for migrating to the 3.x series.
|
---|
| 130 |
|
---|
| 131 | A partial list of 3.1 features that were backported to 2.7:
|
---|
| 132 |
|
---|
| 133 | * The syntax for set literals (``{1,2,3}`` is a mutable set).
|
---|
| 134 | * Dictionary and set comprehensions (``{i: i*2 for i in range(3)}``).
|
---|
| 135 | * Multiple context managers in a single :keyword:`with` statement.
|
---|
| 136 | * A new version of the :mod:`io` library, rewritten in C for performance.
|
---|
| 137 | * The ordered-dictionary type described in :ref:`pep-0372`.
|
---|
| 138 | * The new ``","`` format specifier described in :ref:`pep-0378`.
|
---|
| 139 | * The :class:`memoryview` object.
|
---|
| 140 | * A small subset of the :mod:`importlib` module,
|
---|
| 141 | `described below <#importlib-section>`__.
|
---|
| 142 | * The :func:`repr` of a float ``x`` is shorter in many cases: it's now
|
---|
| 143 | based on the shortest decimal string that's guaranteed to round back
|
---|
| 144 | to ``x``. As in previous versions of Python, it's guaranteed that
|
---|
| 145 | ``float(repr(x))`` recovers ``x``.
|
---|
| 146 | * Float-to-string and string-to-float conversions are correctly rounded.
|
---|
| 147 | The :func:`round` function is also now correctly rounded.
|
---|
| 148 | * The :c:type:`PyCapsule` type, used to provide a C API for extension modules.
|
---|
| 149 | * The :c:func:`PyLong_AsLongAndOverflow` C API function.
|
---|
| 150 |
|
---|
| 151 | Other new Python3-mode warnings include:
|
---|
| 152 |
|
---|
| 153 | * :func:`operator.isCallable` and :func:`operator.sequenceIncludes`,
|
---|
| 154 | which are not supported in 3.x, now trigger warnings.
|
---|
| 155 | * The :option:`-3` switch now automatically
|
---|
| 156 | enables the :option:`-Qwarn <-Q>` switch that causes warnings
|
---|
| 157 | about using classic division with integers and long integers.
|
---|
| 158 |
|
---|
| 159 |
|
---|
| 160 |
|
---|
| 161 | .. ========================================================================
|
---|
| 162 | .. Large, PEP-level features and changes should be described here.
|
---|
| 163 | .. ========================================================================
|
---|
| 164 |
|
---|
| 165 | .. _pep-0372:
|
---|
| 166 |
|
---|
| 167 | PEP 372: Adding an Ordered Dictionary to collections
|
---|
| 168 | ====================================================
|
---|
| 169 |
|
---|
| 170 | Regular Python dictionaries iterate over key/value pairs in arbitrary order.
|
---|
| 171 | Over the years, a number of authors have written alternative implementations
|
---|
| 172 | that remember the order that the keys were originally inserted. Based on
|
---|
| 173 | the experiences from those implementations, 2.7 introduces a new
|
---|
| 174 | :class:`~collections.OrderedDict` class in the :mod:`collections` module.
|
---|
| 175 |
|
---|
| 176 | The :class:`~collections.OrderedDict` API provides the same interface as regular
|
---|
| 177 | dictionaries but iterates over keys and values in a guaranteed order
|
---|
| 178 | depending on when a key was first inserted::
|
---|
| 179 |
|
---|
| 180 | >>> from collections import OrderedDict
|
---|
| 181 | >>> d = OrderedDict([('first', 1),
|
---|
| 182 | ... ('second', 2),
|
---|
| 183 | ... ('third', 3)])
|
---|
| 184 | >>> d.items()
|
---|
| 185 | [('first', 1), ('second', 2), ('third', 3)]
|
---|
| 186 |
|
---|
| 187 | If a new entry overwrites an existing entry, the original insertion
|
---|
| 188 | position is left unchanged::
|
---|
| 189 |
|
---|
| 190 | >>> d['second'] = 4
|
---|
| 191 | >>> d.items()
|
---|
| 192 | [('first', 1), ('second', 4), ('third', 3)]
|
---|
| 193 |
|
---|
| 194 | Deleting an entry and reinserting it will move it to the end::
|
---|
| 195 |
|
---|
| 196 | >>> del d['second']
|
---|
| 197 | >>> d['second'] = 5
|
---|
| 198 | >>> d.items()
|
---|
| 199 | [('first', 1), ('third', 3), ('second', 5)]
|
---|
| 200 |
|
---|
| 201 | The :meth:`~collections.OrderedDict.popitem` method has an optional *last*
|
---|
| 202 | argument that defaults to True. If *last* is True, the most recently
|
---|
| 203 | added key is returned and removed; if it's False, the
|
---|
| 204 | oldest key is selected::
|
---|
| 205 |
|
---|
| 206 | >>> od = OrderedDict([(x,0) for x in range(20)])
|
---|
| 207 | >>> od.popitem()
|
---|
| 208 | (19, 0)
|
---|
| 209 | >>> od.popitem()
|
---|
| 210 | (18, 0)
|
---|
| 211 | >>> od.popitem(last=False)
|
---|
| 212 | (0, 0)
|
---|
| 213 | >>> od.popitem(last=False)
|
---|
| 214 | (1, 0)
|
---|
| 215 |
|
---|
| 216 | Comparing two ordered dictionaries checks both the keys and values,
|
---|
| 217 | and requires that the insertion order was the same::
|
---|
| 218 |
|
---|
| 219 | >>> od1 = OrderedDict([('first', 1),
|
---|
| 220 | ... ('second', 2),
|
---|
| 221 | ... ('third', 3)])
|
---|
| 222 | >>> od2 = OrderedDict([('third', 3),
|
---|
| 223 | ... ('first', 1),
|
---|
| 224 | ... ('second', 2)])
|
---|
| 225 | >>> od1 == od2
|
---|
| 226 | False
|
---|
| 227 | >>> # Move 'third' key to the end
|
---|
| 228 | >>> del od2['third']; od2['third'] = 3
|
---|
| 229 | >>> od1 == od2
|
---|
| 230 | True
|
---|
| 231 |
|
---|
| 232 | Comparing an :class:`~collections.OrderedDict` with a regular dictionary
|
---|
| 233 | ignores the insertion order and just compares the keys and values.
|
---|
| 234 |
|
---|
| 235 | How does the :class:`~collections.OrderedDict` work? It maintains a
|
---|
| 236 | doubly-linked list of keys, appending new keys to the list as they're inserted.
|
---|
| 237 | A secondary dictionary maps keys to their corresponding list node, so
|
---|
| 238 | deletion doesn't have to traverse the entire linked list and therefore
|
---|
| 239 | remains O(1).
|
---|
| 240 |
|
---|
| 241 | The standard library now supports use of ordered dictionaries in several
|
---|
| 242 | modules.
|
---|
| 243 |
|
---|
| 244 | * The :mod:`ConfigParser` module uses them by default, meaning that
|
---|
| 245 | configuration files can now be read, modified, and then written back
|
---|
| 246 | in their original order.
|
---|
| 247 |
|
---|
| 248 | * The :meth:`~collections.somenamedtuple._asdict()` method for
|
---|
| 249 | :func:`collections.namedtuple` now returns an ordered dictionary with the
|
---|
| 250 | values appearing in the same order as the underlying tuple indices.
|
---|
| 251 |
|
---|
| 252 | * The :mod:`json` module's :class:`~json.JSONDecoder` class
|
---|
| 253 | constructor was extended with an *object_pairs_hook* parameter to
|
---|
| 254 | allow :class:`OrderedDict` instances to be built by the decoder.
|
---|
| 255 | Support was also added for third-party tools like
|
---|
| 256 | `PyYAML <http://pyyaml.org/>`_.
|
---|
| 257 |
|
---|
| 258 | .. seealso::
|
---|
| 259 |
|
---|
| 260 | :pep:`372` - Adding an ordered dictionary to collections
|
---|
| 261 | PEP written by Armin Ronacher and Raymond Hettinger;
|
---|
| 262 | implemented by Raymond Hettinger.
|
---|
| 263 |
|
---|
| 264 | .. _pep-0378:
|
---|
| 265 |
|
---|
| 266 | PEP 378: Format Specifier for Thousands Separator
|
---|
| 267 | =================================================
|
---|
| 268 |
|
---|
| 269 | To make program output more readable, it can be useful to add
|
---|
| 270 | separators to large numbers, rendering them as
|
---|
| 271 | 18,446,744,073,709,551,616 instead of 18446744073709551616.
|
---|
| 272 |
|
---|
| 273 | The fully general solution for doing this is the :mod:`locale` module,
|
---|
| 274 | which can use different separators ("," in North America, "." in
|
---|
| 275 | Europe) and different grouping sizes, but :mod:`locale` is complicated
|
---|
| 276 | to use and unsuitable for multi-threaded applications where different
|
---|
| 277 | threads are producing output for different locales.
|
---|
| 278 |
|
---|
| 279 | Therefore, a simple comma-grouping mechanism has been added to the
|
---|
| 280 | mini-language used by the :meth:`str.format` method. When
|
---|
| 281 | formatting a floating-point number, simply include a comma between the
|
---|
| 282 | width and the precision::
|
---|
| 283 |
|
---|
| 284 | >>> '{:20,.2f}'.format(18446744073709551616.0)
|
---|
| 285 | '18,446,744,073,709,551,616.00'
|
---|
| 286 |
|
---|
| 287 | When formatting an integer, include the comma after the width:
|
---|
| 288 |
|
---|
| 289 | >>> '{:20,d}'.format(18446744073709551616)
|
---|
| 290 | '18,446,744,073,709,551,616'
|
---|
| 291 |
|
---|
| 292 | This mechanism is not adaptable at all; commas are always used as the
|
---|
| 293 | separator and the grouping is always into three-digit groups. The
|
---|
| 294 | comma-formatting mechanism isn't as general as the :mod:`locale`
|
---|
| 295 | module, but it's easier to use.
|
---|
| 296 |
|
---|
| 297 | .. seealso::
|
---|
| 298 |
|
---|
| 299 | :pep:`378` - Format Specifier for Thousands Separator
|
---|
| 300 | PEP written by Raymond Hettinger; implemented by Eric Smith.
|
---|
| 301 |
|
---|
| 302 | PEP 389: The argparse Module for Parsing Command Lines
|
---|
| 303 | ======================================================
|
---|
| 304 |
|
---|
| 305 | The :mod:`argparse` module for parsing command-line arguments was
|
---|
| 306 | added as a more powerful replacement for the
|
---|
| 307 | :mod:`optparse` module.
|
---|
| 308 |
|
---|
| 309 | This means Python now supports three different modules for parsing
|
---|
| 310 | command-line arguments: :mod:`getopt`, :mod:`optparse`, and
|
---|
| 311 | :mod:`argparse`. The :mod:`getopt` module closely resembles the C
|
---|
| 312 | library's :c:func:`getopt` function, so it remains useful if you're writing a
|
---|
| 313 | Python prototype that will eventually be rewritten in C.
|
---|
| 314 | :mod:`optparse` becomes redundant, but there are no plans to remove it
|
---|
| 315 | because there are many scripts still using it, and there's no
|
---|
| 316 | automated way to update these scripts. (Making the :mod:`argparse`
|
---|
| 317 | API consistent with :mod:`optparse`'s interface was discussed but
|
---|
| 318 | rejected as too messy and difficult.)
|
---|
| 319 |
|
---|
| 320 | In short, if you're writing a new script and don't need to worry
|
---|
| 321 | about compatibility with earlier versions of Python, use
|
---|
| 322 | :mod:`argparse` instead of :mod:`optparse`.
|
---|
| 323 |
|
---|
| 324 | Here's an example::
|
---|
| 325 |
|
---|
| 326 | import argparse
|
---|
| 327 |
|
---|
| 328 | parser = argparse.ArgumentParser(description='Command-line example.')
|
---|
| 329 |
|
---|
| 330 | # Add optional switches
|
---|
| 331 | parser.add_argument('-v', action='store_true', dest='is_verbose',
|
---|
| 332 | help='produce verbose output')
|
---|
| 333 | parser.add_argument('-o', action='store', dest='output',
|
---|
| 334 | metavar='FILE',
|
---|
| 335 | help='direct output to FILE instead of stdout')
|
---|
| 336 | parser.add_argument('-C', action='store', type=int, dest='context',
|
---|
| 337 | metavar='NUM', default=0,
|
---|
| 338 | help='display NUM lines of added context')
|
---|
| 339 |
|
---|
| 340 | # Allow any number of additional arguments.
|
---|
| 341 | parser.add_argument(nargs='*', action='store', dest='inputs',
|
---|
| 342 | help='input filenames (default is stdin)')
|
---|
| 343 |
|
---|
| 344 | args = parser.parse_args()
|
---|
| 345 | print args.__dict__
|
---|
| 346 |
|
---|
| 347 | Unless you override it, :option:`-h` and :option:`--help` switches
|
---|
| 348 | are automatically added, and produce neatly formatted output::
|
---|
| 349 |
|
---|
| 350 | -> ./python.exe argparse-example.py --help
|
---|
| 351 | usage: argparse-example.py [-h] [-v] [-o FILE] [-C NUM] [inputs [inputs ...]]
|
---|
| 352 |
|
---|
| 353 | Command-line example.
|
---|
| 354 |
|
---|
| 355 | positional arguments:
|
---|
| 356 | inputs input filenames (default is stdin)
|
---|
| 357 |
|
---|
| 358 | optional arguments:
|
---|
| 359 | -h, --help show this help message and exit
|
---|
| 360 | -v produce verbose output
|
---|
| 361 | -o FILE direct output to FILE instead of stdout
|
---|
| 362 | -C NUM display NUM lines of added context
|
---|
| 363 |
|
---|
| 364 | As with :mod:`optparse`, the command-line switches and arguments
|
---|
| 365 | are returned as an object with attributes named by the *dest* parameters::
|
---|
| 366 |
|
---|
| 367 | -> ./python.exe argparse-example.py -v
|
---|
| 368 | {'output': None,
|
---|
| 369 | 'is_verbose': True,
|
---|
| 370 | 'context': 0,
|
---|
| 371 | 'inputs': []}
|
---|
| 372 |
|
---|
| 373 | -> ./python.exe argparse-example.py -v -o /tmp/output -C 4 file1 file2
|
---|
| 374 | {'output': '/tmp/output',
|
---|
| 375 | 'is_verbose': True,
|
---|
| 376 | 'context': 4,
|
---|
| 377 | 'inputs': ['file1', 'file2']}
|
---|
| 378 |
|
---|
| 379 | :mod:`argparse` has much fancier validation than :mod:`optparse`; you
|
---|
| 380 | can specify an exact number of arguments as an integer, 0 or more
|
---|
| 381 | arguments by passing ``'*'``, 1 or more by passing ``'+'``, or an
|
---|
| 382 | optional argument with ``'?'``. A top-level parser can contain
|
---|
| 383 | sub-parsers to define subcommands that have different sets of
|
---|
| 384 | switches, as in ``svn commit``, ``svn checkout``, etc. You can
|
---|
| 385 | specify an argument's type as :class:`~argparse.FileType`, which will
|
---|
| 386 | automatically open files for you and understands that ``'-'`` means
|
---|
| 387 | standard input or output.
|
---|
| 388 |
|
---|
| 389 | .. seealso::
|
---|
| 390 |
|
---|
| 391 | :mod:`argparse` documentation
|
---|
| 392 | The documentation page of the argparse module.
|
---|
| 393 |
|
---|
| 394 | :ref:`argparse-from-optparse`
|
---|
| 395 | Part of the Python documentation, describing how to convert
|
---|
| 396 | code that uses :mod:`optparse`.
|
---|
| 397 |
|
---|
| 398 | :pep:`389` - argparse - New Command Line Parsing Module
|
---|
| 399 | PEP written and implemented by Steven Bethard.
|
---|
| 400 |
|
---|
| 401 | PEP 391: Dictionary-Based Configuration For Logging
|
---|
| 402 | ====================================================
|
---|
| 403 |
|
---|
| 404 | The :mod:`logging` module is very flexible; applications can define
|
---|
| 405 | a tree of logging subsystems, and each logger in this tree can filter
|
---|
| 406 | out certain messages, format them differently, and direct messages to
|
---|
| 407 | a varying number of handlers.
|
---|
| 408 |
|
---|
| 409 | All this flexibility can require a lot of configuration. You can
|
---|
| 410 | write Python statements to create objects and set their properties,
|
---|
| 411 | but a complex set-up requires verbose but boring code.
|
---|
| 412 | :mod:`logging` also supports a :func:`~logging.fileConfig`
|
---|
| 413 | function that parses a file, but the file format doesn't support
|
---|
| 414 | configuring filters, and it's messier to generate programmatically.
|
---|
| 415 |
|
---|
| 416 | Python 2.7 adds a :func:`~logging.dictConfig` function that
|
---|
| 417 | uses a dictionary to configure logging. There are many ways to
|
---|
| 418 | produce a dictionary from different sources: construct one with code;
|
---|
| 419 | parse a file containing JSON; or use a YAML parsing library if one is
|
---|
| 420 | installed. For more information see :ref:`logging-config-api`.
|
---|
| 421 |
|
---|
| 422 | The following example configures two loggers, the root logger and a
|
---|
| 423 | logger named "network". Messages sent to the root logger will be
|
---|
| 424 | sent to the system log using the syslog protocol, and messages
|
---|
| 425 | to the "network" logger will be written to a :file:`network.log` file
|
---|
| 426 | that will be rotated once the log reaches 1MB.
|
---|
| 427 |
|
---|
| 428 | ::
|
---|
| 429 |
|
---|
| 430 | import logging
|
---|
| 431 | import logging.config
|
---|
| 432 |
|
---|
| 433 | configdict = {
|
---|
| 434 | 'version': 1, # Configuration schema in use; must be 1 for now
|
---|
| 435 | 'formatters': {
|
---|
| 436 | 'standard': {
|
---|
| 437 | 'format': ('%(asctime)s %(name)-15s '
|
---|
| 438 | '%(levelname)-8s %(message)s')}},
|
---|
| 439 |
|
---|
| 440 | 'handlers': {'netlog': {'backupCount': 10,
|
---|
| 441 | 'class': 'logging.handlers.RotatingFileHandler',
|
---|
| 442 | 'filename': '/logs/network.log',
|
---|
| 443 | 'formatter': 'standard',
|
---|
| 444 | 'level': 'INFO',
|
---|
| 445 | 'maxBytes': 1000000},
|
---|
| 446 | 'syslog': {'class': 'logging.handlers.SysLogHandler',
|
---|
| 447 | 'formatter': 'standard',
|
---|
| 448 | 'level': 'ERROR'}},
|
---|
| 449 |
|
---|
| 450 | # Specify all the subordinate loggers
|
---|
| 451 | 'loggers': {
|
---|
| 452 | 'network': {
|
---|
| 453 | 'handlers': ['netlog']
|
---|
| 454 | }
|
---|
| 455 | },
|
---|
| 456 | # Specify properties of the root logger
|
---|
| 457 | 'root': {
|
---|
| 458 | 'handlers': ['syslog']
|
---|
| 459 | },
|
---|
| 460 | }
|
---|
| 461 |
|
---|
| 462 | # Set up configuration
|
---|
| 463 | logging.config.dictConfig(configdict)
|
---|
| 464 |
|
---|
| 465 | # As an example, log two error messages
|
---|
| 466 | logger = logging.getLogger('/')
|
---|
| 467 | logger.error('Database not found')
|
---|
| 468 |
|
---|
| 469 | netlogger = logging.getLogger('network')
|
---|
| 470 | netlogger.error('Connection failed')
|
---|
| 471 |
|
---|
| 472 | Three smaller enhancements to the :mod:`logging` module, all
|
---|
| 473 | implemented by Vinay Sajip, are:
|
---|
| 474 |
|
---|
| 475 | .. rev79293
|
---|
| 476 |
|
---|
| 477 | * The :class:`~logging.handlers.SysLogHandler` class now supports
|
---|
| 478 | syslogging over TCP. The constructor has a *socktype* parameter
|
---|
| 479 | giving the type of socket to use, either :const:`socket.SOCK_DGRAM`
|
---|
| 480 | for UDP or :const:`socket.SOCK_STREAM` for TCP. The default
|
---|
| 481 | protocol remains UDP.
|
---|
| 482 |
|
---|
| 483 | * :class:`~logging.Logger` instances gained a :meth:`~logging.Logger.getChild`
|
---|
| 484 | method that retrieves a descendant logger using a relative path.
|
---|
| 485 | For example, once you retrieve a logger by doing ``log = getLogger('app')``,
|
---|
| 486 | calling ``log.getChild('network.listen')`` is equivalent to
|
---|
| 487 | ``getLogger('app.network.listen')``.
|
---|
| 488 |
|
---|
| 489 | * The :class:`~logging.LoggerAdapter` class gained a
|
---|
| 490 | :meth:`~logging.LoggerAdapter.isEnabledFor` method that takes a
|
---|
| 491 | *level* and returns whether the underlying logger would
|
---|
| 492 | process a message of that level of importance.
|
---|
| 493 |
|
---|
| 494 | .. XXX: Logger objects don't have a class declaration so the link don't work
|
---|
| 495 |
|
---|
| 496 | .. seealso::
|
---|
| 497 |
|
---|
| 498 | :pep:`391` - Dictionary-Based Configuration For Logging
|
---|
| 499 | PEP written and implemented by Vinay Sajip.
|
---|
| 500 |
|
---|
| 501 | PEP 3106: Dictionary Views
|
---|
| 502 | ====================================================
|
---|
| 503 |
|
---|
| 504 | The dictionary methods :meth:`~dict.keys`, :meth:`~dict.values`, and
|
---|
| 505 | :meth:`~dict.items` are different in Python 3.x. They return an object
|
---|
| 506 | called a :dfn:`view` instead of a fully materialized list.
|
---|
| 507 |
|
---|
| 508 | It's not possible to change the return values of :meth:`~dict.keys`,
|
---|
| 509 | :meth:`~dict.values`, and :meth:`~dict.items` in Python 2.7 because
|
---|
| 510 | too much code would break. Instead the 3.x versions were added
|
---|
| 511 | under the new names :meth:`~dict.viewkeys`, :meth:`~dict.viewvalues`,
|
---|
| 512 | and :meth:`~dict.viewitems`.
|
---|
| 513 |
|
---|
| 514 | ::
|
---|
| 515 |
|
---|
| 516 | >>> d = dict((i*10, chr(65+i)) for i in range(26))
|
---|
| 517 | >>> d
|
---|
| 518 | {0: 'A', 130: 'N', 10: 'B', 140: 'O', 20: ..., 250: 'Z'}
|
---|
| 519 | >>> d.viewkeys()
|
---|
| 520 | dict_keys([0, 130, 10, 140, 20, 150, 30, ..., 250])
|
---|
| 521 |
|
---|
| 522 | Views can be iterated over, but the key and item views also behave
|
---|
| 523 | like sets. The ``&`` operator performs intersection, and ``|``
|
---|
| 524 | performs a union::
|
---|
| 525 |
|
---|
| 526 | >>> d1 = dict((i*10, chr(65+i)) for i in range(26))
|
---|
| 527 | >>> d2 = dict((i**.5, i) for i in range(1000))
|
---|
| 528 | >>> d1.viewkeys() & d2.viewkeys()
|
---|
| 529 | set([0.0, 10.0, 20.0, 30.0])
|
---|
| 530 | >>> d1.viewkeys() | range(0, 30)
|
---|
| 531 | set([0, 1, 130, 3, 4, 5, 6, ..., 120, 250])
|
---|
| 532 |
|
---|
| 533 | The view keeps track of the dictionary and its contents change as the
|
---|
| 534 | dictionary is modified::
|
---|
| 535 |
|
---|
| 536 | >>> vk = d.viewkeys()
|
---|
| 537 | >>> vk
|
---|
| 538 | dict_keys([0, 130, 10, ..., 250])
|
---|
| 539 | >>> d[260] = '&'
|
---|
| 540 | >>> vk
|
---|
| 541 | dict_keys([0, 130, 260, 10, ..., 250])
|
---|
| 542 |
|
---|
| 543 | However, note that you can't add or remove keys while you're iterating
|
---|
| 544 | over the view::
|
---|
| 545 |
|
---|
| 546 | >>> for k in vk:
|
---|
| 547 | ... d[k*2] = k
|
---|
| 548 | ...
|
---|
| 549 | Traceback (most recent call last):
|
---|
| 550 | File "<stdin>", line 1, in <module>
|
---|
| 551 | RuntimeError: dictionary changed size during iteration
|
---|
| 552 |
|
---|
| 553 | You can use the view methods in Python 2.x code, and the 2to3
|
---|
| 554 | converter will change them to the standard :meth:`~dict.keys`,
|
---|
| 555 | :meth:`~dict.values`, and :meth:`~dict.items` methods.
|
---|
| 556 |
|
---|
| 557 | .. seealso::
|
---|
| 558 |
|
---|
| 559 | :pep:`3106` - Revamping dict.keys(), .values() and .items()
|
---|
| 560 | PEP written by Guido van Rossum.
|
---|
| 561 | Backported to 2.7 by Alexandre Vassalotti; :issue:`1967`.
|
---|
| 562 |
|
---|
| 563 |
|
---|
| 564 | PEP 3137: The memoryview Object
|
---|
| 565 | ====================================================
|
---|
| 566 |
|
---|
| 567 | The :class:`memoryview` object provides a view of another object's
|
---|
| 568 | memory content that matches the :class:`bytes` type's interface.
|
---|
| 569 |
|
---|
| 570 | >>> import string
|
---|
| 571 | >>> m = memoryview(string.letters)
|
---|
| 572 | >>> m
|
---|
| 573 | <memory at 0x37f850>
|
---|
| 574 | >>> len(m) # Returns length of underlying object
|
---|
| 575 | 52
|
---|
| 576 | >>> m[0], m[25], m[26] # Indexing returns one byte
|
---|
| 577 | ('a', 'z', 'A')
|
---|
| 578 | >>> m2 = m[0:26] # Slicing returns another memoryview
|
---|
| 579 | >>> m2
|
---|
| 580 | <memory at 0x37f080>
|
---|
| 581 |
|
---|
| 582 | The content of the view can be converted to a string of bytes or
|
---|
| 583 | a list of integers:
|
---|
| 584 |
|
---|
| 585 | >>> m2.tobytes()
|
---|
| 586 | 'abcdefghijklmnopqrstuvwxyz'
|
---|
| 587 | >>> m2.tolist()
|
---|
| 588 | [97, 98, 99, 100, 101, 102, 103, ... 121, 122]
|
---|
| 589 | >>>
|
---|
| 590 |
|
---|
| 591 | :class:`memoryview` objects allow modifying the underlying object if
|
---|
| 592 | it's a mutable object.
|
---|
| 593 |
|
---|
| 594 | >>> m2[0] = 75
|
---|
| 595 | Traceback (most recent call last):
|
---|
| 596 | File "<stdin>", line 1, in <module>
|
---|
| 597 | TypeError: cannot modify read-only memory
|
---|
| 598 | >>> b = bytearray(string.letters) # Creating a mutable object
|
---|
| 599 | >>> b
|
---|
| 600 | bytearray(b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
|
---|
| 601 | >>> mb = memoryview(b)
|
---|
| 602 | >>> mb[0] = '*' # Assign to view, changing the bytearray.
|
---|
| 603 | >>> b[0:5] # The bytearray has been changed.
|
---|
| 604 | bytearray(b'*bcde')
|
---|
| 605 | >>>
|
---|
| 606 |
|
---|
| 607 | .. seealso::
|
---|
| 608 |
|
---|
| 609 | :pep:`3137` - Immutable Bytes and Mutable Buffer
|
---|
| 610 | PEP written by Guido van Rossum.
|
---|
| 611 | Implemented by Travis Oliphant, Antoine Pitrou and others.
|
---|
| 612 | Backported to 2.7 by Antoine Pitrou; :issue:`2396`.
|
---|
| 613 |
|
---|
| 614 |
|
---|
| 615 |
|
---|
| 616 | Other Language Changes
|
---|
| 617 | ======================
|
---|
| 618 |
|
---|
| 619 | Some smaller changes made to the core Python language are:
|
---|
| 620 |
|
---|
| 621 | * The syntax for set literals has been backported from Python 3.x.
|
---|
| 622 | Curly brackets are used to surround the contents of the resulting
|
---|
| 623 | mutable set; set literals are
|
---|
| 624 | distinguished from dictionaries by not containing colons and values.
|
---|
| 625 | ``{}`` continues to represent an empty dictionary; use
|
---|
| 626 | ``set()`` for an empty set.
|
---|
| 627 |
|
---|
| 628 | >>> {1, 2, 3, 4, 5}
|
---|
| 629 | set([1, 2, 3, 4, 5])
|
---|
| 630 | >>> set() # empty set
|
---|
| 631 | set([])
|
---|
| 632 | >>> {} # empty dict
|
---|
| 633 | {}
|
---|
| 634 |
|
---|
| 635 | Backported by Alexandre Vassalotti; :issue:`2335`.
|
---|
| 636 |
|
---|
| 637 | * Dictionary and set comprehensions are another feature backported from
|
---|
| 638 | 3.x, generalizing list/generator comprehensions to use
|
---|
| 639 | the literal syntax for sets and dictionaries.
|
---|
| 640 |
|
---|
| 641 | >>> {x: x*x for x in range(6)}
|
---|
| 642 | {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
|
---|
| 643 | >>> {('a'*x) for x in range(6)}
|
---|
| 644 | set(['', 'a', 'aa', 'aaa', 'aaaa', 'aaaaa'])
|
---|
| 645 |
|
---|
| 646 | Backported by Alexandre Vassalotti; :issue:`2333`.
|
---|
| 647 |
|
---|
| 648 | * The :keyword:`with` statement can now use multiple context managers
|
---|
| 649 | in one statement. Context managers are processed from left to right
|
---|
| 650 | and each one is treated as beginning a new :keyword:`with` statement.
|
---|
| 651 | This means that::
|
---|
| 652 |
|
---|
| 653 | with A() as a, B() as b:
|
---|
| 654 | ... suite of statements ...
|
---|
| 655 |
|
---|
| 656 | is equivalent to::
|
---|
| 657 |
|
---|
| 658 | with A() as a:
|
---|
| 659 | with B() as b:
|
---|
| 660 | ... suite of statements ...
|
---|
| 661 |
|
---|
| 662 | The :func:`contextlib.nested` function provides a very similar
|
---|
| 663 | function, so it's no longer necessary and has been deprecated.
|
---|
| 664 |
|
---|
| 665 | (Proposed in http://codereview.appspot.com/53094; implemented by
|
---|
| 666 | Georg Brandl.)
|
---|
| 667 |
|
---|
| 668 | * Conversions between floating-point numbers and strings are
|
---|
| 669 | now correctly rounded on most platforms. These conversions occur
|
---|
| 670 | in many different places: :func:`str` on
|
---|
| 671 | floats and complex numbers; the :class:`float` and :class:`complex`
|
---|
| 672 | constructors;
|
---|
| 673 | numeric formatting; serializing and
|
---|
| 674 | deserializing floats and complex numbers using the
|
---|
| 675 | :mod:`marshal`, :mod:`pickle`
|
---|
| 676 | and :mod:`json` modules;
|
---|
| 677 | parsing of float and imaginary literals in Python code;
|
---|
| 678 | and :class:`~decimal.Decimal`-to-float conversion.
|
---|
| 679 |
|
---|
| 680 | Related to this, the :func:`repr` of a floating-point number *x*
|
---|
| 681 | now returns a result based on the shortest decimal string that's
|
---|
| 682 | guaranteed to round back to *x* under correct rounding (with
|
---|
| 683 | round-half-to-even rounding mode). Previously it gave a string
|
---|
| 684 | based on rounding x to 17 decimal digits.
|
---|
| 685 |
|
---|
| 686 | .. maybe add an example?
|
---|
| 687 |
|
---|
| 688 | The rounding library responsible for this improvement works on
|
---|
| 689 | Windows and on Unix platforms using the gcc, icc, or suncc
|
---|
| 690 | compilers. There may be a small number of platforms where correct
|
---|
| 691 | operation of this code cannot be guaranteed, so the code is not
|
---|
| 692 | used on such systems. You can find out which code is being used
|
---|
| 693 | by checking :data:`sys.float_repr_style`, which will be ``short``
|
---|
| 694 | if the new code is in use and ``legacy`` if it isn't.
|
---|
| 695 |
|
---|
| 696 | Implemented by Eric Smith and Mark Dickinson, using David Gay's
|
---|
| 697 | :file:`dtoa.c` library; :issue:`7117`.
|
---|
| 698 |
|
---|
| 699 | * Conversions from long integers and regular integers to floating
|
---|
| 700 | point now round differently, returning the floating-point number
|
---|
| 701 | closest to the number. This doesn't matter for small integers that
|
---|
| 702 | can be converted exactly, but for large numbers that will
|
---|
| 703 | unavoidably lose precision, Python 2.7 now approximates more
|
---|
| 704 | closely. For example, Python 2.6 computed the following::
|
---|
| 705 |
|
---|
| 706 | >>> n = 295147905179352891391
|
---|
| 707 | >>> float(n)
|
---|
| 708 | 2.9514790517935283e+20
|
---|
| 709 | >>> n - long(float(n))
|
---|
| 710 | 65535L
|
---|
| 711 |
|
---|
| 712 | Python 2.7's floating-point result is larger, but much closer to the
|
---|
| 713 | true value::
|
---|
| 714 |
|
---|
| 715 | >>> n = 295147905179352891391
|
---|
| 716 | >>> float(n)
|
---|
| 717 | 2.9514790517935289e+20
|
---|
| 718 | >>> n - long(float(n))
|
---|
| 719 | -1L
|
---|
| 720 |
|
---|
| 721 | (Implemented by Mark Dickinson; :issue:`3166`.)
|
---|
| 722 |
|
---|
| 723 | Integer division is also more accurate in its rounding behaviours. (Also
|
---|
| 724 | implemented by Mark Dickinson; :issue:`1811`.)
|
---|
| 725 |
|
---|
| 726 | * Implicit coercion for complex numbers has been removed; the interpreter
|
---|
| 727 | will no longer ever attempt to call a :meth:`__coerce__` method on complex
|
---|
| 728 | objects. (Removed by Meador Inge and Mark Dickinson; :issue:`5211`.)
|
---|
| 729 |
|
---|
| 730 | * The :meth:`str.format` method now supports automatic numbering of the replacement
|
---|
| 731 | fields. This makes using :meth:`str.format` more closely resemble using
|
---|
| 732 | ``%s`` formatting::
|
---|
| 733 |
|
---|
| 734 | >>> '{}:{}:{}'.format(2009, 04, 'Sunday')
|
---|
| 735 | '2009:4:Sunday'
|
---|
| 736 | >>> '{}:{}:{day}'.format(2009, 4, day='Sunday')
|
---|
| 737 | '2009:4:Sunday'
|
---|
| 738 |
|
---|
| 739 | The auto-numbering takes the fields from left to right, so the first ``{...}``
|
---|
| 740 | specifier will use the first argument to :meth:`str.format`, the next
|
---|
| 741 | specifier will use the next argument, and so on. You can't mix auto-numbering
|
---|
| 742 | and explicit numbering -- either number all of your specifier fields or none
|
---|
| 743 | of them -- but you can mix auto-numbering and named fields, as in the second
|
---|
| 744 | example above. (Contributed by Eric Smith; :issue:`5237`.)
|
---|
| 745 |
|
---|
| 746 | Complex numbers now correctly support usage with :func:`format`,
|
---|
| 747 | and default to being right-aligned.
|
---|
| 748 | Specifying a precision or comma-separation applies to both the real
|
---|
| 749 | and imaginary parts of the number, but a specified field width and
|
---|
| 750 | alignment is applied to the whole of the resulting ``1.5+3j``
|
---|
| 751 | output. (Contributed by Eric Smith; :issue:`1588` and :issue:`7988`.)
|
---|
| 752 |
|
---|
| 753 | The 'F' format code now always formats its output using uppercase characters,
|
---|
| 754 | so it will now produce 'INF' and 'NAN'.
|
---|
| 755 | (Contributed by Eric Smith; :issue:`3382`.)
|
---|
| 756 |
|
---|
| 757 | A low-level change: the :meth:`object.__format__` method now triggers
|
---|
| 758 | a :exc:`PendingDeprecationWarning` if it's passed a format string,
|
---|
| 759 | because the :meth:`__format__` method for :class:`object` converts
|
---|
| 760 | the object to a string representation and formats that. Previously
|
---|
| 761 | the method silently applied the format string to the string
|
---|
| 762 | representation, but that could hide mistakes in Python code. If
|
---|
| 763 | you're supplying formatting information such as an alignment or
|
---|
| 764 | precision, presumably you're expecting the formatting to be applied
|
---|
| 765 | in some object-specific way. (Fixed by Eric Smith; :issue:`7994`.)
|
---|
| 766 |
|
---|
| 767 | * The :func:`int` and :func:`long` types gained a ``bit_length``
|
---|
| 768 | method that returns the number of bits necessary to represent
|
---|
| 769 | its argument in binary::
|
---|
| 770 |
|
---|
| 771 | >>> n = 37
|
---|
| 772 | >>> bin(n)
|
---|
| 773 | '0b100101'
|
---|
| 774 | >>> n.bit_length()
|
---|
| 775 | 6
|
---|
| 776 | >>> n = 2**123-1
|
---|
| 777 | >>> n.bit_length()
|
---|
| 778 | 123
|
---|
| 779 | >>> (n+1).bit_length()
|
---|
| 780 | 124
|
---|
| 781 |
|
---|
| 782 | (Contributed by Fredrik Johansson and Victor Stinner; :issue:`3439`.)
|
---|
| 783 |
|
---|
| 784 | * The :keyword:`import` statement will no longer try an absolute import
|
---|
| 785 | if a relative import (e.g. ``from .os import sep``) fails. This
|
---|
| 786 | fixes a bug, but could possibly break certain :keyword:`import`
|
---|
| 787 | statements that were only working by accident. (Fixed by Meador Inge;
|
---|
| 788 | :issue:`7902`.)
|
---|
| 789 |
|
---|
| 790 | * It's now possible for a subclass of the built-in :class:`unicode` type
|
---|
| 791 | to override the :meth:`__unicode__` method. (Implemented by
|
---|
| 792 | Victor Stinner; :issue:`1583863`.)
|
---|
| 793 |
|
---|
| 794 | * The :class:`bytearray` type's :meth:`~bytearray.translate` method now accepts
|
---|
| 795 | ``None`` as its first argument. (Fixed by Georg Brandl;
|
---|
| 796 | :issue:`4759`.)
|
---|
| 797 |
|
---|
| 798 | .. XXX bytearray doesn't seem to be documented
|
---|
| 799 |
|
---|
| 800 | * When using ``@classmethod`` and ``@staticmethod`` to wrap
|
---|
| 801 | methods as class or static methods, the wrapper object now
|
---|
| 802 | exposes the wrapped function as their :attr:`__func__` attribute.
|
---|
| 803 | (Contributed by Amaury Forgeot d'Arc, after a suggestion by
|
---|
| 804 | George Sakkis; :issue:`5982`.)
|
---|
| 805 |
|
---|
| 806 | * When a restricted set of attributes were set using ``__slots__``,
|
---|
| 807 | deleting an unset attribute would not raise :exc:`AttributeError`
|
---|
| 808 | as you would expect. Fixed by Benjamin Peterson; :issue:`7604`.)
|
---|
| 809 |
|
---|
| 810 | * Two new encodings are now supported: "cp720", used primarily for
|
---|
| 811 | Arabic text; and "cp858", a variant of CP 850 that adds the euro
|
---|
| 812 | symbol. (CP720 contributed by Alexander Belchenko and Amaury
|
---|
| 813 | Forgeot d'Arc in :issue:`1616979`; CP858 contributed by Tim Hatch in
|
---|
| 814 | :issue:`8016`.)
|
---|
| 815 |
|
---|
| 816 | * The :class:`file` object will now set the :attr:`filename` attribute
|
---|
| 817 | on the :exc:`IOError` exception when trying to open a directory
|
---|
| 818 | on POSIX platforms (noted by Jan Kaliszewski; :issue:`4764`), and
|
---|
| 819 | now explicitly checks for and forbids writing to read-only file objects
|
---|
| 820 | instead of trusting the C library to catch and report the error
|
---|
| 821 | (fixed by Stefan Krah; :issue:`5677`).
|
---|
| 822 |
|
---|
| 823 | * The Python tokenizer now translates line endings itself, so the
|
---|
| 824 | :func:`compile` built-in function now accepts code using any
|
---|
| 825 | line-ending convention. Additionally, it no longer requires that the
|
---|
| 826 | code end in a newline.
|
---|
| 827 |
|
---|
| 828 | * Extra parentheses in function definitions are illegal in Python 3.x,
|
---|
| 829 | meaning that you get a syntax error from ``def f((x)): pass``. In
|
---|
| 830 | Python3-warning mode, Python 2.7 will now warn about this odd usage.
|
---|
| 831 | (Noted by James Lingard; :issue:`7362`.)
|
---|
| 832 |
|
---|
| 833 | * It's now possible to create weak references to old-style class
|
---|
| 834 | objects. New-style classes were always weak-referenceable. (Fixed
|
---|
| 835 | by Antoine Pitrou; :issue:`8268`.)
|
---|
| 836 |
|
---|
| 837 | * When a module object is garbage-collected, the module's dictionary is
|
---|
| 838 | now only cleared if no one else is holding a reference to the
|
---|
| 839 | dictionary (:issue:`7140`).
|
---|
| 840 |
|
---|
| 841 | .. ======================================================================
|
---|
| 842 |
|
---|
| 843 | .. _new-27-interpreter:
|
---|
| 844 |
|
---|
| 845 | Interpreter Changes
|
---|
| 846 | -------------------------------
|
---|
| 847 |
|
---|
| 848 | A new environment variable, :envvar:`PYTHONWARNINGS`,
|
---|
| 849 | allows controlling warnings. It should be set to a string
|
---|
| 850 | containing warning settings, equivalent to those
|
---|
| 851 | used with the :option:`-W` switch, separated by commas.
|
---|
| 852 | (Contributed by Brian Curtin; :issue:`7301`.)
|
---|
| 853 |
|
---|
| 854 | For example, the following setting will print warnings every time
|
---|
| 855 | they occur, but turn warnings from the :mod:`Cookie` module into an
|
---|
| 856 | error. (The exact syntax for setting an environment variable varies
|
---|
| 857 | across operating systems and shells.)
|
---|
| 858 |
|
---|
| 859 | ::
|
---|
| 860 |
|
---|
| 861 | export PYTHONWARNINGS=all,error:::Cookie:0
|
---|
| 862 |
|
---|
| 863 | .. ======================================================================
|
---|
| 864 |
|
---|
| 865 |
|
---|
| 866 | Optimizations
|
---|
| 867 | -------------
|
---|
| 868 |
|
---|
| 869 | Several performance enhancements have been added:
|
---|
| 870 |
|
---|
| 871 | * A new opcode was added to perform the initial setup for
|
---|
| 872 | :keyword:`with` statements, looking up the :meth:`__enter__` and
|
---|
| 873 | :meth:`__exit__` methods. (Contributed by Benjamin Peterson.)
|
---|
| 874 |
|
---|
| 875 | * The garbage collector now performs better for one common usage
|
---|
| 876 | pattern: when many objects are being allocated without deallocating
|
---|
| 877 | any of them. This would previously take quadratic
|
---|
| 878 | time for garbage collection, but now the number of full garbage collections
|
---|
| 879 | is reduced as the number of objects on the heap grows.
|
---|
| 880 | The new logic only performs a full garbage collection pass when
|
---|
| 881 | the middle generation has been collected 10 times and when the
|
---|
| 882 | number of survivor objects from the middle generation exceeds 10% of
|
---|
| 883 | the number of objects in the oldest generation. (Suggested by Martin
|
---|
| 884 | von Löwis and implemented by Antoine Pitrou; :issue:`4074`.)
|
---|
| 885 |
|
---|
| 886 | * The garbage collector tries to avoid tracking simple containers
|
---|
| 887 | which can't be part of a cycle. In Python 2.7, this is now true for
|
---|
| 888 | tuples and dicts containing atomic types (such as ints, strings,
|
---|
| 889 | etc.). Transitively, a dict containing tuples of atomic types won't
|
---|
| 890 | be tracked either. This helps reduce the cost of each
|
---|
| 891 | garbage collection by decreasing the number of objects to be
|
---|
| 892 | considered and traversed by the collector.
|
---|
| 893 | (Contributed by Antoine Pitrou; :issue:`4688`.)
|
---|
| 894 |
|
---|
| 895 | * Long integers are now stored internally either in base 2**15 or in base
|
---|
| 896 | 2**30, the base being determined at build time. Previously, they
|
---|
| 897 | were always stored in base 2**15. Using base 2**30 gives
|
---|
| 898 | significant performance improvements on 64-bit machines, but
|
---|
| 899 | benchmark results on 32-bit machines have been mixed. Therefore,
|
---|
| 900 | the default is to use base 2**30 on 64-bit machines and base 2**15
|
---|
| 901 | on 32-bit machines; on Unix, there's a new configure option
|
---|
| 902 | :option:`--enable-big-digits` that can be used to override this default.
|
---|
| 903 |
|
---|
| 904 | Apart from the performance improvements this change should be
|
---|
| 905 | invisible to end users, with one exception: for testing and
|
---|
| 906 | debugging purposes there's a new structseq :data:`sys.long_info` that
|
---|
| 907 | provides information about the internal format, giving the number of
|
---|
| 908 | bits per digit and the size in bytes of the C type used to store
|
---|
| 909 | each digit::
|
---|
| 910 |
|
---|
| 911 | >>> import sys
|
---|
| 912 | >>> sys.long_info
|
---|
| 913 | sys.long_info(bits_per_digit=30, sizeof_digit=4)
|
---|
| 914 |
|
---|
| 915 | (Contributed by Mark Dickinson; :issue:`4258`.)
|
---|
| 916 |
|
---|
| 917 | Another set of changes made long objects a few bytes smaller: 2 bytes
|
---|
| 918 | smaller on 32-bit systems and 6 bytes on 64-bit.
|
---|
| 919 | (Contributed by Mark Dickinson; :issue:`5260`.)
|
---|
| 920 |
|
---|
| 921 | * The division algorithm for long integers has been made faster
|
---|
| 922 | by tightening the inner loop, doing shifts instead of multiplications,
|
---|
| 923 | and fixing an unnecessary extra iteration.
|
---|
| 924 | Various benchmarks show speedups of between 50% and 150% for long
|
---|
| 925 | integer divisions and modulo operations.
|
---|
| 926 | (Contributed by Mark Dickinson; :issue:`5512`.)
|
---|
| 927 | Bitwise operations are also significantly faster (initial patch by
|
---|
| 928 | Gregory Smith; :issue:`1087418`).
|
---|
| 929 |
|
---|
| 930 | * The implementation of ``%`` checks for the left-side operand being
|
---|
| 931 | a Python string and special-cases it; this results in a 1-3%
|
---|
| 932 | performance increase for applications that frequently use ``%``
|
---|
| 933 | with strings, such as templating libraries.
|
---|
| 934 | (Implemented by Collin Winter; :issue:`5176`.)
|
---|
| 935 |
|
---|
| 936 | * List comprehensions with an ``if`` condition are compiled into
|
---|
| 937 | faster bytecode. (Patch by Antoine Pitrou, back-ported to 2.7
|
---|
| 938 | by Jeffrey Yasskin; :issue:`4715`.)
|
---|
| 939 |
|
---|
| 940 | * Converting an integer or long integer to a decimal string was made
|
---|
| 941 | faster by special-casing base 10 instead of using a generalized
|
---|
| 942 | conversion function that supports arbitrary bases.
|
---|
| 943 | (Patch by Gawain Bolton; :issue:`6713`.)
|
---|
| 944 |
|
---|
| 945 | * The :meth:`split`, :meth:`replace`, :meth:`rindex`,
|
---|
| 946 | :meth:`rpartition`, and :meth:`rsplit` methods of string-like types
|
---|
| 947 | (strings, Unicode strings, and :class:`bytearray` objects) now use a
|
---|
| 948 | fast reverse-search algorithm instead of a character-by-character
|
---|
| 949 | scan. This is sometimes faster by a factor of 10. (Added by
|
---|
| 950 | Florent Xicluna; :issue:`7462` and :issue:`7622`.)
|
---|
| 951 |
|
---|
| 952 | * The :mod:`pickle` and :mod:`cPickle` modules now automatically
|
---|
| 953 | intern the strings used for attribute names, reducing memory usage
|
---|
| 954 | of the objects resulting from unpickling. (Contributed by Jake
|
---|
| 955 | McGuire; :issue:`5084`.)
|
---|
| 956 |
|
---|
| 957 | * The :mod:`cPickle` module now special-cases dictionaries,
|
---|
| 958 | nearly halving the time required to pickle them.
|
---|
| 959 | (Contributed by Collin Winter; :issue:`5670`.)
|
---|
| 960 |
|
---|
| 961 | .. ======================================================================
|
---|
| 962 |
|
---|
| 963 | New and Improved Modules
|
---|
| 964 | ========================
|
---|
| 965 |
|
---|
| 966 | As in every release, Python's standard library received a number of
|
---|
| 967 | enhancements and bug fixes. Here's a partial list of the most notable
|
---|
| 968 | changes, sorted alphabetically by module name. Consult the
|
---|
| 969 | :file:`Misc/NEWS` file in the source tree for a more complete list of
|
---|
| 970 | changes, or look through the Subversion logs for all the details.
|
---|
| 971 |
|
---|
| 972 | * The :mod:`bdb` module's base debugging class :class:`~bdb.Bdb`
|
---|
| 973 | gained a feature for skipping modules. The constructor
|
---|
| 974 | now takes an iterable containing glob-style patterns such as
|
---|
| 975 | ``django.*``; the debugger will not step into stack frames
|
---|
| 976 | from a module that matches one of these patterns.
|
---|
| 977 | (Contributed by Maru Newby after a suggestion by
|
---|
| 978 | Senthil Kumaran; :issue:`5142`.)
|
---|
| 979 |
|
---|
| 980 | * The :mod:`binascii` module now supports the buffer API, so it can be
|
---|
| 981 | used with :class:`memoryview` instances and other similar buffer objects.
|
---|
| 982 | (Backported from 3.x by Florent Xicluna; :issue:`7703`.)
|
---|
| 983 |
|
---|
| 984 | * Updated module: the :mod:`bsddb` module has been updated from 4.7.2devel9
|
---|
| 985 | to version 4.8.4 of
|
---|
| 986 | `the pybsddb package <http://www.jcea.es/programacion/pybsddb.htm>`__.
|
---|
| 987 | The new version features better Python 3.x compatibility, various bug fixes,
|
---|
| 988 | and adds several new BerkeleyDB flags and methods.
|
---|
| 989 | (Updated by Jesús Cea Avión; :issue:`8156`. The pybsddb
|
---|
| 990 | changelog can be read at http://hg.jcea.es/pybsddb/file/tip/ChangeLog.)
|
---|
| 991 |
|
---|
| 992 | * The :mod:`bz2` module's :class:`~bz2.BZ2File` now supports the context
|
---|
| 993 | management protocol, so you can write ``with bz2.BZ2File(...) as f:``.
|
---|
| 994 | (Contributed by Hagen FÃŒrstenau; :issue:`3860`.)
|
---|
| 995 |
|
---|
| 996 | * New class: the :class:`~collections.Counter` class in the :mod:`collections`
|
---|
| 997 | module is useful for tallying data. :class:`~collections.Counter` instances
|
---|
| 998 | behave mostly like dictionaries but return zero for missing keys instead of
|
---|
| 999 | raising a :exc:`KeyError`:
|
---|
| 1000 |
|
---|
| 1001 | .. doctest::
|
---|
| 1002 | :options: +NORMALIZE_WHITESPACE
|
---|
| 1003 |
|
---|
| 1004 | >>> from collections import Counter
|
---|
| 1005 | >>> c = Counter()
|
---|
| 1006 | >>> for letter in 'here is a sample of english text':
|
---|
| 1007 | ... c[letter] += 1
|
---|
| 1008 | ...
|
---|
| 1009 | >>> c
|
---|
| 1010 | Counter({' ': 6, 'e': 5, 's': 3, 'a': 2, 'i': 2, 'h': 2,
|
---|
| 1011 | 'l': 2, 't': 2, 'g': 1, 'f': 1, 'm': 1, 'o': 1, 'n': 1,
|
---|
| 1012 | 'p': 1, 'r': 1, 'x': 1})
|
---|
| 1013 | >>> c['e']
|
---|
| 1014 | 5
|
---|
| 1015 | >>> c['z']
|
---|
| 1016 | 0
|
---|
| 1017 |
|
---|
| 1018 | There are three additional :class:`~collections.Counter` methods.
|
---|
| 1019 | :meth:`~collections.Counter.most_common` returns the N most common
|
---|
| 1020 | elements and their counts. :meth:`~collections.Counter.elements`
|
---|
| 1021 | returns an iterator over the contained elements, repeating each
|
---|
| 1022 | element as many times as its count.
|
---|
| 1023 | :meth:`~collections.Counter.subtract` takes an iterable and
|
---|
| 1024 | subtracts one for each element instead of adding; if the argument is
|
---|
| 1025 | a dictionary or another :class:`Counter`, the counts are
|
---|
| 1026 | subtracted. ::
|
---|
| 1027 |
|
---|
| 1028 | >>> c.most_common(5)
|
---|
| 1029 | [(' ', 6), ('e', 5), ('s', 3), ('a', 2), ('i', 2)]
|
---|
| 1030 | >>> c.elements() ->
|
---|
| 1031 | 'a', 'a', ' ', ' ', ' ', ' ', ' ', ' ',
|
---|
| 1032 | 'e', 'e', 'e', 'e', 'e', 'g', 'f', 'i', 'i',
|
---|
| 1033 | 'h', 'h', 'm', 'l', 'l', 'o', 'n', 'p', 's',
|
---|
| 1034 | 's', 's', 'r', 't', 't', 'x'
|
---|
| 1035 | >>> c['e']
|
---|
| 1036 | 5
|
---|
| 1037 | >>> c.subtract('very heavy on the letter e')
|
---|
| 1038 | >>> c['e'] # Count is now lower
|
---|
| 1039 | -1
|
---|
| 1040 |
|
---|
| 1041 | Contributed by Raymond Hettinger; :issue:`1696199`.
|
---|
| 1042 |
|
---|
| 1043 | .. revision 79660
|
---|
| 1044 |
|
---|
| 1045 | New class: :class:`~collections.OrderedDict` is described in the earlier
|
---|
| 1046 | section :ref:`pep-0372`.
|
---|
| 1047 |
|
---|
| 1048 | New method: The :class:`~collections.deque` data type now has a
|
---|
| 1049 | :meth:`~collections.deque.count` method that returns the number of
|
---|
| 1050 | contained elements equal to the supplied argument *x*, and a
|
---|
| 1051 | :meth:`~collections.deque.reverse` method that reverses the elements
|
---|
| 1052 | of the deque in-place. :class:`~collections.deque` also exposes its maximum
|
---|
| 1053 | length as the read-only :attr:`~collections.deque.maxlen` attribute.
|
---|
| 1054 | (Both features added by Raymond Hettinger.)
|
---|
| 1055 |
|
---|
| 1056 | The :class:`~collections.namedtuple` class now has an optional *rename* parameter.
|
---|
| 1057 | If *rename* is true, field names that are invalid because they've
|
---|
| 1058 | been repeated or aren't legal Python identifiers will be
|
---|
| 1059 | renamed to legal names that are derived from the field's
|
---|
| 1060 | position within the list of fields:
|
---|
| 1061 |
|
---|
| 1062 | >>> from collections import namedtuple
|
---|
| 1063 | >>> T = namedtuple('T', ['field1', '$illegal', 'for', 'field2'], rename=True)
|
---|
| 1064 | >>> T._fields
|
---|
| 1065 | ('field1', '_1', '_2', 'field2')
|
---|
| 1066 |
|
---|
| 1067 | (Added by Raymond Hettinger; :issue:`1818`.)
|
---|
| 1068 |
|
---|
| 1069 | Finally, the :class:`~collections.Mapping` abstract base class now
|
---|
| 1070 | returns :const:`NotImplemented` if a mapping is compared to
|
---|
| 1071 | another type that isn't a :class:`Mapping`.
|
---|
| 1072 | (Fixed by Daniel Stutzbach; :issue:`8729`.)
|
---|
| 1073 |
|
---|
| 1074 | * Constructors for the parsing classes in the :mod:`ConfigParser` module now
|
---|
| 1075 | take a *allow_no_value* parameter, defaulting to false; if true,
|
---|
| 1076 | options without values will be allowed. For example::
|
---|
| 1077 |
|
---|
| 1078 | >>> import ConfigParser, StringIO
|
---|
| 1079 | >>> sample_config = """
|
---|
| 1080 | ... [mysqld]
|
---|
| 1081 | ... user = mysql
|
---|
| 1082 | ... pid-file = /var/run/mysqld/mysqld.pid
|
---|
| 1083 | ... skip-bdb
|
---|
| 1084 | ... """
|
---|
| 1085 | >>> config = ConfigParser.RawConfigParser(allow_no_value=True)
|
---|
| 1086 | >>> config.readfp(StringIO.StringIO(sample_config))
|
---|
| 1087 | >>> config.get('mysqld', 'user')
|
---|
| 1088 | 'mysql'
|
---|
| 1089 | >>> print config.get('mysqld', 'skip-bdb')
|
---|
| 1090 | None
|
---|
| 1091 | >>> print config.get('mysqld', 'unknown')
|
---|
| 1092 | Traceback (most recent call last):
|
---|
| 1093 | ...
|
---|
| 1094 | NoOptionError: No option 'unknown' in section: 'mysqld'
|
---|
| 1095 |
|
---|
| 1096 | (Contributed by Mats Kindahl; :issue:`7005`.)
|
---|
| 1097 |
|
---|
| 1098 | * Deprecated function: :func:`contextlib.nested`, which allows
|
---|
| 1099 | handling more than one context manager with a single :keyword:`with`
|
---|
| 1100 | statement, has been deprecated, because the :keyword:`with` statement
|
---|
| 1101 | now supports multiple context managers.
|
---|
| 1102 |
|
---|
| 1103 | * The :mod:`cookielib` module now ignores cookies that have an invalid
|
---|
| 1104 | version field, one that doesn't contain an integer value. (Fixed by
|
---|
| 1105 | John J. Lee; :issue:`3924`.)
|
---|
| 1106 |
|
---|
| 1107 | * The :mod:`copy` module's :func:`~copy.deepcopy` function will now
|
---|
| 1108 | correctly copy bound instance methods. (Implemented by
|
---|
| 1109 | Robert Collins; :issue:`1515`.)
|
---|
| 1110 |
|
---|
| 1111 | * The :mod:`ctypes` module now always converts ``None`` to a C NULL
|
---|
| 1112 | pointer for arguments declared as pointers. (Changed by Thomas
|
---|
| 1113 | Heller; :issue:`4606`.) The underlying `libffi library
|
---|
| 1114 | <http://sourceware.org/libffi/>`__ has been updated to version
|
---|
| 1115 | 3.0.9, containing various fixes for different platforms. (Updated
|
---|
| 1116 | by Matthias Klose; :issue:`8142`.)
|
---|
| 1117 |
|
---|
| 1118 | * New method: the :mod:`datetime` module's :class:`~datetime.timedelta` class
|
---|
| 1119 | gained a :meth:`~datetime.timedelta.total_seconds` method that returns the
|
---|
| 1120 | number of seconds in the duration. (Contributed by Brian Quinlan; :issue:`5788`.)
|
---|
| 1121 |
|
---|
| 1122 | * New method: the :class:`~decimal.Decimal` class gained a
|
---|
| 1123 | :meth:`~decimal.Decimal.from_float` class method that performs an exact
|
---|
| 1124 | conversion of a floating-point number to a :class:`~decimal.Decimal`.
|
---|
| 1125 | This exact conversion strives for the
|
---|
| 1126 | closest decimal approximation to the floating-point representation's value;
|
---|
| 1127 | the resulting decimal value will therefore still include the inaccuracy,
|
---|
| 1128 | if any.
|
---|
| 1129 | For example, ``Decimal.from_float(0.1)`` returns
|
---|
| 1130 | ``Decimal('0.1000000000000000055511151231257827021181583404541015625')``.
|
---|
| 1131 | (Implemented by Raymond Hettinger; :issue:`4796`.)
|
---|
| 1132 |
|
---|
| 1133 | Comparing instances of :class:`~decimal.Decimal` with floating-point
|
---|
| 1134 | numbers now produces sensible results based on the numeric values
|
---|
| 1135 | of the operands. Previously such comparisons would fall back to
|
---|
| 1136 | Python's default rules for comparing objects, which produced arbitrary
|
---|
| 1137 | results based on their type. Note that you still cannot combine
|
---|
| 1138 | :class:`Decimal` and floating-point in other operations such as addition,
|
---|
| 1139 | since you should be explicitly choosing how to convert between float and
|
---|
| 1140 | :class:`~decimal.Decimal`. (Fixed by Mark Dickinson; :issue:`2531`.)
|
---|
| 1141 |
|
---|
| 1142 | The constructor for :class:`~decimal.Decimal` now accepts
|
---|
| 1143 | floating-point numbers (added by Raymond Hettinger; :issue:`8257`)
|
---|
| 1144 | and non-European Unicode characters such as Arabic-Indic digits
|
---|
| 1145 | (contributed by Mark Dickinson; :issue:`6595`).
|
---|
| 1146 |
|
---|
| 1147 | Most of the methods of the :class:`~decimal.Context` class now accept integers
|
---|
| 1148 | as well as :class:`~decimal.Decimal` instances; the only exceptions are the
|
---|
| 1149 | :meth:`~decimal.Context.canonical` and :meth:`~decimal.Context.is_canonical`
|
---|
| 1150 | methods. (Patch by Juan José Conti; :issue:`7633`.)
|
---|
| 1151 |
|
---|
| 1152 | When using :class:`~decimal.Decimal` instances with a string's
|
---|
| 1153 | :meth:`~str.format` method, the default alignment was previously
|
---|
| 1154 | left-alignment. This has been changed to right-alignment, which is
|
---|
| 1155 | more sensible for numeric types. (Changed by Mark Dickinson; :issue:`6857`.)
|
---|
| 1156 |
|
---|
| 1157 | Comparisons involving a signaling NaN value (or ``sNAN``) now signal
|
---|
| 1158 | :const:`InvalidOperation` instead of silently returning a true or
|
---|
| 1159 | false value depending on the comparison operator. Quiet NaN values
|
---|
| 1160 | (or ``NaN``) are now hashable. (Fixed by Mark Dickinson;
|
---|
| 1161 | :issue:`7279`.)
|
---|
| 1162 |
|
---|
| 1163 | * The :mod:`difflib` module now produces output that is more
|
---|
| 1164 | compatible with modern :command:`diff`/:command:`patch` tools
|
---|
| 1165 | through one small change, using a tab character instead of spaces as
|
---|
| 1166 | a separator in the header giving the filename. (Fixed by Anatoly
|
---|
| 1167 | Techtonik; :issue:`7585`.)
|
---|
| 1168 |
|
---|
| 1169 | * The Distutils ``sdist`` command now always regenerates the
|
---|
| 1170 | :file:`MANIFEST` file, since even if the :file:`MANIFEST.in` or
|
---|
| 1171 | :file:`setup.py` files haven't been modified, the user might have
|
---|
| 1172 | created some new files that should be included.
|
---|
| 1173 | (Fixed by Tarek Ziadé; :issue:`8688`.)
|
---|
| 1174 |
|
---|
| 1175 | * The :mod:`doctest` module's :const:`IGNORE_EXCEPTION_DETAIL` flag
|
---|
| 1176 | will now ignore the name of the module containing the exception
|
---|
| 1177 | being tested. (Patch by Lennart Regebro; :issue:`7490`.)
|
---|
| 1178 |
|
---|
| 1179 | * The :mod:`email` module's :class:`~email.message.Message` class will
|
---|
| 1180 | now accept a Unicode-valued payload, automatically converting the
|
---|
| 1181 | payload to the encoding specified by :attr:`output_charset`.
|
---|
| 1182 | (Added by R. David Murray; :issue:`1368247`.)
|
---|
| 1183 |
|
---|
| 1184 | * The :class:`~fractions.Fraction` class now accepts a single float or
|
---|
| 1185 | :class:`~decimal.Decimal` instance, or two rational numbers, as
|
---|
| 1186 | arguments to its constructor. (Implemented by Mark Dickinson;
|
---|
| 1187 | rationals added in :issue:`5812`, and float/decimal in
|
---|
| 1188 | :issue:`8294`.)
|
---|
| 1189 |
|
---|
| 1190 | Ordering comparisons (``<``, ``<=``, ``>``, ``>=``) between
|
---|
| 1191 | fractions and complex numbers now raise a :exc:`TypeError`.
|
---|
| 1192 | This fixes an oversight, making the :class:`~fractions.Fraction`
|
---|
| 1193 | match the other numeric types.
|
---|
| 1194 |
|
---|
| 1195 | .. revision 79455
|
---|
| 1196 |
|
---|
| 1197 | * New class: :class:`~ftplib.FTP_TLS` in
|
---|
| 1198 | the :mod:`ftplib` module provides secure FTP
|
---|
| 1199 | connections using TLS encapsulation of authentication as well as
|
---|
| 1200 | subsequent control and data transfers.
|
---|
| 1201 | (Contributed by Giampaolo Rodola; :issue:`2054`.)
|
---|
| 1202 |
|
---|
| 1203 | The :meth:`~ftplib.FTP.storbinary` method for binary uploads can now restart
|
---|
| 1204 | uploads thanks to an added *rest* parameter (patch by Pablo Mouzo;
|
---|
| 1205 | :issue:`6845`.)
|
---|
| 1206 |
|
---|
| 1207 | * New class decorator: :func:`~functools.total_ordering` in the :mod:`functools`
|
---|
| 1208 | module takes a class that defines an :meth:`__eq__` method and one of
|
---|
| 1209 | :meth:`__lt__`, :meth:`__le__`, :meth:`__gt__`, or :meth:`__ge__`,
|
---|
| 1210 | and generates the missing comparison methods. Since the
|
---|
| 1211 | :meth:`__cmp__` method is being deprecated in Python 3.x,
|
---|
| 1212 | this decorator makes it easier to define ordered classes.
|
---|
| 1213 | (Added by Raymond Hettinger; :issue:`5479`.)
|
---|
| 1214 |
|
---|
| 1215 | New function: :func:`~functools.cmp_to_key` will take an old-style comparison
|
---|
| 1216 | function that expects two arguments and return a new callable that
|
---|
| 1217 | can be used as the *key* parameter to functions such as
|
---|
| 1218 | :func:`sorted`, :func:`min` and :func:`max`, etc. The primary
|
---|
| 1219 | intended use is to help with making code compatible with Python 3.x.
|
---|
| 1220 | (Added by Raymond Hettinger.)
|
---|
| 1221 |
|
---|
| 1222 | * New function: the :mod:`gc` module's :func:`~gc.is_tracked` returns
|
---|
| 1223 | true if a given instance is tracked by the garbage collector, false
|
---|
| 1224 | otherwise. (Contributed by Antoine Pitrou; :issue:`4688`.)
|
---|
| 1225 |
|
---|
| 1226 | * The :mod:`gzip` module's :class:`~gzip.GzipFile` now supports the context
|
---|
| 1227 | management protocol, so you can write ``with gzip.GzipFile(...) as f:``
|
---|
| 1228 | (contributed by Hagen FÃŒrstenau; :issue:`3860`), and it now implements
|
---|
| 1229 | the :class:`io.BufferedIOBase` ABC, so you can wrap it with
|
---|
| 1230 | :class:`io.BufferedReader` for faster processing
|
---|
| 1231 | (contributed by Nir Aides; :issue:`7471`).
|
---|
| 1232 | It's also now possible to override the modification time
|
---|
| 1233 | recorded in a gzipped file by providing an optional timestamp to
|
---|
| 1234 | the constructor. (Contributed by Jacques Frechet; :issue:`4272`.)
|
---|
| 1235 |
|
---|
| 1236 | Files in gzip format can be padded with trailing zero bytes; the
|
---|
| 1237 | :mod:`gzip` module will now consume these trailing bytes. (Fixed by
|
---|
| 1238 | Tadek Pietraszek and Brian Curtin; :issue:`2846`.)
|
---|
| 1239 |
|
---|
| 1240 | * New attribute: the :mod:`hashlib` module now has an :attr:`~hashlib.hashlib.algorithms`
|
---|
| 1241 | attribute containing a tuple naming the supported algorithms.
|
---|
| 1242 | In Python 2.7, ``hashlib.algorithms`` contains
|
---|
| 1243 | ``('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')``.
|
---|
| 1244 | (Contributed by Carl Chenet; :issue:`7418`.)
|
---|
| 1245 |
|
---|
| 1246 | * The default :class:`~httplib.HTTPResponse` class used by the :mod:`httplib` module now
|
---|
| 1247 | supports buffering, resulting in much faster reading of HTTP responses.
|
---|
| 1248 | (Contributed by Kristján Valur Jónsson; :issue:`4879`.)
|
---|
| 1249 |
|
---|
| 1250 | The :class:`~httplib.HTTPConnection` and :class:`~httplib.HTTPSConnection` classes
|
---|
| 1251 | now support a *source_address* parameter, a ``(host, port)`` 2-tuple
|
---|
| 1252 | giving the source address that will be used for the connection.
|
---|
| 1253 | (Contributed by Eldon Ziegler; :issue:`3972`.)
|
---|
| 1254 |
|
---|
| 1255 | * The :mod:`ihooks` module now supports relative imports. Note that
|
---|
| 1256 | :mod:`ihooks` is an older module for customizing imports,
|
---|
| 1257 | superseded by the :mod:`imputil` module added in Python 2.0.
|
---|
| 1258 | (Relative import support added by Neil Schemenauer.)
|
---|
| 1259 |
|
---|
| 1260 | .. revision 75423
|
---|
| 1261 |
|
---|
| 1262 | * The :mod:`imaplib` module now supports IPv6 addresses.
|
---|
| 1263 | (Contributed by Derek Morr; :issue:`1655`.)
|
---|
| 1264 |
|
---|
| 1265 | * New function: the :mod:`inspect` module's :func:`~inspect.getcallargs`
|
---|
| 1266 | takes a callable and its positional and keyword arguments,
|
---|
| 1267 | and figures out which of the callable's parameters will receive each argument,
|
---|
| 1268 | returning a dictionary mapping argument names to their values. For example::
|
---|
| 1269 |
|
---|
| 1270 | >>> from inspect import getcallargs
|
---|
| 1271 | >>> def f(a, b=1, *pos, **named):
|
---|
| 1272 | ... pass
|
---|
| 1273 | >>> getcallargs(f, 1, 2, 3)
|
---|
| 1274 | {'a': 1, 'b': 2, 'pos': (3,), 'named': {}}
|
---|
| 1275 | >>> getcallargs(f, a=2, x=4)
|
---|
| 1276 | {'a': 2, 'b': 1, 'pos': (), 'named': {'x': 4}}
|
---|
| 1277 | >>> getcallargs(f)
|
---|
| 1278 | Traceback (most recent call last):
|
---|
| 1279 | ...
|
---|
| 1280 | TypeError: f() takes at least 1 argument (0 given)
|
---|
| 1281 |
|
---|
| 1282 | Contributed by George Sakkis; :issue:`3135`.
|
---|
| 1283 |
|
---|
| 1284 | * Updated module: The :mod:`io` library has been upgraded to the version shipped with
|
---|
| 1285 | Python 3.1. For 3.1, the I/O library was entirely rewritten in C
|
---|
| 1286 | and is 2 to 20 times faster depending on the task being performed. The
|
---|
| 1287 | original Python version was renamed to the :mod:`_pyio` module.
|
---|
| 1288 |
|
---|
| 1289 | One minor resulting change: the :class:`io.TextIOBase` class now
|
---|
| 1290 | has an :attr:`errors` attribute giving the error setting
|
---|
| 1291 | used for encoding and decoding errors (one of ``'strict'``, ``'replace'``,
|
---|
| 1292 | ``'ignore'``).
|
---|
| 1293 |
|
---|
| 1294 | The :class:`io.FileIO` class now raises an :exc:`OSError` when passed
|
---|
| 1295 | an invalid file descriptor. (Implemented by Benjamin Peterson;
|
---|
| 1296 | :issue:`4991`.) The :meth:`~io.IOBase.truncate` method now preserves the
|
---|
| 1297 | file position; previously it would change the file position to the
|
---|
| 1298 | end of the new file. (Fixed by Pascal Chambon; :issue:`6939`.)
|
---|
| 1299 |
|
---|
| 1300 | * New function: ``itertools.compress(data, selectors)`` takes two
|
---|
| 1301 | iterators. Elements of *data* are returned if the corresponding
|
---|
| 1302 | value in *selectors* is true::
|
---|
| 1303 |
|
---|
| 1304 | itertools.compress('ABCDEF', [1,0,1,0,1,1]) =>
|
---|
| 1305 | A, C, E, F
|
---|
| 1306 |
|
---|
| 1307 | .. maybe here is better to use >>> list(itertools.compress(...)) instead
|
---|
| 1308 |
|
---|
| 1309 | New function: ``itertools.combinations_with_replacement(iter, r)``
|
---|
| 1310 | returns all the possible *r*-length combinations of elements from the
|
---|
| 1311 | iterable *iter*. Unlike :func:`~itertools.combinations`, individual elements
|
---|
| 1312 | can be repeated in the generated combinations::
|
---|
| 1313 |
|
---|
| 1314 | itertools.combinations_with_replacement('abc', 2) =>
|
---|
| 1315 | ('a', 'a'), ('a', 'b'), ('a', 'c'),
|
---|
| 1316 | ('b', 'b'), ('b', 'c'), ('c', 'c')
|
---|
| 1317 |
|
---|
| 1318 | Note that elements are treated as unique depending on their position
|
---|
| 1319 | in the input, not their actual values.
|
---|
| 1320 |
|
---|
| 1321 | The :func:`itertools.count` function now has a *step* argument that
|
---|
| 1322 | allows incrementing by values other than 1. :func:`~itertools.count` also
|
---|
| 1323 | now allows keyword arguments, and using non-integer values such as
|
---|
| 1324 | floats or :class:`~decimal.Decimal` instances. (Implemented by Raymond
|
---|
| 1325 | Hettinger; :issue:`5032`.)
|
---|
| 1326 |
|
---|
| 1327 | :func:`itertools.combinations` and :func:`itertools.product`
|
---|
| 1328 | previously raised :exc:`ValueError` for values of *r* larger than
|
---|
| 1329 | the input iterable. This was deemed a specification error, so they
|
---|
| 1330 | now return an empty iterator. (Fixed by Raymond Hettinger; :issue:`4816`.)
|
---|
| 1331 |
|
---|
| 1332 | * Updated module: The :mod:`json` module was upgraded to version 2.0.9 of the
|
---|
| 1333 | simplejson package, which includes a C extension that makes
|
---|
| 1334 | encoding and decoding faster.
|
---|
| 1335 | (Contributed by Bob Ippolito; :issue:`4136`.)
|
---|
| 1336 |
|
---|
| 1337 | To support the new :class:`collections.OrderedDict` type, :func:`json.load`
|
---|
| 1338 | now has an optional *object_pairs_hook* parameter that will be called
|
---|
| 1339 | with any object literal that decodes to a list of pairs.
|
---|
| 1340 | (Contributed by Raymond Hettinger; :issue:`5381`.)
|
---|
| 1341 |
|
---|
| 1342 | * The :mod:`mailbox` module's :class:`~mailbox.Maildir` class now records the
|
---|
| 1343 | timestamp on the directories it reads, and only re-reads them if the
|
---|
| 1344 | modification time has subsequently changed. This improves
|
---|
| 1345 | performance by avoiding unneeded directory scans. (Fixed by
|
---|
| 1346 | A.M. Kuchling and Antoine Pitrou; :issue:`1607951`, :issue:`6896`.)
|
---|
| 1347 |
|
---|
| 1348 | * New functions: the :mod:`math` module gained
|
---|
| 1349 | :func:`~math.erf` and :func:`~math.erfc` for the error function and the complementary error function,
|
---|
| 1350 | :func:`~math.expm1` which computes ``e**x - 1`` with more precision than
|
---|
| 1351 | using :func:`~math.exp` and subtracting 1,
|
---|
| 1352 | :func:`~math.gamma` for the Gamma function, and
|
---|
| 1353 | :func:`~math.lgamma` for the natural log of the Gamma function.
|
---|
| 1354 | (Contributed by Mark Dickinson and nirinA raseliarison; :issue:`3366`.)
|
---|
| 1355 |
|
---|
| 1356 | * The :mod:`multiprocessing` module's :class:`Manager*` classes
|
---|
| 1357 | can now be passed a callable that will be called whenever
|
---|
| 1358 | a subprocess is started, along with a set of arguments that will be
|
---|
| 1359 | passed to the callable.
|
---|
| 1360 | (Contributed by lekma; :issue:`5585`.)
|
---|
| 1361 |
|
---|
| 1362 | The :class:`~multiprocessing.Pool` class, which controls a pool of worker processes,
|
---|
| 1363 | now has an optional *maxtasksperchild* parameter. Worker processes
|
---|
| 1364 | will perform the specified number of tasks and then exit, causing the
|
---|
| 1365 | :class:`~multiprocessing.Pool` to start a new worker. This is useful if tasks may leak
|
---|
| 1366 | memory or other resources, or if some tasks will cause the worker to
|
---|
| 1367 | become very large.
|
---|
| 1368 | (Contributed by Charles Cazabon; :issue:`6963`.)
|
---|
| 1369 |
|
---|
| 1370 | * The :mod:`nntplib` module now supports IPv6 addresses.
|
---|
| 1371 | (Contributed by Derek Morr; :issue:`1664`.)
|
---|
| 1372 |
|
---|
| 1373 | * New functions: the :mod:`os` module wraps the following POSIX system
|
---|
| 1374 | calls: :func:`~os.getresgid` and :func:`~os.getresuid`, which return the
|
---|
| 1375 | real, effective, and saved GIDs and UIDs;
|
---|
| 1376 | :func:`~os.setresgid` and :func:`~os.setresuid`, which set
|
---|
| 1377 | real, effective, and saved GIDs and UIDs to new values;
|
---|
| 1378 | :func:`~os.initgroups`, which initialize the group access list
|
---|
| 1379 | for the current process. (GID/UID functions
|
---|
| 1380 | contributed by Travis H.; :issue:`6508`. Support for initgroups added
|
---|
| 1381 | by Jean-Paul Calderone; :issue:`7333`.)
|
---|
| 1382 |
|
---|
| 1383 | The :func:`os.fork` function now re-initializes the import lock in
|
---|
| 1384 | the child process; this fixes problems on Solaris when :func:`~os.fork`
|
---|
| 1385 | is called from a thread. (Fixed by Zsolt Cserna; :issue:`7242`.)
|
---|
| 1386 |
|
---|
| 1387 | * In the :mod:`os.path` module, the :func:`~os.path.normpath` and
|
---|
| 1388 | :func:`~os.path.abspath` functions now preserve Unicode; if their input path
|
---|
| 1389 | is a Unicode string, the return value is also a Unicode string.
|
---|
| 1390 | (:meth:`~os.path.normpath` fixed by Matt Giuca in :issue:`5827`;
|
---|
| 1391 | :meth:`~os.path.abspath` fixed by Ezio Melotti in :issue:`3426`.)
|
---|
| 1392 |
|
---|
| 1393 | * The :mod:`pydoc` module now has help for the various symbols that Python
|
---|
| 1394 | uses. You can now do ``help('<<')`` or ``help('@')``, for example.
|
---|
| 1395 | (Contributed by David Laban; :issue:`4739`.)
|
---|
| 1396 |
|
---|
| 1397 | * The :mod:`re` module's :func:`~re.split`, :func:`~re.sub`, and :func:`~re.subn`
|
---|
| 1398 | now accept an optional *flags* argument, for consistency with the
|
---|
| 1399 | other functions in the module. (Added by Gregory P. Smith.)
|
---|
| 1400 |
|
---|
| 1401 | * New function: :func:`~runpy.run_path` in the :mod:`runpy` module
|
---|
| 1402 | will execute the code at a provided *path* argument. *path* can be
|
---|
| 1403 | the path of a Python source file (:file:`example.py`), a compiled
|
---|
| 1404 | bytecode file (:file:`example.pyc`), a directory
|
---|
| 1405 | (:file:`./package/`), or a zip archive (:file:`example.zip`). If a
|
---|
| 1406 | directory or zip path is provided, it will be added to the front of
|
---|
| 1407 | ``sys.path`` and the module :mod:`__main__` will be imported. It's
|
---|
| 1408 | expected that the directory or zip contains a :file:`__main__.py`;
|
---|
| 1409 | if it doesn't, some other :file:`__main__.py` might be imported from
|
---|
| 1410 | a location later in ``sys.path``. This makes more of the machinery
|
---|
| 1411 | of :mod:`runpy` available to scripts that want to mimic the way
|
---|
| 1412 | Python's command line processes an explicit path name.
|
---|
| 1413 | (Added by Nick Coghlan; :issue:`6816`.)
|
---|
| 1414 |
|
---|
| 1415 | * New function: in the :mod:`shutil` module, :func:`~shutil.make_archive`
|
---|
| 1416 | takes a filename, archive type (zip or tar-format), and a directory
|
---|
| 1417 | path, and creates an archive containing the directory's contents.
|
---|
| 1418 | (Added by Tarek Ziadé.)
|
---|
| 1419 |
|
---|
| 1420 | :mod:`shutil`'s :func:`~shutil.copyfile` and :func:`~shutil.copytree`
|
---|
| 1421 | functions now raise a :exc:`~shutil.SpecialFileError` exception when
|
---|
| 1422 | asked to copy a named pipe. Previously the code would treat
|
---|
| 1423 | named pipes like a regular file by opening them for reading, and
|
---|
| 1424 | this would block indefinitely. (Fixed by Antoine Pitrou; :issue:`3002`.)
|
---|
| 1425 |
|
---|
| 1426 | * The :mod:`signal` module no longer re-installs the signal handler
|
---|
| 1427 | unless this is truly necessary, which fixes a bug that could make it
|
---|
| 1428 | impossible to catch the EINTR signal robustly. (Fixed by
|
---|
| 1429 | Charles-Francois Natali; :issue:`8354`.)
|
---|
| 1430 |
|
---|
| 1431 | * New functions: in the :mod:`site` module, three new functions
|
---|
| 1432 | return various site- and user-specific paths.
|
---|
| 1433 | :func:`~site.getsitepackages` returns a list containing all
|
---|
| 1434 | global site-packages directories,
|
---|
| 1435 | :func:`~site.getusersitepackages` returns the path of the user's
|
---|
| 1436 | site-packages directory, and
|
---|
| 1437 | :func:`~site.getuserbase` returns the value of the :envvar:`USER_BASE`
|
---|
| 1438 | environment variable, giving the path to a directory that can be used
|
---|
| 1439 | to store data.
|
---|
| 1440 | (Contributed by Tarek Ziadé; :issue:`6693`.)
|
---|
| 1441 |
|
---|
| 1442 | The :mod:`site` module now reports exceptions occurring
|
---|
| 1443 | when the :mod:`sitecustomize` module is imported, and will no longer
|
---|
| 1444 | catch and swallow the :exc:`KeyboardInterrupt` exception. (Fixed by
|
---|
| 1445 | Victor Stinner; :issue:`3137`.)
|
---|
| 1446 |
|
---|
| 1447 | * The :func:`~socket.create_connection` function
|
---|
| 1448 | gained a *source_address* parameter, a ``(host, port)`` 2-tuple
|
---|
| 1449 | giving the source address that will be used for the connection.
|
---|
| 1450 | (Contributed by Eldon Ziegler; :issue:`3972`.)
|
---|
| 1451 |
|
---|
| 1452 | The :meth:`~socket.socket.recv_into` and :meth:`~socket.socket.recvfrom_into`
|
---|
| 1453 | methods will now write into objects that support the buffer API, most usefully
|
---|
| 1454 | the :class:`bytearray` and :class:`memoryview` objects. (Implemented by
|
---|
| 1455 | Antoine Pitrou; :issue:`8104`.)
|
---|
| 1456 |
|
---|
| 1457 | * The :mod:`SocketServer` module's :class:`~SocketServer.TCPServer` class now
|
---|
| 1458 | supports socket timeouts and disabling the Nagle algorithm.
|
---|
| 1459 | The :attr:`~SocketServer.TCPServer.disable_nagle_algorithm` class attribute
|
---|
| 1460 | defaults to False; if overridden to be True,
|
---|
| 1461 | new request connections will have the TCP_NODELAY option set to
|
---|
| 1462 | prevent buffering many small sends into a single TCP packet.
|
---|
| 1463 | The :attr:`~SocketServer.BaseServer.timeout` class attribute can hold
|
---|
| 1464 | a timeout in seconds that will be applied to the request socket; if
|
---|
| 1465 | no request is received within that time, :meth:`~SocketServer.BaseServer.handle_timeout`
|
---|
| 1466 | will be called and :meth:`~SocketServer.BaseServer.handle_request` will return.
|
---|
| 1467 | (Contributed by Kristján Valur Jónsson; :issue:`6192` and :issue:`6267`.)
|
---|
| 1468 |
|
---|
| 1469 | * Updated module: the :mod:`sqlite3` module has been updated to
|
---|
| 1470 | version 2.6.0 of the `pysqlite package <http://code.google.com/p/pysqlite/>`__. Version 2.6.0 includes a number of bugfixes, and adds
|
---|
| 1471 | the ability to load SQLite extensions from shared libraries.
|
---|
| 1472 | Call the ``enable_load_extension(True)`` method to enable extensions,
|
---|
| 1473 | and then call :meth:`~sqlite3.Connection.load_extension` to load a particular shared library.
|
---|
| 1474 | (Updated by Gerhard HÀring.)
|
---|
| 1475 |
|
---|
| 1476 | * The :mod:`ssl` module's :class:`~ssl.SSLSocket` objects now support the
|
---|
| 1477 | buffer API, which fixed a test suite failure (fix by Antoine Pitrou;
|
---|
| 1478 | :issue:`7133`) and automatically set
|
---|
| 1479 | OpenSSL's :c:macro:`SSL_MODE_AUTO_RETRY`, which will prevent an error
|
---|
| 1480 | code being returned from :meth:`recv` operations that trigger an SSL
|
---|
| 1481 | renegotiation (fix by Antoine Pitrou; :issue:`8222`).
|
---|
| 1482 |
|
---|
| 1483 | The :func:`ssl.wrap_socket` constructor function now takes a
|
---|
| 1484 | *ciphers* argument that's a string listing the encryption algorithms
|
---|
| 1485 | to be allowed; the format of the string is described
|
---|
| 1486 | `in the OpenSSL documentation
|
---|
| 1487 | <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`__.
|
---|
| 1488 | (Added by Antoine Pitrou; :issue:`8322`.)
|
---|
| 1489 |
|
---|
| 1490 | Another change makes the extension load all of OpenSSL's ciphers and
|
---|
| 1491 | digest algorithms so that they're all available. Some SSL
|
---|
| 1492 | certificates couldn't be verified, reporting an "unknown algorithm"
|
---|
| 1493 | error. (Reported by Beda Kosata, and fixed by Antoine Pitrou;
|
---|
| 1494 | :issue:`8484`.)
|
---|
| 1495 |
|
---|
| 1496 | The version of OpenSSL being used is now available as the module
|
---|
| 1497 | attributes :data:`ssl.OPENSSL_VERSION` (a string),
|
---|
| 1498 | :data:`ssl.OPENSSL_VERSION_INFO` (a 5-tuple), and
|
---|
| 1499 | :data:`ssl.OPENSSL_VERSION_NUMBER` (an integer). (Added by Antoine
|
---|
| 1500 | Pitrou; :issue:`8321`.)
|
---|
| 1501 |
|
---|
| 1502 | * The :mod:`struct` module will no longer silently ignore overflow
|
---|
| 1503 | errors when a value is too large for a particular integer format
|
---|
| 1504 | code (one of ``bBhHiIlLqQ``); it now always raises a
|
---|
| 1505 | :exc:`struct.error` exception. (Changed by Mark Dickinson;
|
---|
| 1506 | :issue:`1523`.) The :func:`~struct.pack` function will also
|
---|
| 1507 | attempt to use :meth:`__index__` to convert and pack non-integers
|
---|
| 1508 | before trying the :meth:`__int__` method or reporting an error.
|
---|
| 1509 | (Changed by Mark Dickinson; :issue:`8300`.)
|
---|
| 1510 |
|
---|
| 1511 | * New function: the :mod:`subprocess` module's
|
---|
| 1512 | :func:`~subprocess.check_output` runs a command with a specified set of arguments
|
---|
| 1513 | and returns the command's output as a string when the command runs without
|
---|
| 1514 | error, or raises a :exc:`~subprocess.CalledProcessError` exception otherwise.
|
---|
| 1515 |
|
---|
| 1516 | ::
|
---|
| 1517 |
|
---|
| 1518 | >>> subprocess.check_output(['df', '-h', '.'])
|
---|
| 1519 | 'Filesystem Size Used Avail Capacity Mounted on\n
|
---|
| 1520 | /dev/disk0s2 52G 49G 3.0G 94% /\n'
|
---|
| 1521 |
|
---|
| 1522 | >>> subprocess.check_output(['df', '-h', '/bogus'])
|
---|
| 1523 | ...
|
---|
| 1524 | subprocess.CalledProcessError: Command '['df', '-h', '/bogus']' returned non-zero exit status 1
|
---|
| 1525 |
|
---|
| 1526 | (Contributed by Gregory P. Smith.)
|
---|
| 1527 |
|
---|
| 1528 | The :mod:`subprocess` module will now retry its internal system calls
|
---|
| 1529 | on receiving an :const:`EINTR` signal. (Reported by several people; final
|
---|
| 1530 | patch by Gregory P. Smith in :issue:`1068268`.)
|
---|
| 1531 |
|
---|
| 1532 | * New function: :func:`~symtable.Symbol.is_declared_global` in the :mod:`symtable` module
|
---|
| 1533 | returns true for variables that are explicitly declared to be global,
|
---|
| 1534 | false for ones that are implicitly global.
|
---|
| 1535 | (Contributed by Jeremy Hylton.)
|
---|
| 1536 |
|
---|
| 1537 | * The :mod:`syslog` module will now use the value of ``sys.argv[0]`` as the
|
---|
| 1538 | identifier instead of the previous default value of ``'python'``.
|
---|
| 1539 | (Changed by Sean Reifschneider; :issue:`8451`.)
|
---|
| 1540 |
|
---|
| 1541 | * The ``sys.version_info`` value is now a named tuple, with attributes
|
---|
| 1542 | named :attr:`major`, :attr:`minor`, :attr:`micro`,
|
---|
| 1543 | :attr:`releaselevel`, and :attr:`serial`. (Contributed by Ross
|
---|
| 1544 | Light; :issue:`4285`.)
|
---|
| 1545 |
|
---|
| 1546 | :func:`sys.getwindowsversion` also returns a named tuple,
|
---|
| 1547 | with attributes named :attr:`major`, :attr:`minor`, :attr:`build`,
|
---|
| 1548 | :attr:`platform`, :attr:`service_pack`, :attr:`service_pack_major`,
|
---|
| 1549 | :attr:`service_pack_minor`, :attr:`suite_mask`, and
|
---|
| 1550 | :attr:`product_type`. (Contributed by Brian Curtin; :issue:`7766`.)
|
---|
| 1551 |
|
---|
| 1552 | * The :mod:`tarfile` module's default error handling has changed, to
|
---|
| 1553 | no longer suppress fatal errors. The default error level was previously 0,
|
---|
| 1554 | which meant that errors would only result in a message being written to the
|
---|
| 1555 | debug log, but because the debug log is not activated by default,
|
---|
| 1556 | these errors go unnoticed. The default error level is now 1,
|
---|
| 1557 | which raises an exception if there's an error.
|
---|
| 1558 | (Changed by Lars GustÀbel; :issue:`7357`.)
|
---|
| 1559 |
|
---|
| 1560 | :mod:`tarfile` now supports filtering the :class:`~tarfile.TarInfo`
|
---|
| 1561 | objects being added to a tar file. When you call :meth:`~tarfile.TarFile.add`,
|
---|
| 1562 | you may supply an optional *filter* argument
|
---|
| 1563 | that's a callable. The *filter* callable will be passed the
|
---|
| 1564 | :class:`~tarfile.TarInfo` for every file being added, and can modify and return it.
|
---|
| 1565 | If the callable returns ``None``, the file will be excluded from the
|
---|
| 1566 | resulting archive. This is more powerful than the existing
|
---|
| 1567 | *exclude* argument, which has therefore been deprecated.
|
---|
| 1568 | (Added by Lars GustÀbel; :issue:`6856`.)
|
---|
| 1569 | The :class:`~tarfile.TarFile` class also now supports the context manager protocol.
|
---|
| 1570 | (Added by Lars GustÀbel; :issue:`7232`.)
|
---|
| 1571 |
|
---|
| 1572 | * The :meth:`~threading.Event.wait` method of the :class:`threading.Event` class
|
---|
| 1573 | now returns the internal flag on exit. This means the method will usually
|
---|
| 1574 | return true because :meth:`~threading.Event.wait` is supposed to block until the
|
---|
| 1575 | internal flag becomes true. The return value will only be false if
|
---|
| 1576 | a timeout was provided and the operation timed out.
|
---|
| 1577 | (Contributed by Tim Lesher; :issue:`1674032`.)
|
---|
| 1578 |
|
---|
| 1579 | * The Unicode database provided by the :mod:`unicodedata` module is
|
---|
| 1580 | now used internally to determine which characters are numeric,
|
---|
| 1581 | whitespace, or represent line breaks. The database also
|
---|
| 1582 | includes information from the :file:`Unihan.txt` data file (patch
|
---|
| 1583 | by Anders Chrigström and Amaury Forgeot d'Arc; :issue:`1571184`)
|
---|
| 1584 | and has been updated to version 5.2.0 (updated by
|
---|
| 1585 | Florent Xicluna; :issue:`8024`).
|
---|
| 1586 |
|
---|
| 1587 | * The :mod:`urlparse` module's :func:`~urlparse.urlsplit` now handles
|
---|
| 1588 | unknown URL schemes in a fashion compliant with :rfc:`3986`: if the
|
---|
| 1589 | URL is of the form ``"<something>://..."``, the text before the
|
---|
| 1590 | ``://`` is treated as the scheme, even if it's a made-up scheme that
|
---|
| 1591 | the module doesn't know about. This change may break code that
|
---|
| 1592 | worked around the old behaviour. For example, Python 2.6.4 or 2.5
|
---|
| 1593 | will return the following:
|
---|
| 1594 |
|
---|
| 1595 | >>> import urlparse
|
---|
| 1596 | >>> urlparse.urlsplit('invented://host/filename?query')
|
---|
| 1597 | ('invented', '', '//host/filename?query', '', '')
|
---|
| 1598 |
|
---|
| 1599 | Python 2.7 (and Python 2.6.5) will return:
|
---|
| 1600 |
|
---|
| 1601 | >>> import urlparse
|
---|
| 1602 | >>> urlparse.urlsplit('invented://host/filename?query')
|
---|
| 1603 | ('invented', 'host', '/filename?query', '', '')
|
---|
| 1604 |
|
---|
| 1605 | (Python 2.7 actually produces slightly different output, since it
|
---|
| 1606 | returns a named tuple instead of a standard tuple.)
|
---|
| 1607 |
|
---|
| 1608 | The :mod:`urlparse` module also supports IPv6 literal addresses as defined by
|
---|
| 1609 | :rfc:`2732` (contributed by Senthil Kumaran; :issue:`2987`). ::
|
---|
| 1610 |
|
---|
| 1611 | >>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo')
|
---|
| 1612 | ParseResult(scheme='http', netloc='[1080::8:800:200C:417A]',
|
---|
| 1613 | path='/foo', params='', query='', fragment='')
|
---|
| 1614 |
|
---|
| 1615 | * New class: the :class:`~weakref.WeakSet` class in the :mod:`weakref`
|
---|
| 1616 | module is a set that only holds weak references to its elements; elements
|
---|
| 1617 | will be removed once there are no references pointing to them.
|
---|
| 1618 | (Originally implemented in Python 3.x by Raymond Hettinger, and backported
|
---|
| 1619 | to 2.7 by Michael Foord.)
|
---|
| 1620 |
|
---|
| 1621 | * The ElementTree library, :mod:`xml.etree`, no longer escapes
|
---|
| 1622 | ampersands and angle brackets when outputting an XML processing
|
---|
| 1623 | instruction (which looks like ``<?xml-stylesheet href="#style1"?>``)
|
---|
| 1624 | or comment (which looks like ``<!-- comment -->``).
|
---|
| 1625 | (Patch by Neil Muller; :issue:`2746`.)
|
---|
| 1626 |
|
---|
| 1627 | * The XML-RPC client and server, provided by the :mod:`xmlrpclib` and
|
---|
| 1628 | :mod:`SimpleXMLRPCServer` modules, have improved performance by
|
---|
| 1629 | supporting HTTP/1.1 keep-alive and by optionally using gzip encoding
|
---|
| 1630 | to compress the XML being exchanged. The gzip compression is
|
---|
| 1631 | controlled by the :attr:`encode_threshold` attribute of
|
---|
| 1632 | :class:`SimpleXMLRPCRequestHandler`, which contains a size in bytes;
|
---|
| 1633 | responses larger than this will be compressed.
|
---|
| 1634 | (Contributed by Kristján Valur Jónsson; :issue:`6267`.)
|
---|
| 1635 |
|
---|
| 1636 | * The :mod:`zipfile` module's :class:`~zipfile.ZipFile` now supports the context
|
---|
| 1637 | management protocol, so you can write ``with zipfile.ZipFile(...) as f:``.
|
---|
| 1638 | (Contributed by Brian Curtin; :issue:`5511`.)
|
---|
| 1639 |
|
---|
| 1640 | :mod:`zipfile` now also supports archiving empty directories and
|
---|
| 1641 | extracts them correctly. (Fixed by Kuba Wieczorek; :issue:`4710`.)
|
---|
| 1642 | Reading files out of an archive is faster, and interleaving
|
---|
| 1643 | :meth:`~zipfile.ZipFile.read` and :meth:`~zipfile.ZipFile.readline` now works correctly.
|
---|
| 1644 | (Contributed by Nir Aides; :issue:`7610`.)
|
---|
| 1645 |
|
---|
| 1646 | The :func:`~zipfile.is_zipfile` function now
|
---|
| 1647 | accepts a file object, in addition to the path names accepted in earlier
|
---|
| 1648 | versions. (Contributed by Gabriel Genellina; :issue:`4756`.)
|
---|
| 1649 |
|
---|
| 1650 | The :meth:`~zipfile.ZipFile.writestr` method now has an optional *compress_type* parameter
|
---|
| 1651 | that lets you override the default compression method specified in the
|
---|
| 1652 | :class:`~zipfile.ZipFile` constructor. (Contributed by Ronald Oussoren;
|
---|
| 1653 | :issue:`6003`.)
|
---|
| 1654 |
|
---|
| 1655 |
|
---|
| 1656 | .. ======================================================================
|
---|
| 1657 | .. whole new modules get described in subsections here
|
---|
| 1658 |
|
---|
| 1659 |
|
---|
| 1660 | .. _importlib-section:
|
---|
| 1661 |
|
---|
| 1662 | New module: importlib
|
---|
| 1663 | ------------------------------
|
---|
| 1664 |
|
---|
| 1665 | Python 3.1 includes the :mod:`importlib` package, a re-implementation
|
---|
| 1666 | of the logic underlying Python's :keyword:`import` statement.
|
---|
| 1667 | :mod:`importlib` is useful for implementors of Python interpreters and
|
---|
| 1668 | to users who wish to write new importers that can participate in the
|
---|
| 1669 | import process. Python 2.7 doesn't contain the complete
|
---|
| 1670 | :mod:`importlib` package, but instead has a tiny subset that contains
|
---|
| 1671 | a single function, :func:`~importlib.import_module`.
|
---|
| 1672 |
|
---|
| 1673 | ``import_module(name, package=None)`` imports a module. *name* is
|
---|
| 1674 | a string containing the module or package's name. It's possible to do
|
---|
| 1675 | relative imports by providing a string that begins with a ``.``
|
---|
| 1676 | character, such as ``..utils.errors``. For relative imports, the
|
---|
| 1677 | *package* argument must be provided and is the name of the package that
|
---|
| 1678 | will be used as the anchor for
|
---|
| 1679 | the relative import. :func:`~importlib.import_module` both inserts the imported
|
---|
| 1680 | module into ``sys.modules`` and returns the module object.
|
---|
| 1681 |
|
---|
| 1682 | Here are some examples::
|
---|
| 1683 |
|
---|
| 1684 | >>> from importlib import import_module
|
---|
| 1685 | >>> anydbm = import_module('anydbm') # Standard absolute import
|
---|
| 1686 | >>> anydbm
|
---|
| 1687 | <module 'anydbm' from '/p/python/Lib/anydbm.py'>
|
---|
| 1688 | >>> # Relative import
|
---|
| 1689 | >>> file_util = import_module('..file_util', 'distutils.command')
|
---|
| 1690 | >>> file_util
|
---|
| 1691 | <module 'distutils.file_util' from '/python/Lib/distutils/file_util.pyc'>
|
---|
| 1692 |
|
---|
| 1693 | :mod:`importlib` was implemented by Brett Cannon and introduced in
|
---|
| 1694 | Python 3.1.
|
---|
| 1695 |
|
---|
| 1696 |
|
---|
| 1697 | New module: sysconfig
|
---|
| 1698 | ---------------------------------
|
---|
| 1699 |
|
---|
| 1700 | The :mod:`sysconfig` module has been pulled out of the Distutils
|
---|
| 1701 | package, becoming a new top-level module in its own right.
|
---|
| 1702 | :mod:`sysconfig` provides functions for getting information about
|
---|
| 1703 | Python's build process: compiler switches, installation paths, the
|
---|
| 1704 | platform name, and whether Python is running from its source
|
---|
| 1705 | directory.
|
---|
| 1706 |
|
---|
| 1707 | Some of the functions in the module are:
|
---|
| 1708 |
|
---|
| 1709 | * :func:`~sysconfig.get_config_var` returns variables from Python's
|
---|
| 1710 | Makefile and the :file:`pyconfig.h` file.
|
---|
| 1711 | * :func:`~sysconfig.get_config_vars` returns a dictionary containing
|
---|
| 1712 | all of the configuration variables.
|
---|
| 1713 | * :func:`~sysconfig.get_path` returns the configured path for
|
---|
| 1714 | a particular type of module: the standard library,
|
---|
| 1715 | site-specific modules, platform-specific modules, etc.
|
---|
| 1716 | * :func:`~sysconfig.is_python_build` returns true if you're running a
|
---|
| 1717 | binary from a Python source tree, and false otherwise.
|
---|
| 1718 |
|
---|
| 1719 | Consult the :mod:`sysconfig` documentation for more details and for
|
---|
| 1720 | a complete list of functions.
|
---|
| 1721 |
|
---|
| 1722 | The Distutils package and :mod:`sysconfig` are now maintained by Tarek
|
---|
| 1723 | Ziadé, who has also started a Distutils2 package (source repository at
|
---|
| 1724 | http://hg.python.org/distutils2/) for developing a next-generation
|
---|
| 1725 | version of Distutils.
|
---|
| 1726 |
|
---|
| 1727 |
|
---|
| 1728 | ttk: Themed Widgets for Tk
|
---|
| 1729 | --------------------------
|
---|
| 1730 |
|
---|
| 1731 | Tcl/Tk 8.5 includes a set of themed widgets that re-implement basic Tk
|
---|
| 1732 | widgets but have a more customizable appearance and can therefore more
|
---|
| 1733 | closely resemble the native platform's widgets. This widget
|
---|
| 1734 | set was originally called Tile, but was renamed to Ttk (for "themed Tk")
|
---|
| 1735 | on being added to Tcl/Tck release 8.5.
|
---|
| 1736 |
|
---|
| 1737 | To learn more, read the :mod:`ttk` module documentation. You may also
|
---|
| 1738 | wish to read the Tcl/Tk manual page describing the
|
---|
| 1739 | Ttk theme engine, available at
|
---|
| 1740 | http://www.tcl.tk/man/tcl8.5/TkCmd/ttk_intro.htm. Some
|
---|
| 1741 | screenshots of the Python/Ttk code in use are at
|
---|
| 1742 | http://code.google.com/p/python-ttk/wiki/Screenshots.
|
---|
| 1743 |
|
---|
| 1744 | The :mod:`ttk` module was written by Guilherme Polo and added in
|
---|
| 1745 | :issue:`2983`. An alternate version called ``Tile.py``, written by
|
---|
| 1746 | Martin Franklin and maintained by Kevin Walzer, was proposed for
|
---|
| 1747 | inclusion in :issue:`2618`, but the authors argued that Guilherme
|
---|
| 1748 | Polo's work was more comprehensive.
|
---|
| 1749 |
|
---|
| 1750 |
|
---|
| 1751 | .. _unittest-section:
|
---|
| 1752 |
|
---|
| 1753 | Updated module: unittest
|
---|
| 1754 | ---------------------------------
|
---|
| 1755 |
|
---|
| 1756 | The :mod:`unittest` module was greatly enhanced; many
|
---|
| 1757 | new features were added. Most of these features were implemented
|
---|
| 1758 | by Michael Foord, unless otherwise noted. The enhanced version of
|
---|
| 1759 | the module is downloadable separately for use with Python versions 2.4 to 2.6,
|
---|
| 1760 | packaged as the :mod:`unittest2` package, from
|
---|
| 1761 | http://pypi.python.org/pypi/unittest2.
|
---|
| 1762 |
|
---|
| 1763 | When used from the command line, the module can automatically discover
|
---|
| 1764 | tests. It's not as fancy as `py.test <http://pytest.org>`__ or
|
---|
| 1765 | `nose <http://code.google.com/p/python-nose/>`__, but provides a simple way
|
---|
| 1766 | to run tests kept within a set of package directories. For example,
|
---|
| 1767 | the following command will search the :file:`test/` subdirectory for
|
---|
| 1768 | any importable test files named ``test*.py``::
|
---|
| 1769 |
|
---|
| 1770 | python -m unittest discover -s test
|
---|
| 1771 |
|
---|
| 1772 | Consult the :mod:`unittest` module documentation for more details.
|
---|
| 1773 | (Developed in :issue:`6001`.)
|
---|
| 1774 |
|
---|
| 1775 | The :func:`~unittest.main` function supports some other new options:
|
---|
| 1776 |
|
---|
| 1777 | * :option:`-b` or :option:`--buffer` will buffer the standard output
|
---|
| 1778 | and standard error streams during each test. If the test passes,
|
---|
| 1779 | any resulting output will be discarded; on failure, the buffered
|
---|
| 1780 | output will be displayed.
|
---|
| 1781 |
|
---|
| 1782 | * :option:`-c` or :option:`--catch` will cause the control-C interrupt
|
---|
| 1783 | to be handled more gracefully. Instead of interrupting the test
|
---|
| 1784 | process immediately, the currently running test will be completed
|
---|
| 1785 | and then the partial results up to the interruption will be reported.
|
---|
| 1786 | If you're impatient, a second press of control-C will cause an immediate
|
---|
| 1787 | interruption.
|
---|
| 1788 |
|
---|
| 1789 | This control-C handler tries to avoid causing problems when the code
|
---|
| 1790 | being tested or the tests being run have defined a signal handler of
|
---|
| 1791 | their own, by noticing that a signal handler was already set and
|
---|
| 1792 | calling it. If this doesn't work for you, there's a
|
---|
| 1793 | :func:`~unittest.removeHandler` decorator that can be used to mark tests that
|
---|
| 1794 | should have the control-C handling disabled.
|
---|
| 1795 |
|
---|
| 1796 | * :option:`-f` or :option:`--failfast` makes
|
---|
| 1797 | test execution stop immediately when a test fails instead of
|
---|
| 1798 | continuing to execute further tests. (Suggested by Cliff Dyer and
|
---|
| 1799 | implemented by Michael Foord; :issue:`8074`.)
|
---|
| 1800 |
|
---|
| 1801 | The progress messages now show 'x' for expected failures
|
---|
| 1802 | and 'u' for unexpected successes when run in verbose mode.
|
---|
| 1803 | (Contributed by Benjamin Peterson.)
|
---|
| 1804 |
|
---|
| 1805 | Test cases can raise the :exc:`~unittest.SkipTest` exception to skip a
|
---|
| 1806 | test (:issue:`1034053`).
|
---|
| 1807 |
|
---|
| 1808 | The error messages for :meth:`~unittest.TestCase.assertEqual`,
|
---|
| 1809 | :meth:`~unittest.TestCase.assertTrue`, and :meth:`~unittest.TestCase.assertFalse`
|
---|
| 1810 | failures now provide more information. If you set the
|
---|
| 1811 | :attr:`~unittest.TestCase.longMessage` attribute of your :class:`~unittest.TestCase` classes to
|
---|
| 1812 | True, both the standard error message and any additional message you
|
---|
| 1813 | provide will be printed for failures. (Added by Michael Foord; :issue:`5663`.)
|
---|
| 1814 |
|
---|
| 1815 | The :meth:`~unittest.TestCase.assertRaises` method now
|
---|
| 1816 | returns a context handler when called without providing a callable
|
---|
| 1817 | object to run. For example, you can write this::
|
---|
| 1818 |
|
---|
| 1819 | with self.assertRaises(KeyError):
|
---|
| 1820 | {}['foo']
|
---|
| 1821 |
|
---|
| 1822 | (Implemented by Antoine Pitrou; :issue:`4444`.)
|
---|
| 1823 |
|
---|
| 1824 | .. rev 78774
|
---|
| 1825 |
|
---|
| 1826 | Module- and class-level setup and teardown fixtures are now supported.
|
---|
| 1827 | Modules can contain :func:`~unittest.setUpModule` and :func:`~unittest.tearDownModule`
|
---|
| 1828 | functions. Classes can have :meth:`~unittest.TestCase.setUpClass` and
|
---|
| 1829 | :meth:`~unittest.TestCase.tearDownClass` methods that must be defined as class methods
|
---|
| 1830 | (using ``@classmethod`` or equivalent). These functions and
|
---|
| 1831 | methods are invoked when the test runner switches to a test case in a
|
---|
| 1832 | different module or class.
|
---|
| 1833 |
|
---|
| 1834 | The methods :meth:`~unittest.TestCase.addCleanup` and
|
---|
| 1835 | :meth:`~unittest.TestCase.doCleanups` were added.
|
---|
| 1836 | :meth:`~unittest.TestCase.addCleanup` lets you add cleanup functions that
|
---|
| 1837 | will be called unconditionally (after :meth:`~unittest.TestCase.setUp` if
|
---|
| 1838 | :meth:`~unittest.TestCase.setUp` fails, otherwise after :meth:`~unittest.TestCase.tearDown`). This allows
|
---|
| 1839 | for much simpler resource allocation and deallocation during tests
|
---|
| 1840 | (:issue:`5679`).
|
---|
| 1841 |
|
---|
| 1842 | A number of new methods were added that provide more specialized
|
---|
| 1843 | tests. Many of these methods were written by Google engineers
|
---|
| 1844 | for use in their test suites; Gregory P. Smith, Michael Foord, and
|
---|
| 1845 | GvR worked on merging them into Python's version of :mod:`unittest`.
|
---|
| 1846 |
|
---|
| 1847 | * :meth:`~unittest.TestCase.assertIsNone` and :meth:`~unittest.TestCase.assertIsNotNone` take one
|
---|
| 1848 | expression and verify that the result is or is not ``None``.
|
---|
| 1849 |
|
---|
| 1850 | * :meth:`~unittest.TestCase.assertIs` and :meth:`~unittest.TestCase.assertIsNot`
|
---|
| 1851 | take two values and check whether the two values evaluate to the same object or not.
|
---|
| 1852 | (Added by Michael Foord; :issue:`2578`.)
|
---|
| 1853 |
|
---|
| 1854 | * :meth:`~unittest.TestCase.assertIsInstance` and
|
---|
| 1855 | :meth:`~unittest.TestCase.assertNotIsInstance` check whether
|
---|
| 1856 | the resulting object is an instance of a particular class, or of
|
---|
| 1857 | one of a tuple of classes. (Added by Georg Brandl; :issue:`7031`.)
|
---|
| 1858 |
|
---|
| 1859 | * :meth:`~unittest.TestCase.assertGreater`, :meth:`~unittest.TestCase.assertGreaterEqual`,
|
---|
| 1860 | :meth:`~unittest.TestCase.assertLess`, and :meth:`~unittest.TestCase.assertLessEqual` compare
|
---|
| 1861 | two quantities.
|
---|
| 1862 |
|
---|
| 1863 | * :meth:`~unittest.TestCase.assertMultiLineEqual` compares two strings, and if they're
|
---|
| 1864 | not equal, displays a helpful comparison that highlights the
|
---|
| 1865 | differences in the two strings. This comparison is now used by
|
---|
| 1866 | default when Unicode strings are compared with :meth:`~unittest.TestCase.assertEqual`.
|
---|
| 1867 |
|
---|
| 1868 | * :meth:`~unittest.TestCase.assertRegexpMatches` and
|
---|
| 1869 | :meth:`~unittest.TestCase.assertNotRegexpMatches` checks whether the
|
---|
| 1870 | first argument is a string matching or not matching the regular
|
---|
| 1871 | expression provided as the second argument (:issue:`8038`).
|
---|
| 1872 |
|
---|
| 1873 | * :meth:`~unittest.TestCase.assertRaisesRegexp` checks whether a particular exception
|
---|
| 1874 | is raised, and then also checks that the string representation of
|
---|
| 1875 | the exception matches the provided regular expression.
|
---|
| 1876 |
|
---|
| 1877 | * :meth:`~unittest.TestCase.assertIn` and :meth:`~unittest.TestCase.assertNotIn`
|
---|
| 1878 | tests whether *first* is or is not in *second*.
|
---|
| 1879 |
|
---|
| 1880 | * :meth:`~unittest.TestCase.assertItemsEqual` tests whether two provided sequences
|
---|
| 1881 | contain the same elements.
|
---|
| 1882 |
|
---|
| 1883 | * :meth:`~unittest.TestCase.assertSetEqual` compares whether two sets are equal, and
|
---|
| 1884 | only reports the differences between the sets in case of error.
|
---|
| 1885 |
|
---|
| 1886 | * Similarly, :meth:`~unittest.TestCase.assertListEqual` and :meth:`~unittest.TestCase.assertTupleEqual`
|
---|
| 1887 | compare the specified types and explain any differences without necessarily
|
---|
| 1888 | printing their full values; these methods are now used by default
|
---|
| 1889 | when comparing lists and tuples using :meth:`~unittest.TestCase.assertEqual`.
|
---|
| 1890 | More generally, :meth:`~unittest.TestCase.assertSequenceEqual` compares two sequences
|
---|
| 1891 | and can optionally check whether both sequences are of a
|
---|
| 1892 | particular type.
|
---|
| 1893 |
|
---|
| 1894 | * :meth:`~unittest.TestCase.assertDictEqual` compares two dictionaries and reports the
|
---|
| 1895 | differences; it's now used by default when you compare two dictionaries
|
---|
| 1896 | using :meth:`~unittest.TestCase.assertEqual`. :meth:`~unittest.TestCase.assertDictContainsSubset` checks whether
|
---|
| 1897 | all of the key/value pairs in *first* are found in *second*.
|
---|
| 1898 |
|
---|
| 1899 | * :meth:`~unittest.TestCase.assertAlmostEqual` and :meth:`~unittest.TestCase.assertNotAlmostEqual` test
|
---|
| 1900 | whether *first* and *second* are approximately equal. This method
|
---|
| 1901 | can either round their difference to an optionally-specified number
|
---|
| 1902 | of *places* (the default is 7) and compare it to zero, or require
|
---|
| 1903 | the difference to be smaller than a supplied *delta* value.
|
---|
| 1904 |
|
---|
| 1905 | * :meth:`~unittest.TestLoader.loadTestsFromName` properly honors the
|
---|
| 1906 | :attr:`~unittest.TestLoader.suiteClass` attribute of
|
---|
| 1907 | the :class:`~unittest.TestLoader`. (Fixed by Mark Roddy; :issue:`6866`.)
|
---|
| 1908 |
|
---|
| 1909 | * A new hook lets you extend the :meth:`~unittest.TestCase.assertEqual` method to handle
|
---|
| 1910 | new data types. The :meth:`~unittest.TestCase.addTypeEqualityFunc` method takes a type
|
---|
| 1911 | object and a function. The function will be used when both of the
|
---|
| 1912 | objects being compared are of the specified type. This function
|
---|
| 1913 | should compare the two objects and raise an exception if they don't
|
---|
| 1914 | match; it's a good idea for the function to provide additional
|
---|
| 1915 | information about why the two objects aren't matching, much as the new
|
---|
| 1916 | sequence comparison methods do.
|
---|
| 1917 |
|
---|
| 1918 | :func:`unittest.main` now takes an optional ``exit`` argument. If
|
---|
| 1919 | False, :func:`~unittest.main` doesn't call :func:`sys.exit`, allowing
|
---|
| 1920 | :func:`~unittest.main` to be used from the interactive interpreter.
|
---|
| 1921 | (Contributed by J. Pablo Fernández; :issue:`3379`.)
|
---|
| 1922 |
|
---|
| 1923 | :class:`~unittest.TestResult` has new :meth:`~unittest.TestResult.startTestRun` and
|
---|
| 1924 | :meth:`~unittest.TestResult.stopTestRun` methods that are called immediately before
|
---|
| 1925 | and after a test run. (Contributed by Robert Collins; :issue:`5728`.)
|
---|
| 1926 |
|
---|
| 1927 | With all these changes, the :file:`unittest.py` was becoming awkwardly
|
---|
| 1928 | large, so the module was turned into a package and the code split into
|
---|
| 1929 | several files (by Benjamin Peterson). This doesn't affect how the
|
---|
| 1930 | module is imported or used.
|
---|
| 1931 |
|
---|
| 1932 | .. seealso::
|
---|
| 1933 |
|
---|
| 1934 | http://www.voidspace.org.uk/python/articles/unittest2.shtml
|
---|
| 1935 | Describes the new features, how to use them, and the
|
---|
| 1936 | rationale for various design decisions. (By Michael Foord.)
|
---|
| 1937 |
|
---|
| 1938 | .. _elementtree-section:
|
---|
| 1939 |
|
---|
| 1940 | Updated module: ElementTree 1.3
|
---|
| 1941 | ---------------------------------
|
---|
| 1942 |
|
---|
| 1943 | The version of the ElementTree library included with Python was updated to
|
---|
| 1944 | version 1.3. Some of the new features are:
|
---|
| 1945 |
|
---|
| 1946 | * The various parsing functions now take a *parser* keyword argument
|
---|
| 1947 | giving an :class:`~xml.etree.ElementTree.XMLParser` instance that will
|
---|
| 1948 | be used. This makes it possible to override the file's internal encoding::
|
---|
| 1949 |
|
---|
| 1950 | p = ET.XMLParser(encoding='utf-8')
|
---|
| 1951 | t = ET.XML("""<root/>""", parser=p)
|
---|
| 1952 |
|
---|
| 1953 | Errors in parsing XML now raise a :exc:`ParseError` exception, whose
|
---|
| 1954 | instances have a :attr:`position` attribute
|
---|
| 1955 | containing a (*line*, *column*) tuple giving the location of the problem.
|
---|
| 1956 |
|
---|
| 1957 | * ElementTree's code for converting trees to a string has been
|
---|
| 1958 | significantly reworked, making it roughly twice as fast in many
|
---|
| 1959 | cases. The :meth:`ElementTree.write() <xml.etree.ElementTree.ElementTree.write>`
|
---|
| 1960 | and :meth:`Element.write` methods now have a *method* parameter that can be
|
---|
| 1961 | "xml" (the default), "html", or "text". HTML mode will output empty
|
---|
| 1962 | elements as ``<empty></empty>`` instead of ``<empty/>``, and text
|
---|
| 1963 | mode will skip over elements and only output the text chunks. If
|
---|
| 1964 | you set the :attr:`tag` attribute of an element to ``None`` but
|
---|
| 1965 | leave its children in place, the element will be omitted when the
|
---|
| 1966 | tree is written out, so you don't need to do more extensive rearrangement
|
---|
| 1967 | to remove a single element.
|
---|
| 1968 |
|
---|
| 1969 | Namespace handling has also been improved. All ``xmlns:<whatever>``
|
---|
| 1970 | declarations are now output on the root element, not scattered throughout
|
---|
| 1971 | the resulting XML. You can set the default namespace for a tree
|
---|
| 1972 | by setting the :attr:`default_namespace` attribute and can
|
---|
| 1973 | register new prefixes with :meth:`~xml.etree.ElementTree.register_namespace`. In XML mode,
|
---|
| 1974 | you can use the true/false *xml_declaration* parameter to suppress the
|
---|
| 1975 | XML declaration.
|
---|
| 1976 |
|
---|
| 1977 | * New :class:`~xml.etree.ElementTree.Element` method:
|
---|
| 1978 | :meth:`~xml.etree.ElementTree.Element.extend` appends the items from a
|
---|
| 1979 | sequence to the element's children. Elements themselves behave like
|
---|
| 1980 | sequences, so it's easy to move children from one element to
|
---|
| 1981 | another::
|
---|
| 1982 |
|
---|
| 1983 | from xml.etree import ElementTree as ET
|
---|
| 1984 |
|
---|
| 1985 | t = ET.XML("""<list>
|
---|
| 1986 | <item>1</item> <item>2</item> <item>3</item>
|
---|
| 1987 | </list>""")
|
---|
| 1988 | new = ET.XML('<root/>')
|
---|
| 1989 | new.extend(t)
|
---|
| 1990 |
|
---|
| 1991 | # Outputs <root><item>1</item>...</root>
|
---|
| 1992 | print ET.tostring(new)
|
---|
| 1993 |
|
---|
| 1994 | * New :class:`Element` method:
|
---|
| 1995 | :meth:`~xml.etree.ElementTree.Element.iter` yields the children of the
|
---|
| 1996 | element as a generator. It's also possible to write ``for child in
|
---|
| 1997 | elem:`` to loop over an element's children. The existing method
|
---|
| 1998 | :meth:`getiterator` is now deprecated, as is :meth:`getchildren`
|
---|
| 1999 | which constructs and returns a list of children.
|
---|
| 2000 |
|
---|
| 2001 | * New :class:`Element` method:
|
---|
| 2002 | :meth:`~xml.etree.ElementTree.Element.itertext` yields all chunks of
|
---|
| 2003 | text that are descendants of the element. For example::
|
---|
| 2004 |
|
---|
| 2005 | t = ET.XML("""<list>
|
---|
| 2006 | <item>1</item> <item>2</item> <item>3</item>
|
---|
| 2007 | </list>""")
|
---|
| 2008 |
|
---|
| 2009 | # Outputs ['\n ', '1', ' ', '2', ' ', '3', '\n']
|
---|
| 2010 | print list(t.itertext())
|
---|
| 2011 |
|
---|
| 2012 | * Deprecated: using an element as a Boolean (i.e., ``if elem:``) would
|
---|
| 2013 | return true if the element had any children, or false if there were
|
---|
| 2014 | no children. This behaviour is confusing -- ``None`` is false, but
|
---|
| 2015 | so is a childless element? -- so it will now trigger a
|
---|
| 2016 | :exc:`FutureWarning`. In your code, you should be explicit: write
|
---|
| 2017 | ``len(elem) != 0`` if you're interested in the number of children,
|
---|
| 2018 | or ``elem is not None``.
|
---|
| 2019 |
|
---|
| 2020 | Fredrik Lundh develops ElementTree and produced the 1.3 version;
|
---|
| 2021 | you can read his article describing 1.3 at
|
---|
| 2022 | http://effbot.org/zone/elementtree-13-intro.htm.
|
---|
| 2023 | Florent Xicluna updated the version included with
|
---|
| 2024 | Python, after discussions on python-dev and in :issue:`6472`.)
|
---|
| 2025 |
|
---|
| 2026 | .. ======================================================================
|
---|
| 2027 |
|
---|
| 2028 |
|
---|
| 2029 | Build and C API Changes
|
---|
| 2030 | =======================
|
---|
| 2031 |
|
---|
| 2032 | Changes to Python's build process and to the C API include:
|
---|
| 2033 |
|
---|
| 2034 | * The latest release of the GNU Debugger, GDB 7, can be `scripted
|
---|
| 2035 | using Python
|
---|
| 2036 | <http://sourceware.org/gdb/current/onlinedocs/gdb/Python.html>`__.
|
---|
| 2037 | When you begin debugging an executable program P, GDB will look for
|
---|
| 2038 | a file named ``P-gdb.py`` and automatically read it. Dave Malcolm
|
---|
| 2039 | contributed a :file:`python-gdb.py` that adds a number of
|
---|
| 2040 | commands useful when debugging Python itself. For example,
|
---|
| 2041 | ``py-up`` and ``py-down`` go up or down one Python stack frame,
|
---|
| 2042 | which usually corresponds to several C stack frames. ``py-print``
|
---|
| 2043 | prints the value of a Python variable, and ``py-bt`` prints the
|
---|
| 2044 | Python stack trace. (Added as a result of :issue:`8032`.)
|
---|
| 2045 |
|
---|
| 2046 | * If you use the :file:`.gdbinit` file provided with Python,
|
---|
| 2047 | the "pyo" macro in the 2.7 version now works correctly when the thread being
|
---|
| 2048 | debugged doesn't hold the GIL; the macro now acquires it before printing.
|
---|
| 2049 | (Contributed by Victor Stinner; :issue:`3632`.)
|
---|
| 2050 |
|
---|
| 2051 | * :c:func:`Py_AddPendingCall` is now thread-safe, letting any
|
---|
| 2052 | worker thread submit notifications to the main Python thread. This
|
---|
| 2053 | is particularly useful for asynchronous IO operations.
|
---|
| 2054 | (Contributed by Kristján Valur Jónsson; :issue:`4293`.)
|
---|
| 2055 |
|
---|
| 2056 | * New function: :c:func:`PyCode_NewEmpty` creates an empty code object;
|
---|
| 2057 | only the filename, function name, and first line number are required.
|
---|
| 2058 | This is useful for extension modules that are attempting to
|
---|
| 2059 | construct a more useful traceback stack. Previously such
|
---|
| 2060 | extensions needed to call :c:func:`PyCode_New`, which had many
|
---|
| 2061 | more arguments. (Added by Jeffrey Yasskin.)
|
---|
| 2062 |
|
---|
| 2063 | * New function: :c:func:`PyErr_NewExceptionWithDoc` creates a new
|
---|
| 2064 | exception class, just as the existing :c:func:`PyErr_NewException` does,
|
---|
| 2065 | but takes an extra ``char *`` argument containing the docstring for the
|
---|
| 2066 | new exception class. (Added by 'lekma' on the Python bug tracker;
|
---|
| 2067 | :issue:`7033`.)
|
---|
| 2068 |
|
---|
| 2069 | * New function: :c:func:`PyFrame_GetLineNumber` takes a frame object
|
---|
| 2070 | and returns the line number that the frame is currently executing.
|
---|
| 2071 | Previously code would need to get the index of the bytecode
|
---|
| 2072 | instruction currently executing, and then look up the line number
|
---|
| 2073 | corresponding to that address. (Added by Jeffrey Yasskin.)
|
---|
| 2074 |
|
---|
| 2075 | * New functions: :c:func:`PyLong_AsLongAndOverflow` and
|
---|
| 2076 | :c:func:`PyLong_AsLongLongAndOverflow` approximates a Python long
|
---|
| 2077 | integer as a C :c:type:`long` or :c:type:`long long`.
|
---|
| 2078 | If the number is too large to fit into
|
---|
| 2079 | the output type, an *overflow* flag is set and returned to the caller.
|
---|
| 2080 | (Contributed by Case Van Horsen; :issue:`7528` and :issue:`7767`.)
|
---|
| 2081 |
|
---|
| 2082 | * New function: stemming from the rewrite of string-to-float conversion,
|
---|
| 2083 | a new :c:func:`PyOS_string_to_double` function was added. The old
|
---|
| 2084 | :c:func:`PyOS_ascii_strtod` and :c:func:`PyOS_ascii_atof` functions
|
---|
| 2085 | are now deprecated.
|
---|
| 2086 |
|
---|
| 2087 | * New function: :c:func:`PySys_SetArgvEx` sets the value of
|
---|
| 2088 | ``sys.argv`` and can optionally update ``sys.path`` to include the
|
---|
| 2089 | directory containing the script named by ``sys.argv[0]`` depending
|
---|
| 2090 | on the value of an *updatepath* parameter.
|
---|
| 2091 |
|
---|
| 2092 | This function was added to close a security hole for applications
|
---|
| 2093 | that embed Python. The old function, :c:func:`PySys_SetArgv`, would
|
---|
| 2094 | always update ``sys.path``, and sometimes it would add the current
|
---|
| 2095 | directory. This meant that, if you ran an application embedding
|
---|
| 2096 | Python in a directory controlled by someone else, attackers could
|
---|
| 2097 | put a Trojan-horse module in the directory (say, a file named
|
---|
| 2098 | :file:`os.py`) that your application would then import and run.
|
---|
| 2099 |
|
---|
| 2100 | If you maintain a C/C++ application that embeds Python, check
|
---|
| 2101 | whether you're calling :c:func:`PySys_SetArgv` and carefully consider
|
---|
| 2102 | whether the application should be using :c:func:`PySys_SetArgvEx`
|
---|
| 2103 | with *updatepath* set to false.
|
---|
| 2104 |
|
---|
| 2105 | Security issue reported as `CVE-2008-5983
|
---|
| 2106 | <http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983>`_;
|
---|
| 2107 | discussed in :issue:`5753`, and fixed by Antoine Pitrou.
|
---|
| 2108 |
|
---|
| 2109 | * New macros: the Python header files now define the following macros:
|
---|
| 2110 | :c:macro:`Py_ISALNUM`,
|
---|
| 2111 | :c:macro:`Py_ISALPHA`,
|
---|
| 2112 | :c:macro:`Py_ISDIGIT`,
|
---|
| 2113 | :c:macro:`Py_ISLOWER`,
|
---|
| 2114 | :c:macro:`Py_ISSPACE`,
|
---|
| 2115 | :c:macro:`Py_ISUPPER`,
|
---|
| 2116 | :c:macro:`Py_ISXDIGIT`,
|
---|
| 2117 | :c:macro:`Py_TOLOWER`, and :c:macro:`Py_TOUPPER`.
|
---|
| 2118 | All of these functions are analogous to the C
|
---|
| 2119 | standard macros for classifying characters, but ignore the current
|
---|
| 2120 | locale setting, because in
|
---|
| 2121 | several places Python needs to analyze characters in a
|
---|
| 2122 | locale-independent way. (Added by Eric Smith;
|
---|
| 2123 | :issue:`5793`.)
|
---|
| 2124 |
|
---|
| 2125 | .. XXX these macros don't seem to be described in the c-api docs.
|
---|
| 2126 |
|
---|
| 2127 | * Removed function: :c:macro:`PyEval_CallObject` is now only available
|
---|
| 2128 | as a macro. A function version was being kept around to preserve
|
---|
| 2129 | ABI linking compatibility, but that was in 1997; it can certainly be
|
---|
| 2130 | deleted by now. (Removed by Antoine Pitrou; :issue:`8276`.)
|
---|
| 2131 |
|
---|
| 2132 | * New format codes: the :c:func:`PyFormat_FromString`,
|
---|
| 2133 | :c:func:`PyFormat_FromStringV`, and :c:func:`PyErr_Format` functions now
|
---|
| 2134 | accept ``%lld`` and ``%llu`` format codes for displaying
|
---|
| 2135 | C's :c:type:`long long` types.
|
---|
| 2136 | (Contributed by Mark Dickinson; :issue:`7228`.)
|
---|
| 2137 |
|
---|
| 2138 | * The complicated interaction between threads and process forking has
|
---|
| 2139 | been changed. Previously, the child process created by
|
---|
| 2140 | :func:`os.fork` might fail because the child is created with only a
|
---|
| 2141 | single thread running, the thread performing the :func:`os.fork`.
|
---|
| 2142 | If other threads were holding a lock, such as Python's import lock,
|
---|
| 2143 | when the fork was performed, the lock would still be marked as
|
---|
| 2144 | "held" in the new process. But in the child process nothing would
|
---|
| 2145 | ever release the lock, since the other threads weren't replicated,
|
---|
| 2146 | and the child process would no longer be able to perform imports.
|
---|
| 2147 |
|
---|
| 2148 | Python 2.7 acquires the import lock before performing an
|
---|
| 2149 | :func:`os.fork`, and will also clean up any locks created using the
|
---|
| 2150 | :mod:`threading` module. C extension modules that have internal
|
---|
| 2151 | locks, or that call :c:func:`fork()` themselves, will not benefit
|
---|
| 2152 | from this clean-up.
|
---|
| 2153 |
|
---|
| 2154 | (Fixed by Thomas Wouters; :issue:`1590864`.)
|
---|
| 2155 |
|
---|
| 2156 | * The :c:func:`Py_Finalize` function now calls the internal
|
---|
| 2157 | :func:`threading._shutdown` function; this prevents some exceptions from
|
---|
| 2158 | being raised when an interpreter shuts down.
|
---|
| 2159 | (Patch by Adam Olsen; :issue:`1722344`.)
|
---|
| 2160 |
|
---|
| 2161 | * When using the :c:type:`PyMemberDef` structure to define attributes
|
---|
| 2162 | of a type, Python will no longer let you try to delete or set a
|
---|
| 2163 | :const:`T_STRING_INPLACE` attribute.
|
---|
| 2164 |
|
---|
| 2165 | .. rev 79644
|
---|
| 2166 |
|
---|
| 2167 | * Global symbols defined by the :mod:`ctypes` module are now prefixed
|
---|
| 2168 | with ``Py``, or with ``_ctypes``. (Implemented by Thomas
|
---|
| 2169 | Heller; :issue:`3102`.)
|
---|
| 2170 |
|
---|
| 2171 | * New configure option: the :option:`--with-system-expat` switch allows
|
---|
| 2172 | building the :mod:`pyexpat` module to use the system Expat library.
|
---|
| 2173 | (Contributed by Arfrever Frehtes Taifersar Arahesis; :issue:`7609`.)
|
---|
| 2174 |
|
---|
| 2175 | * New configure option: the
|
---|
| 2176 | :option:`--with-valgrind` option will now disable the pymalloc
|
---|
| 2177 | allocator, which is difficult for the Valgrind memory-error detector
|
---|
| 2178 | to analyze correctly.
|
---|
| 2179 | Valgrind will therefore be better at detecting memory leaks and
|
---|
| 2180 | overruns. (Contributed by James Henstridge; :issue:`2422`.)
|
---|
| 2181 |
|
---|
| 2182 | * New configure option: you can now supply an empty string to
|
---|
| 2183 | :option:`--with-dbmliborder=` in order to disable all of the various
|
---|
| 2184 | DBM modules. (Added by Arfrever Frehtes Taifersar Arahesis;
|
---|
| 2185 | :issue:`6491`.)
|
---|
| 2186 |
|
---|
| 2187 | * The :program:`configure` script now checks for floating-point rounding bugs
|
---|
| 2188 | on certain 32-bit Intel chips and defines a :c:macro:`X87_DOUBLE_ROUNDING`
|
---|
| 2189 | preprocessor definition. No code currently uses this definition,
|
---|
| 2190 | but it's available if anyone wishes to use it.
|
---|
| 2191 | (Added by Mark Dickinson; :issue:`2937`.)
|
---|
| 2192 |
|
---|
| 2193 | :program:`configure` also now sets a :envvar:`LDCXXSHARED` Makefile
|
---|
| 2194 | variable for supporting C++ linking. (Contributed by Arfrever
|
---|
| 2195 | Frehtes Taifersar Arahesis; :issue:`1222585`.)
|
---|
| 2196 |
|
---|
| 2197 | * The build process now creates the necessary files for pkg-config
|
---|
| 2198 | support. (Contributed by Clinton Roy; :issue:`3585`.)
|
---|
| 2199 |
|
---|
| 2200 | * The build process now supports Subversion 1.7. (Contributed by
|
---|
| 2201 | Arfrever Frehtes Taifersar Arahesis; :issue:`6094`.)
|
---|
| 2202 |
|
---|
| 2203 |
|
---|
| 2204 | .. _whatsnew27-capsules:
|
---|
| 2205 |
|
---|
| 2206 | Capsules
|
---|
| 2207 | -------------------
|
---|
| 2208 |
|
---|
| 2209 | Python 3.1 adds a new C datatype, :c:type:`PyCapsule`, for providing a
|
---|
| 2210 | C API to an extension module. A capsule is essentially the holder of
|
---|
| 2211 | a C ``void *`` pointer, and is made available as a module attribute; for
|
---|
| 2212 | example, the :mod:`socket` module's API is exposed as ``socket.CAPI``,
|
---|
| 2213 | and :mod:`unicodedata` exposes ``ucnhash_CAPI``. Other extensions
|
---|
| 2214 | can import the module, access its dictionary to get the capsule
|
---|
| 2215 | object, and then get the ``void *`` pointer, which will usually point
|
---|
| 2216 | to an array of pointers to the module's various API functions.
|
---|
| 2217 |
|
---|
| 2218 | There is an existing data type already used for this,
|
---|
| 2219 | :c:type:`PyCObject`, but it doesn't provide type safety. Evil code
|
---|
| 2220 | written in pure Python could cause a segmentation fault by taking a
|
---|
| 2221 | :c:type:`PyCObject` from module A and somehow substituting it for the
|
---|
| 2222 | :c:type:`PyCObject` in module B. Capsules know their own name,
|
---|
| 2223 | and getting the pointer requires providing the name::
|
---|
| 2224 |
|
---|
| 2225 | void *vtable;
|
---|
| 2226 |
|
---|
| 2227 | if (!PyCapsule_IsValid(capsule, "mymodule.CAPI") {
|
---|
| 2228 | PyErr_SetString(PyExc_ValueError, "argument type invalid");
|
---|
| 2229 | return NULL;
|
---|
| 2230 | }
|
---|
| 2231 |
|
---|
| 2232 | vtable = PyCapsule_GetPointer(capsule, "mymodule.CAPI");
|
---|
| 2233 |
|
---|
| 2234 | You are assured that ``vtable`` points to whatever you're expecting.
|
---|
| 2235 | If a different capsule was passed in, :c:func:`PyCapsule_IsValid` would
|
---|
| 2236 | detect the mismatched name and return false. Refer to
|
---|
| 2237 | :ref:`using-capsules` for more information on using these objects.
|
---|
| 2238 |
|
---|
| 2239 | Python 2.7 now uses capsules internally to provide various
|
---|
| 2240 | extension-module APIs, but the :c:func:`PyCObject_AsVoidPtr` was
|
---|
| 2241 | modified to handle capsules, preserving compile-time compatibility
|
---|
| 2242 | with the :c:type:`CObject` interface. Use of
|
---|
| 2243 | :c:func:`PyCObject_AsVoidPtr` will signal a
|
---|
| 2244 | :exc:`PendingDeprecationWarning`, which is silent by default.
|
---|
| 2245 |
|
---|
| 2246 | Implemented in Python 3.1 and backported to 2.7 by Larry Hastings;
|
---|
| 2247 | discussed in :issue:`5630`.
|
---|
| 2248 |
|
---|
| 2249 |
|
---|
| 2250 | .. ======================================================================
|
---|
| 2251 |
|
---|
| 2252 | Port-Specific Changes: Windows
|
---|
| 2253 | -----------------------------------
|
---|
| 2254 |
|
---|
| 2255 | * The :mod:`msvcrt` module now contains some constants from
|
---|
| 2256 | the :file:`crtassem.h` header file:
|
---|
| 2257 | :data:`CRT_ASSEMBLY_VERSION`,
|
---|
| 2258 | :data:`VC_ASSEMBLY_PUBLICKEYTOKEN`,
|
---|
| 2259 | and :data:`LIBRARIES_ASSEMBLY_NAME_PREFIX`.
|
---|
| 2260 | (Contributed by David Cournapeau; :issue:`4365`.)
|
---|
| 2261 |
|
---|
| 2262 | * The :mod:`_winreg` module for accessing the registry now implements
|
---|
| 2263 | the :func:`~_winreg.CreateKeyEx` and :func:`~_winreg.DeleteKeyEx`
|
---|
| 2264 | functions, extended versions of previously-supported functions that
|
---|
| 2265 | take several extra arguments. The :func:`~_winreg.DisableReflectionKey`,
|
---|
| 2266 | :func:`~_winreg.EnableReflectionKey`, and :func:`~_winreg.QueryReflectionKey`
|
---|
| 2267 | were also tested and documented.
|
---|
| 2268 | (Implemented by Brian Curtin: :issue:`7347`.)
|
---|
| 2269 |
|
---|
| 2270 | * The new :c:func:`_beginthreadex` API is used to start threads, and
|
---|
| 2271 | the native thread-local storage functions are now used.
|
---|
| 2272 | (Contributed by Kristján Valur Jónsson; :issue:`3582`.)
|
---|
| 2273 |
|
---|
| 2274 | * The :func:`os.kill` function now works on Windows. The signal value
|
---|
| 2275 | can be the constants :const:`CTRL_C_EVENT`,
|
---|
| 2276 | :const:`CTRL_BREAK_EVENT`, or any integer. The first two constants
|
---|
| 2277 | will send Control-C and Control-Break keystroke events to
|
---|
| 2278 | subprocesses; any other value will use the :c:func:`TerminateProcess`
|
---|
| 2279 | API. (Contributed by Miki Tebeka; :issue:`1220212`.)
|
---|
| 2280 |
|
---|
| 2281 | * The :func:`os.listdir` function now correctly fails
|
---|
| 2282 | for an empty path. (Fixed by Hirokazu Yamamoto; :issue:`5913`.)
|
---|
| 2283 |
|
---|
| 2284 | * The :mod:`mimelib` module will now read the MIME database from
|
---|
| 2285 | the Windows registry when initializing.
|
---|
| 2286 | (Patch by Gabriel Genellina; :issue:`4969`.)
|
---|
| 2287 |
|
---|
| 2288 | .. ======================================================================
|
---|
| 2289 |
|
---|
| 2290 | Port-Specific Changes: Mac OS X
|
---|
| 2291 | -----------------------------------
|
---|
| 2292 |
|
---|
| 2293 | * The path ``/Library/Python/2.7/site-packages`` is now appended to
|
---|
| 2294 | ``sys.path``, in order to share added packages between the system
|
---|
| 2295 | installation and a user-installed copy of the same version.
|
---|
| 2296 | (Changed by Ronald Oussoren; :issue:`4865`.)
|
---|
| 2297 |
|
---|
| 2298 | Port-Specific Changes: FreeBSD
|
---|
| 2299 | -----------------------------------
|
---|
| 2300 |
|
---|
| 2301 | * FreeBSD 7.1's :const:`SO_SETFIB` constant, used with
|
---|
| 2302 | :func:`~socket.getsockopt`/:func:`~socket.setsockopt` to select an
|
---|
| 2303 | alternate routing table, is now available in the :mod:`socket`
|
---|
| 2304 | module. (Added by Kyle VanderBeek; :issue:`8235`.)
|
---|
| 2305 |
|
---|
| 2306 | Other Changes and Fixes
|
---|
| 2307 | =======================
|
---|
| 2308 |
|
---|
| 2309 | * Two benchmark scripts, :file:`iobench` and :file:`ccbench`, were
|
---|
| 2310 | added to the :file:`Tools` directory. :file:`iobench` measures the
|
---|
| 2311 | speed of the built-in file I/O objects returned by :func:`open`
|
---|
| 2312 | while performing various operations, and :file:`ccbench` is a
|
---|
| 2313 | concurrency benchmark that tries to measure computing throughput,
|
---|
| 2314 | thread switching latency, and IO processing bandwidth when
|
---|
| 2315 | performing several tasks using a varying number of threads.
|
---|
| 2316 |
|
---|
| 2317 | * The :file:`Tools/i18n/msgfmt.py` script now understands plural
|
---|
| 2318 | forms in :file:`.po` files. (Fixed by Martin von Löwis;
|
---|
| 2319 | :issue:`5464`.)
|
---|
| 2320 |
|
---|
| 2321 | * When importing a module from a :file:`.pyc` or :file:`.pyo` file
|
---|
| 2322 | with an existing :file:`.py` counterpart, the :attr:`co_filename`
|
---|
| 2323 | attributes of the resulting code objects are overwritten when the
|
---|
| 2324 | original filename is obsolete. This can happen if the file has been
|
---|
| 2325 | renamed, moved, or is accessed through different paths. (Patch by
|
---|
| 2326 | Ziga Seilnacht and Jean-Paul Calderone; :issue:`1180193`.)
|
---|
| 2327 |
|
---|
| 2328 | * The :file:`regrtest.py` script now takes a :option:`--randseed=`
|
---|
| 2329 | switch that takes an integer that will be used as the random seed
|
---|
| 2330 | for the :option:`-r` option that executes tests in random order.
|
---|
| 2331 | The :option:`-r` option also reports the seed that was used
|
---|
| 2332 | (Added by Collin Winter.)
|
---|
| 2333 |
|
---|
| 2334 | * Another :file:`regrtest.py` switch is :option:`-j`, which
|
---|
| 2335 | takes an integer specifying how many tests run in parallel. This
|
---|
| 2336 | allows reducing the total runtime on multi-core machines.
|
---|
| 2337 | This option is compatible with several other options, including the
|
---|
| 2338 | :option:`-R` switch which is known to produce long runtimes.
|
---|
| 2339 | (Added by Antoine Pitrou, :issue:`6152`.) This can also be used
|
---|
| 2340 | with a new :option:`-F` switch that runs selected tests in a loop
|
---|
| 2341 | until they fail. (Added by Antoine Pitrou; :issue:`7312`.)
|
---|
| 2342 |
|
---|
| 2343 | * When executed as a script, the :file:`py_compile.py` module now
|
---|
| 2344 | accepts ``'-'`` as an argument, which will read standard input for
|
---|
| 2345 | the list of filenames to be compiled. (Contributed by Piotr
|
---|
| 2346 | OÅŒarowski; :issue:`8233`.)
|
---|
| 2347 |
|
---|
| 2348 | .. ======================================================================
|
---|
| 2349 |
|
---|
| 2350 | Porting to Python 2.7
|
---|
| 2351 | =====================
|
---|
| 2352 |
|
---|
| 2353 | This section lists previously described changes and other bugfixes
|
---|
| 2354 | that may require changes to your code:
|
---|
| 2355 |
|
---|
| 2356 | * The :func:`range` function processes its arguments more
|
---|
| 2357 | consistently; it will now call :meth:`__int__` on non-float,
|
---|
| 2358 | non-integer arguments that are supplied to it. (Fixed by Alexander
|
---|
| 2359 | Belopolsky; :issue:`1533`.)
|
---|
| 2360 |
|
---|
| 2361 | * The string :meth:`format` method changed the default precision used
|
---|
| 2362 | for floating-point and complex numbers from 6 decimal
|
---|
| 2363 | places to 12, which matches the precision used by :func:`str`.
|
---|
| 2364 | (Changed by Eric Smith; :issue:`5920`.)
|
---|
| 2365 |
|
---|
| 2366 | * Because of an optimization for the :keyword:`with` statement, the special
|
---|
| 2367 | methods :meth:`__enter__` and :meth:`__exit__` must belong to the object's
|
---|
| 2368 | type, and cannot be directly attached to the object's instance. This
|
---|
| 2369 | affects new-style classes (derived from :class:`object`) and C extension
|
---|
| 2370 | types. (:issue:`6101`.)
|
---|
| 2371 |
|
---|
| 2372 | * Due to a bug in Python 2.6, the *exc_value* parameter to
|
---|
| 2373 | :meth:`__exit__` methods was often the string representation of the
|
---|
| 2374 | exception, not an instance. This was fixed in 2.7, so *exc_value*
|
---|
| 2375 | will be an instance as expected. (Fixed by Florent Xicluna;
|
---|
| 2376 | :issue:`7853`.)
|
---|
| 2377 |
|
---|
| 2378 | * When a restricted set of attributes were set using ``__slots__``,
|
---|
| 2379 | deleting an unset attribute would not raise :exc:`AttributeError`
|
---|
| 2380 | as you would expect. Fixed by Benjamin Peterson; :issue:`7604`.)
|
---|
| 2381 |
|
---|
| 2382 | In the standard library:
|
---|
| 2383 |
|
---|
| 2384 | * Operations with :class:`~datetime.datetime` instances that resulted in a year
|
---|
| 2385 | falling outside the supported range didn't always raise
|
---|
| 2386 | :exc:`OverflowError`. Such errors are now checked more carefully
|
---|
| 2387 | and will now raise the exception. (Reported by Mark Leander, patch
|
---|
| 2388 | by Anand B. Pillai and Alexander Belopolsky; :issue:`7150`.)
|
---|
| 2389 |
|
---|
| 2390 | * When using :class:`~decimal.Decimal` instances with a string's
|
---|
| 2391 | :meth:`format` method, the default alignment was previously
|
---|
| 2392 | left-alignment. This has been changed to right-alignment, which might
|
---|
| 2393 | change the output of your programs.
|
---|
| 2394 | (Changed by Mark Dickinson; :issue:`6857`.)
|
---|
| 2395 |
|
---|
| 2396 | Comparisons involving a signaling NaN value (or ``sNAN``) now signal
|
---|
| 2397 | :const:`~decimal.InvalidOperation` instead of silently returning a true or
|
---|
| 2398 | false value depending on the comparison operator. Quiet NaN values
|
---|
| 2399 | (or ``NaN``) are now hashable. (Fixed by Mark Dickinson;
|
---|
| 2400 | :issue:`7279`.)
|
---|
| 2401 |
|
---|
| 2402 | * The ElementTree library, :mod:`xml.etree`, no longer escapes
|
---|
| 2403 | ampersands and angle brackets when outputting an XML processing
|
---|
| 2404 | instruction (which looks like `<?xml-stylesheet href="#style1"?>`)
|
---|
| 2405 | or comment (which looks like `<!-- comment -->`).
|
---|
| 2406 | (Patch by Neil Muller; :issue:`2746`.)
|
---|
| 2407 |
|
---|
| 2408 | * The :meth:`~StringIO.StringIO.readline` method of :class:`~StringIO.StringIO` objects now does
|
---|
| 2409 | nothing when a negative length is requested, as other file-like
|
---|
| 2410 | objects do. (:issue:`7348`).
|
---|
| 2411 |
|
---|
| 2412 | * The :mod:`syslog` module will now use the value of ``sys.argv[0]`` as the
|
---|
| 2413 | identifier instead of the previous default value of ``'python'``.
|
---|
| 2414 | (Changed by Sean Reifschneider; :issue:`8451`.)
|
---|
| 2415 |
|
---|
| 2416 | * The :mod:`tarfile` module's default error handling has changed, to
|
---|
| 2417 | no longer suppress fatal errors. The default error level was previously 0,
|
---|
| 2418 | which meant that errors would only result in a message being written to the
|
---|
| 2419 | debug log, but because the debug log is not activated by default,
|
---|
| 2420 | these errors go unnoticed. The default error level is now 1,
|
---|
| 2421 | which raises an exception if there's an error.
|
---|
| 2422 | (Changed by Lars GustÀbel; :issue:`7357`.)
|
---|
| 2423 |
|
---|
| 2424 | * The :mod:`urlparse` module's :func:`~urlparse.urlsplit` now handles
|
---|
| 2425 | unknown URL schemes in a fashion compliant with :rfc:`3986`: if the
|
---|
| 2426 | URL is of the form ``"<something>://..."``, the text before the
|
---|
| 2427 | ``://`` is treated as the scheme, even if it's a made-up scheme that
|
---|
| 2428 | the module doesn't know about. This change may break code that
|
---|
| 2429 | worked around the old behaviour. For example, Python 2.6.4 or 2.5
|
---|
| 2430 | will return the following:
|
---|
| 2431 |
|
---|
| 2432 | >>> import urlparse
|
---|
| 2433 | >>> urlparse.urlsplit('invented://host/filename?query')
|
---|
| 2434 | ('invented', '', '//host/filename?query', '', '')
|
---|
| 2435 |
|
---|
| 2436 | Python 2.7 (and Python 2.6.5) will return:
|
---|
| 2437 |
|
---|
| 2438 | >>> import urlparse
|
---|
| 2439 | >>> urlparse.urlsplit('invented://host/filename?query')
|
---|
| 2440 | ('invented', 'host', '/filename?query', '', '')
|
---|
| 2441 |
|
---|
| 2442 | (Python 2.7 actually produces slightly different output, since it
|
---|
| 2443 | returns a named tuple instead of a standard tuple.)
|
---|
| 2444 |
|
---|
| 2445 | For C extensions:
|
---|
| 2446 |
|
---|
| 2447 | * C extensions that use integer format codes with the ``PyArg_Parse*``
|
---|
| 2448 | family of functions will now raise a :exc:`TypeError` exception
|
---|
| 2449 | instead of triggering a :exc:`DeprecationWarning` (:issue:`5080`).
|
---|
| 2450 |
|
---|
| 2451 | * Use the new :c:func:`PyOS_string_to_double` function instead of the old
|
---|
| 2452 | :c:func:`PyOS_ascii_strtod` and :c:func:`PyOS_ascii_atof` functions,
|
---|
| 2453 | which are now deprecated.
|
---|
| 2454 |
|
---|
| 2455 | For applications that embed Python:
|
---|
| 2456 |
|
---|
| 2457 | * The :c:func:`PySys_SetArgvEx` function was added, letting
|
---|
| 2458 | applications close a security hole when the existing
|
---|
| 2459 | :c:func:`PySys_SetArgv` function was used. Check whether you're
|
---|
| 2460 | calling :c:func:`PySys_SetArgv` and carefully consider whether the
|
---|
| 2461 | application should be using :c:func:`PySys_SetArgvEx` with
|
---|
| 2462 | *updatepath* set to false.
|
---|
| 2463 |
|
---|
| 2464 | .. ======================================================================
|
---|
| 2465 |
|
---|
| 2466 |
|
---|
| 2467 | .. _acks27:
|
---|
| 2468 |
|
---|
| 2469 | Acknowledgements
|
---|
| 2470 | ================
|
---|
| 2471 |
|
---|
| 2472 | The author would like to thank the following people for offering
|
---|
| 2473 | suggestions, corrections and assistance with various drafts of this
|
---|
| 2474 | article: Nick Coghlan, Philip Jenvey, Ryan Lovett, R. David Murray,
|
---|
| 2475 | Hugh Secker-Walker.
|
---|
| 2476 |
|
---|